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.

281187 lines
7.6MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #elif defined (JUCE_ANDROID)
  55. #undef JUCE_ANDROID
  56. #define JUCE_ANDROID 1
  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_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. #ifndef JUCE_OPENGL
  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 <signal.h>
  634. /* Got a build error here? You'll need to install the freetype library...
  635. The name of the package to install is "libfreetype6-dev".
  636. */
  637. #include <ft2build.h>
  638. #include FT_FREETYPE_H
  639. #include <X11/Xlib.h>
  640. #include <X11/Xatom.h>
  641. #include <X11/Xresource.h>
  642. #include <X11/Xutil.h>
  643. #include <X11/Xmd.h>
  644. #include <X11/keysym.h>
  645. #include <X11/cursorfont.h>
  646. #if JUCE_USE_XINERAMA
  647. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  648. #include <X11/extensions/Xinerama.h>
  649. #endif
  650. #if JUCE_USE_XSHM
  651. #include <X11/extensions/XShm.h>
  652. #include <sys/shm.h>
  653. #include <sys/ipc.h>
  654. #endif
  655. #if JUCE_USE_XRENDER
  656. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  657. #include <X11/extensions/Xrender.h>
  658. #include <X11/extensions/Xcomposite.h>
  659. #endif
  660. #if JUCE_USE_XCURSOR
  661. // If you're missing this header, try installing the libxcursor-dev package
  662. #include <X11/Xcursor/Xcursor.h>
  663. #endif
  664. #if JUCE_OPENGL
  665. /* Got an include error here?
  666. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  667. and "freeglut3-dev".
  668. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  669. want to disable it.
  670. */
  671. #include <GL/glx.h>
  672. #endif
  673. #undef KeyPress
  674. #if JUCE_ALSA
  675. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  676. not got your paths set up correctly to find its header files.
  677. The package you need to install to get ASLA support is "libasound2-dev".
  678. If you don't have the ALSA library and don't want to build Juce with audio support,
  679. just disable the JUCE_ALSA flag in juce_Config.h
  680. */
  681. #include <alsa/asoundlib.h>
  682. #endif
  683. #if JUCE_JACK
  684. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  685. installed, or you've not got your paths set up correctly to find its header files.
  686. The package you need to install to get JACK support is "libjack-dev".
  687. If you don't have the jack-audio-connection-kit library and don't want to build
  688. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  689. */
  690. #include <jack/jack.h>
  691. //#include <jack/transport.h>
  692. #endif
  693. #undef SIZEOF
  694. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  695. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  696. #elif JUCE_MAC || JUCE_IOS
  697. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  698. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  699. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  700. #define USE_COREGRAPHICS_RENDERING 1
  701. #if JUCE_IOS
  702. #import <Foundation/Foundation.h>
  703. #import <UIKit/UIKit.h>
  704. #import <AudioToolbox/AudioToolbox.h>
  705. #import <AVFoundation/AVFoundation.h>
  706. #import <CoreData/CoreData.h>
  707. #import <MobileCoreServices/MobileCoreServices.h>
  708. #import <QuartzCore/QuartzCore.h>
  709. #include <sys/fcntl.h>
  710. #if JUCE_OPENGL
  711. #include <OpenGLES/ES1/gl.h>
  712. #include <OpenGLES/ES1/glext.h>
  713. #endif
  714. #else
  715. #import <Cocoa/Cocoa.h>
  716. #import <CoreAudio/HostTime.h>
  717. #if JUCE_BUILD_NATIVE
  718. #import <CoreAudio/AudioHardware.h>
  719. #import <CoreMIDI/MIDIServices.h>
  720. #import <QTKit/QTKit.h>
  721. #import <WebKit/WebKit.h>
  722. #import <DiscRecording/DiscRecording.h>
  723. #import <IOKit/IOKitLib.h>
  724. #import <IOKit/IOCFPlugIn.h>
  725. #import <IOKit/hid/IOHIDLib.h>
  726. #import <IOKit/hid/IOHIDKeys.h>
  727. #import <IOKit/pwr_mgt/IOPMLib.h>
  728. #endif
  729. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  730. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  731. #include <Carbon/Carbon.h>
  732. #endif
  733. #include <sys/dir.h>
  734. #endif
  735. #include <sys/socket.h>
  736. #include <sys/sysctl.h>
  737. #include <sys/stat.h>
  738. #include <sys/param.h>
  739. #include <sys/mount.h>
  740. #include <fnmatch.h>
  741. #include <utime.h>
  742. #include <dlfcn.h>
  743. #include <ifaddrs.h>
  744. #include <net/if_dl.h>
  745. #include <mach/mach_time.h>
  746. #include <mach-o/dyld.h>
  747. #if MACOS_10_4_OR_EARLIER
  748. #include <GLUT/glut.h>
  749. #endif
  750. #if ! CGFLOAT_DEFINED
  751. #define CGFloat float
  752. #endif
  753. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  754. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  755. #elif JUCE_ANDROID
  756. /*** Start of inlined file: juce_android_NativeIncludes.h ***/
  757. #ifndef __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  758. #define __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  759. #include <pthread.h>
  760. #include <sched.h>
  761. #include <sys/time.h>
  762. #include <utime.h>
  763. #include <errno.h>
  764. #include <fcntl.h>
  765. #include <dlfcn.h>
  766. #include <sys/stat.h>
  767. #include <sys/statfs.h>
  768. #include <sys/ptrace.h>
  769. #include <sys/sysinfo.h>
  770. #include <pwd.h>
  771. #include <dirent.h>
  772. #include <fnmatch.h>
  773. #if JUCE_OPENGL
  774. #include <GLES/gl.h>
  775. #endif
  776. #endif // __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  777. /*** End of inlined file: juce_android_NativeIncludes.h ***/
  778. #else
  779. #error "Unknown platform!"
  780. #endif
  781. #endif
  782. //==============================================================================
  783. #define DONT_SET_USING_JUCE_NAMESPACE 1
  784. #undef max
  785. #undef min
  786. #define NO_DUMMY_DECL
  787. #define JUCE_AMALGAMATED_TEMPLATE 1
  788. #if JUCE_BUILD_NATIVE
  789. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  790. #endif
  791. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  792. #pragma warning (disable: 4309 4305)
  793. #endif
  794. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  795. BEGIN_JUCE_NAMESPACE
  796. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  797. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  798. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  799. /**
  800. Creates a floating carbon window that can be used to hold a carbon UI.
  801. This is a handy class that's designed to be inlined where needed, e.g.
  802. in the audio plugin hosting code.
  803. */
  804. class CarbonViewWrapperComponent : public Component,
  805. public ComponentMovementWatcher,
  806. public Timer
  807. {
  808. public:
  809. CarbonViewWrapperComponent()
  810. : ComponentMovementWatcher (this),
  811. wrapperWindow (0),
  812. carbonWindow (0),
  813. embeddedView (0),
  814. recursiveResize (false)
  815. {
  816. }
  817. virtual ~CarbonViewWrapperComponent()
  818. {
  819. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  820. }
  821. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  822. virtual void removeView (HIViewRef embeddedView) = 0;
  823. virtual void mouseDown (int, int) {}
  824. virtual void paint() {}
  825. virtual bool getEmbeddedViewSize (int& w, int& h)
  826. {
  827. if (embeddedView == 0)
  828. return false;
  829. HIRect bounds;
  830. HIViewGetBounds (embeddedView, &bounds);
  831. w = jmax (1, roundToInt (bounds.size.width));
  832. h = jmax (1, roundToInt (bounds.size.height));
  833. return true;
  834. }
  835. void createWindow()
  836. {
  837. if (wrapperWindow == 0)
  838. {
  839. Rect r;
  840. r.left = getScreenX();
  841. r.top = getScreenY();
  842. r.right = r.left + getWidth();
  843. r.bottom = r.top + getHeight();
  844. CreateNewWindow (kDocumentWindowClass,
  845. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  846. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  847. &r, &wrapperWindow);
  848. jassert (wrapperWindow != 0);
  849. if (wrapperWindow == 0)
  850. return;
  851. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  852. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  853. [ownerWindow addChildWindow: carbonWindow
  854. ordered: NSWindowAbove];
  855. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  856. EventTypeSpec windowEventTypes[] =
  857. {
  858. { kEventClassWindow, kEventWindowGetClickActivation },
  859. { kEventClassWindow, kEventWindowHandleDeactivate },
  860. { kEventClassWindow, kEventWindowBoundsChanging },
  861. { kEventClassMouse, kEventMouseDown },
  862. { kEventClassMouse, kEventMouseMoved },
  863. { kEventClassMouse, kEventMouseDragged },
  864. { kEventClassMouse, kEventMouseUp},
  865. { kEventClassWindow, kEventWindowDrawContent },
  866. { kEventClassWindow, kEventWindowShown },
  867. { kEventClassWindow, kEventWindowHidden }
  868. };
  869. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  870. InstallWindowEventHandler (wrapperWindow, upp,
  871. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  872. windowEventTypes, this, &eventHandlerRef);
  873. setOurSizeToEmbeddedViewSize();
  874. setEmbeddedWindowToOurSize();
  875. creationTime = Time::getCurrentTime();
  876. }
  877. }
  878. void deleteWindow()
  879. {
  880. removeView (embeddedView);
  881. embeddedView = 0;
  882. if (wrapperWindow != 0)
  883. {
  884. RemoveEventHandler (eventHandlerRef);
  885. DisposeWindow (wrapperWindow);
  886. wrapperWindow = 0;
  887. }
  888. }
  889. void setOurSizeToEmbeddedViewSize()
  890. {
  891. int w, h;
  892. if (getEmbeddedViewSize (w, h))
  893. {
  894. if (w != getWidth() || h != getHeight())
  895. {
  896. startTimer (50);
  897. setSize (w, h);
  898. if (getParentComponent() != 0)
  899. getParentComponent()->setSize (w, h);
  900. }
  901. else
  902. {
  903. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  904. }
  905. }
  906. else
  907. {
  908. stopTimer();
  909. }
  910. }
  911. void setEmbeddedWindowToOurSize()
  912. {
  913. if (! recursiveResize)
  914. {
  915. recursiveResize = true;
  916. if (embeddedView != 0)
  917. {
  918. HIRect r;
  919. r.origin.x = 0;
  920. r.origin.y = 0;
  921. r.size.width = (float) getWidth();
  922. r.size.height = (float) getHeight();
  923. HIViewSetFrame (embeddedView, &r);
  924. }
  925. if (wrapperWindow != 0)
  926. {
  927. Rect wr;
  928. wr.left = getScreenX();
  929. wr.top = getScreenY();
  930. wr.right = wr.left + getWidth();
  931. wr.bottom = wr.top + getHeight();
  932. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  933. ShowWindow (wrapperWindow);
  934. }
  935. recursiveResize = false;
  936. }
  937. }
  938. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  939. {
  940. setEmbeddedWindowToOurSize();
  941. }
  942. void componentPeerChanged()
  943. {
  944. deleteWindow();
  945. createWindow();
  946. }
  947. void componentVisibilityChanged()
  948. {
  949. if (isShowing())
  950. createWindow();
  951. else
  952. deleteWindow();
  953. setEmbeddedWindowToOurSize();
  954. }
  955. static void recursiveHIViewRepaint (HIViewRef view)
  956. {
  957. HIViewSetNeedsDisplay (view, true);
  958. HIViewRef child = HIViewGetFirstSubview (view);
  959. while (child != 0)
  960. {
  961. recursiveHIViewRepaint (child);
  962. child = HIViewGetNextView (child);
  963. }
  964. }
  965. void timerCallback()
  966. {
  967. setOurSizeToEmbeddedViewSize();
  968. // To avoid strange overpainting problems when the UI is first opened, we'll
  969. // repaint it a few times during the first second that it's on-screen..
  970. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  971. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  972. }
  973. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  974. {
  975. switch (GetEventKind (event))
  976. {
  977. case kEventWindowHandleDeactivate:
  978. ActivateWindow (wrapperWindow, TRUE);
  979. return noErr;
  980. case kEventWindowGetClickActivation:
  981. {
  982. getTopLevelComponent()->toFront (false);
  983. [carbonWindow makeKeyAndOrderFront: nil];
  984. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  985. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  986. sizeof (ClickActivationResult), &howToHandleClick);
  987. HIViewSetNeedsDisplay (embeddedView, true);
  988. return noErr;
  989. }
  990. }
  991. return eventNotHandledErr;
  992. }
  993. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  994. {
  995. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  996. }
  997. protected:
  998. WindowRef wrapperWindow;
  999. NSWindow* carbonWindow;
  1000. HIViewRef embeddedView;
  1001. bool recursiveResize;
  1002. Time creationTime;
  1003. EventHandlerRef eventHandlerRef;
  1004. };
  1005. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  1006. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  1007. END_JUCE_NAMESPACE
  1008. #endif
  1009. //==============================================================================
  1010. #if JUCE_BUILD_CORE
  1011. /*** Start of inlined file: juce_FileLogger.cpp ***/
  1012. BEGIN_JUCE_NAMESPACE
  1013. FileLogger::FileLogger (const File& logFile_,
  1014. const String& welcomeMessage,
  1015. const int maxInitialFileSizeBytes)
  1016. : logFile (logFile_)
  1017. {
  1018. if (maxInitialFileSizeBytes >= 0)
  1019. trimFileSize (maxInitialFileSizeBytes);
  1020. if (! logFile_.exists())
  1021. {
  1022. // do this so that the parent directories get created..
  1023. logFile_.create();
  1024. }
  1025. String welcome;
  1026. welcome << newLine
  1027. << "**********************************************************" << newLine
  1028. << welcomeMessage << newLine
  1029. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1030. logMessage (welcome);
  1031. }
  1032. FileLogger::~FileLogger()
  1033. {
  1034. }
  1035. void FileLogger::logMessage (const String& message)
  1036. {
  1037. DBG (message);
  1038. const ScopedLock sl (logLock);
  1039. FileOutputStream out (logFile, 256);
  1040. out << message << newLine;
  1041. }
  1042. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1043. {
  1044. if (maxFileSizeBytes <= 0)
  1045. {
  1046. logFile.deleteFile();
  1047. }
  1048. else
  1049. {
  1050. const int64 fileSize = logFile.getSize();
  1051. if (fileSize > maxFileSizeBytes)
  1052. {
  1053. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1054. jassert (in != 0);
  1055. if (in != 0)
  1056. {
  1057. in->setPosition (fileSize - maxFileSizeBytes);
  1058. String content;
  1059. {
  1060. MemoryBlock contentToSave;
  1061. contentToSave.setSize (maxFileSizeBytes + 4);
  1062. contentToSave.fillWith (0);
  1063. in->read (contentToSave.getData(), maxFileSizeBytes);
  1064. in = 0;
  1065. content = contentToSave.toString();
  1066. }
  1067. int newStart = 0;
  1068. while (newStart < fileSize
  1069. && content[newStart] != '\n'
  1070. && content[newStart] != '\r')
  1071. ++newStart;
  1072. logFile.deleteFile();
  1073. logFile.appendText (content.substring (newStart), false, false);
  1074. }
  1075. }
  1076. }
  1077. }
  1078. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1079. const String& logFileName,
  1080. const String& welcomeMessage,
  1081. const int maxInitialFileSizeBytes)
  1082. {
  1083. #if JUCE_MAC
  1084. File logFile ("~/Library/Logs");
  1085. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1086. .getChildFile (logFileName);
  1087. #else
  1088. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1089. if (logFile.isDirectory())
  1090. {
  1091. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1092. .getChildFile (logFileName);
  1093. }
  1094. #endif
  1095. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1096. }
  1097. END_JUCE_NAMESPACE
  1098. /*** End of inlined file: juce_FileLogger.cpp ***/
  1099. /*** Start of inlined file: juce_Logger.cpp ***/
  1100. BEGIN_JUCE_NAMESPACE
  1101. Logger::Logger()
  1102. {
  1103. }
  1104. Logger::~Logger()
  1105. {
  1106. }
  1107. Logger* Logger::currentLogger = 0;
  1108. void Logger::setCurrentLogger (Logger* const newLogger,
  1109. const bool deleteOldLogger)
  1110. {
  1111. Logger* const oldLogger = currentLogger;
  1112. currentLogger = newLogger;
  1113. if (deleteOldLogger)
  1114. delete oldLogger;
  1115. }
  1116. void Logger::writeToLog (const String& message)
  1117. {
  1118. if (currentLogger != 0)
  1119. currentLogger->logMessage (message);
  1120. else
  1121. outputDebugString (message);
  1122. }
  1123. #if JUCE_LOG_ASSERTIONS
  1124. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1125. {
  1126. String m ("JUCE Assertion failure in ");
  1127. m << filename << ", line " << lineNum;
  1128. Logger::writeToLog (m);
  1129. }
  1130. #endif
  1131. END_JUCE_NAMESPACE
  1132. /*** End of inlined file: juce_Logger.cpp ***/
  1133. /*** Start of inlined file: juce_Random.cpp ***/
  1134. BEGIN_JUCE_NAMESPACE
  1135. Random::Random (const int64 seedValue) throw()
  1136. : seed (seedValue)
  1137. {
  1138. }
  1139. Random::~Random() throw()
  1140. {
  1141. }
  1142. void Random::setSeed (const int64 newSeed) throw()
  1143. {
  1144. seed = newSeed;
  1145. }
  1146. void Random::combineSeed (const int64 seedValue) throw()
  1147. {
  1148. seed ^= nextInt64() ^ seedValue;
  1149. }
  1150. void Random::setSeedRandomly()
  1151. {
  1152. combineSeed ((int64) (pointer_sized_int) this);
  1153. combineSeed (Time::getMillisecondCounter());
  1154. combineSeed (Time::getHighResolutionTicks());
  1155. combineSeed (Time::getHighResolutionTicksPerSecond());
  1156. combineSeed (Time::currentTimeMillis());
  1157. }
  1158. int Random::nextInt() throw()
  1159. {
  1160. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1161. return (int) (seed >> 16);
  1162. }
  1163. int Random::nextInt (const int maxValue) throw()
  1164. {
  1165. jassert (maxValue > 0);
  1166. return (nextInt() & 0x7fffffff) % maxValue;
  1167. }
  1168. int64 Random::nextInt64() throw()
  1169. {
  1170. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1171. }
  1172. bool Random::nextBool() throw()
  1173. {
  1174. return (nextInt() & 0x80000000) != 0;
  1175. }
  1176. float Random::nextFloat() throw()
  1177. {
  1178. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1179. }
  1180. double Random::nextDouble() throw()
  1181. {
  1182. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1183. }
  1184. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1185. {
  1186. BigInteger n;
  1187. do
  1188. {
  1189. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1190. }
  1191. while (n >= maximumValue);
  1192. return n;
  1193. }
  1194. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1195. {
  1196. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1197. while ((startBit & 31) != 0 && numBits > 0)
  1198. {
  1199. arrayToChange.setBit (startBit++, nextBool());
  1200. --numBits;
  1201. }
  1202. while (numBits >= 32)
  1203. {
  1204. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1205. startBit += 32;
  1206. numBits -= 32;
  1207. }
  1208. while (--numBits >= 0)
  1209. arrayToChange.setBit (startBit + numBits, nextBool());
  1210. }
  1211. Random& Random::getSystemRandom() throw()
  1212. {
  1213. static Random sysRand (1);
  1214. return sysRand;
  1215. }
  1216. END_JUCE_NAMESPACE
  1217. /*** End of inlined file: juce_Random.cpp ***/
  1218. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1219. BEGIN_JUCE_NAMESPACE
  1220. RelativeTime::RelativeTime (const double seconds_) throw()
  1221. : seconds (seconds_)
  1222. {
  1223. }
  1224. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1225. : seconds (other.seconds)
  1226. {
  1227. }
  1228. RelativeTime::~RelativeTime() throw()
  1229. {
  1230. }
  1231. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1232. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1233. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1234. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1235. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1236. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1237. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1238. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1239. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1240. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1241. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1242. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1243. {
  1244. if (seconds < 0.001 && seconds > -0.001)
  1245. return returnValueForZeroTime;
  1246. String result;
  1247. result.preallocateStorage (16);
  1248. if (seconds < 0)
  1249. result << '-';
  1250. int fieldsShown = 0;
  1251. int n = std::abs ((int) inWeeks());
  1252. if (n > 0)
  1253. {
  1254. result << n << (n == 1 ? TRANS(" week ")
  1255. : TRANS(" weeks "));
  1256. ++fieldsShown;
  1257. }
  1258. n = std::abs ((int) inDays()) % 7;
  1259. if (n > 0)
  1260. {
  1261. result << n << (n == 1 ? TRANS(" day ")
  1262. : TRANS(" days "));
  1263. ++fieldsShown;
  1264. }
  1265. if (fieldsShown < 2)
  1266. {
  1267. n = std::abs ((int) inHours()) % 24;
  1268. if (n > 0)
  1269. {
  1270. result << n << (n == 1 ? TRANS(" hr ")
  1271. : TRANS(" hrs "));
  1272. ++fieldsShown;
  1273. }
  1274. if (fieldsShown < 2)
  1275. {
  1276. n = std::abs ((int) inMinutes()) % 60;
  1277. if (n > 0)
  1278. {
  1279. result << n << (n == 1 ? TRANS(" min ")
  1280. : TRANS(" mins "));
  1281. ++fieldsShown;
  1282. }
  1283. if (fieldsShown < 2)
  1284. {
  1285. n = std::abs ((int) inSeconds()) % 60;
  1286. if (n > 0)
  1287. {
  1288. result << n << (n == 1 ? TRANS(" sec ")
  1289. : TRANS(" secs "));
  1290. ++fieldsShown;
  1291. }
  1292. if (fieldsShown == 0)
  1293. {
  1294. n = std::abs ((int) inMilliseconds()) % 1000;
  1295. if (n > 0)
  1296. result << n << TRANS(" ms");
  1297. }
  1298. }
  1299. }
  1300. }
  1301. return result.trimEnd();
  1302. }
  1303. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1304. {
  1305. seconds = other.seconds;
  1306. return *this;
  1307. }
  1308. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1309. {
  1310. seconds += timeToAdd.seconds;
  1311. return *this;
  1312. }
  1313. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1314. {
  1315. seconds -= timeToSubtract.seconds;
  1316. return *this;
  1317. }
  1318. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1319. {
  1320. seconds += secondsToAdd;
  1321. return *this;
  1322. }
  1323. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1324. {
  1325. seconds -= secondsToSubtract;
  1326. return *this;
  1327. }
  1328. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1329. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  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. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1335. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1336. END_JUCE_NAMESPACE
  1337. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1338. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1339. BEGIN_JUCE_NAMESPACE
  1340. SystemStats::CPUFlags SystemStats::cpuFlags;
  1341. const String SystemStats::getJUCEVersion()
  1342. {
  1343. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1344. + "." + String (JUCE_MINOR_VERSION)
  1345. + "." + String (JUCE_BUILDNUMBER);
  1346. }
  1347. #ifdef JUCE_DLL
  1348. void* juce_Malloc (int size) { return malloc (size); }
  1349. void* juce_Calloc (int size) { return calloc (1, size); }
  1350. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1351. void juce_Free (void* block) { free (block); }
  1352. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1353. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1354. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1355. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1356. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1357. #endif
  1358. #endif
  1359. END_JUCE_NAMESPACE
  1360. /*** End of inlined file: juce_SystemStats.cpp ***/
  1361. /*** Start of inlined file: juce_Time.cpp ***/
  1362. #if JUCE_MSVC
  1363. #pragma warning (push)
  1364. #pragma warning (disable: 4514)
  1365. #endif
  1366. #ifndef JUCE_WINDOWS
  1367. #include <sys/time.h>
  1368. #else
  1369. #include <ctime>
  1370. #endif
  1371. #include <sys/timeb.h>
  1372. #if JUCE_MSVC
  1373. #pragma warning (pop)
  1374. #ifdef _INC_TIME_INL
  1375. #define USE_NEW_SECURE_TIME_FNS
  1376. #endif
  1377. #endif
  1378. BEGIN_JUCE_NAMESPACE
  1379. namespace TimeHelpers
  1380. {
  1381. static struct tm millisToLocal (const int64 millis) throw()
  1382. {
  1383. struct tm result;
  1384. const int64 seconds = millis / 1000;
  1385. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1386. {
  1387. // use extended maths for dates beyond 1970 to 2037..
  1388. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1389. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1390. const int days = (int) (jdm / literal64bit (86400));
  1391. const int a = 32044 + days;
  1392. const int b = (4 * a + 3) / 146097;
  1393. const int c = a - (b * 146097) / 4;
  1394. const int d = (4 * c + 3) / 1461;
  1395. const int e = c - (d * 1461) / 4;
  1396. const int m = (5 * e + 2) / 153;
  1397. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1398. result.tm_mon = m + 2 - 12 * (m / 10);
  1399. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1400. result.tm_wday = (days + 1) % 7;
  1401. result.tm_yday = -1;
  1402. int t = (int) (jdm % literal64bit (86400));
  1403. result.tm_hour = t / 3600;
  1404. t %= 3600;
  1405. result.tm_min = t / 60;
  1406. result.tm_sec = t % 60;
  1407. result.tm_isdst = -1;
  1408. }
  1409. else
  1410. {
  1411. time_t now = static_cast <time_t> (seconds);
  1412. #if JUCE_WINDOWS
  1413. #ifdef USE_NEW_SECURE_TIME_FNS
  1414. if (now >= 0 && now <= 0x793406fff)
  1415. localtime_s (&result, &now);
  1416. else
  1417. zeromem (&result, sizeof (result));
  1418. #else
  1419. result = *localtime (&now);
  1420. #endif
  1421. #else
  1422. // more thread-safe
  1423. localtime_r (&now, &result);
  1424. #endif
  1425. }
  1426. return result;
  1427. }
  1428. static int extendedModulo (const int64 value, const int modulo) throw()
  1429. {
  1430. return (int) (value >= 0 ? (value % modulo)
  1431. : (value - ((value / modulo) + 1) * modulo));
  1432. }
  1433. static uint32 lastMSCounterValue = 0;
  1434. }
  1435. Time::Time() throw()
  1436. : millisSinceEpoch (0)
  1437. {
  1438. }
  1439. Time::Time (const Time& other) throw()
  1440. : millisSinceEpoch (other.millisSinceEpoch)
  1441. {
  1442. }
  1443. Time::Time (const int64 ms) throw()
  1444. : millisSinceEpoch (ms)
  1445. {
  1446. }
  1447. Time::Time (const int year,
  1448. const int month,
  1449. const int day,
  1450. const int hours,
  1451. const int minutes,
  1452. const int seconds,
  1453. const int milliseconds,
  1454. const bool useLocalTime) throw()
  1455. {
  1456. jassert (year > 100); // year must be a 4-digit version
  1457. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1458. {
  1459. // use extended maths for dates beyond 1970 to 2037..
  1460. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1461. : 0;
  1462. const int a = (13 - month) / 12;
  1463. const int y = year + 4800 - a;
  1464. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1465. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1466. - 32045;
  1467. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1468. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1469. + milliseconds;
  1470. }
  1471. else
  1472. {
  1473. struct tm t;
  1474. t.tm_year = year - 1900;
  1475. t.tm_mon = month;
  1476. t.tm_mday = day;
  1477. t.tm_hour = hours;
  1478. t.tm_min = minutes;
  1479. t.tm_sec = seconds;
  1480. t.tm_isdst = -1;
  1481. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1482. if (millisSinceEpoch < 0)
  1483. millisSinceEpoch = 0;
  1484. else
  1485. millisSinceEpoch += milliseconds;
  1486. }
  1487. }
  1488. Time::~Time() throw()
  1489. {
  1490. }
  1491. Time& Time::operator= (const Time& other) throw()
  1492. {
  1493. millisSinceEpoch = other.millisSinceEpoch;
  1494. return *this;
  1495. }
  1496. int64 Time::currentTimeMillis() throw()
  1497. {
  1498. static uint32 lastCounterResult = 0xffffffff;
  1499. static int64 correction = 0;
  1500. const uint32 now = getMillisecondCounter();
  1501. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1502. if (now < lastCounterResult)
  1503. {
  1504. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1505. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1506. {
  1507. // get the time once using normal library calls, and store the difference needed to
  1508. // turn the millisecond counter into a real time.
  1509. #if JUCE_WINDOWS
  1510. struct _timeb t;
  1511. #ifdef USE_NEW_SECURE_TIME_FNS
  1512. _ftime_s (&t);
  1513. #else
  1514. _ftime (&t);
  1515. #endif
  1516. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1517. #else
  1518. struct timeval tv;
  1519. struct timezone tz;
  1520. gettimeofday (&tv, &tz);
  1521. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1522. #endif
  1523. }
  1524. }
  1525. lastCounterResult = now;
  1526. return correction + now;
  1527. }
  1528. uint32 juce_millisecondsSinceStartup() throw();
  1529. uint32 Time::getMillisecondCounter() throw()
  1530. {
  1531. const uint32 now = juce_millisecondsSinceStartup();
  1532. if (now < TimeHelpers::lastMSCounterValue)
  1533. {
  1534. // in multi-threaded apps this might be called concurrently, so
  1535. // make sure that our last counter value only increases and doesn't
  1536. // go backwards..
  1537. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1538. TimeHelpers::lastMSCounterValue = now;
  1539. }
  1540. else
  1541. {
  1542. TimeHelpers::lastMSCounterValue = now;
  1543. }
  1544. return now;
  1545. }
  1546. uint32 Time::getApproximateMillisecondCounter() throw()
  1547. {
  1548. jassert (TimeHelpers::lastMSCounterValue != 0);
  1549. return TimeHelpers::lastMSCounterValue;
  1550. }
  1551. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1552. {
  1553. for (;;)
  1554. {
  1555. const uint32 now = getMillisecondCounter();
  1556. if (now >= targetTime)
  1557. break;
  1558. const int toWait = targetTime - now;
  1559. if (toWait > 2)
  1560. {
  1561. Thread::sleep (jmin (20, toWait >> 1));
  1562. }
  1563. else
  1564. {
  1565. // xxx should consider using mutex_pause on the mac as it apparently
  1566. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1567. for (int i = 10; --i >= 0;)
  1568. Thread::yield();
  1569. }
  1570. }
  1571. }
  1572. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1573. {
  1574. return ticks / (double) getHighResolutionTicksPerSecond();
  1575. }
  1576. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1577. {
  1578. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1579. }
  1580. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1581. {
  1582. return Time (currentTimeMillis());
  1583. }
  1584. const String Time::toString (const bool includeDate,
  1585. const bool includeTime,
  1586. const bool includeSeconds,
  1587. const bool use24HourClock) const throw()
  1588. {
  1589. String result;
  1590. if (includeDate)
  1591. {
  1592. result << getDayOfMonth() << ' '
  1593. << getMonthName (true) << ' '
  1594. << getYear();
  1595. if (includeTime)
  1596. result << ' ';
  1597. }
  1598. if (includeTime)
  1599. {
  1600. const int mins = getMinutes();
  1601. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1602. << (mins < 10 ? ":0" : ":") << mins;
  1603. if (includeSeconds)
  1604. {
  1605. const int secs = getSeconds();
  1606. result << (secs < 10 ? ":0" : ":") << secs;
  1607. }
  1608. if (! use24HourClock)
  1609. result << (isAfternoon() ? "pm" : "am");
  1610. }
  1611. return result.trimEnd();
  1612. }
  1613. const String Time::formatted (const String& format) const
  1614. {
  1615. String buffer;
  1616. int bufferSize = 128;
  1617. buffer.preallocateStorage (bufferSize);
  1618. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1619. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1620. {
  1621. bufferSize += 128;
  1622. buffer.preallocateStorage (bufferSize);
  1623. }
  1624. return buffer;
  1625. }
  1626. int Time::getYear() const throw()
  1627. {
  1628. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1629. }
  1630. int Time::getMonth() const throw()
  1631. {
  1632. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1633. }
  1634. int Time::getDayOfMonth() const throw()
  1635. {
  1636. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1637. }
  1638. int Time::getDayOfWeek() const throw()
  1639. {
  1640. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1641. }
  1642. int Time::getHours() const throw()
  1643. {
  1644. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1645. }
  1646. int Time::getHoursInAmPmFormat() const throw()
  1647. {
  1648. const int hours = getHours();
  1649. if (hours == 0)
  1650. return 12;
  1651. else if (hours <= 12)
  1652. return hours;
  1653. else
  1654. return hours - 12;
  1655. }
  1656. bool Time::isAfternoon() const throw()
  1657. {
  1658. return getHours() >= 12;
  1659. }
  1660. int Time::getMinutes() const throw()
  1661. {
  1662. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1663. }
  1664. int Time::getSeconds() const throw()
  1665. {
  1666. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1667. }
  1668. int Time::getMilliseconds() const throw()
  1669. {
  1670. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1671. }
  1672. bool Time::isDaylightSavingTime() const throw()
  1673. {
  1674. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1675. }
  1676. const String Time::getTimeZone() const throw()
  1677. {
  1678. String zone[2];
  1679. #if JUCE_WINDOWS
  1680. _tzset();
  1681. #ifdef USE_NEW_SECURE_TIME_FNS
  1682. {
  1683. char name [128];
  1684. size_t length;
  1685. for (int i = 0; i < 2; ++i)
  1686. {
  1687. zeromem (name, sizeof (name));
  1688. _get_tzname (&length, name, 127, i);
  1689. zone[i] = name;
  1690. }
  1691. }
  1692. #else
  1693. const char** const zonePtr = (const char**) _tzname;
  1694. zone[0] = zonePtr[0];
  1695. zone[1] = zonePtr[1];
  1696. #endif
  1697. #else
  1698. tzset();
  1699. const char** const zonePtr = (const char**) tzname;
  1700. zone[0] = zonePtr[0];
  1701. zone[1] = zonePtr[1];
  1702. #endif
  1703. if (isDaylightSavingTime())
  1704. {
  1705. zone[0] = zone[1];
  1706. if (zone[0].length() > 3
  1707. && zone[0].containsIgnoreCase ("daylight")
  1708. && zone[0].contains ("GMT"))
  1709. zone[0] = "BST";
  1710. }
  1711. return zone[0].substring (0, 3);
  1712. }
  1713. const String Time::getMonthName (const bool threeLetterVersion) const
  1714. {
  1715. return getMonthName (getMonth(), threeLetterVersion);
  1716. }
  1717. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1718. {
  1719. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1720. }
  1721. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1722. {
  1723. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1724. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1725. monthNumber %= 12;
  1726. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1727. : longMonthNames [monthNumber]);
  1728. }
  1729. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1730. {
  1731. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1732. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1733. day %= 7;
  1734. return TRANS (threeLetterVersion ? shortDayNames [day]
  1735. : longDayNames [day]);
  1736. }
  1737. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1738. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1739. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1740. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1741. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1742. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1743. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1744. bool operator!= (const Time& time1, const Time& time2) { return 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. END_JUCE_NAMESPACE
  1750. /*** End of inlined file: juce_Time.cpp ***/
  1751. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1752. BEGIN_JUCE_NAMESPACE
  1753. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1754. #endif
  1755. #if JUCE_WINDOWS
  1756. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1757. #endif
  1758. #if JUCE_DEBUG
  1759. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1760. #endif
  1761. static bool juceInitialisedNonGUI = false;
  1762. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1763. {
  1764. if (! juceInitialisedNonGUI)
  1765. {
  1766. juceInitialisedNonGUI = true;
  1767. JUCE_AUTORELEASEPOOL
  1768. DBG (SystemStats::getJUCEVersion());
  1769. SystemStats::initialiseStats();
  1770. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1771. }
  1772. // Some basic tests, to keep an eye on things and make sure these types work ok
  1773. // on all platforms. Let me know if any of these assertions fail on your system!
  1774. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1775. static_jassert (sizeof (int8) == 1);
  1776. static_jassert (sizeof (uint8) == 1);
  1777. static_jassert (sizeof (int16) == 2);
  1778. static_jassert (sizeof (uint16) == 2);
  1779. static_jassert (sizeof (int32) == 4);
  1780. static_jassert (sizeof (uint32) == 4);
  1781. static_jassert (sizeof (int64) == 8);
  1782. static_jassert (sizeof (uint64) == 8);
  1783. }
  1784. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1785. {
  1786. if (juceInitialisedNonGUI)
  1787. {
  1788. juceInitialisedNonGUI = false;
  1789. JUCE_AUTORELEASEPOOL
  1790. LocalisedStrings::setCurrentMappings (0);
  1791. Thread::stopAllThreads (3000);
  1792. #if JUCE_WINDOWS
  1793. juce_shutdownWin32Sockets();
  1794. #endif
  1795. #if JUCE_DEBUG
  1796. juce_CheckForDanglingStreams();
  1797. #endif
  1798. }
  1799. }
  1800. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1801. static bool juceInitialisedGUI = false;
  1802. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1803. {
  1804. if (! juceInitialisedGUI)
  1805. {
  1806. juceInitialisedGUI = true;
  1807. JUCE_AUTORELEASEPOOL
  1808. initialiseJuce_NonGUI();
  1809. MessageManager::getInstance();
  1810. LookAndFeel::setDefaultLookAndFeel (0);
  1811. #if JUCE_DEBUG
  1812. try // This section is just a safety-net for catching builds without RTTI enabled..
  1813. {
  1814. MemoryOutputStream mo;
  1815. OutputStream* o = &mo;
  1816. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1817. o = dynamic_cast <MemoryOutputStream*> (o);
  1818. jassert (o != 0);
  1819. }
  1820. catch (...)
  1821. {
  1822. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1823. jassertfalse;
  1824. }
  1825. #endif
  1826. }
  1827. }
  1828. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1829. {
  1830. if (juceInitialisedGUI)
  1831. {
  1832. juceInitialisedGUI = false;
  1833. JUCE_AUTORELEASEPOOL
  1834. DeletedAtShutdown::deleteAll();
  1835. LookAndFeel::clearDefaultLookAndFeel();
  1836. delete MessageManager::getInstance();
  1837. shutdownJuce_NonGUI();
  1838. }
  1839. }
  1840. #endif
  1841. #if JUCE_UNIT_TESTS
  1842. class AtomicTests : public UnitTest
  1843. {
  1844. public:
  1845. AtomicTests() : UnitTest ("Atomics") {}
  1846. void runTest()
  1847. {
  1848. beginTest ("Misc");
  1849. char a1[7];
  1850. expect (numElementsInArray(a1) == 7);
  1851. int a2[3];
  1852. expect (numElementsInArray(a2) == 3);
  1853. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1854. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1855. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1856. beginTest ("Atomic types");
  1857. AtomicTester <int>::testInteger (*this);
  1858. AtomicTester <unsigned int>::testInteger (*this);
  1859. AtomicTester <int32>::testInteger (*this);
  1860. AtomicTester <uint32>::testInteger (*this);
  1861. AtomicTester <long>::testInteger (*this);
  1862. AtomicTester <void*>::testInteger (*this);
  1863. AtomicTester <int*>::testInteger (*this);
  1864. AtomicTester <float>::testFloat (*this);
  1865. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1866. AtomicTester <int64>::testInteger (*this);
  1867. AtomicTester <uint64>::testInteger (*this);
  1868. AtomicTester <double>::testFloat (*this);
  1869. #endif
  1870. }
  1871. template <typename Type>
  1872. class AtomicTester
  1873. {
  1874. public:
  1875. AtomicTester() {}
  1876. static void testInteger (UnitTest& test)
  1877. {
  1878. Atomic<Type> a, b;
  1879. a.set ((Type) 10);
  1880. a += (Type) 15;
  1881. a.memoryBarrier();
  1882. a -= (Type) 5;
  1883. ++a; ++a; --a;
  1884. a.memoryBarrier();
  1885. testFloat (test);
  1886. }
  1887. static void testFloat (UnitTest& test)
  1888. {
  1889. Atomic<Type> a, b;
  1890. a = (Type) 21;
  1891. a.memoryBarrier();
  1892. /* These are some simple test cases to check the atomics - let me know
  1893. if any of these assertions fail on your system!
  1894. */
  1895. test.expect (a.get() == (Type) 21);
  1896. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1897. test.expect (a.get() == (Type) 21);
  1898. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1899. test.expect (a.get() == (Type) 101);
  1900. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1901. test.expect (a.get() == (Type) 101);
  1902. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1903. test.expect (a.get() == (Type) 200);
  1904. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1905. test.expect (a.get() == (Type) 300);
  1906. b = a;
  1907. test.expect (b.get() == a.get());
  1908. }
  1909. };
  1910. };
  1911. static AtomicTests atomicUnitTests;
  1912. #endif
  1913. END_JUCE_NAMESPACE
  1914. /*** End of inlined file: juce_Initialisation.cpp ***/
  1915. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1916. BEGIN_JUCE_NAMESPACE
  1917. AbstractFifo::AbstractFifo (const int capacity) throw()
  1918. : bufferSize (capacity)
  1919. {
  1920. jassert (bufferSize > 0);
  1921. }
  1922. AbstractFifo::~AbstractFifo() {}
  1923. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1924. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1925. int AbstractFifo::getNumReady() const throw()
  1926. {
  1927. const int vs = validStart.get();
  1928. const int ve = validEnd.get();
  1929. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1930. }
  1931. void AbstractFifo::reset() throw()
  1932. {
  1933. validEnd = 0;
  1934. validStart = 0;
  1935. }
  1936. void AbstractFifo::setTotalSize (int newSize) throw()
  1937. {
  1938. jassert (newSize > 0);
  1939. reset();
  1940. bufferSize = newSize;
  1941. }
  1942. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1943. {
  1944. const int vs = validStart.get();
  1945. const int ve = validEnd.value;
  1946. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1947. numToWrite = jmin (numToWrite, freeSpace - 1);
  1948. if (numToWrite <= 0)
  1949. {
  1950. startIndex1 = 0;
  1951. startIndex2 = 0;
  1952. blockSize1 = 0;
  1953. blockSize2 = 0;
  1954. }
  1955. else
  1956. {
  1957. startIndex1 = ve;
  1958. startIndex2 = 0;
  1959. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1960. numToWrite -= blockSize1;
  1961. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1962. }
  1963. }
  1964. void AbstractFifo::finishedWrite (int numWritten) throw()
  1965. {
  1966. jassert (numWritten >= 0 && numWritten < bufferSize);
  1967. int newEnd = validEnd.value + numWritten;
  1968. if (newEnd >= bufferSize)
  1969. newEnd -= bufferSize;
  1970. validEnd = newEnd;
  1971. }
  1972. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1973. {
  1974. const int vs = validStart.value;
  1975. const int ve = validEnd.get();
  1976. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1977. numWanted = jmin (numWanted, numReady);
  1978. if (numWanted <= 0)
  1979. {
  1980. startIndex1 = 0;
  1981. startIndex2 = 0;
  1982. blockSize1 = 0;
  1983. blockSize2 = 0;
  1984. }
  1985. else
  1986. {
  1987. startIndex1 = vs;
  1988. startIndex2 = 0;
  1989. blockSize1 = jmin (bufferSize - vs, numWanted);
  1990. numWanted -= blockSize1;
  1991. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  1992. }
  1993. }
  1994. void AbstractFifo::finishedRead (int numRead) throw()
  1995. {
  1996. jassert (numRead >= 0 && numRead <= bufferSize);
  1997. int newStart = validStart.value + numRead;
  1998. if (newStart >= bufferSize)
  1999. newStart -= bufferSize;
  2000. validStart = newStart;
  2001. }
  2002. #if JUCE_UNIT_TESTS
  2003. class AbstractFifoTests : public UnitTest
  2004. {
  2005. public:
  2006. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2007. class WriteThread : public Thread
  2008. {
  2009. public:
  2010. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2011. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2012. {
  2013. startThread();
  2014. }
  2015. ~WriteThread()
  2016. {
  2017. stopThread (5000);
  2018. }
  2019. void run()
  2020. {
  2021. int n = 0;
  2022. while (! threadShouldExit())
  2023. {
  2024. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2025. int start1, size1, start2, size2;
  2026. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2027. jassert (size1 >= 0 && size2 >= 0);
  2028. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2029. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2030. int i;
  2031. for (i = 0; i < size1; ++i)
  2032. buffer [start1 + i] = n++;
  2033. for (i = 0; i < size2; ++i)
  2034. buffer [start2 + i] = n++;
  2035. fifo.finishedWrite (size1 + size2);
  2036. }
  2037. }
  2038. private:
  2039. AbstractFifo& fifo;
  2040. int* buffer;
  2041. };
  2042. void runTest()
  2043. {
  2044. beginTest ("AbstractFifo");
  2045. int buffer [5000];
  2046. AbstractFifo fifo (numElementsInArray (buffer));
  2047. WriteThread writer (fifo, buffer);
  2048. int n = 0;
  2049. for (int count = 1000000; --count >= 0;)
  2050. {
  2051. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2052. int start1, size1, start2, size2;
  2053. fifo.prepareToRead (num, start1, size1, start2, size2);
  2054. if (! (size1 >= 0 && size2 >= 0)
  2055. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2056. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2057. {
  2058. expect (false, "prepareToRead returned -ve values");
  2059. break;
  2060. }
  2061. bool failed = false;
  2062. int i;
  2063. for (i = 0; i < size1; ++i)
  2064. failed = (buffer [start1 + i] != n++) || failed;
  2065. for (i = 0; i < size2; ++i)
  2066. failed = (buffer [start2 + i] != n++) || failed;
  2067. if (failed)
  2068. {
  2069. expect (false, "read values were incorrect");
  2070. break;
  2071. }
  2072. fifo.finishedRead (size1 + size2);
  2073. }
  2074. }
  2075. };
  2076. static AbstractFifoTests fifoUnitTests;
  2077. #endif
  2078. END_JUCE_NAMESPACE
  2079. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2080. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2081. BEGIN_JUCE_NAMESPACE
  2082. BigInteger::BigInteger()
  2083. : numValues (4),
  2084. highestBit (-1),
  2085. negative (false)
  2086. {
  2087. values.calloc (numValues + 1);
  2088. }
  2089. BigInteger::BigInteger (const int32 value)
  2090. : numValues (4),
  2091. highestBit (31),
  2092. negative (value < 0)
  2093. {
  2094. values.calloc (numValues + 1);
  2095. values[0] = abs (value);
  2096. highestBit = getHighestBit();
  2097. }
  2098. BigInteger::BigInteger (const uint32 value)
  2099. : numValues (4),
  2100. highestBit (31),
  2101. negative (false)
  2102. {
  2103. values.calloc (numValues + 1);
  2104. values[0] = value;
  2105. highestBit = getHighestBit();
  2106. }
  2107. BigInteger::BigInteger (int64 value)
  2108. : numValues (4),
  2109. highestBit (63),
  2110. negative (value < 0)
  2111. {
  2112. values.calloc (numValues + 1);
  2113. if (value < 0)
  2114. value = -value;
  2115. values[0] = (uint32) value;
  2116. values[1] = (uint32) (value >> 32);
  2117. highestBit = getHighestBit();
  2118. }
  2119. BigInteger::BigInteger (const BigInteger& other)
  2120. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2121. highestBit (other.getHighestBit()),
  2122. negative (other.negative)
  2123. {
  2124. values.malloc (numValues + 1);
  2125. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2126. }
  2127. BigInteger::~BigInteger()
  2128. {
  2129. }
  2130. void BigInteger::swapWith (BigInteger& other) throw()
  2131. {
  2132. values.swapWith (other.values);
  2133. swapVariables (numValues, other.numValues);
  2134. swapVariables (highestBit, other.highestBit);
  2135. swapVariables (negative, other.negative);
  2136. }
  2137. BigInteger& BigInteger::operator= (const BigInteger& other)
  2138. {
  2139. if (this != &other)
  2140. {
  2141. highestBit = other.getHighestBit();
  2142. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2143. negative = other.negative;
  2144. values.malloc (numValues + 1);
  2145. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2146. }
  2147. return *this;
  2148. }
  2149. void BigInteger::ensureSize (const int numVals)
  2150. {
  2151. if (numVals + 2 >= numValues)
  2152. {
  2153. int oldSize = numValues;
  2154. numValues = ((numVals + 2) * 3) / 2;
  2155. values.realloc (numValues + 1);
  2156. while (oldSize < numValues)
  2157. values [oldSize++] = 0;
  2158. }
  2159. }
  2160. bool BigInteger::operator[] (const int bit) const throw()
  2161. {
  2162. return bit <= highestBit && bit >= 0
  2163. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2164. }
  2165. int BigInteger::toInteger() const throw()
  2166. {
  2167. const int n = (int) (values[0] & 0x7fffffff);
  2168. return negative ? -n : n;
  2169. }
  2170. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2171. {
  2172. BigInteger r;
  2173. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2174. r.ensureSize (bitToIndex (numBits));
  2175. r.highestBit = numBits;
  2176. int i = 0;
  2177. while (numBits > 0)
  2178. {
  2179. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2180. numBits -= 32;
  2181. startBit += 32;
  2182. }
  2183. r.highestBit = r.getHighestBit();
  2184. return r;
  2185. }
  2186. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2187. {
  2188. if (numBits > 32)
  2189. {
  2190. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2191. numBits = 32;
  2192. }
  2193. numBits = jmin (numBits, highestBit + 1 - startBit);
  2194. if (numBits <= 0)
  2195. return 0;
  2196. const int pos = bitToIndex (startBit);
  2197. const int offset = startBit & 31;
  2198. const int endSpace = 32 - numBits;
  2199. uint32 n = ((uint32) values [pos]) >> offset;
  2200. if (offset > endSpace)
  2201. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2202. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2203. }
  2204. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2205. {
  2206. if (numBits > 32)
  2207. {
  2208. jassertfalse;
  2209. numBits = 32;
  2210. }
  2211. for (int i = 0; i < numBits; ++i)
  2212. {
  2213. setBit (startBit + i, (valueToSet & 1) != 0);
  2214. valueToSet >>= 1;
  2215. }
  2216. }
  2217. void BigInteger::clear()
  2218. {
  2219. if (numValues > 16)
  2220. {
  2221. numValues = 4;
  2222. values.calloc (numValues + 1);
  2223. }
  2224. else
  2225. {
  2226. zeromem (values, sizeof (uint32) * (numValues + 1));
  2227. }
  2228. highestBit = -1;
  2229. negative = false;
  2230. }
  2231. void BigInteger::setBit (const int bit)
  2232. {
  2233. if (bit >= 0)
  2234. {
  2235. if (bit > highestBit)
  2236. {
  2237. ensureSize (bitToIndex (bit));
  2238. highestBit = bit;
  2239. }
  2240. values [bitToIndex (bit)] |= bitToMask (bit);
  2241. }
  2242. }
  2243. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2244. {
  2245. if (shouldBeSet)
  2246. setBit (bit);
  2247. else
  2248. clearBit (bit);
  2249. }
  2250. void BigInteger::clearBit (const int bit) throw()
  2251. {
  2252. if (bit >= 0 && bit <= highestBit)
  2253. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2254. }
  2255. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2256. {
  2257. while (--numBits >= 0)
  2258. setBit (startBit++, shouldBeSet);
  2259. }
  2260. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2261. {
  2262. if (bit >= 0)
  2263. shiftBits (1, bit);
  2264. setBit (bit, shouldBeSet);
  2265. }
  2266. bool BigInteger::isZero() const throw()
  2267. {
  2268. return getHighestBit() < 0;
  2269. }
  2270. bool BigInteger::isOne() const throw()
  2271. {
  2272. return getHighestBit() == 0 && ! negative;
  2273. }
  2274. bool BigInteger::isNegative() const throw()
  2275. {
  2276. return negative && ! isZero();
  2277. }
  2278. void BigInteger::setNegative (const bool neg) throw()
  2279. {
  2280. negative = neg;
  2281. }
  2282. void BigInteger::negate() throw()
  2283. {
  2284. negative = (! negative) && ! isZero();
  2285. }
  2286. #if JUCE_USE_INTRINSICS
  2287. #pragma intrinsic (_BitScanReverse)
  2288. #endif
  2289. namespace BitFunctions
  2290. {
  2291. inline int countBitsInInt32 (uint32 n) throw()
  2292. {
  2293. n -= ((n >> 1) & 0x55555555);
  2294. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2295. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2296. n += (n >> 8);
  2297. n += (n >> 16);
  2298. return n & 0x3f;
  2299. }
  2300. inline int highestBitInInt (uint32 n) throw()
  2301. {
  2302. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2303. #if JUCE_GCC
  2304. return 31 - __builtin_clz (n);
  2305. #elif JUCE_USE_INTRINSICS
  2306. unsigned long highest;
  2307. _BitScanReverse (&highest, n);
  2308. return (int) highest;
  2309. #else
  2310. n |= (n >> 1);
  2311. n |= (n >> 2);
  2312. n |= (n >> 4);
  2313. n |= (n >> 8);
  2314. n |= (n >> 16);
  2315. return countBitsInInt32 (n >> 1);
  2316. #endif
  2317. }
  2318. }
  2319. int BigInteger::countNumberOfSetBits() const throw()
  2320. {
  2321. int total = 0;
  2322. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2323. total += BitFunctions::countBitsInInt32 (values[i]);
  2324. return total;
  2325. }
  2326. int BigInteger::getHighestBit() const throw()
  2327. {
  2328. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2329. {
  2330. const uint32 n = values[i];
  2331. if (n != 0)
  2332. return BitFunctions::highestBitInInt (n) + (i << 5);
  2333. }
  2334. return -1;
  2335. }
  2336. int BigInteger::findNextSetBit (int i) const throw()
  2337. {
  2338. for (; i <= highestBit; ++i)
  2339. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2340. return i;
  2341. return -1;
  2342. }
  2343. int BigInteger::findNextClearBit (int i) const throw()
  2344. {
  2345. for (; i <= highestBit; ++i)
  2346. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2347. break;
  2348. return i;
  2349. }
  2350. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2351. {
  2352. if (other.isNegative())
  2353. return operator-= (-other);
  2354. if (isNegative())
  2355. {
  2356. if (compareAbsolute (other) < 0)
  2357. {
  2358. BigInteger temp (*this);
  2359. temp.negate();
  2360. *this = other;
  2361. operator-= (temp);
  2362. }
  2363. else
  2364. {
  2365. negate();
  2366. operator-= (other);
  2367. negate();
  2368. }
  2369. }
  2370. else
  2371. {
  2372. if (other.highestBit > highestBit)
  2373. highestBit = other.highestBit;
  2374. ++highestBit;
  2375. const int numInts = bitToIndex (highestBit) + 1;
  2376. ensureSize (numInts);
  2377. int64 remainder = 0;
  2378. for (int i = 0; i <= numInts; ++i)
  2379. {
  2380. if (i < numValues)
  2381. remainder += values[i];
  2382. if (i < other.numValues)
  2383. remainder += other.values[i];
  2384. values[i] = (uint32) remainder;
  2385. remainder >>= 32;
  2386. }
  2387. jassert (remainder == 0);
  2388. highestBit = getHighestBit();
  2389. }
  2390. return *this;
  2391. }
  2392. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2393. {
  2394. if (other.isNegative())
  2395. return operator+= (-other);
  2396. if (! isNegative())
  2397. {
  2398. if (compareAbsolute (other) < 0)
  2399. {
  2400. BigInteger temp (other);
  2401. swapWith (temp);
  2402. operator-= (temp);
  2403. negate();
  2404. return *this;
  2405. }
  2406. }
  2407. else
  2408. {
  2409. negate();
  2410. operator+= (other);
  2411. negate();
  2412. return *this;
  2413. }
  2414. const int numInts = bitToIndex (highestBit) + 1;
  2415. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2416. int64 amountToSubtract = 0;
  2417. for (int i = 0; i <= numInts; ++i)
  2418. {
  2419. if (i <= maxOtherInts)
  2420. amountToSubtract += (int64) other.values[i];
  2421. if (values[i] >= amountToSubtract)
  2422. {
  2423. values[i] = (uint32) (values[i] - amountToSubtract);
  2424. amountToSubtract = 0;
  2425. }
  2426. else
  2427. {
  2428. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2429. values[i] = (uint32) n;
  2430. amountToSubtract = 1;
  2431. }
  2432. }
  2433. return *this;
  2434. }
  2435. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2436. {
  2437. BigInteger total;
  2438. highestBit = getHighestBit();
  2439. const bool wasNegative = isNegative();
  2440. setNegative (false);
  2441. for (int i = 0; i <= highestBit; ++i)
  2442. {
  2443. if (operator[](i))
  2444. {
  2445. BigInteger n (other);
  2446. n.setNegative (false);
  2447. n <<= i;
  2448. total += n;
  2449. }
  2450. }
  2451. total.setNegative (wasNegative ^ other.isNegative());
  2452. swapWith (total);
  2453. return *this;
  2454. }
  2455. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2456. {
  2457. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2458. const int divHB = divisor.getHighestBit();
  2459. const int ourHB = getHighestBit();
  2460. if (divHB < 0 || ourHB < 0)
  2461. {
  2462. // division by zero
  2463. remainder.clear();
  2464. clear();
  2465. }
  2466. else
  2467. {
  2468. const bool wasNegative = isNegative();
  2469. swapWith (remainder);
  2470. remainder.setNegative (false);
  2471. clear();
  2472. BigInteger temp (divisor);
  2473. temp.setNegative (false);
  2474. int leftShift = ourHB - divHB;
  2475. temp <<= leftShift;
  2476. while (leftShift >= 0)
  2477. {
  2478. if (remainder.compareAbsolute (temp) >= 0)
  2479. {
  2480. remainder -= temp;
  2481. setBit (leftShift);
  2482. }
  2483. if (--leftShift >= 0)
  2484. temp >>= 1;
  2485. }
  2486. negative = wasNegative ^ divisor.isNegative();
  2487. remainder.setNegative (wasNegative);
  2488. }
  2489. }
  2490. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2491. {
  2492. BigInteger remainder;
  2493. divideBy (other, remainder);
  2494. return *this;
  2495. }
  2496. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2497. {
  2498. // this operation doesn't take into account negative values..
  2499. jassert (isNegative() == other.isNegative());
  2500. if (other.highestBit >= 0)
  2501. {
  2502. ensureSize (bitToIndex (other.highestBit));
  2503. int n = bitToIndex (other.highestBit) + 1;
  2504. while (--n >= 0)
  2505. values[n] |= other.values[n];
  2506. if (other.highestBit > highestBit)
  2507. highestBit = other.highestBit;
  2508. highestBit = getHighestBit();
  2509. }
  2510. return *this;
  2511. }
  2512. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2513. {
  2514. // this operation doesn't take into account negative values..
  2515. jassert (isNegative() == other.isNegative());
  2516. int n = numValues;
  2517. while (n > other.numValues)
  2518. values[--n] = 0;
  2519. while (--n >= 0)
  2520. values[n] &= other.values[n];
  2521. if (other.highestBit < highestBit)
  2522. highestBit = other.highestBit;
  2523. highestBit = getHighestBit();
  2524. return *this;
  2525. }
  2526. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2527. {
  2528. // this operation will only work with the absolute values
  2529. jassert (isNegative() == other.isNegative());
  2530. if (other.highestBit >= 0)
  2531. {
  2532. ensureSize (bitToIndex (other.highestBit));
  2533. int n = bitToIndex (other.highestBit) + 1;
  2534. while (--n >= 0)
  2535. values[n] ^= other.values[n];
  2536. if (other.highestBit > highestBit)
  2537. highestBit = other.highestBit;
  2538. highestBit = getHighestBit();
  2539. }
  2540. return *this;
  2541. }
  2542. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2543. {
  2544. BigInteger remainder;
  2545. divideBy (divisor, remainder);
  2546. swapWith (remainder);
  2547. return *this;
  2548. }
  2549. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2550. {
  2551. shiftBits (numBitsToShift, 0);
  2552. return *this;
  2553. }
  2554. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2555. {
  2556. return operator<<= (-numBitsToShift);
  2557. }
  2558. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2559. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2560. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2561. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2562. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2563. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2564. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2565. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2566. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2567. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2568. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2569. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2570. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2571. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2572. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2573. int BigInteger::compare (const BigInteger& other) const throw()
  2574. {
  2575. if (isNegative() == other.isNegative())
  2576. {
  2577. const int absComp = compareAbsolute (other);
  2578. return isNegative() ? -absComp : absComp;
  2579. }
  2580. else
  2581. {
  2582. return isNegative() ? -1 : 1;
  2583. }
  2584. }
  2585. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2586. {
  2587. const int h1 = getHighestBit();
  2588. const int h2 = other.getHighestBit();
  2589. if (h1 > h2)
  2590. return 1;
  2591. else if (h1 < h2)
  2592. return -1;
  2593. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2594. if (values[i] != other.values[i])
  2595. return (values[i] > other.values[i]) ? 1 : -1;
  2596. return 0;
  2597. }
  2598. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2599. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2600. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2601. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2602. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2603. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2604. void BigInteger::shiftBits (int bits, const int startBit)
  2605. {
  2606. if (highestBit < 0)
  2607. return;
  2608. if (startBit > 0)
  2609. {
  2610. if (bits < 0)
  2611. {
  2612. // right shift
  2613. for (int i = startBit; i <= highestBit; ++i)
  2614. setBit (i, operator[] (i - bits));
  2615. highestBit = getHighestBit();
  2616. }
  2617. else if (bits > 0)
  2618. {
  2619. // left shift
  2620. for (int i = highestBit + 1; --i >= startBit;)
  2621. setBit (i + bits, operator[] (i));
  2622. while (--bits >= 0)
  2623. clearBit (bits + startBit);
  2624. }
  2625. }
  2626. else
  2627. {
  2628. if (bits < 0)
  2629. {
  2630. // right shift
  2631. bits = -bits;
  2632. if (bits > highestBit)
  2633. {
  2634. clear();
  2635. }
  2636. else
  2637. {
  2638. const int wordsToMove = bitToIndex (bits);
  2639. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2640. highestBit -= bits;
  2641. if (wordsToMove > 0)
  2642. {
  2643. int i;
  2644. for (i = 0; i < top; ++i)
  2645. values [i] = values [i + wordsToMove];
  2646. for (i = 0; i < wordsToMove; ++i)
  2647. values [top + i] = 0;
  2648. bits &= 31;
  2649. }
  2650. if (bits != 0)
  2651. {
  2652. const int invBits = 32 - bits;
  2653. --top;
  2654. for (int i = 0; i < top; ++i)
  2655. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2656. values[top] = (values[top] >> bits);
  2657. }
  2658. highestBit = getHighestBit();
  2659. }
  2660. }
  2661. else if (bits > 0)
  2662. {
  2663. // left shift
  2664. ensureSize (bitToIndex (highestBit + bits) + 1);
  2665. const int wordsToMove = bitToIndex (bits);
  2666. int top = 1 + bitToIndex (highestBit);
  2667. highestBit += bits;
  2668. if (wordsToMove > 0)
  2669. {
  2670. int i;
  2671. for (i = top; --i >= 0;)
  2672. values [i + wordsToMove] = values [i];
  2673. for (i = 0; i < wordsToMove; ++i)
  2674. values [i] = 0;
  2675. bits &= 31;
  2676. }
  2677. if (bits != 0)
  2678. {
  2679. const int invBits = 32 - bits;
  2680. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2681. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2682. values [wordsToMove] = values [wordsToMove] << bits;
  2683. }
  2684. highestBit = getHighestBit();
  2685. }
  2686. }
  2687. }
  2688. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2689. {
  2690. while (! m->isZero())
  2691. {
  2692. if (n->compareAbsolute (*m) > 0)
  2693. swapVariables (m, n);
  2694. *m -= *n;
  2695. }
  2696. return *n;
  2697. }
  2698. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2699. {
  2700. BigInteger m (*this);
  2701. while (! n.isZero())
  2702. {
  2703. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2704. return simpleGCD (&m, &n);
  2705. BigInteger temp1 (m), temp2;
  2706. temp1.divideBy (n, temp2);
  2707. m = n;
  2708. n = temp2;
  2709. }
  2710. return m;
  2711. }
  2712. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2713. {
  2714. BigInteger exp (exponent);
  2715. exp %= modulus;
  2716. BigInteger value (1);
  2717. swapWith (value);
  2718. value %= modulus;
  2719. while (! exp.isZero())
  2720. {
  2721. if (exp [0])
  2722. {
  2723. operator*= (value);
  2724. operator%= (modulus);
  2725. }
  2726. value *= value;
  2727. value %= modulus;
  2728. exp >>= 1;
  2729. }
  2730. }
  2731. void BigInteger::inverseModulo (const BigInteger& modulus)
  2732. {
  2733. if (modulus.isOne() || modulus.isNegative())
  2734. {
  2735. clear();
  2736. return;
  2737. }
  2738. if (isNegative() || compareAbsolute (modulus) >= 0)
  2739. operator%= (modulus);
  2740. if (isOne())
  2741. return;
  2742. if (! (*this)[0])
  2743. {
  2744. // not invertible
  2745. clear();
  2746. return;
  2747. }
  2748. BigInteger a1 (modulus);
  2749. BigInteger a2 (*this);
  2750. BigInteger b1 (modulus);
  2751. BigInteger b2 (1);
  2752. while (! a2.isOne())
  2753. {
  2754. BigInteger temp1, temp2, multiplier (a1);
  2755. multiplier.divideBy (a2, temp1);
  2756. temp1 = a2;
  2757. temp1 *= multiplier;
  2758. temp2 = a1;
  2759. temp2 -= temp1;
  2760. a1 = a2;
  2761. a2 = temp2;
  2762. temp1 = b2;
  2763. temp1 *= multiplier;
  2764. temp2 = b1;
  2765. temp2 -= temp1;
  2766. b1 = b2;
  2767. b2 = temp2;
  2768. }
  2769. while (b2.isNegative())
  2770. b2 += modulus;
  2771. b2 %= modulus;
  2772. swapWith (b2);
  2773. }
  2774. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2775. {
  2776. return stream << value.toString (10);
  2777. }
  2778. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2779. {
  2780. String s;
  2781. BigInteger v (*this);
  2782. if (base == 2 || base == 8 || base == 16)
  2783. {
  2784. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2785. static const char* const hexDigits = "0123456789abcdef";
  2786. for (;;)
  2787. {
  2788. const int remainder = v.getBitRangeAsInt (0, bits);
  2789. v >>= bits;
  2790. if (remainder == 0 && v.isZero())
  2791. break;
  2792. s = String::charToString (hexDigits [remainder]) + s;
  2793. }
  2794. }
  2795. else if (base == 10)
  2796. {
  2797. const BigInteger ten (10);
  2798. BigInteger remainder;
  2799. for (;;)
  2800. {
  2801. v.divideBy (ten, remainder);
  2802. if (remainder.isZero() && v.isZero())
  2803. break;
  2804. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2805. }
  2806. }
  2807. else
  2808. {
  2809. jassertfalse; // can't do the specified base!
  2810. return String::empty;
  2811. }
  2812. s = s.paddedLeft ('0', minimumNumCharacters);
  2813. return isNegative() ? "-" + s : s;
  2814. }
  2815. void BigInteger::parseString (const String& text, const int base)
  2816. {
  2817. clear();
  2818. const juce_wchar* t = text;
  2819. if (base == 2 || base == 8 || base == 16)
  2820. {
  2821. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2822. for (;;)
  2823. {
  2824. const juce_wchar c = *t++;
  2825. const int digit = CharacterFunctions::getHexDigitValue (c);
  2826. if (((uint32) digit) < (uint32) base)
  2827. {
  2828. operator<<= (bits);
  2829. operator+= (digit);
  2830. }
  2831. else if (c == 0)
  2832. {
  2833. break;
  2834. }
  2835. }
  2836. }
  2837. else if (base == 10)
  2838. {
  2839. const BigInteger ten ((uint32) 10);
  2840. for (;;)
  2841. {
  2842. const juce_wchar c = *t++;
  2843. if (c >= '0' && c <= '9')
  2844. {
  2845. operator*= (ten);
  2846. operator+= ((int) (c - '0'));
  2847. }
  2848. else if (c == 0)
  2849. {
  2850. break;
  2851. }
  2852. }
  2853. }
  2854. setNegative (text.trimStart().startsWithChar ('-'));
  2855. }
  2856. const MemoryBlock BigInteger::toMemoryBlock() const
  2857. {
  2858. const int numBytes = (getHighestBit() + 8) >> 3;
  2859. MemoryBlock mb ((size_t) numBytes);
  2860. for (int i = 0; i < numBytes; ++i)
  2861. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2862. return mb;
  2863. }
  2864. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2865. {
  2866. clear();
  2867. for (int i = (int) data.getSize(); --i >= 0;)
  2868. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2869. }
  2870. END_JUCE_NAMESPACE
  2871. /*** End of inlined file: juce_BigInteger.cpp ***/
  2872. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2873. BEGIN_JUCE_NAMESPACE
  2874. MemoryBlock::MemoryBlock() throw()
  2875. : size (0)
  2876. {
  2877. }
  2878. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2879. {
  2880. if (initialSize > 0)
  2881. {
  2882. size = initialSize;
  2883. data.allocate (initialSize, initialiseToZero);
  2884. }
  2885. else
  2886. {
  2887. size = 0;
  2888. }
  2889. }
  2890. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2891. : size (other.size)
  2892. {
  2893. if (size > 0)
  2894. {
  2895. jassert (other.data != 0);
  2896. data.malloc (size);
  2897. memcpy (data, other.data, size);
  2898. }
  2899. }
  2900. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2901. : size (jmax ((size_t) 0, sizeInBytes))
  2902. {
  2903. jassert (sizeInBytes >= 0);
  2904. if (size > 0)
  2905. {
  2906. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2907. data.malloc (size);
  2908. if (dataToInitialiseFrom != 0)
  2909. memcpy (data, dataToInitialiseFrom, size);
  2910. }
  2911. }
  2912. MemoryBlock::~MemoryBlock() throw()
  2913. {
  2914. jassert (size >= 0); // should never happen
  2915. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2916. }
  2917. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2918. {
  2919. if (this != &other)
  2920. {
  2921. setSize (other.size, false);
  2922. memcpy (data, other.data, size);
  2923. }
  2924. return *this;
  2925. }
  2926. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2927. {
  2928. return matches (other.data, other.size);
  2929. }
  2930. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2931. {
  2932. return ! operator== (other);
  2933. }
  2934. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2935. {
  2936. return size == dataSize
  2937. && memcmp (data, dataToCompare, size) == 0;
  2938. }
  2939. // this will resize the block to this size
  2940. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2941. {
  2942. if (size != newSize)
  2943. {
  2944. if (newSize <= 0)
  2945. {
  2946. data.free();
  2947. size = 0;
  2948. }
  2949. else
  2950. {
  2951. if (data != 0)
  2952. {
  2953. data.realloc (newSize);
  2954. if (initialiseToZero && (newSize > size))
  2955. zeromem (data + size, newSize - size);
  2956. }
  2957. else
  2958. {
  2959. data.allocate (newSize, initialiseToZero);
  2960. }
  2961. size = newSize;
  2962. }
  2963. }
  2964. }
  2965. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2966. {
  2967. if (size < minimumSize)
  2968. setSize (minimumSize, initialiseToZero);
  2969. }
  2970. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2971. {
  2972. swapVariables (size, other.size);
  2973. data.swapWith (other.data);
  2974. }
  2975. void MemoryBlock::fillWith (const uint8 value) throw()
  2976. {
  2977. memset (data, (int) value, size);
  2978. }
  2979. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2980. {
  2981. if (numBytes > 0)
  2982. {
  2983. const size_t oldSize = size;
  2984. setSize (size + numBytes);
  2985. memcpy (data + oldSize, srcData, numBytes);
  2986. }
  2987. }
  2988. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2989. {
  2990. const char* d = static_cast<const char*> (src);
  2991. if (offset < 0)
  2992. {
  2993. d -= offset;
  2994. num -= offset;
  2995. offset = 0;
  2996. }
  2997. if (offset + num > size)
  2998. num = size - offset;
  2999. if (num > 0)
  3000. memcpy (data + offset, d, num);
  3001. }
  3002. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3003. {
  3004. char* d = static_cast<char*> (dst);
  3005. if (offset < 0)
  3006. {
  3007. zeromem (d, -offset);
  3008. d -= offset;
  3009. num += offset;
  3010. offset = 0;
  3011. }
  3012. if (offset + num > size)
  3013. {
  3014. const size_t newNum = size - offset;
  3015. zeromem (d + newNum, num - newNum);
  3016. num = newNum;
  3017. }
  3018. if (num > 0)
  3019. memcpy (d, data + offset, num);
  3020. }
  3021. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3022. {
  3023. if (startByte + numBytesToRemove >= size)
  3024. {
  3025. setSize (startByte);
  3026. }
  3027. else if (numBytesToRemove > 0)
  3028. {
  3029. memmove (data + startByte,
  3030. data + startByte + numBytesToRemove,
  3031. size - (startByte + numBytesToRemove));
  3032. setSize (size - numBytesToRemove);
  3033. }
  3034. }
  3035. const String MemoryBlock::toString() const
  3036. {
  3037. return String (static_cast <const char*> (getData()), size);
  3038. }
  3039. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3040. {
  3041. int res = 0;
  3042. size_t byte = bitRangeStart >> 3;
  3043. int offsetInByte = (int) bitRangeStart & 7;
  3044. size_t bitsSoFar = 0;
  3045. while (numBits > 0 && (size_t) byte < size)
  3046. {
  3047. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3048. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3049. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3050. bitsSoFar += bitsThisTime;
  3051. numBits -= bitsThisTime;
  3052. ++byte;
  3053. offsetInByte = 0;
  3054. }
  3055. return res;
  3056. }
  3057. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3058. {
  3059. size_t byte = bitRangeStart >> 3;
  3060. int offsetInByte = (int) bitRangeStart & 7;
  3061. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3062. while (numBits > 0 && (size_t) byte < size)
  3063. {
  3064. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3065. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3066. const unsigned int tempBits = bitsToSet << offsetInByte;
  3067. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3068. ++byte;
  3069. numBits -= bitsThisTime;
  3070. bitsToSet >>= bitsThisTime;
  3071. mask >>= bitsThisTime;
  3072. offsetInByte = 0;
  3073. }
  3074. }
  3075. void MemoryBlock::loadFromHexString (const String& hex)
  3076. {
  3077. ensureSize (hex.length() >> 1);
  3078. char* dest = data;
  3079. int i = 0;
  3080. for (;;)
  3081. {
  3082. int byte = 0;
  3083. for (int loop = 2; --loop >= 0;)
  3084. {
  3085. byte <<= 4;
  3086. for (;;)
  3087. {
  3088. const juce_wchar c = hex [i++];
  3089. if (c >= '0' && c <= '9')
  3090. {
  3091. byte |= c - '0';
  3092. break;
  3093. }
  3094. else if (c >= 'a' && c <= 'z')
  3095. {
  3096. byte |= c - ('a' - 10);
  3097. break;
  3098. }
  3099. else if (c >= 'A' && c <= 'Z')
  3100. {
  3101. byte |= c - ('A' - 10);
  3102. break;
  3103. }
  3104. else if (c == 0)
  3105. {
  3106. setSize (static_cast <size_t> (dest - data));
  3107. return;
  3108. }
  3109. }
  3110. }
  3111. *dest++ = (char) byte;
  3112. }
  3113. }
  3114. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3115. const String MemoryBlock::toBase64Encoding() const
  3116. {
  3117. const size_t numChars = ((size << 3) + 5) / 6;
  3118. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3119. const int initialLen = destString.length();
  3120. destString.preallocateStorage (initialLen + 2 + numChars);
  3121. juce_wchar* d = destString;
  3122. d += initialLen;
  3123. *d++ = '.';
  3124. for (size_t i = 0; i < numChars; ++i)
  3125. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3126. *d++ = 0;
  3127. return destString;
  3128. }
  3129. bool MemoryBlock::fromBase64Encoding (const String& s)
  3130. {
  3131. const int startPos = s.indexOfChar ('.') + 1;
  3132. if (startPos <= 0)
  3133. return false;
  3134. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3135. setSize (numBytesNeeded, true);
  3136. const int numChars = s.length() - startPos;
  3137. const juce_wchar* srcChars = s;
  3138. srcChars += startPos;
  3139. int pos = 0;
  3140. for (int i = 0; i < numChars; ++i)
  3141. {
  3142. const char c = (char) srcChars[i];
  3143. for (int j = 0; j < 64; ++j)
  3144. {
  3145. if (encodingTable[j] == c)
  3146. {
  3147. setBitRange (pos, 6, j);
  3148. pos += 6;
  3149. break;
  3150. }
  3151. }
  3152. }
  3153. return true;
  3154. }
  3155. END_JUCE_NAMESPACE
  3156. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3157. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3158. BEGIN_JUCE_NAMESPACE
  3159. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3160. : properties (ignoreCaseOfKeyNames),
  3161. fallbackProperties (0),
  3162. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3163. {
  3164. }
  3165. PropertySet::PropertySet (const PropertySet& other)
  3166. : properties (other.properties),
  3167. fallbackProperties (other.fallbackProperties),
  3168. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3169. {
  3170. }
  3171. PropertySet& PropertySet::operator= (const PropertySet& other)
  3172. {
  3173. properties = other.properties;
  3174. fallbackProperties = other.fallbackProperties;
  3175. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3176. propertyChanged();
  3177. return *this;
  3178. }
  3179. PropertySet::~PropertySet()
  3180. {
  3181. }
  3182. void PropertySet::clear()
  3183. {
  3184. const ScopedLock sl (lock);
  3185. if (properties.size() > 0)
  3186. {
  3187. properties.clear();
  3188. propertyChanged();
  3189. }
  3190. }
  3191. const String PropertySet::getValue (const String& keyName,
  3192. const String& defaultValue) const throw()
  3193. {
  3194. const ScopedLock sl (lock);
  3195. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3196. if (index >= 0)
  3197. return properties.getAllValues() [index];
  3198. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3199. : defaultValue;
  3200. }
  3201. int PropertySet::getIntValue (const String& keyName,
  3202. const int defaultValue) const throw()
  3203. {
  3204. const ScopedLock sl (lock);
  3205. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3206. if (index >= 0)
  3207. return properties.getAllValues() [index].getIntValue();
  3208. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3209. : defaultValue;
  3210. }
  3211. double PropertySet::getDoubleValue (const String& keyName,
  3212. const double defaultValue) const throw()
  3213. {
  3214. const ScopedLock sl (lock);
  3215. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3216. if (index >= 0)
  3217. return properties.getAllValues()[index].getDoubleValue();
  3218. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3219. : defaultValue;
  3220. }
  3221. bool PropertySet::getBoolValue (const String& keyName,
  3222. const bool defaultValue) const throw()
  3223. {
  3224. const ScopedLock sl (lock);
  3225. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3226. if (index >= 0)
  3227. return properties.getAllValues() [index].getIntValue() != 0;
  3228. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3229. : defaultValue;
  3230. }
  3231. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3232. {
  3233. return XmlDocument::parse (getValue (keyName));
  3234. }
  3235. void PropertySet::setValue (const String& keyName, const var& v)
  3236. {
  3237. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3238. if (keyName.isNotEmpty())
  3239. {
  3240. const String value (v.toString());
  3241. const ScopedLock sl (lock);
  3242. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3243. if (index < 0 || properties.getAllValues() [index] != value)
  3244. {
  3245. properties.set (keyName, value);
  3246. propertyChanged();
  3247. }
  3248. }
  3249. }
  3250. void PropertySet::removeValue (const String& keyName)
  3251. {
  3252. if (keyName.isNotEmpty())
  3253. {
  3254. const ScopedLock sl (lock);
  3255. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3256. if (index >= 0)
  3257. {
  3258. properties.remove (keyName);
  3259. propertyChanged();
  3260. }
  3261. }
  3262. }
  3263. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3264. {
  3265. setValue (keyName, xml == 0 ? var::null
  3266. : var (xml->createDocument (String::empty, true)));
  3267. }
  3268. bool PropertySet::containsKey (const String& keyName) const throw()
  3269. {
  3270. const ScopedLock sl (lock);
  3271. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3272. }
  3273. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3274. {
  3275. const ScopedLock sl (lock);
  3276. fallbackProperties = fallbackProperties_;
  3277. }
  3278. XmlElement* PropertySet::createXml (const String& nodeName) const
  3279. {
  3280. const ScopedLock sl (lock);
  3281. XmlElement* const xml = new XmlElement (nodeName);
  3282. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3283. {
  3284. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3285. e->setAttribute ("name", properties.getAllKeys()[i]);
  3286. e->setAttribute ("val", properties.getAllValues()[i]);
  3287. }
  3288. return xml;
  3289. }
  3290. void PropertySet::restoreFromXml (const XmlElement& xml)
  3291. {
  3292. const ScopedLock sl (lock);
  3293. clear();
  3294. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3295. {
  3296. if (e->hasAttribute ("name")
  3297. && e->hasAttribute ("val"))
  3298. {
  3299. properties.set (e->getStringAttribute ("name"),
  3300. e->getStringAttribute ("val"));
  3301. }
  3302. }
  3303. if (properties.size() > 0)
  3304. propertyChanged();
  3305. }
  3306. void PropertySet::propertyChanged()
  3307. {
  3308. }
  3309. END_JUCE_NAMESPACE
  3310. /*** End of inlined file: juce_PropertySet.cpp ***/
  3311. /*** Start of inlined file: juce_Identifier.cpp ***/
  3312. BEGIN_JUCE_NAMESPACE
  3313. StringPool& Identifier::getPool()
  3314. {
  3315. static StringPool pool;
  3316. return pool;
  3317. }
  3318. Identifier::Identifier() throw()
  3319. : name (0)
  3320. {
  3321. }
  3322. Identifier::Identifier (const Identifier& other) throw()
  3323. : name (other.name)
  3324. {
  3325. }
  3326. Identifier& Identifier::operator= (const Identifier& other) throw()
  3327. {
  3328. name = other.name;
  3329. return *this;
  3330. }
  3331. Identifier::Identifier (const String& name_)
  3332. : name (Identifier::getPool().getPooledString (name_))
  3333. {
  3334. /* An Identifier string must be suitable for use as a script variable or XML
  3335. attribute, so it can only contain this limited set of characters.. */
  3336. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3337. }
  3338. Identifier::Identifier (const char* const name_)
  3339. : name (Identifier::getPool().getPooledString (name_))
  3340. {
  3341. /* An Identifier string must be suitable for use as a script variable or XML
  3342. attribute, so it can only contain this limited set of characters.. */
  3343. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3344. }
  3345. Identifier::~Identifier()
  3346. {
  3347. }
  3348. END_JUCE_NAMESPACE
  3349. /*** End of inlined file: juce_Identifier.cpp ***/
  3350. /*** Start of inlined file: juce_Variant.cpp ***/
  3351. BEGIN_JUCE_NAMESPACE
  3352. class var::VariantType
  3353. {
  3354. public:
  3355. VariantType() {}
  3356. virtual ~VariantType() {}
  3357. virtual int toInt (const ValueUnion&) const { return 0; }
  3358. virtual double toDouble (const ValueUnion&) const { return 0; }
  3359. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3360. virtual bool toBool (const ValueUnion&) const { return false; }
  3361. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3362. virtual bool isVoid() const throw() { return false; }
  3363. virtual bool isInt() const throw() { return false; }
  3364. virtual bool isBool() const throw() { return false; }
  3365. virtual bool isDouble() const throw() { return false; }
  3366. virtual bool isString() const throw() { return false; }
  3367. virtual bool isObject() const throw() { return false; }
  3368. virtual bool isMethod() const throw() { return false; }
  3369. virtual void cleanUp (ValueUnion&) const throw() {}
  3370. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3371. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3372. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3373. };
  3374. class var::VariantType_Void : public var::VariantType
  3375. {
  3376. public:
  3377. VariantType_Void() {}
  3378. static const VariantType_Void instance;
  3379. bool isVoid() const throw() { return true; }
  3380. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3381. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3382. };
  3383. class var::VariantType_Int : public var::VariantType
  3384. {
  3385. public:
  3386. VariantType_Int() {}
  3387. static const VariantType_Int instance;
  3388. int toInt (const ValueUnion& data) const { return data.intValue; };
  3389. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3390. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3391. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3392. bool isInt() const throw() { return true; }
  3393. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3394. {
  3395. return otherType.toInt (otherData) == data.intValue;
  3396. }
  3397. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3398. {
  3399. output.writeCompressedInt (5);
  3400. output.writeByte (1);
  3401. output.writeInt (data.intValue);
  3402. }
  3403. };
  3404. class var::VariantType_Double : public var::VariantType
  3405. {
  3406. public:
  3407. VariantType_Double() {}
  3408. static const VariantType_Double instance;
  3409. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3410. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3411. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3412. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3413. bool isDouble() const throw() { return true; }
  3414. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3415. {
  3416. return otherType.toDouble (otherData) == data.doubleValue;
  3417. }
  3418. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3419. {
  3420. output.writeCompressedInt (9);
  3421. output.writeByte (4);
  3422. output.writeDouble (data.doubleValue);
  3423. }
  3424. };
  3425. class var::VariantType_Bool : public var::VariantType
  3426. {
  3427. public:
  3428. VariantType_Bool() {}
  3429. static const VariantType_Bool instance;
  3430. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3431. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3432. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3433. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3434. bool isBool() const throw() { return true; }
  3435. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3436. {
  3437. return otherType.toBool (otherData) == data.boolValue;
  3438. }
  3439. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3440. {
  3441. output.writeCompressedInt (1);
  3442. output.writeByte (data.boolValue ? 2 : 3);
  3443. }
  3444. };
  3445. class var::VariantType_String : public var::VariantType
  3446. {
  3447. public:
  3448. VariantType_String() {}
  3449. static const VariantType_String instance;
  3450. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3451. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3452. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3453. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3454. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3455. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3456. || data.stringValue->trim().equalsIgnoreCase ("true")
  3457. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3458. bool isString() const throw() { return true; }
  3459. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3460. {
  3461. return otherType.toString (otherData) == *data.stringValue;
  3462. }
  3463. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3464. {
  3465. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3466. output.writeCompressedInt (len + 1);
  3467. output.writeByte (5);
  3468. HeapBlock<char> temp (len);
  3469. data.stringValue->copyToUTF8 (temp, len);
  3470. output.write (temp, len);
  3471. }
  3472. };
  3473. class var::VariantType_Object : public var::VariantType
  3474. {
  3475. public:
  3476. VariantType_Object() {}
  3477. static const VariantType_Object instance;
  3478. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3479. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3480. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3481. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3482. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3483. bool isObject() const throw() { return true; }
  3484. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3485. {
  3486. return otherType.toObject (otherData) == data.objectValue;
  3487. }
  3488. void writeToStream (const ValueUnion&, OutputStream& output) const
  3489. {
  3490. jassertfalse; // Can't write an object to a stream!
  3491. output.writeCompressedInt (0);
  3492. }
  3493. };
  3494. class var::VariantType_Method : public var::VariantType
  3495. {
  3496. public:
  3497. VariantType_Method() {}
  3498. static const VariantType_Method instance;
  3499. const String toString (const ValueUnion&) const { return "Method"; }
  3500. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3501. bool isMethod() const throw() { return true; }
  3502. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3503. {
  3504. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3505. }
  3506. void writeToStream (const ValueUnion&, OutputStream& output) const
  3507. {
  3508. jassertfalse; // Can't write a method to a stream!
  3509. output.writeCompressedInt (0);
  3510. }
  3511. };
  3512. const var::VariantType_Void var::VariantType_Void::instance;
  3513. const var::VariantType_Int var::VariantType_Int::instance;
  3514. const var::VariantType_Bool var::VariantType_Bool::instance;
  3515. const var::VariantType_Double var::VariantType_Double::instance;
  3516. const var::VariantType_String var::VariantType_String::instance;
  3517. const var::VariantType_Object var::VariantType_Object::instance;
  3518. const var::VariantType_Method var::VariantType_Method::instance;
  3519. var::var() throw() : type (&VariantType_Void::instance)
  3520. {
  3521. }
  3522. var::~var() throw()
  3523. {
  3524. type->cleanUp (value);
  3525. }
  3526. const var var::null;
  3527. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3528. {
  3529. type->createCopy (value, valueToCopy.value);
  3530. }
  3531. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3532. {
  3533. value.intValue = value_;
  3534. }
  3535. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3536. {
  3537. value.boolValue = value_;
  3538. }
  3539. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3540. {
  3541. value.doubleValue = value_;
  3542. }
  3543. var::var (const String& value_) : type (&VariantType_String::instance)
  3544. {
  3545. value.stringValue = new String (value_);
  3546. }
  3547. var::var (const char* const value_) : type (&VariantType_String::instance)
  3548. {
  3549. value.stringValue = new String (value_);
  3550. }
  3551. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3552. {
  3553. value.stringValue = new String (value_);
  3554. }
  3555. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3556. {
  3557. value.objectValue = object;
  3558. if (object != 0)
  3559. object->incReferenceCount();
  3560. }
  3561. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3562. {
  3563. value.methodValue = method_;
  3564. }
  3565. bool var::isVoid() const throw() { return type->isVoid(); }
  3566. bool var::isInt() const throw() { return type->isInt(); }
  3567. bool var::isBool() const throw() { return type->isBool(); }
  3568. bool var::isDouble() const throw() { return type->isDouble(); }
  3569. bool var::isString() const throw() { return type->isString(); }
  3570. bool var::isObject() const throw() { return type->isObject(); }
  3571. bool var::isMethod() const throw() { return type->isMethod(); }
  3572. var::operator int() const { return type->toInt (value); }
  3573. var::operator bool() const { return type->toBool (value); }
  3574. var::operator float() const { return (float) type->toDouble (value); }
  3575. var::operator double() const { return type->toDouble (value); }
  3576. const String var::toString() const { return type->toString (value); }
  3577. var::operator const String() const { return type->toString (value); }
  3578. DynamicObject* var::getObject() const { return type->toObject (value); }
  3579. void var::swapWith (var& other) throw()
  3580. {
  3581. swapVariables (type, other.type);
  3582. swapVariables (value, other.value);
  3583. }
  3584. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3585. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3586. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3587. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3588. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3589. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3590. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3591. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3592. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3593. bool var::equals (const var& other) const throw()
  3594. {
  3595. return type->equals (value, other.value, *other.type);
  3596. }
  3597. bool var::equalsWithSameType (const var& other) const throw()
  3598. {
  3599. return type == other.type && equals (other);
  3600. }
  3601. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3602. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3603. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3604. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3605. void var::writeToStream (OutputStream& output) const
  3606. {
  3607. type->writeToStream (value, output);
  3608. }
  3609. const var var::readFromStream (InputStream& input)
  3610. {
  3611. const int numBytes = input.readCompressedInt();
  3612. if (numBytes > 0)
  3613. {
  3614. switch (input.readByte())
  3615. {
  3616. case 1: return var (input.readInt());
  3617. case 2: return var (true);
  3618. case 3: return var (false);
  3619. case 4: return var (input.readDouble());
  3620. case 5:
  3621. {
  3622. MemoryOutputStream mo;
  3623. mo.writeFromInputStream (input, numBytes - 1);
  3624. return var (mo.toUTF8());
  3625. }
  3626. default: input.skipNextBytes (numBytes - 1); break;
  3627. }
  3628. }
  3629. return var::null;
  3630. }
  3631. const var var::operator[] (const Identifier& propertyName) const
  3632. {
  3633. DynamicObject* const o = getObject();
  3634. return o != 0 ? o->getProperty (propertyName) : var::null;
  3635. }
  3636. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3637. {
  3638. DynamicObject* const o = getObject();
  3639. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3640. }
  3641. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3642. {
  3643. if (isMethod())
  3644. {
  3645. DynamicObject* const target = targetObject.getObject();
  3646. if (target != 0)
  3647. return (target->*(value.methodValue)) (arguments, numArguments);
  3648. }
  3649. return var::null;
  3650. }
  3651. const var var::call (const Identifier& method) const
  3652. {
  3653. return invoke (method, 0, 0);
  3654. }
  3655. const var var::call (const Identifier& method, const var& arg1) const
  3656. {
  3657. return invoke (method, &arg1, 1);
  3658. }
  3659. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3660. {
  3661. var args[] = { arg1, arg2 };
  3662. return invoke (method, args, 2);
  3663. }
  3664. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3665. {
  3666. var args[] = { arg1, arg2, arg3 };
  3667. return invoke (method, args, 3);
  3668. }
  3669. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3670. {
  3671. var args[] = { arg1, arg2, arg3, arg4 };
  3672. return invoke (method, args, 4);
  3673. }
  3674. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3675. {
  3676. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3677. return invoke (method, args, 5);
  3678. }
  3679. END_JUCE_NAMESPACE
  3680. /*** End of inlined file: juce_Variant.cpp ***/
  3681. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3682. BEGIN_JUCE_NAMESPACE
  3683. NamedValueSet::NamedValue::NamedValue() throw()
  3684. {
  3685. }
  3686. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3687. : name (name_), value (value_)
  3688. {
  3689. }
  3690. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3691. : name (other.name), value (other.value)
  3692. {
  3693. }
  3694. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3695. {
  3696. name = other.name;
  3697. value = other.value;
  3698. return *this;
  3699. }
  3700. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3701. {
  3702. return name == other.name && value == other.value;
  3703. }
  3704. NamedValueSet::NamedValueSet() throw()
  3705. {
  3706. }
  3707. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3708. {
  3709. values.addCopyOfList (other.values);
  3710. }
  3711. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3712. {
  3713. clear();
  3714. values.addCopyOfList (other.values);
  3715. return *this;
  3716. }
  3717. NamedValueSet::~NamedValueSet()
  3718. {
  3719. clear();
  3720. }
  3721. void NamedValueSet::clear()
  3722. {
  3723. values.deleteAll();
  3724. }
  3725. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3726. {
  3727. const NamedValue* i1 = values;
  3728. const NamedValue* i2 = other.values;
  3729. while (i1 != 0 && i2 != 0)
  3730. {
  3731. if (! (*i1 == *i2))
  3732. return false;
  3733. i1 = i1->nextListItem;
  3734. i2 = i2->nextListItem;
  3735. }
  3736. return true;
  3737. }
  3738. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3739. {
  3740. return ! operator== (other);
  3741. }
  3742. int NamedValueSet::size() const throw()
  3743. {
  3744. return values.size();
  3745. }
  3746. const var& NamedValueSet::operator[] (const Identifier& name) const
  3747. {
  3748. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3749. if (i->name == name)
  3750. return i->value;
  3751. return var::null;
  3752. }
  3753. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3754. {
  3755. const var* v = getVarPointer (name);
  3756. return v != 0 ? *v : defaultReturnValue;
  3757. }
  3758. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3759. {
  3760. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3761. if (i->name == name)
  3762. return &(i->value);
  3763. return 0;
  3764. }
  3765. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3766. {
  3767. LinkedListPointer<NamedValue>* i = &values;
  3768. while (i->get() != 0)
  3769. {
  3770. NamedValue* const v = i->get();
  3771. if (v->name == name)
  3772. {
  3773. if (v->value == newValue)
  3774. return false;
  3775. v->value = newValue;
  3776. return true;
  3777. }
  3778. i = &(v->nextListItem);
  3779. }
  3780. i->insertNext (new NamedValue (name, newValue));
  3781. return true;
  3782. }
  3783. bool NamedValueSet::contains (const Identifier& name) const
  3784. {
  3785. return getVarPointer (name) != 0;
  3786. }
  3787. bool NamedValueSet::remove (const Identifier& name)
  3788. {
  3789. LinkedListPointer<NamedValue>* i = &values;
  3790. for (;;)
  3791. {
  3792. NamedValue* const v = i->get();
  3793. if (v == 0)
  3794. break;
  3795. if (v->name == name)
  3796. {
  3797. delete i->removeNext();
  3798. return true;
  3799. }
  3800. i = &(v->nextListItem);
  3801. }
  3802. return false;
  3803. }
  3804. const Identifier NamedValueSet::getName (const int index) const
  3805. {
  3806. const NamedValue* const v = values[index];
  3807. jassert (v != 0);
  3808. return v->name;
  3809. }
  3810. const var NamedValueSet::getValueAt (const int index) const
  3811. {
  3812. const NamedValue* const v = values[index];
  3813. jassert (v != 0);
  3814. return v->value;
  3815. }
  3816. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3817. {
  3818. clear();
  3819. LinkedListPointer<NamedValue>::Appender appender (values);
  3820. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3821. for (int i = 0; i < numAtts; ++i)
  3822. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3823. }
  3824. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3825. {
  3826. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3827. {
  3828. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3829. xml.setAttribute (i->name.toString(),
  3830. i->value.toString());
  3831. }
  3832. }
  3833. END_JUCE_NAMESPACE
  3834. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3835. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3836. BEGIN_JUCE_NAMESPACE
  3837. DynamicObject::DynamicObject()
  3838. {
  3839. }
  3840. DynamicObject::~DynamicObject()
  3841. {
  3842. }
  3843. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3844. {
  3845. var* const v = properties.getVarPointer (propertyName);
  3846. return v != 0 && ! v->isMethod();
  3847. }
  3848. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3849. {
  3850. return properties [propertyName];
  3851. }
  3852. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3853. {
  3854. properties.set (propertyName, newValue);
  3855. }
  3856. void DynamicObject::removeProperty (const Identifier& propertyName)
  3857. {
  3858. properties.remove (propertyName);
  3859. }
  3860. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3861. {
  3862. return getProperty (methodName).isMethod();
  3863. }
  3864. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3865. const var* parameters,
  3866. int numParameters)
  3867. {
  3868. return properties [methodName].invoke (var (this), parameters, numParameters);
  3869. }
  3870. void DynamicObject::setMethod (const Identifier& name,
  3871. var::MethodFunction methodFunction)
  3872. {
  3873. properties.set (name, var (methodFunction));
  3874. }
  3875. void DynamicObject::clear()
  3876. {
  3877. properties.clear();
  3878. }
  3879. END_JUCE_NAMESPACE
  3880. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3881. /*** Start of inlined file: juce_Expression.cpp ***/
  3882. BEGIN_JUCE_NAMESPACE
  3883. class Expression::Term : public ReferenceCountedObject
  3884. {
  3885. public:
  3886. Term() {}
  3887. virtual ~Term() {}
  3888. virtual Type getType() const throw() = 0;
  3889. virtual Term* clone() const = 0;
  3890. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3891. virtual const String toString() const = 0;
  3892. virtual double toDouble() const { return 0; }
  3893. virtual int getInputIndexFor (const Term*) const { return -1; }
  3894. virtual int getOperatorPrecedence() const { return 0; }
  3895. virtual int getNumInputs() const { return 0; }
  3896. virtual Term* getInput (int) const { return 0; }
  3897. virtual const ReferenceCountedObjectPtr<Term> negated();
  3898. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3899. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3900. {
  3901. jassertfalse;
  3902. return 0;
  3903. }
  3904. virtual const String getName() const
  3905. {
  3906. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3907. return String::empty;
  3908. }
  3909. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3910. {
  3911. for (int i = getNumInputs(); --i >= 0;)
  3912. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3913. }
  3914. class SymbolVisitor
  3915. {
  3916. public:
  3917. virtual ~SymbolVisitor() {}
  3918. virtual void useSymbol (const Symbol&) = 0;
  3919. };
  3920. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3921. {
  3922. for (int i = getNumInputs(); --i >= 0;)
  3923. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3924. }
  3925. private:
  3926. JUCE_DECLARE_NON_COPYABLE (Term);
  3927. };
  3928. class Expression::Helpers
  3929. {
  3930. public:
  3931. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3932. // This helper function is needed to work around VC6 scoping bugs
  3933. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3934. static void checkRecursionDepth (const int depth)
  3935. {
  3936. if (depth > 256)
  3937. throw EvaluationError ("Recursive symbol references");
  3938. }
  3939. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3940. /** An exception that can be thrown by Expression::evaluate(). */
  3941. class EvaluationError : public std::exception
  3942. {
  3943. public:
  3944. EvaluationError (const String& description_)
  3945. : description (description_)
  3946. {
  3947. DBG ("Expression::EvaluationError: " + description);
  3948. }
  3949. String description;
  3950. };
  3951. class Constant : public Term
  3952. {
  3953. public:
  3954. Constant (const double value_, const bool isResolutionTarget_)
  3955. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3956. Type getType() const throw() { return constantType; }
  3957. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3958. const TermPtr resolve (const Scope&, int) { return this; }
  3959. double toDouble() const { return value; }
  3960. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  3961. const String toString() const
  3962. {
  3963. String s (value);
  3964. if (isResolutionTarget)
  3965. s = "@" + s;
  3966. return s;
  3967. }
  3968. double value;
  3969. bool isResolutionTarget;
  3970. };
  3971. class BinaryTerm : public Term
  3972. {
  3973. public:
  3974. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3975. {
  3976. jassert (left_ != 0 && right_ != 0);
  3977. }
  3978. int getInputIndexFor (const Term* possibleInput) const
  3979. {
  3980. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3981. }
  3982. Type getType() const throw() { return operatorType; }
  3983. int getNumInputs() const { return 2; }
  3984. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  3985. virtual double performFunction (double left, double right) const = 0;
  3986. virtual void writeOperator (String& dest) const = 0;
  3987. const TermPtr resolve (const Scope& scope, int recursionDepth)
  3988. {
  3989. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  3990. right->resolve (scope, recursionDepth)->toDouble()), false);
  3991. }
  3992. const String toString() const
  3993. {
  3994. String s;
  3995. const int ourPrecendence = getOperatorPrecedence();
  3996. if (left->getOperatorPrecedence() > ourPrecendence)
  3997. s << '(' << left->toString() << ')';
  3998. else
  3999. s = left->toString();
  4000. writeOperator (s);
  4001. if (right->getOperatorPrecedence() >= ourPrecendence)
  4002. s << '(' << right->toString() << ')';
  4003. else
  4004. s << right->toString();
  4005. return s;
  4006. }
  4007. protected:
  4008. const TermPtr left, right;
  4009. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4010. {
  4011. jassert (input == left || input == right);
  4012. if (input != left && input != right)
  4013. return 0;
  4014. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4015. if (dest == 0)
  4016. return new Constant (overallTarget, false);
  4017. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4018. }
  4019. };
  4020. class SymbolTerm : public Term
  4021. {
  4022. public:
  4023. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4024. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4025. {
  4026. checkRecursionDepth (recursionDepth);
  4027. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4028. }
  4029. Type getType() const throw() { return symbolType; }
  4030. Term* clone() const { return new SymbolTerm (symbol); }
  4031. const String toString() const { return symbol; }
  4032. const String getName() const { return symbol; }
  4033. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4034. {
  4035. checkRecursionDepth (recursionDepth);
  4036. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4037. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4038. }
  4039. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4040. {
  4041. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4042. symbol = newName;
  4043. }
  4044. String symbol;
  4045. };
  4046. class Function : public Term
  4047. {
  4048. public:
  4049. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4050. Function (const String& functionName_, const Array<Expression>& parameters_)
  4051. : functionName (functionName_), parameters (parameters_)
  4052. {}
  4053. Type getType() const throw() { return functionType; }
  4054. Term* clone() const { return new Function (functionName, parameters); }
  4055. int getNumInputs() const { return parameters.size(); }
  4056. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4057. const String getName() const { return functionName; }
  4058. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4059. {
  4060. checkRecursionDepth (recursionDepth);
  4061. double result = 0;
  4062. const int numParams = parameters.size();
  4063. if (numParams > 0)
  4064. {
  4065. HeapBlock<double> params (numParams);
  4066. for (int i = 0; i < numParams; ++i)
  4067. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4068. result = scope.evaluateFunction (functionName, params, numParams);
  4069. }
  4070. else
  4071. {
  4072. result = scope.evaluateFunction (functionName, 0, 0);
  4073. }
  4074. return new Constant (result, false);
  4075. }
  4076. int getInputIndexFor (const Term* possibleInput) const
  4077. {
  4078. for (int i = 0; i < parameters.size(); ++i)
  4079. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4080. return i;
  4081. return -1;
  4082. }
  4083. const String toString() const
  4084. {
  4085. if (parameters.size() == 0)
  4086. return functionName + "()";
  4087. String s (functionName + " (");
  4088. for (int i = 0; i < parameters.size(); ++i)
  4089. {
  4090. s << getTermFor (parameters.getReference(i))->toString();
  4091. if (i < parameters.size() - 1)
  4092. s << ", ";
  4093. }
  4094. s << ')';
  4095. return s;
  4096. }
  4097. const String functionName;
  4098. Array<Expression> parameters;
  4099. };
  4100. class DotOperator : public BinaryTerm
  4101. {
  4102. public:
  4103. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4104. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4105. {
  4106. checkRecursionDepth (recursionDepth);
  4107. EvaluationVisitor visitor (right, recursionDepth + 1);
  4108. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4109. return visitor.output;
  4110. }
  4111. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4112. const String getName() const { return "."; }
  4113. int getOperatorPrecedence() const { return 1; }
  4114. void writeOperator (String& dest) const { dest << '.'; }
  4115. double performFunction (double, double) const { return 0.0; }
  4116. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4117. {
  4118. checkRecursionDepth (recursionDepth);
  4119. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4120. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4121. try
  4122. {
  4123. scope.visitRelativeScope (getSymbol()->symbol, v);
  4124. }
  4125. catch (...) {}
  4126. }
  4127. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4128. {
  4129. checkRecursionDepth (recursionDepth);
  4130. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4131. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4132. try
  4133. {
  4134. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4135. }
  4136. catch (...) {}
  4137. }
  4138. private:
  4139. class EvaluationVisitor : public Scope::Visitor
  4140. {
  4141. public:
  4142. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4143. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4144. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4145. const TermPtr input;
  4146. TermPtr output;
  4147. const int recursionCount;
  4148. private:
  4149. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4150. };
  4151. class SymbolVisitingVisitor : public Scope::Visitor
  4152. {
  4153. public:
  4154. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4155. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4156. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4157. private:
  4158. const TermPtr input;
  4159. SymbolVisitor& visitor;
  4160. const int recursionCount;
  4161. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4162. };
  4163. class SymbolRenamingVisitor : public Scope::Visitor
  4164. {
  4165. public:
  4166. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4167. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4168. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4169. private:
  4170. const TermPtr input;
  4171. const Symbol& symbol;
  4172. const String newName;
  4173. const int recursionCount;
  4174. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4175. };
  4176. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4177. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4178. };
  4179. class Negate : public Term
  4180. {
  4181. public:
  4182. explicit Negate (const TermPtr& input_) : input (input_)
  4183. {
  4184. jassert (input_ != 0);
  4185. }
  4186. Type getType() const throw() { return operatorType; }
  4187. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4188. int getNumInputs() const { return 1; }
  4189. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4190. Term* clone() const { return new Negate (input->clone()); }
  4191. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4192. {
  4193. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4194. }
  4195. const String getName() const { return "-"; }
  4196. const TermPtr negated() { return input; }
  4197. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4198. {
  4199. (void) input_;
  4200. jassert (input_ == input);
  4201. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4202. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4203. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4204. }
  4205. const String toString() const
  4206. {
  4207. if (input->getOperatorPrecedence() > 0)
  4208. return "-(" + input->toString() + ")";
  4209. else
  4210. return "-" + input->toString();
  4211. }
  4212. private:
  4213. const TermPtr input;
  4214. };
  4215. class Add : public BinaryTerm
  4216. {
  4217. public:
  4218. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4219. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4220. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4221. int getOperatorPrecedence() const { return 3; }
  4222. const String getName() const { return "+"; }
  4223. void writeOperator (String& dest) const { dest << " + "; }
  4224. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4225. {
  4226. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4227. if (newDest == 0)
  4228. return 0;
  4229. return new Subtract (newDest, (input == left ? right : left)->clone());
  4230. }
  4231. private:
  4232. JUCE_DECLARE_NON_COPYABLE (Add);
  4233. };
  4234. class Subtract : public BinaryTerm
  4235. {
  4236. public:
  4237. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4238. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4239. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4240. int getOperatorPrecedence() const { return 3; }
  4241. const String getName() const { return "-"; }
  4242. void writeOperator (String& dest) const { dest << " - "; }
  4243. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4244. {
  4245. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4246. if (newDest == 0)
  4247. return 0;
  4248. if (input == left)
  4249. return new Add (newDest, right->clone());
  4250. else
  4251. return new Subtract (left->clone(), newDest);
  4252. }
  4253. private:
  4254. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4255. };
  4256. class Multiply : public BinaryTerm
  4257. {
  4258. public:
  4259. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4260. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4261. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4262. const String getName() const { return "*"; }
  4263. void writeOperator (String& dest) const { dest << " * "; }
  4264. int getOperatorPrecedence() const { return 2; }
  4265. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4266. {
  4267. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4268. if (newDest == 0)
  4269. return 0;
  4270. return new Divide (newDest, (input == left ? right : left)->clone());
  4271. }
  4272. private:
  4273. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4274. };
  4275. class Divide : public BinaryTerm
  4276. {
  4277. public:
  4278. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4279. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4280. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4281. const String getName() const { return "/"; }
  4282. void writeOperator (String& dest) const { dest << " / "; }
  4283. int getOperatorPrecedence() const { return 2; }
  4284. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4285. {
  4286. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4287. if (newDest == 0)
  4288. return 0;
  4289. if (input == left)
  4290. return new Multiply (newDest, right->clone());
  4291. else
  4292. return new Divide (left->clone(), newDest);
  4293. }
  4294. private:
  4295. JUCE_DECLARE_NON_COPYABLE (Divide);
  4296. };
  4297. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4298. {
  4299. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4300. if (inputIndex >= 0)
  4301. return topLevel;
  4302. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4303. {
  4304. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4305. if (t != 0)
  4306. return t;
  4307. }
  4308. return 0;
  4309. }
  4310. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4311. {
  4312. {
  4313. Constant* const c = dynamic_cast<Constant*> (term);
  4314. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4315. return c;
  4316. }
  4317. if (dynamic_cast<Function*> (term) != 0)
  4318. return 0;
  4319. int i;
  4320. const int numIns = term->getNumInputs();
  4321. for (i = 0; i < numIns; ++i)
  4322. {
  4323. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4324. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4325. return c;
  4326. }
  4327. for (i = 0; i < numIns; ++i)
  4328. {
  4329. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4330. if (c != 0)
  4331. return c;
  4332. }
  4333. return 0;
  4334. }
  4335. static bool containsAnySymbols (const Term* const t)
  4336. {
  4337. if (t->getType() == Expression::symbolType)
  4338. return true;
  4339. for (int i = t->getNumInputs(); --i >= 0;)
  4340. if (containsAnySymbols (t->getInput (i)))
  4341. return true;
  4342. return false;
  4343. }
  4344. class SymbolCheckVisitor : public Term::SymbolVisitor
  4345. {
  4346. public:
  4347. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4348. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4349. bool wasFound;
  4350. private:
  4351. const Symbol& symbol;
  4352. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4353. };
  4354. class SymbolListVisitor : public Term::SymbolVisitor
  4355. {
  4356. public:
  4357. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4358. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4359. private:
  4360. Array<Symbol>& list;
  4361. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4362. };
  4363. class Parser
  4364. {
  4365. public:
  4366. Parser (const String& stringToParse, int& textIndex_)
  4367. : textString (stringToParse), textIndex (textIndex_)
  4368. {
  4369. text = textString;
  4370. }
  4371. const TermPtr readUpToComma()
  4372. {
  4373. if (textString.isEmpty())
  4374. return new Constant (0.0, false);
  4375. const TermPtr e (readExpression());
  4376. if (e == 0 || ((! readOperator (",")) && text [textIndex] != 0))
  4377. throw ParseError ("Syntax error: \"" + textString.substring (textIndex) + "\"");
  4378. return e;
  4379. }
  4380. private:
  4381. const String textString;
  4382. const juce_wchar* text;
  4383. int& textIndex;
  4384. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4385. {
  4386. return c >= '0' && c <= '9';
  4387. }
  4388. void skipWhitespace (int& i) throw()
  4389. {
  4390. while (CharacterFunctions::isWhitespace (text [i]))
  4391. ++i;
  4392. }
  4393. bool readChar (const juce_wchar required) throw()
  4394. {
  4395. if (text[textIndex] == required)
  4396. {
  4397. ++textIndex;
  4398. return true;
  4399. }
  4400. return false;
  4401. }
  4402. bool readOperator (const char* ops, char* const opType = 0) throw()
  4403. {
  4404. skipWhitespace (textIndex);
  4405. while (*ops != 0)
  4406. {
  4407. if (readChar (*ops))
  4408. {
  4409. if (opType != 0)
  4410. *opType = *ops;
  4411. return true;
  4412. }
  4413. ++ops;
  4414. }
  4415. return false;
  4416. }
  4417. bool readIdentifier (String& identifier) throw()
  4418. {
  4419. skipWhitespace (textIndex);
  4420. int i = textIndex;
  4421. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4422. {
  4423. ++i;
  4424. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_')
  4425. ++i;
  4426. }
  4427. if (i > textIndex)
  4428. {
  4429. identifier = String (text + textIndex, i - textIndex);
  4430. textIndex = i;
  4431. return true;
  4432. }
  4433. return false;
  4434. }
  4435. Term* readNumber() throw()
  4436. {
  4437. skipWhitespace (textIndex);
  4438. int i = textIndex;
  4439. const bool isResolutionTarget = (text[i] == '@');
  4440. if (isResolutionTarget)
  4441. {
  4442. ++i;
  4443. skipWhitespace (i);
  4444. textIndex = i;
  4445. }
  4446. if (text[i] == '-')
  4447. {
  4448. ++i;
  4449. skipWhitespace (i);
  4450. }
  4451. int numDigits = 0;
  4452. while (isDecimalDigit (text[i]))
  4453. {
  4454. ++i;
  4455. ++numDigits;
  4456. }
  4457. const bool hasPoint = (text[i] == '.');
  4458. if (hasPoint)
  4459. {
  4460. ++i;
  4461. while (isDecimalDigit (text[i]))
  4462. {
  4463. ++i;
  4464. ++numDigits;
  4465. }
  4466. }
  4467. if (numDigits == 0)
  4468. return 0;
  4469. juce_wchar c = text[i];
  4470. const bool hasExponent = (c == 'e' || c == 'E');
  4471. if (hasExponent)
  4472. {
  4473. ++i;
  4474. c = text[i];
  4475. if (c == '+' || c == '-')
  4476. ++i;
  4477. int numExpDigits = 0;
  4478. while (isDecimalDigit (text[i]))
  4479. {
  4480. ++i;
  4481. ++numExpDigits;
  4482. }
  4483. if (numExpDigits == 0)
  4484. return 0;
  4485. }
  4486. const int start = textIndex;
  4487. textIndex = i;
  4488. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4489. }
  4490. const TermPtr readExpression()
  4491. {
  4492. TermPtr lhs (readMultiplyOrDivideExpression());
  4493. char opType;
  4494. while (lhs != 0 && readOperator ("+-", &opType))
  4495. {
  4496. TermPtr rhs (readMultiplyOrDivideExpression());
  4497. if (rhs == 0)
  4498. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4499. if (opType == '+')
  4500. lhs = new Add (lhs, rhs);
  4501. else
  4502. lhs = new Subtract (lhs, rhs);
  4503. }
  4504. return lhs;
  4505. }
  4506. const TermPtr readMultiplyOrDivideExpression()
  4507. {
  4508. TermPtr lhs (readUnaryExpression());
  4509. char opType;
  4510. while (lhs != 0 && readOperator ("*/", &opType))
  4511. {
  4512. TermPtr rhs (readUnaryExpression());
  4513. if (rhs == 0)
  4514. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4515. if (opType == '*')
  4516. lhs = new Multiply (lhs, rhs);
  4517. else
  4518. lhs = new Divide (lhs, rhs);
  4519. }
  4520. return lhs;
  4521. }
  4522. const TermPtr readUnaryExpression()
  4523. {
  4524. char opType;
  4525. if (readOperator ("+-", &opType))
  4526. {
  4527. TermPtr term (readUnaryExpression());
  4528. if (term == 0)
  4529. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4530. if (opType == '-')
  4531. term = term->negated();
  4532. return term;
  4533. }
  4534. return readPrimaryExpression();
  4535. }
  4536. const TermPtr readPrimaryExpression()
  4537. {
  4538. TermPtr e (readParenthesisedExpression());
  4539. if (e != 0)
  4540. return e;
  4541. e = readNumber();
  4542. if (e != 0)
  4543. return e;
  4544. return readSymbolOrFunction();
  4545. }
  4546. const TermPtr readSymbolOrFunction()
  4547. {
  4548. String identifier;
  4549. if (readIdentifier (identifier))
  4550. {
  4551. if (readOperator ("(")) // method call...
  4552. {
  4553. Function* const f = new Function (identifier);
  4554. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4555. TermPtr param (readExpression());
  4556. if (param == 0)
  4557. {
  4558. if (readOperator (")"))
  4559. return func.release();
  4560. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4561. }
  4562. f->parameters.add (Expression (param));
  4563. while (readOperator (","))
  4564. {
  4565. param = readExpression();
  4566. if (param == 0)
  4567. throw ParseError ("Expected expression after \",\"");
  4568. f->parameters.add (Expression (param));
  4569. }
  4570. if (readOperator (")"))
  4571. return func.release();
  4572. throw ParseError ("Expected \")\"");
  4573. }
  4574. else if (readOperator ("."))
  4575. {
  4576. TermPtr rhs (readSymbolOrFunction());
  4577. if (rhs == 0)
  4578. throw ParseError ("Expected symbol or function after \".\"");
  4579. if (identifier == "this")
  4580. return rhs;
  4581. return new DotOperator (new SymbolTerm (identifier), rhs);
  4582. }
  4583. else // just a symbol..
  4584. {
  4585. jassert (identifier.trim() == identifier);
  4586. return new SymbolTerm (identifier);
  4587. }
  4588. }
  4589. return 0;
  4590. }
  4591. const TermPtr readParenthesisedExpression()
  4592. {
  4593. if (! readOperator ("("))
  4594. return 0;
  4595. const TermPtr e (readExpression());
  4596. if (e == 0 || ! readOperator (")"))
  4597. return 0;
  4598. return e;
  4599. }
  4600. JUCE_DECLARE_NON_COPYABLE (Parser);
  4601. };
  4602. };
  4603. Expression::Expression()
  4604. : term (new Expression::Helpers::Constant (0, false))
  4605. {
  4606. }
  4607. Expression::~Expression()
  4608. {
  4609. }
  4610. Expression::Expression (Term* const term_)
  4611. : term (term_)
  4612. {
  4613. jassert (term != 0);
  4614. }
  4615. Expression::Expression (const double constant)
  4616. : term (new Expression::Helpers::Constant (constant, false))
  4617. {
  4618. }
  4619. Expression::Expression (const Expression& other)
  4620. : term (other.term)
  4621. {
  4622. }
  4623. Expression& Expression::operator= (const Expression& other)
  4624. {
  4625. term = other.term;
  4626. return *this;
  4627. }
  4628. Expression::Expression (const String& stringToParse)
  4629. {
  4630. int i = 0;
  4631. Helpers::Parser parser (stringToParse, i);
  4632. term = parser.readUpToComma();
  4633. }
  4634. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4635. {
  4636. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4637. return Expression (parser.readUpToComma());
  4638. }
  4639. double Expression::evaluate() const
  4640. {
  4641. return evaluate (Expression::Scope());
  4642. }
  4643. double Expression::evaluate (const Expression::Scope& scope) const
  4644. {
  4645. try
  4646. {
  4647. return term->resolve (scope, 0)->toDouble();
  4648. }
  4649. catch (Helpers::EvaluationError&)
  4650. {}
  4651. return 0;
  4652. }
  4653. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4654. {
  4655. try
  4656. {
  4657. return term->resolve (scope, 0)->toDouble();
  4658. }
  4659. catch (Helpers::EvaluationError& e)
  4660. {
  4661. evaluationError = e.description;
  4662. }
  4663. return 0;
  4664. }
  4665. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4666. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4667. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4668. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4669. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4670. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4671. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4672. {
  4673. return Expression (new Helpers::Function (functionName, parameters));
  4674. }
  4675. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4676. {
  4677. ScopedPointer<Term> newTerm (term->clone());
  4678. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4679. if (termToAdjust == 0)
  4680. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4681. if (termToAdjust == 0)
  4682. {
  4683. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4684. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4685. }
  4686. jassert (termToAdjust != 0);
  4687. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4688. if (parent == 0)
  4689. {
  4690. termToAdjust->value = targetValue;
  4691. }
  4692. else
  4693. {
  4694. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4695. if (reverseTerm == 0)
  4696. return Expression (targetValue);
  4697. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4698. }
  4699. return Expression (newTerm.release());
  4700. }
  4701. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4702. {
  4703. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4704. if (oldSymbol.symbolName == newName)
  4705. return *this;
  4706. Expression e (term->clone());
  4707. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4708. return e;
  4709. }
  4710. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4711. {
  4712. Helpers::SymbolCheckVisitor visitor (symbol);
  4713. try
  4714. {
  4715. term->visitAllSymbols (visitor, scope, 0);
  4716. }
  4717. catch (Helpers::EvaluationError&)
  4718. {}
  4719. return visitor.wasFound;
  4720. }
  4721. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4722. {
  4723. try
  4724. {
  4725. Helpers::SymbolListVisitor visitor (results);
  4726. term->visitAllSymbols (visitor, scope, 0);
  4727. }
  4728. catch (Helpers::EvaluationError&)
  4729. {}
  4730. }
  4731. const String Expression::toString() const { return term->toString(); }
  4732. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4733. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4734. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4735. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4736. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4737. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4738. {
  4739. return new Helpers::Negate (this);
  4740. }
  4741. Expression::ParseError::ParseError (const String& message)
  4742. : description (message)
  4743. {
  4744. DBG ("Expression::ParseError: " + message);
  4745. }
  4746. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4747. : scopeUID (scopeUID_), symbolName (symbolName_)
  4748. {
  4749. }
  4750. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4751. {
  4752. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4753. }
  4754. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4755. {
  4756. return ! operator== (other);
  4757. }
  4758. Expression::Scope::Scope() {}
  4759. Expression::Scope::~Scope() {}
  4760. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4761. {
  4762. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4763. }
  4764. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4765. {
  4766. if (numParams > 0)
  4767. {
  4768. if (functionName == "min")
  4769. {
  4770. double v = parameters[0];
  4771. for (int i = 1; i < numParams; ++i)
  4772. v = jmin (v, parameters[i]);
  4773. return v;
  4774. }
  4775. else if (functionName == "max")
  4776. {
  4777. double v = parameters[0];
  4778. for (int i = 1; i < numParams; ++i)
  4779. v = jmax (v, parameters[i]);
  4780. return v;
  4781. }
  4782. else if (numParams == 1)
  4783. {
  4784. if (functionName == "sin") return sin (parameters[0]);
  4785. else if (functionName == "cos") return cos (parameters[0]);
  4786. else if (functionName == "tan") return tan (parameters[0]);
  4787. else if (functionName == "abs") return std::abs (parameters[0]);
  4788. }
  4789. }
  4790. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4791. }
  4792. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4793. {
  4794. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4795. }
  4796. const String Expression::Scope::getScopeUID() const
  4797. {
  4798. return String::empty;
  4799. }
  4800. END_JUCE_NAMESPACE
  4801. /*** End of inlined file: juce_Expression.cpp ***/
  4802. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4803. BEGIN_JUCE_NAMESPACE
  4804. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4805. {
  4806. jassert (keyData != 0);
  4807. jassert (keyBytes > 0);
  4808. static const uint32 initialPValues [18] =
  4809. {
  4810. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4811. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4812. 0x9216d5d9, 0x8979fb1b
  4813. };
  4814. static const uint32 initialSValues [4 * 256] =
  4815. {
  4816. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4817. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4818. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4819. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4820. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4821. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4822. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4823. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4824. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4825. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4826. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4827. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4828. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4829. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4830. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4831. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4832. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4833. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4834. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4835. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4836. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4837. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4838. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4839. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4840. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4841. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4842. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4843. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4844. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4845. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4846. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4847. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4848. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4849. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4850. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4851. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4852. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4853. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4854. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4855. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4856. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4857. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4858. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4859. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4860. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4861. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4862. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4863. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4864. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4865. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4866. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4867. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4868. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4869. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4870. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4871. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4872. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4873. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4874. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4875. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4876. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4877. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4878. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4879. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4880. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4881. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4882. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4883. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4884. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4885. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4886. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4887. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4888. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4889. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4890. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4891. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4892. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4893. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4894. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4895. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4896. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4897. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4898. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4899. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4900. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4901. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4902. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4903. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4904. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4905. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4906. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4907. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4908. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4909. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4910. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4911. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4912. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4913. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4914. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4915. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4916. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4917. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4918. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4919. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4920. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4921. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4922. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4923. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4924. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4925. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4926. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4927. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4928. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4929. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4930. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4931. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4932. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4933. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4934. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4935. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4936. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4937. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4938. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4939. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4940. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4941. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4942. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4943. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4944. };
  4945. memcpy (p, initialPValues, sizeof (p));
  4946. int i, j = 0;
  4947. for (i = 4; --i >= 0;)
  4948. {
  4949. s[i].malloc (256);
  4950. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4951. }
  4952. for (i = 0; i < 18; ++i)
  4953. {
  4954. uint32 d = 0;
  4955. for (int k = 0; k < 4; ++k)
  4956. {
  4957. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4958. if (++j >= keyBytes)
  4959. j = 0;
  4960. }
  4961. p[i] = initialPValues[i] ^ d;
  4962. }
  4963. uint32 l = 0, r = 0;
  4964. for (i = 0; i < 18; i += 2)
  4965. {
  4966. encrypt (l, r);
  4967. p[i] = l;
  4968. p[i + 1] = r;
  4969. }
  4970. for (i = 0; i < 4; ++i)
  4971. {
  4972. for (j = 0; j < 256; j += 2)
  4973. {
  4974. encrypt (l, r);
  4975. s[i][j] = l;
  4976. s[i][j + 1] = r;
  4977. }
  4978. }
  4979. }
  4980. BlowFish::BlowFish (const BlowFish& other)
  4981. {
  4982. for (int i = 4; --i >= 0;)
  4983. s[i].malloc (256);
  4984. operator= (other);
  4985. }
  4986. BlowFish& BlowFish::operator= (const BlowFish& other)
  4987. {
  4988. memcpy (p, other.p, sizeof (p));
  4989. for (int i = 4; --i >= 0;)
  4990. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4991. return *this;
  4992. }
  4993. BlowFish::~BlowFish()
  4994. {
  4995. }
  4996. uint32 BlowFish::F (const uint32 x) const throw()
  4997. {
  4998. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4999. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  5000. }
  5001. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  5002. {
  5003. uint32 l = data1;
  5004. uint32 r = data2;
  5005. for (int i = 0; i < 16; ++i)
  5006. {
  5007. l ^= p[i];
  5008. r ^= F(l);
  5009. swapVariables (l, r);
  5010. }
  5011. data1 = r ^ p[17];
  5012. data2 = l ^ p[16];
  5013. }
  5014. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  5015. {
  5016. uint32 l = data1;
  5017. uint32 r = data2;
  5018. for (int i = 17; i > 1; --i)
  5019. {
  5020. l ^= p[i];
  5021. r ^= F(l);
  5022. swapVariables (l, r);
  5023. }
  5024. data1 = r ^ p[0];
  5025. data2 = l ^ p[1];
  5026. }
  5027. END_JUCE_NAMESPACE
  5028. /*** End of inlined file: juce_BlowFish.cpp ***/
  5029. /*** Start of inlined file: juce_MD5.cpp ***/
  5030. BEGIN_JUCE_NAMESPACE
  5031. MD5::MD5()
  5032. {
  5033. zerostruct (result);
  5034. }
  5035. MD5::MD5 (const MD5& other)
  5036. {
  5037. memcpy (result, other.result, sizeof (result));
  5038. }
  5039. MD5& MD5::operator= (const MD5& other)
  5040. {
  5041. memcpy (result, other.result, sizeof (result));
  5042. return *this;
  5043. }
  5044. MD5::MD5 (const MemoryBlock& data)
  5045. {
  5046. ProcessContext context;
  5047. context.processBlock (data.getData(), data.getSize());
  5048. context.finish (result);
  5049. }
  5050. MD5::MD5 (const void* data, const size_t numBytes)
  5051. {
  5052. ProcessContext context;
  5053. context.processBlock (data, numBytes);
  5054. context.finish (result);
  5055. }
  5056. MD5::MD5 (const String& text)
  5057. {
  5058. ProcessContext context;
  5059. const int len = text.length();
  5060. const juce_wchar* const t = text;
  5061. for (int i = 0; i < len; ++i)
  5062. {
  5063. // force the string into integer-sized unicode characters, to try to make it
  5064. // get the same results on all platforms + compilers.
  5065. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  5066. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5067. }
  5068. context.finish (result);
  5069. }
  5070. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5071. {
  5072. ProcessContext context;
  5073. if (numBytesToRead < 0)
  5074. numBytesToRead = std::numeric_limits<int64>::max();
  5075. while (numBytesToRead > 0)
  5076. {
  5077. uint8 tempBuffer [512];
  5078. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5079. if (bytesRead <= 0)
  5080. break;
  5081. numBytesToRead -= bytesRead;
  5082. context.processBlock (tempBuffer, bytesRead);
  5083. }
  5084. context.finish (result);
  5085. }
  5086. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5087. {
  5088. processStream (input, numBytesToRead);
  5089. }
  5090. MD5::MD5 (const File& file)
  5091. {
  5092. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5093. if (fin != 0)
  5094. processStream (*fin, -1);
  5095. else
  5096. zerostruct (result);
  5097. }
  5098. MD5::~MD5()
  5099. {
  5100. }
  5101. namespace MD5Functions
  5102. {
  5103. void encode (void* const output, const void* const input, const int numBytes) throw()
  5104. {
  5105. for (int i = 0; i < (numBytes >> 2); ++i)
  5106. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5107. }
  5108. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5109. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5110. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5111. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5112. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5113. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5114. {
  5115. a += F (b, c, d) + x + ac;
  5116. a = rotateLeft (a, s) + b;
  5117. }
  5118. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5119. {
  5120. a += G (b, c, d) + x + ac;
  5121. a = rotateLeft (a, s) + b;
  5122. }
  5123. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5124. {
  5125. a += H (b, c, d) + x + ac;
  5126. a = rotateLeft (a, s) + b;
  5127. }
  5128. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5129. {
  5130. a += I (b, c, d) + x + ac;
  5131. a = rotateLeft (a, s) + b;
  5132. }
  5133. }
  5134. MD5::ProcessContext::ProcessContext()
  5135. {
  5136. state[0] = 0x67452301;
  5137. state[1] = 0xefcdab89;
  5138. state[2] = 0x98badcfe;
  5139. state[3] = 0x10325476;
  5140. count[0] = 0;
  5141. count[1] = 0;
  5142. }
  5143. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5144. {
  5145. int bufferPos = ((count[0] >> 3) & 0x3F);
  5146. count[0] += (uint32) (dataSize << 3);
  5147. if (count[0] < ((uint32) dataSize << 3))
  5148. count[1]++;
  5149. count[1] += (uint32) (dataSize >> 29);
  5150. const size_t spaceLeft = 64 - bufferPos;
  5151. size_t i = 0;
  5152. if (dataSize >= spaceLeft)
  5153. {
  5154. memcpy (buffer + bufferPos, data, spaceLeft);
  5155. transform (buffer);
  5156. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5157. transform (static_cast <const char*> (data) + i);
  5158. bufferPos = 0;
  5159. }
  5160. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5161. }
  5162. void MD5::ProcessContext::finish (void* const result)
  5163. {
  5164. unsigned char encodedLength[8];
  5165. MD5Functions::encode (encodedLength, count, 8);
  5166. // Pad out to 56 mod 64.
  5167. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5168. const int paddingLength = (index < 56) ? (56 - index)
  5169. : (120 - index);
  5170. uint8 paddingBuffer [64];
  5171. zeromem (paddingBuffer, paddingLength);
  5172. paddingBuffer [0] = 0x80;
  5173. processBlock (paddingBuffer, paddingLength);
  5174. processBlock (encodedLength, 8);
  5175. MD5Functions::encode (result, state, 16);
  5176. zerostruct (buffer);
  5177. }
  5178. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5179. {
  5180. using namespace MD5Functions;
  5181. uint32 a = state[0];
  5182. uint32 b = state[1];
  5183. uint32 c = state[2];
  5184. uint32 d = state[3];
  5185. uint32 x[16];
  5186. encode (x, bufferToTransform, 64);
  5187. enum Constants
  5188. {
  5189. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5190. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5191. };
  5192. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5193. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5194. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5195. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5196. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5197. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5198. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5199. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5200. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5201. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5202. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5203. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5204. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5205. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5206. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5207. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5208. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5209. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5210. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5211. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5212. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5213. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5214. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5215. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5216. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5217. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5218. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5219. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5220. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5221. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5222. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5223. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5224. state[0] += a;
  5225. state[1] += b;
  5226. state[2] += c;
  5227. state[3] += d;
  5228. zerostruct (x);
  5229. }
  5230. const MemoryBlock MD5::getRawChecksumData() const
  5231. {
  5232. return MemoryBlock (result, sizeof (result));
  5233. }
  5234. const String MD5::toHexString() const
  5235. {
  5236. return String::toHexString (result, sizeof (result), 0);
  5237. }
  5238. bool MD5::operator== (const MD5& other) const
  5239. {
  5240. return memcmp (result, other.result, sizeof (result)) == 0;
  5241. }
  5242. bool MD5::operator!= (const MD5& other) const
  5243. {
  5244. return ! operator== (other);
  5245. }
  5246. END_JUCE_NAMESPACE
  5247. /*** End of inlined file: juce_MD5.cpp ***/
  5248. /*** Start of inlined file: juce_Primes.cpp ***/
  5249. BEGIN_JUCE_NAMESPACE
  5250. namespace PrimesHelpers
  5251. {
  5252. void createSmallSieve (const int numBits, BigInteger& result)
  5253. {
  5254. result.setBit (numBits);
  5255. result.clearBit (numBits); // to enlarge the array
  5256. result.setBit (0);
  5257. int n = 2;
  5258. do
  5259. {
  5260. for (int i = n + n; i < numBits; i += n)
  5261. result.setBit (i);
  5262. n = result.findNextClearBit (n + 1);
  5263. }
  5264. while (n <= (numBits >> 1));
  5265. }
  5266. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5267. const BigInteger& smallSieve, const int smallSieveSize)
  5268. {
  5269. jassert (! base[0]); // must be even!
  5270. result.setBit (numBits);
  5271. result.clearBit (numBits); // to enlarge the array
  5272. int index = smallSieve.findNextClearBit (0);
  5273. do
  5274. {
  5275. const int prime = (index << 1) + 1;
  5276. BigInteger r (base), remainder;
  5277. r.divideBy (prime, remainder);
  5278. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5279. if (r.isZero())
  5280. i += prime;
  5281. if ((i & 1) == 0)
  5282. i += prime;
  5283. i = (i - 1) >> 1;
  5284. while (i < numBits)
  5285. {
  5286. result.setBit (i);
  5287. i += prime;
  5288. }
  5289. index = smallSieve.findNextClearBit (index + 1);
  5290. }
  5291. while (index < smallSieveSize);
  5292. }
  5293. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5294. const int numBits, BigInteger& result, const int certainty)
  5295. {
  5296. for (int i = 0; i < numBits; ++i)
  5297. {
  5298. if (! sieve[i])
  5299. {
  5300. result = base + (unsigned int) ((i << 1) + 1);
  5301. if (Primes::isProbablyPrime (result, certainty))
  5302. return true;
  5303. }
  5304. }
  5305. return false;
  5306. }
  5307. bool passesMillerRabin (const BigInteger& n, int iterations)
  5308. {
  5309. const BigInteger one (1), two (2);
  5310. const BigInteger nMinusOne (n - one);
  5311. BigInteger d (nMinusOne);
  5312. const int s = d.findNextSetBit (0);
  5313. d >>= s;
  5314. BigInteger smallPrimes;
  5315. int numBitsInSmallPrimes = 0;
  5316. for (;;)
  5317. {
  5318. numBitsInSmallPrimes += 256;
  5319. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5320. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5321. if (numPrimesFound > iterations + 1)
  5322. break;
  5323. }
  5324. int smallPrime = 2;
  5325. while (--iterations >= 0)
  5326. {
  5327. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5328. BigInteger r (smallPrime);
  5329. r.exponentModulo (d, n);
  5330. if (r != one && r != nMinusOne)
  5331. {
  5332. for (int j = 0; j < s; ++j)
  5333. {
  5334. r.exponentModulo (two, n);
  5335. if (r == nMinusOne)
  5336. break;
  5337. }
  5338. if (r != nMinusOne)
  5339. return false;
  5340. }
  5341. }
  5342. return true;
  5343. }
  5344. }
  5345. const BigInteger Primes::createProbablePrime (const int bitLength,
  5346. const int certainty,
  5347. const int* randomSeeds,
  5348. int numRandomSeeds)
  5349. {
  5350. using namespace PrimesHelpers;
  5351. int defaultSeeds [16];
  5352. if (numRandomSeeds <= 0)
  5353. {
  5354. randomSeeds = defaultSeeds;
  5355. numRandomSeeds = numElementsInArray (defaultSeeds);
  5356. Random r (0);
  5357. for (int j = 10; --j >= 0;)
  5358. {
  5359. r.setSeedRandomly();
  5360. for (int i = numRandomSeeds; --i >= 0;)
  5361. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5362. }
  5363. }
  5364. BigInteger smallSieve;
  5365. const int smallSieveSize = 15000;
  5366. createSmallSieve (smallSieveSize, smallSieve);
  5367. BigInteger p;
  5368. for (int i = numRandomSeeds; --i >= 0;)
  5369. {
  5370. BigInteger p2;
  5371. Random r (randomSeeds[i]);
  5372. r.fillBitsRandomly (p2, 0, bitLength);
  5373. p ^= p2;
  5374. }
  5375. p.setBit (bitLength - 1);
  5376. p.clearBit (0);
  5377. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5378. while (p.getHighestBit() < bitLength)
  5379. {
  5380. p += 2 * searchLen;
  5381. BigInteger sieve;
  5382. bigSieve (p, searchLen, sieve,
  5383. smallSieve, smallSieveSize);
  5384. BigInteger candidate;
  5385. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5386. return candidate;
  5387. }
  5388. jassertfalse;
  5389. return BigInteger();
  5390. }
  5391. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5392. {
  5393. using namespace PrimesHelpers;
  5394. if (! number[0])
  5395. return false;
  5396. if (number.getHighestBit() <= 10)
  5397. {
  5398. const int num = number.getBitRangeAsInt (0, 10);
  5399. for (int i = num / 2; --i > 1;)
  5400. if (num % i == 0)
  5401. return false;
  5402. return true;
  5403. }
  5404. else
  5405. {
  5406. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5407. return false;
  5408. return passesMillerRabin (number, certainty);
  5409. }
  5410. }
  5411. END_JUCE_NAMESPACE
  5412. /*** End of inlined file: juce_Primes.cpp ***/
  5413. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5414. BEGIN_JUCE_NAMESPACE
  5415. RSAKey::RSAKey()
  5416. {
  5417. }
  5418. RSAKey::RSAKey (const String& s)
  5419. {
  5420. if (s.containsChar (','))
  5421. {
  5422. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5423. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5424. }
  5425. else
  5426. {
  5427. // the string needs to be two hex numbers, comma-separated..
  5428. jassertfalse;
  5429. }
  5430. }
  5431. RSAKey::~RSAKey()
  5432. {
  5433. }
  5434. bool RSAKey::operator== (const RSAKey& other) const throw()
  5435. {
  5436. return part1 == other.part1 && part2 == other.part2;
  5437. }
  5438. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5439. {
  5440. return ! operator== (other);
  5441. }
  5442. const String RSAKey::toString() const
  5443. {
  5444. return part1.toString (16) + "," + part2.toString (16);
  5445. }
  5446. bool RSAKey::applyToValue (BigInteger& value) const
  5447. {
  5448. if (part1.isZero() || part2.isZero() || value <= 0)
  5449. {
  5450. jassertfalse; // using an uninitialised key
  5451. value.clear();
  5452. return false;
  5453. }
  5454. BigInteger result;
  5455. while (! value.isZero())
  5456. {
  5457. result *= part2;
  5458. BigInteger remainder;
  5459. value.divideBy (part2, remainder);
  5460. remainder.exponentModulo (part1, part2);
  5461. result += remainder;
  5462. }
  5463. value.swapWith (result);
  5464. return true;
  5465. }
  5466. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5467. {
  5468. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5469. // are fast to divide + multiply
  5470. for (int i = 2; i <= 65536; i *= 2)
  5471. {
  5472. const BigInteger e (1 + i);
  5473. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5474. return e;
  5475. }
  5476. BigInteger e (4);
  5477. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5478. ++e;
  5479. return e;
  5480. }
  5481. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5482. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5483. {
  5484. jassert (numBits > 16); // not much point using less than this..
  5485. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5486. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5487. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5488. const BigInteger n (p * q);
  5489. const BigInteger m (--p * --q);
  5490. const BigInteger e (findBestCommonDivisor (p, q));
  5491. BigInteger d (e);
  5492. d.inverseModulo (m);
  5493. publicKey.part1 = e;
  5494. publicKey.part2 = n;
  5495. privateKey.part1 = d;
  5496. privateKey.part2 = n;
  5497. }
  5498. END_JUCE_NAMESPACE
  5499. /*** End of inlined file: juce_RSAKey.cpp ***/
  5500. /*** Start of inlined file: juce_InputStream.cpp ***/
  5501. BEGIN_JUCE_NAMESPACE
  5502. char InputStream::readByte()
  5503. {
  5504. char temp = 0;
  5505. read (&temp, 1);
  5506. return temp;
  5507. }
  5508. bool InputStream::readBool()
  5509. {
  5510. return readByte() != 0;
  5511. }
  5512. short InputStream::readShort()
  5513. {
  5514. char temp[2];
  5515. if (read (temp, 2) == 2)
  5516. return (short) ByteOrder::littleEndianShort (temp);
  5517. return 0;
  5518. }
  5519. short InputStream::readShortBigEndian()
  5520. {
  5521. char temp[2];
  5522. if (read (temp, 2) == 2)
  5523. return (short) ByteOrder::bigEndianShort (temp);
  5524. return 0;
  5525. }
  5526. int InputStream::readInt()
  5527. {
  5528. char temp[4];
  5529. if (read (temp, 4) == 4)
  5530. return (int) ByteOrder::littleEndianInt (temp);
  5531. return 0;
  5532. }
  5533. int InputStream::readIntBigEndian()
  5534. {
  5535. char temp[4];
  5536. if (read (temp, 4) == 4)
  5537. return (int) ByteOrder::bigEndianInt (temp);
  5538. return 0;
  5539. }
  5540. int InputStream::readCompressedInt()
  5541. {
  5542. const unsigned char sizeByte = readByte();
  5543. if (sizeByte == 0)
  5544. return 0;
  5545. const int numBytes = (sizeByte & 0x7f);
  5546. if (numBytes > 4)
  5547. {
  5548. jassertfalse; // trying to read corrupt data - this method must only be used
  5549. // to read data that was written by OutputStream::writeCompressedInt()
  5550. return 0;
  5551. }
  5552. char bytes[4] = { 0, 0, 0, 0 };
  5553. if (read (bytes, numBytes) != numBytes)
  5554. return 0;
  5555. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5556. return (sizeByte >> 7) ? -num : num;
  5557. }
  5558. int64 InputStream::readInt64()
  5559. {
  5560. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5561. if (read (n.asBytes, 8) == 8)
  5562. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5563. return 0;
  5564. }
  5565. int64 InputStream::readInt64BigEndian()
  5566. {
  5567. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5568. if (read (n.asBytes, 8) == 8)
  5569. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5570. return 0;
  5571. }
  5572. float InputStream::readFloat()
  5573. {
  5574. // the union below relies on these types being the same size...
  5575. static_jassert (sizeof (int32) == sizeof (float));
  5576. union { int32 asInt; float asFloat; } n;
  5577. n.asInt = (int32) readInt();
  5578. return n.asFloat;
  5579. }
  5580. float InputStream::readFloatBigEndian()
  5581. {
  5582. union { int32 asInt; float asFloat; } n;
  5583. n.asInt = (int32) readIntBigEndian();
  5584. return n.asFloat;
  5585. }
  5586. double InputStream::readDouble()
  5587. {
  5588. union { int64 asInt; double asDouble; } n;
  5589. n.asInt = readInt64();
  5590. return n.asDouble;
  5591. }
  5592. double InputStream::readDoubleBigEndian()
  5593. {
  5594. union { int64 asInt; double asDouble; } n;
  5595. n.asInt = readInt64BigEndian();
  5596. return n.asDouble;
  5597. }
  5598. const String InputStream::readString()
  5599. {
  5600. MemoryBlock buffer (256);
  5601. char* data = static_cast<char*> (buffer.getData());
  5602. size_t i = 0;
  5603. while ((data[i] = readByte()) != 0)
  5604. {
  5605. if (++i >= buffer.getSize())
  5606. {
  5607. buffer.setSize (buffer.getSize() + 512);
  5608. data = static_cast<char*> (buffer.getData());
  5609. }
  5610. }
  5611. return String::fromUTF8 (data, (int) i);
  5612. }
  5613. const String InputStream::readNextLine()
  5614. {
  5615. MemoryBlock buffer (256);
  5616. char* data = static_cast<char*> (buffer.getData());
  5617. size_t i = 0;
  5618. while ((data[i] = readByte()) != 0)
  5619. {
  5620. if (data[i] == '\n')
  5621. break;
  5622. if (data[i] == '\r')
  5623. {
  5624. const int64 lastPos = getPosition();
  5625. if (readByte() != '\n')
  5626. setPosition (lastPos);
  5627. break;
  5628. }
  5629. if (++i >= buffer.getSize())
  5630. {
  5631. buffer.setSize (buffer.getSize() + 512);
  5632. data = static_cast<char*> (buffer.getData());
  5633. }
  5634. }
  5635. return String::fromUTF8 (data, (int) i);
  5636. }
  5637. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5638. {
  5639. MemoryOutputStream mo (block, true);
  5640. return mo.writeFromInputStream (*this, numBytes);
  5641. }
  5642. const String InputStream::readEntireStreamAsString()
  5643. {
  5644. MemoryOutputStream mo;
  5645. mo.writeFromInputStream (*this, -1);
  5646. return mo.toString();
  5647. }
  5648. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5649. {
  5650. if (numBytesToSkip > 0)
  5651. {
  5652. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5653. HeapBlock<char> temp (skipBufferSize);
  5654. while (numBytesToSkip > 0 && ! isExhausted())
  5655. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5656. }
  5657. }
  5658. END_JUCE_NAMESPACE
  5659. /*** End of inlined file: juce_InputStream.cpp ***/
  5660. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5661. BEGIN_JUCE_NAMESPACE
  5662. #if JUCE_DEBUG
  5663. static Array<void*, CriticalSection> activeStreams;
  5664. void juce_CheckForDanglingStreams()
  5665. {
  5666. /*
  5667. It's always a bad idea to leak any object, but if you're leaking output
  5668. streams, then there's a good chance that you're failing to flush a file
  5669. to disk properly, which could result in corrupted data and other similar
  5670. nastiness..
  5671. */
  5672. jassert (activeStreams.size() == 0);
  5673. };
  5674. #endif
  5675. OutputStream::OutputStream()
  5676. : newLineString (NewLine::getDefault())
  5677. {
  5678. #if JUCE_DEBUG
  5679. activeStreams.add (this);
  5680. #endif
  5681. }
  5682. OutputStream::~OutputStream()
  5683. {
  5684. #if JUCE_DEBUG
  5685. activeStreams.removeValue (this);
  5686. #endif
  5687. }
  5688. void OutputStream::writeBool (const bool b)
  5689. {
  5690. writeByte (b ? (char) 1
  5691. : (char) 0);
  5692. }
  5693. void OutputStream::writeByte (char byte)
  5694. {
  5695. write (&byte, 1);
  5696. }
  5697. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5698. {
  5699. while (--numTimesToRepeat >= 0)
  5700. writeByte (byte);
  5701. }
  5702. void OutputStream::writeShort (short value)
  5703. {
  5704. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5705. write (&v, 2);
  5706. }
  5707. void OutputStream::writeShortBigEndian (short value)
  5708. {
  5709. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5710. write (&v, 2);
  5711. }
  5712. void OutputStream::writeInt (int value)
  5713. {
  5714. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5715. write (&v, 4);
  5716. }
  5717. void OutputStream::writeIntBigEndian (int value)
  5718. {
  5719. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5720. write (&v, 4);
  5721. }
  5722. void OutputStream::writeCompressedInt (int value)
  5723. {
  5724. unsigned int un = (value < 0) ? (unsigned int) -value
  5725. : (unsigned int) value;
  5726. uint8 data[5];
  5727. int num = 0;
  5728. while (un > 0)
  5729. {
  5730. data[++num] = (uint8) un;
  5731. un >>= 8;
  5732. }
  5733. data[0] = (uint8) num;
  5734. if (value < 0)
  5735. data[0] |= 0x80;
  5736. write (data, num + 1);
  5737. }
  5738. void OutputStream::writeInt64 (int64 value)
  5739. {
  5740. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5741. write (&v, 8);
  5742. }
  5743. void OutputStream::writeInt64BigEndian (int64 value)
  5744. {
  5745. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5746. write (&v, 8);
  5747. }
  5748. void OutputStream::writeFloat (float value)
  5749. {
  5750. union { int asInt; float asFloat; } n;
  5751. n.asFloat = value;
  5752. writeInt (n.asInt);
  5753. }
  5754. void OutputStream::writeFloatBigEndian (float value)
  5755. {
  5756. union { int asInt; float asFloat; } n;
  5757. n.asFloat = value;
  5758. writeIntBigEndian (n.asInt);
  5759. }
  5760. void OutputStream::writeDouble (double value)
  5761. {
  5762. union { int64 asInt; double asDouble; } n;
  5763. n.asDouble = value;
  5764. writeInt64 (n.asInt);
  5765. }
  5766. void OutputStream::writeDoubleBigEndian (double value)
  5767. {
  5768. union { int64 asInt; double asDouble; } n;
  5769. n.asDouble = value;
  5770. writeInt64BigEndian (n.asInt);
  5771. }
  5772. void OutputStream::writeString (const String& text)
  5773. {
  5774. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5775. // if lots of large, persistent strings were to be written to streams).
  5776. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5777. HeapBlock<char> temp (numBytes);
  5778. text.copyToUTF8 (temp, numBytes);
  5779. write (temp, numBytes);
  5780. }
  5781. void OutputStream::writeText (const String& text, const bool asUnicode,
  5782. const bool writeUnicodeHeaderBytes)
  5783. {
  5784. if (asUnicode)
  5785. {
  5786. if (writeUnicodeHeaderBytes)
  5787. write ("\x0ff\x0fe", 2);
  5788. const juce_wchar* src = text;
  5789. bool lastCharWasReturn = false;
  5790. while (*src != 0)
  5791. {
  5792. if (*src == L'\n' && ! lastCharWasReturn)
  5793. writeShort ((short) L'\r');
  5794. lastCharWasReturn = (*src == L'\r');
  5795. writeShort ((short) *src++);
  5796. }
  5797. }
  5798. else
  5799. {
  5800. const char* src = text.toUTF8();
  5801. const char* t = src;
  5802. for (;;)
  5803. {
  5804. if (*t == '\n')
  5805. {
  5806. if (t > src)
  5807. write (src, (int) (t - src));
  5808. write ("\r\n", 2);
  5809. src = t + 1;
  5810. }
  5811. else if (*t == '\r')
  5812. {
  5813. if (t[1] == '\n')
  5814. ++t;
  5815. }
  5816. else if (*t == 0)
  5817. {
  5818. if (t > src)
  5819. write (src, (int) (t - src));
  5820. break;
  5821. }
  5822. ++t;
  5823. }
  5824. }
  5825. }
  5826. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5827. {
  5828. if (numBytesToWrite < 0)
  5829. numBytesToWrite = std::numeric_limits<int64>::max();
  5830. int numWritten = 0;
  5831. while (numBytesToWrite > 0 && ! source.isExhausted())
  5832. {
  5833. char buffer [8192];
  5834. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5835. if (num <= 0)
  5836. break;
  5837. write (buffer, num);
  5838. numBytesToWrite -= num;
  5839. numWritten += num;
  5840. }
  5841. return numWritten;
  5842. }
  5843. void OutputStream::setNewLineString (const String& newLineString_)
  5844. {
  5845. newLineString = newLineString_;
  5846. }
  5847. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5848. {
  5849. return stream << String (number);
  5850. }
  5851. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5852. {
  5853. return stream << String (number);
  5854. }
  5855. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5856. {
  5857. stream.writeByte (character);
  5858. return stream;
  5859. }
  5860. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5861. {
  5862. stream.write (text, (int) strlen (text));
  5863. return stream;
  5864. }
  5865. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5866. {
  5867. stream.write (data.getData(), (int) data.getSize());
  5868. return stream;
  5869. }
  5870. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5871. {
  5872. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5873. if (in != 0)
  5874. stream.writeFromInputStream (*in, -1);
  5875. return stream;
  5876. }
  5877. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5878. {
  5879. return stream << stream.getNewLineString();
  5880. }
  5881. END_JUCE_NAMESPACE
  5882. /*** End of inlined file: juce_OutputStream.cpp ***/
  5883. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5884. BEGIN_JUCE_NAMESPACE
  5885. DirectoryIterator::DirectoryIterator (const File& directory,
  5886. bool isRecursive_,
  5887. const String& wildCard_,
  5888. const int whatToLookFor_)
  5889. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5890. wildCard (wildCard_),
  5891. path (File::addTrailingSeparator (directory.getFullPathName())),
  5892. index (-1),
  5893. totalNumFiles (-1),
  5894. whatToLookFor (whatToLookFor_),
  5895. isRecursive (isRecursive_),
  5896. hasBeenAdvanced (false)
  5897. {
  5898. // you have to specify the type of files you're looking for!
  5899. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5900. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5901. }
  5902. DirectoryIterator::~DirectoryIterator()
  5903. {
  5904. }
  5905. bool DirectoryIterator::next()
  5906. {
  5907. return next (0, 0, 0, 0, 0, 0);
  5908. }
  5909. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5910. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5911. {
  5912. hasBeenAdvanced = true;
  5913. if (subIterator != 0)
  5914. {
  5915. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5916. return true;
  5917. subIterator = 0;
  5918. }
  5919. String filename;
  5920. bool isDirectory, isHidden;
  5921. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5922. {
  5923. ++index;
  5924. if (! filename.containsOnly ("."))
  5925. {
  5926. const File fileFound (path + filename, 0);
  5927. bool matches = false;
  5928. if (isDirectory)
  5929. {
  5930. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5931. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5932. matches = (whatToLookFor & File::findDirectories) != 0;
  5933. }
  5934. else
  5935. {
  5936. matches = (whatToLookFor & File::findFiles) != 0;
  5937. }
  5938. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5939. if (matches && isRecursive)
  5940. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5941. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5942. matches = ! isHidden;
  5943. if (matches)
  5944. {
  5945. currentFile = fileFound;
  5946. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5947. if (isDirResult != 0) *isDirResult = isDirectory;
  5948. return true;
  5949. }
  5950. else if (subIterator != 0)
  5951. {
  5952. return next();
  5953. }
  5954. }
  5955. }
  5956. return false;
  5957. }
  5958. const File DirectoryIterator::getFile() const
  5959. {
  5960. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5961. return subIterator->getFile();
  5962. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5963. jassert (hasBeenAdvanced);
  5964. return currentFile;
  5965. }
  5966. float DirectoryIterator::getEstimatedProgress() const
  5967. {
  5968. if (totalNumFiles < 0)
  5969. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5970. if (totalNumFiles <= 0)
  5971. return 0.0f;
  5972. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5973. : (float) index;
  5974. return detailedIndex / totalNumFiles;
  5975. }
  5976. END_JUCE_NAMESPACE
  5977. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5978. /*** Start of inlined file: juce_File.cpp ***/
  5979. #if ! JUCE_WINDOWS
  5980. #include <pwd.h>
  5981. #endif
  5982. BEGIN_JUCE_NAMESPACE
  5983. File::File (const String& fullPathName)
  5984. : fullPath (parseAbsolutePath (fullPathName))
  5985. {
  5986. }
  5987. File::File (const String& path, int)
  5988. : fullPath (path)
  5989. {
  5990. }
  5991. const File File::createFileWithoutCheckingPath (const String& path)
  5992. {
  5993. return File (path, 0);
  5994. }
  5995. File::File (const File& other)
  5996. : fullPath (other.fullPath)
  5997. {
  5998. }
  5999. File& File::operator= (const String& newPath)
  6000. {
  6001. fullPath = parseAbsolutePath (newPath);
  6002. return *this;
  6003. }
  6004. File& File::operator= (const File& other)
  6005. {
  6006. fullPath = other.fullPath;
  6007. return *this;
  6008. }
  6009. const File File::nonexistent;
  6010. const String File::parseAbsolutePath (const String& p)
  6011. {
  6012. if (p.isEmpty())
  6013. return String::empty;
  6014. #if JUCE_WINDOWS
  6015. // Windows..
  6016. String path (p.replaceCharacter ('/', '\\'));
  6017. if (path.startsWithChar (File::separator))
  6018. {
  6019. if (path[1] != File::separator)
  6020. {
  6021. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6022. If you're trying to parse a string that may be either a relative path or an absolute path,
  6023. you MUST provide a context against which the partial path can be evaluated - you can do
  6024. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6025. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6026. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6027. */
  6028. jassertfalse;
  6029. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  6030. }
  6031. }
  6032. else if (! path.containsChar (':'))
  6033. {
  6034. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6035. If you're trying to parse a string that may be either a relative path or an absolute path,
  6036. you MUST provide a context against which the partial path can be evaluated - you can do
  6037. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6038. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6039. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6040. */
  6041. jassertfalse;
  6042. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6043. }
  6044. #else
  6045. // Mac or Linux..
  6046. String path (p.replaceCharacter ('\\', '/'));
  6047. if (path.startsWithChar ('~'))
  6048. {
  6049. if (path[1] == File::separator || path[1] == 0)
  6050. {
  6051. // expand a name of the form "~/abc"
  6052. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6053. + path.substring (1);
  6054. }
  6055. else
  6056. {
  6057. // expand a name of type "~dave/abc"
  6058. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6059. struct passwd* const pw = getpwnam (userName.toUTF8());
  6060. if (pw != 0)
  6061. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6062. }
  6063. }
  6064. else if (! path.startsWithChar (File::separator))
  6065. {
  6066. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6067. If you're trying to parse a string that may be either a relative path or an absolute path,
  6068. you MUST provide a context against which the partial path can be evaluated - you can do
  6069. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6070. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6071. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6072. */
  6073. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6074. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6075. }
  6076. #endif
  6077. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6078. path = path.dropLastCharacters (1);
  6079. return path;
  6080. }
  6081. const String File::addTrailingSeparator (const String& path)
  6082. {
  6083. return path.endsWithChar (File::separator) ? path
  6084. : path + File::separator;
  6085. }
  6086. #if JUCE_LINUX
  6087. #define NAMES_ARE_CASE_SENSITIVE 1
  6088. #endif
  6089. bool File::areFileNamesCaseSensitive()
  6090. {
  6091. #if NAMES_ARE_CASE_SENSITIVE
  6092. return true;
  6093. #else
  6094. return false;
  6095. #endif
  6096. }
  6097. bool File::operator== (const File& other) const
  6098. {
  6099. #if NAMES_ARE_CASE_SENSITIVE
  6100. return fullPath == other.fullPath;
  6101. #else
  6102. return fullPath.equalsIgnoreCase (other.fullPath);
  6103. #endif
  6104. }
  6105. bool File::operator!= (const File& other) const
  6106. {
  6107. return ! operator== (other);
  6108. }
  6109. bool File::operator< (const File& other) const
  6110. {
  6111. #if NAMES_ARE_CASE_SENSITIVE
  6112. return fullPath < other.fullPath;
  6113. #else
  6114. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6115. #endif
  6116. }
  6117. bool File::operator> (const File& other) const
  6118. {
  6119. #if NAMES_ARE_CASE_SENSITIVE
  6120. return fullPath > other.fullPath;
  6121. #else
  6122. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6123. #endif
  6124. }
  6125. bool File::setReadOnly (const bool shouldBeReadOnly,
  6126. const bool applyRecursively) const
  6127. {
  6128. bool worked = true;
  6129. if (applyRecursively && isDirectory())
  6130. {
  6131. Array <File> subFiles;
  6132. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6133. for (int i = subFiles.size(); --i >= 0;)
  6134. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6135. }
  6136. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6137. }
  6138. bool File::deleteRecursively() const
  6139. {
  6140. bool worked = true;
  6141. if (isDirectory())
  6142. {
  6143. Array<File> subFiles;
  6144. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6145. for (int i = subFiles.size(); --i >= 0;)
  6146. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6147. }
  6148. return deleteFile() && worked;
  6149. }
  6150. bool File::moveFileTo (const File& newFile) const
  6151. {
  6152. if (newFile.fullPath == fullPath)
  6153. return true;
  6154. #if ! NAMES_ARE_CASE_SENSITIVE
  6155. if (*this != newFile)
  6156. #endif
  6157. if (! newFile.deleteFile())
  6158. return false;
  6159. return moveInternal (newFile);
  6160. }
  6161. bool File::copyFileTo (const File& newFile) const
  6162. {
  6163. return (*this == newFile)
  6164. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6165. }
  6166. bool File::copyDirectoryTo (const File& newDirectory) const
  6167. {
  6168. if (isDirectory() && newDirectory.createDirectory())
  6169. {
  6170. Array<File> subFiles;
  6171. findChildFiles (subFiles, File::findFiles, false);
  6172. int i;
  6173. for (i = 0; i < subFiles.size(); ++i)
  6174. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6175. return false;
  6176. subFiles.clear();
  6177. findChildFiles (subFiles, File::findDirectories, false);
  6178. for (i = 0; i < subFiles.size(); ++i)
  6179. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6180. return false;
  6181. return true;
  6182. }
  6183. return false;
  6184. }
  6185. const String File::getPathUpToLastSlash() const
  6186. {
  6187. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6188. if (lastSlash > 0)
  6189. return fullPath.substring (0, lastSlash);
  6190. else if (lastSlash == 0)
  6191. return separatorString;
  6192. else
  6193. return fullPath;
  6194. }
  6195. const File File::getParentDirectory() const
  6196. {
  6197. return File (getPathUpToLastSlash(), (int) 0);
  6198. }
  6199. const String File::getFileName() const
  6200. {
  6201. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6202. }
  6203. int File::hashCode() const
  6204. {
  6205. return fullPath.hashCode();
  6206. }
  6207. int64 File::hashCode64() const
  6208. {
  6209. return fullPath.hashCode64();
  6210. }
  6211. const String File::getFileNameWithoutExtension() const
  6212. {
  6213. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6214. const int lastDot = fullPath.lastIndexOfChar ('.');
  6215. if (lastDot > lastSlash)
  6216. return fullPath.substring (lastSlash, lastDot);
  6217. else
  6218. return fullPath.substring (lastSlash);
  6219. }
  6220. bool File::isAChildOf (const File& potentialParent) const
  6221. {
  6222. if (potentialParent == File::nonexistent)
  6223. return false;
  6224. const String ourPath (getPathUpToLastSlash());
  6225. #if NAMES_ARE_CASE_SENSITIVE
  6226. if (potentialParent.fullPath == ourPath)
  6227. #else
  6228. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6229. #endif
  6230. {
  6231. return true;
  6232. }
  6233. else if (potentialParent.fullPath.length() >= ourPath.length())
  6234. {
  6235. return false;
  6236. }
  6237. else
  6238. {
  6239. return getParentDirectory().isAChildOf (potentialParent);
  6240. }
  6241. }
  6242. bool File::isAbsolutePath (const String& path)
  6243. {
  6244. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6245. #if JUCE_WINDOWS
  6246. || (path.isNotEmpty() && path[1] == ':');
  6247. #else
  6248. || path.startsWithChar ('~');
  6249. #endif
  6250. }
  6251. const File File::getChildFile (String relativePath) const
  6252. {
  6253. if (isAbsolutePath (relativePath))
  6254. {
  6255. // the path is really absolute..
  6256. return File (relativePath);
  6257. }
  6258. else
  6259. {
  6260. // it's relative, so remove any ../ or ./ bits at the start.
  6261. String path (fullPath);
  6262. if (relativePath[0] == '.')
  6263. {
  6264. #if JUCE_WINDOWS
  6265. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6266. #else
  6267. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6268. #endif
  6269. while (relativePath[0] == '.')
  6270. {
  6271. if (relativePath[1] == '.')
  6272. {
  6273. if (relativePath [2] == 0 || relativePath[2] == separator)
  6274. {
  6275. const int lastSlash = path.lastIndexOfChar (separator);
  6276. if (lastSlash >= 0)
  6277. path = path.substring (0, lastSlash);
  6278. relativePath = relativePath.substring (3);
  6279. }
  6280. else
  6281. {
  6282. break;
  6283. }
  6284. }
  6285. else if (relativePath[1] == separator)
  6286. {
  6287. relativePath = relativePath.substring (2);
  6288. }
  6289. else
  6290. {
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. return File (addTrailingSeparator (path) + relativePath);
  6296. }
  6297. }
  6298. const File File::getSiblingFile (const String& fileName) const
  6299. {
  6300. return getParentDirectory().getChildFile (fileName);
  6301. }
  6302. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6303. {
  6304. if (bytes == 1)
  6305. {
  6306. return "1 byte";
  6307. }
  6308. else if (bytes < 1024)
  6309. {
  6310. return String ((int) bytes) + " bytes";
  6311. }
  6312. else if (bytes < 1024 * 1024)
  6313. {
  6314. return String (bytes / 1024.0, 1) + " KB";
  6315. }
  6316. else if (bytes < 1024 * 1024 * 1024)
  6317. {
  6318. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6319. }
  6320. else
  6321. {
  6322. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6323. }
  6324. }
  6325. bool File::create() const
  6326. {
  6327. if (exists())
  6328. return true;
  6329. {
  6330. const File parentDir (getParentDirectory());
  6331. if (parentDir == *this || ! parentDir.createDirectory())
  6332. return false;
  6333. FileOutputStream fo (*this, 8);
  6334. }
  6335. return exists();
  6336. }
  6337. bool File::createDirectory() const
  6338. {
  6339. if (! isDirectory())
  6340. {
  6341. const File parentDir (getParentDirectory());
  6342. if (parentDir == *this || ! parentDir.createDirectory())
  6343. return false;
  6344. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6345. return isDirectory();
  6346. }
  6347. return true;
  6348. }
  6349. const Time File::getCreationTime() const
  6350. {
  6351. int64 m, a, c;
  6352. getFileTimesInternal (m, a, c);
  6353. return Time (c);
  6354. }
  6355. const Time File::getLastModificationTime() const
  6356. {
  6357. int64 m, a, c;
  6358. getFileTimesInternal (m, a, c);
  6359. return Time (m);
  6360. }
  6361. const Time File::getLastAccessTime() const
  6362. {
  6363. int64 m, a, c;
  6364. getFileTimesInternal (m, a, c);
  6365. return Time (a);
  6366. }
  6367. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6368. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6369. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6370. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6371. {
  6372. if (! existsAsFile())
  6373. return false;
  6374. FileInputStream in (*this);
  6375. return getSize() == in.readIntoMemoryBlock (destBlock);
  6376. }
  6377. const String File::loadFileAsString() const
  6378. {
  6379. if (! existsAsFile())
  6380. return String::empty;
  6381. FileInputStream in (*this);
  6382. return in.readEntireStreamAsString();
  6383. }
  6384. int File::findChildFiles (Array<File>& results,
  6385. const int whatToLookFor,
  6386. const bool searchRecursively,
  6387. const String& wildCardPattern) const
  6388. {
  6389. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6390. int total = 0;
  6391. while (di.next())
  6392. {
  6393. results.add (di.getFile());
  6394. ++total;
  6395. }
  6396. return total;
  6397. }
  6398. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6399. {
  6400. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6401. int total = 0;
  6402. while (di.next())
  6403. ++total;
  6404. return total;
  6405. }
  6406. bool File::containsSubDirectories() const
  6407. {
  6408. if (isDirectory())
  6409. {
  6410. DirectoryIterator di (*this, false, "*", findDirectories);
  6411. return di.next();
  6412. }
  6413. return false;
  6414. }
  6415. const File File::getNonexistentChildFile (const String& prefix_,
  6416. const String& suffix,
  6417. bool putNumbersInBrackets) const
  6418. {
  6419. File f (getChildFile (prefix_ + suffix));
  6420. if (f.exists())
  6421. {
  6422. int num = 2;
  6423. String prefix (prefix_);
  6424. // remove any bracketed numbers that may already be on the end..
  6425. if (prefix.trim().endsWithChar (')'))
  6426. {
  6427. putNumbersInBrackets = true;
  6428. const int openBracks = prefix.lastIndexOfChar ('(');
  6429. const int closeBracks = prefix.lastIndexOfChar (')');
  6430. if (openBracks > 0
  6431. && closeBracks > openBracks
  6432. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6433. {
  6434. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6435. prefix = prefix.substring (0, openBracks);
  6436. }
  6437. }
  6438. // also use brackets if it ends in a digit.
  6439. putNumbersInBrackets = putNumbersInBrackets
  6440. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6441. do
  6442. {
  6443. if (putNumbersInBrackets)
  6444. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6445. else
  6446. f = getChildFile (prefix + String (num++) + suffix);
  6447. } while (f.exists());
  6448. }
  6449. return f;
  6450. }
  6451. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6452. {
  6453. if (exists())
  6454. {
  6455. return getParentDirectory()
  6456. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6457. getFileExtension(),
  6458. putNumbersInBrackets);
  6459. }
  6460. else
  6461. {
  6462. return *this;
  6463. }
  6464. }
  6465. const String File::getFileExtension() const
  6466. {
  6467. String ext;
  6468. if (! isDirectory())
  6469. {
  6470. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6471. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6472. ext = fullPath.substring (indexOfDot);
  6473. }
  6474. return ext;
  6475. }
  6476. bool File::hasFileExtension (const String& possibleSuffix) const
  6477. {
  6478. if (possibleSuffix.isEmpty())
  6479. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6480. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6481. if (semicolon >= 0)
  6482. {
  6483. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6484. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6485. }
  6486. else
  6487. {
  6488. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6489. {
  6490. if (possibleSuffix.startsWithChar ('.'))
  6491. return true;
  6492. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6493. if (dotPos >= 0)
  6494. return fullPath [dotPos] == '.';
  6495. }
  6496. }
  6497. return false;
  6498. }
  6499. const File File::withFileExtension (const String& newExtension) const
  6500. {
  6501. if (fullPath.isEmpty())
  6502. return File::nonexistent;
  6503. String filePart (getFileName());
  6504. int i = filePart.lastIndexOfChar ('.');
  6505. if (i >= 0)
  6506. filePart = filePart.substring (0, i);
  6507. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6508. filePart << '.';
  6509. return getSiblingFile (filePart + newExtension);
  6510. }
  6511. bool File::startAsProcess (const String& parameters) const
  6512. {
  6513. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6514. }
  6515. FileInputStream* File::createInputStream() const
  6516. {
  6517. if (existsAsFile())
  6518. return new FileInputStream (*this);
  6519. return 0;
  6520. }
  6521. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6522. {
  6523. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6524. if (out->failedToOpen())
  6525. return 0;
  6526. return out.release();
  6527. }
  6528. bool File::appendData (const void* const dataToAppend,
  6529. const int numberOfBytes) const
  6530. {
  6531. if (numberOfBytes > 0)
  6532. {
  6533. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6534. if (out == 0)
  6535. return false;
  6536. out->write (dataToAppend, numberOfBytes);
  6537. }
  6538. return true;
  6539. }
  6540. bool File::replaceWithData (const void* const dataToWrite,
  6541. const int numberOfBytes) const
  6542. {
  6543. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6544. if (numberOfBytes <= 0)
  6545. return deleteFile();
  6546. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6547. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6548. return tempFile.overwriteTargetFileWithTemporary();
  6549. }
  6550. bool File::appendText (const String& text,
  6551. const bool asUnicode,
  6552. const bool writeUnicodeHeaderBytes) const
  6553. {
  6554. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6555. if (out != 0)
  6556. {
  6557. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6558. return true;
  6559. }
  6560. return false;
  6561. }
  6562. bool File::replaceWithText (const String& textToWrite,
  6563. const bool asUnicode,
  6564. const bool writeUnicodeHeaderBytes) const
  6565. {
  6566. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6567. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6568. return tempFile.overwriteTargetFileWithTemporary();
  6569. }
  6570. bool File::hasIdenticalContentTo (const File& other) const
  6571. {
  6572. if (other == *this)
  6573. return true;
  6574. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6575. {
  6576. FileInputStream in1 (*this), in2 (other);
  6577. const int bufferSize = 4096;
  6578. HeapBlock <char> buffer1, buffer2;
  6579. buffer1.malloc (bufferSize);
  6580. buffer2.malloc (bufferSize);
  6581. for (;;)
  6582. {
  6583. const int num1 = in1.read (buffer1, bufferSize);
  6584. const int num2 = in2.read (buffer2, bufferSize);
  6585. if (num1 != num2)
  6586. break;
  6587. if (num1 <= 0)
  6588. return true;
  6589. if (memcmp (buffer1, buffer2, num1) != 0)
  6590. break;
  6591. }
  6592. }
  6593. return false;
  6594. }
  6595. const String File::createLegalPathName (const String& original)
  6596. {
  6597. String s (original);
  6598. String start;
  6599. if (s[1] == ':')
  6600. {
  6601. start = s.substring (0, 2);
  6602. s = s.substring (2);
  6603. }
  6604. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6605. .substring (0, 1024);
  6606. }
  6607. const String File::createLegalFileName (const String& original)
  6608. {
  6609. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6610. const int maxLength = 128; // only the length of the filename, not the whole path
  6611. const int len = s.length();
  6612. if (len > maxLength)
  6613. {
  6614. const int lastDot = s.lastIndexOfChar ('.');
  6615. if (lastDot > jmax (0, len - 12))
  6616. {
  6617. s = s.substring (0, maxLength - (len - lastDot))
  6618. + s.substring (lastDot);
  6619. }
  6620. else
  6621. {
  6622. s = s.substring (0, maxLength);
  6623. }
  6624. }
  6625. return s;
  6626. }
  6627. const String File::getRelativePathFrom (const File& dir) const
  6628. {
  6629. String thisPath (fullPath);
  6630. {
  6631. int len = thisPath.length();
  6632. while (--len >= 0 && thisPath [len] == File::separator)
  6633. thisPath [len] = 0;
  6634. }
  6635. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6636. : dir.fullPath));
  6637. const int len = jmin (thisPath.length(), dirPath.length());
  6638. int commonBitLength = 0;
  6639. for (int i = 0; i < len; ++i)
  6640. {
  6641. #if NAMES_ARE_CASE_SENSITIVE
  6642. if (thisPath[i] != dirPath[i])
  6643. #else
  6644. if (CharacterFunctions::toLowerCase (thisPath[i])
  6645. != CharacterFunctions::toLowerCase (dirPath[i]))
  6646. #endif
  6647. {
  6648. break;
  6649. }
  6650. ++commonBitLength;
  6651. }
  6652. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6653. --commonBitLength;
  6654. // if the only common bit is the root, then just return the full path..
  6655. if (commonBitLength <= 0
  6656. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6657. return fullPath;
  6658. thisPath = thisPath.substring (commonBitLength);
  6659. dirPath = dirPath.substring (commonBitLength);
  6660. while (dirPath.isNotEmpty())
  6661. {
  6662. #if JUCE_WINDOWS
  6663. thisPath = "..\\" + thisPath;
  6664. #else
  6665. thisPath = "../" + thisPath;
  6666. #endif
  6667. const int sep = dirPath.indexOfChar (separator);
  6668. if (sep >= 0)
  6669. dirPath = dirPath.substring (sep + 1);
  6670. else
  6671. dirPath = String::empty;
  6672. }
  6673. return thisPath;
  6674. }
  6675. const File File::createTempFile (const String& fileNameEnding)
  6676. {
  6677. const File tempFile (getSpecialLocation (tempDirectory)
  6678. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6679. .withFileExtension (fileNameEnding));
  6680. if (tempFile.exists())
  6681. return createTempFile (fileNameEnding);
  6682. else
  6683. return tempFile;
  6684. }
  6685. #if JUCE_UNIT_TESTS
  6686. class FileTests : public UnitTest
  6687. {
  6688. public:
  6689. FileTests() : UnitTest ("Files") {}
  6690. void runTest()
  6691. {
  6692. beginTest ("Reading");
  6693. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6694. const File temp (File::getSpecialLocation (File::tempDirectory));
  6695. expect (! File::nonexistent.exists());
  6696. expect (home.isDirectory());
  6697. expect (home.exists());
  6698. expect (! home.existsAsFile());
  6699. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6700. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6701. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6702. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6703. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6704. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6705. expect (home.getBytesFreeOnVolume() > 0);
  6706. expect (! home.isHidden());
  6707. expect (home.isOnHardDisk());
  6708. expect (! home.isOnCDRomDrive());
  6709. expect (File::getCurrentWorkingDirectory().exists());
  6710. expect (home.setAsCurrentWorkingDirectory());
  6711. expect (File::getCurrentWorkingDirectory() == home);
  6712. {
  6713. Array<File> roots;
  6714. File::findFileSystemRoots (roots);
  6715. expect (roots.size() > 0);
  6716. int numRootsExisting = 0;
  6717. for (int i = 0; i < roots.size(); ++i)
  6718. if (roots[i].exists())
  6719. ++numRootsExisting;
  6720. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6721. expect (numRootsExisting > 0);
  6722. }
  6723. beginTest ("Writing");
  6724. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6725. expect (demoFolder.deleteRecursively());
  6726. expect (demoFolder.createDirectory());
  6727. expect (demoFolder.isDirectory());
  6728. expect (demoFolder.getParentDirectory() == temp);
  6729. expect (temp.isDirectory());
  6730. {
  6731. Array<File> files;
  6732. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6733. expect (files.contains (demoFolder));
  6734. }
  6735. {
  6736. Array<File> files;
  6737. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6738. expect (files.contains (demoFolder));
  6739. }
  6740. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6741. expect (tempFile.getFileExtension() == ".txt");
  6742. expect (tempFile.hasFileExtension (".txt"));
  6743. expect (tempFile.hasFileExtension ("txt"));
  6744. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6745. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6746. expect (tempFile.hasWriteAccess());
  6747. {
  6748. FileOutputStream fo (tempFile);
  6749. fo.write ("0123456789", 10);
  6750. }
  6751. expect (tempFile.exists());
  6752. expect (tempFile.getSize() == 10);
  6753. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6754. expect (tempFile.loadFileAsString() == "0123456789");
  6755. expect (! demoFolder.containsSubDirectories());
  6756. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6757. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6758. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6759. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6760. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6761. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6762. expect (demoFolder.containsSubDirectories());
  6763. expect (tempFile.hasWriteAccess());
  6764. tempFile.setReadOnly (true);
  6765. expect (! tempFile.hasWriteAccess());
  6766. tempFile.setReadOnly (false);
  6767. expect (tempFile.hasWriteAccess());
  6768. Time t (Time::getCurrentTime());
  6769. tempFile.setLastModificationTime (t);
  6770. Time t2 = tempFile.getLastModificationTime();
  6771. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6772. {
  6773. MemoryBlock mb;
  6774. tempFile.loadFileAsData (mb);
  6775. expect (mb.getSize() == 10);
  6776. expect (mb[0] == '0');
  6777. }
  6778. expect (tempFile.appendData ("abcdefghij", 10));
  6779. expect (tempFile.getSize() == 20);
  6780. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6781. expect (tempFile.getSize() == 10);
  6782. File tempFile2 (tempFile.getNonexistentSibling (false));
  6783. expect (tempFile.copyFileTo (tempFile2));
  6784. expect (tempFile2.exists());
  6785. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6786. expect (tempFile.deleteFile());
  6787. expect (! tempFile.exists());
  6788. expect (tempFile2.moveFileTo (tempFile));
  6789. expect (tempFile.exists());
  6790. expect (! tempFile2.exists());
  6791. expect (demoFolder.deleteRecursively());
  6792. expect (! demoFolder.exists());
  6793. }
  6794. };
  6795. static FileTests fileUnitTests;
  6796. #endif
  6797. END_JUCE_NAMESPACE
  6798. /*** End of inlined file: juce_File.cpp ***/
  6799. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6800. BEGIN_JUCE_NAMESPACE
  6801. int64 juce_fileSetPosition (void* handle, int64 pos);
  6802. FileInputStream::FileInputStream (const File& f)
  6803. : file (f),
  6804. fileHandle (0),
  6805. currentPosition (0),
  6806. totalSize (0),
  6807. needToSeek (true)
  6808. {
  6809. openHandle();
  6810. }
  6811. FileInputStream::~FileInputStream()
  6812. {
  6813. closeHandle();
  6814. }
  6815. int64 FileInputStream::getTotalLength()
  6816. {
  6817. return totalSize;
  6818. }
  6819. int FileInputStream::read (void* buffer, int bytesToRead)
  6820. {
  6821. if (needToSeek)
  6822. {
  6823. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6824. return 0;
  6825. needToSeek = false;
  6826. }
  6827. const size_t num = readInternal (buffer, bytesToRead);
  6828. currentPosition += num;
  6829. return (int) num;
  6830. }
  6831. bool FileInputStream::isExhausted()
  6832. {
  6833. return currentPosition >= totalSize;
  6834. }
  6835. int64 FileInputStream::getPosition()
  6836. {
  6837. return currentPosition;
  6838. }
  6839. bool FileInputStream::setPosition (int64 pos)
  6840. {
  6841. pos = jlimit ((int64) 0, totalSize, pos);
  6842. needToSeek |= (currentPosition != pos);
  6843. currentPosition = pos;
  6844. return true;
  6845. }
  6846. END_JUCE_NAMESPACE
  6847. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6848. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6849. BEGIN_JUCE_NAMESPACE
  6850. int64 juce_fileSetPosition (void* handle, int64 pos);
  6851. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6852. : file (f),
  6853. fileHandle (0),
  6854. currentPosition (0),
  6855. bufferSize (bufferSize_),
  6856. bytesInBuffer (0),
  6857. buffer (jmax (bufferSize_, 16))
  6858. {
  6859. openHandle();
  6860. }
  6861. FileOutputStream::~FileOutputStream()
  6862. {
  6863. flush();
  6864. closeHandle();
  6865. }
  6866. int64 FileOutputStream::getPosition()
  6867. {
  6868. return currentPosition;
  6869. }
  6870. bool FileOutputStream::setPosition (int64 newPosition)
  6871. {
  6872. if (newPosition != currentPosition)
  6873. {
  6874. flush();
  6875. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6876. }
  6877. return newPosition == currentPosition;
  6878. }
  6879. void FileOutputStream::flush()
  6880. {
  6881. if (bytesInBuffer > 0)
  6882. {
  6883. writeInternal (buffer, bytesInBuffer);
  6884. bytesInBuffer = 0;
  6885. }
  6886. flushInternal();
  6887. }
  6888. bool FileOutputStream::write (const void* const src, const int numBytes)
  6889. {
  6890. if (bytesInBuffer + numBytes < bufferSize)
  6891. {
  6892. memcpy (buffer + bytesInBuffer, src, numBytes);
  6893. bytesInBuffer += numBytes;
  6894. currentPosition += numBytes;
  6895. }
  6896. else
  6897. {
  6898. if (bytesInBuffer > 0)
  6899. {
  6900. // flush the reservoir
  6901. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6902. bytesInBuffer = 0;
  6903. if (! wroteOk)
  6904. return false;
  6905. }
  6906. if (numBytes < bufferSize)
  6907. {
  6908. memcpy (buffer + bytesInBuffer, src, numBytes);
  6909. bytesInBuffer += numBytes;
  6910. currentPosition += numBytes;
  6911. }
  6912. else
  6913. {
  6914. const int bytesWritten = writeInternal (src, numBytes);
  6915. if (bytesWritten < 0)
  6916. return false;
  6917. currentPosition += bytesWritten;
  6918. return bytesWritten == numBytes;
  6919. }
  6920. }
  6921. return true;
  6922. }
  6923. END_JUCE_NAMESPACE
  6924. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6925. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6926. BEGIN_JUCE_NAMESPACE
  6927. FileSearchPath::FileSearchPath()
  6928. {
  6929. }
  6930. FileSearchPath::FileSearchPath (const String& path)
  6931. {
  6932. init (path);
  6933. }
  6934. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6935. : directories (other.directories)
  6936. {
  6937. }
  6938. FileSearchPath::~FileSearchPath()
  6939. {
  6940. }
  6941. FileSearchPath& FileSearchPath::operator= (const String& path)
  6942. {
  6943. init (path);
  6944. return *this;
  6945. }
  6946. void FileSearchPath::init (const String& path)
  6947. {
  6948. directories.clear();
  6949. directories.addTokens (path, ";", "\"");
  6950. directories.trim();
  6951. directories.removeEmptyStrings();
  6952. for (int i = directories.size(); --i >= 0;)
  6953. directories.set (i, directories[i].unquoted());
  6954. }
  6955. int FileSearchPath::getNumPaths() const
  6956. {
  6957. return directories.size();
  6958. }
  6959. const File FileSearchPath::operator[] (const int index) const
  6960. {
  6961. return File (directories [index]);
  6962. }
  6963. const String FileSearchPath::toString() const
  6964. {
  6965. StringArray directories2 (directories);
  6966. for (int i = directories2.size(); --i >= 0;)
  6967. if (directories2[i].containsChar (';'))
  6968. directories2.set (i, directories2[i].quoted());
  6969. return directories2.joinIntoString (";");
  6970. }
  6971. void FileSearchPath::add (const File& dir, const int insertIndex)
  6972. {
  6973. directories.insert (insertIndex, dir.getFullPathName());
  6974. }
  6975. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6976. {
  6977. for (int i = 0; i < directories.size(); ++i)
  6978. if (File (directories[i]) == dir)
  6979. return;
  6980. add (dir);
  6981. }
  6982. void FileSearchPath::remove (const int index)
  6983. {
  6984. directories.remove (index);
  6985. }
  6986. void FileSearchPath::addPath (const FileSearchPath& other)
  6987. {
  6988. for (int i = 0; i < other.getNumPaths(); ++i)
  6989. addIfNotAlreadyThere (other[i]);
  6990. }
  6991. void FileSearchPath::removeRedundantPaths()
  6992. {
  6993. for (int i = directories.size(); --i >= 0;)
  6994. {
  6995. const File d1 (directories[i]);
  6996. for (int j = directories.size(); --j >= 0;)
  6997. {
  6998. const File d2 (directories[j]);
  6999. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  7000. {
  7001. directories.remove (i);
  7002. break;
  7003. }
  7004. }
  7005. }
  7006. }
  7007. void FileSearchPath::removeNonExistentPaths()
  7008. {
  7009. for (int i = directories.size(); --i >= 0;)
  7010. if (! File (directories[i]).isDirectory())
  7011. directories.remove (i);
  7012. }
  7013. int FileSearchPath::findChildFiles (Array<File>& results,
  7014. const int whatToLookFor,
  7015. const bool searchRecursively,
  7016. const String& wildCardPattern) const
  7017. {
  7018. int total = 0;
  7019. for (int i = 0; i < directories.size(); ++i)
  7020. total += operator[] (i).findChildFiles (results,
  7021. whatToLookFor,
  7022. searchRecursively,
  7023. wildCardPattern);
  7024. return total;
  7025. }
  7026. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  7027. const bool checkRecursively) const
  7028. {
  7029. for (int i = directories.size(); --i >= 0;)
  7030. {
  7031. const File d (directories[i]);
  7032. if (checkRecursively)
  7033. {
  7034. if (fileToCheck.isAChildOf (d))
  7035. return true;
  7036. }
  7037. else
  7038. {
  7039. if (fileToCheck.getParentDirectory() == d)
  7040. return true;
  7041. }
  7042. }
  7043. return false;
  7044. }
  7045. END_JUCE_NAMESPACE
  7046. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7047. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7048. BEGIN_JUCE_NAMESPACE
  7049. NamedPipe::NamedPipe()
  7050. : internal (0)
  7051. {
  7052. }
  7053. NamedPipe::~NamedPipe()
  7054. {
  7055. close();
  7056. }
  7057. bool NamedPipe::openExisting (const String& pipeName)
  7058. {
  7059. currentPipeName = pipeName;
  7060. return openInternal (pipeName, false);
  7061. }
  7062. bool NamedPipe::createNewPipe (const String& pipeName)
  7063. {
  7064. currentPipeName = pipeName;
  7065. return openInternal (pipeName, true);
  7066. }
  7067. bool NamedPipe::isOpen() const
  7068. {
  7069. return internal != 0;
  7070. }
  7071. const String NamedPipe::getName() const
  7072. {
  7073. return currentPipeName;
  7074. }
  7075. // other methods for this class are implemented in the platform-specific files
  7076. END_JUCE_NAMESPACE
  7077. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7078. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7079. BEGIN_JUCE_NAMESPACE
  7080. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7081. {
  7082. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7083. "temp_" + String (Random::getSystemRandom().nextInt()),
  7084. suffix,
  7085. optionFlags);
  7086. }
  7087. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7088. : targetFile (targetFile_)
  7089. {
  7090. // If you use this constructor, you need to give it a valid target file!
  7091. jassert (targetFile != File::nonexistent);
  7092. createTempFile (targetFile.getParentDirectory(),
  7093. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7094. targetFile.getFileExtension(),
  7095. optionFlags);
  7096. }
  7097. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7098. const String& suffix, const int optionFlags)
  7099. {
  7100. if ((optionFlags & useHiddenFile) != 0)
  7101. name = "." + name;
  7102. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7103. }
  7104. TemporaryFile::~TemporaryFile()
  7105. {
  7106. if (! deleteTemporaryFile())
  7107. {
  7108. /* Failed to delete our temporary file! The most likely reason for this would be
  7109. that you've not closed an output stream that was being used to write to file.
  7110. If you find that something beyond your control is changing permissions on
  7111. your temporary files and preventing them from being deleted, you may want to
  7112. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7113. handle them appropriately.
  7114. */
  7115. jassertfalse;
  7116. }
  7117. }
  7118. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7119. {
  7120. // This method only works if you created this object with the constructor
  7121. // that takes a target file!
  7122. jassert (targetFile != File::nonexistent);
  7123. if (temporaryFile.exists())
  7124. {
  7125. // Have a few attempts at overwriting the file before giving up..
  7126. for (int i = 5; --i >= 0;)
  7127. {
  7128. if (temporaryFile.moveFileTo (targetFile))
  7129. return true;
  7130. Thread::sleep (100);
  7131. }
  7132. }
  7133. else
  7134. {
  7135. // There's no temporary file to use. If your write failed, you should
  7136. // probably check, and not bother calling this method.
  7137. jassertfalse;
  7138. }
  7139. return false;
  7140. }
  7141. bool TemporaryFile::deleteTemporaryFile() const
  7142. {
  7143. // Have a few attempts at deleting the file before giving up..
  7144. for (int i = 5; --i >= 0;)
  7145. {
  7146. if (temporaryFile.deleteFile())
  7147. return true;
  7148. Thread::sleep (50);
  7149. }
  7150. return false;
  7151. }
  7152. END_JUCE_NAMESPACE
  7153. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7154. /*** Start of inlined file: juce_Socket.cpp ***/
  7155. #if JUCE_WINDOWS
  7156. #include <winsock2.h>
  7157. #if JUCE_MSVC
  7158. #pragma warning (push)
  7159. #pragma warning (disable : 4127 4389 4018)
  7160. #endif
  7161. #else
  7162. #if JUCE_LINUX || JUCE_ANDROID
  7163. #include <sys/types.h>
  7164. #include <sys/socket.h>
  7165. #include <sys/errno.h>
  7166. #include <unistd.h>
  7167. #include <netinet/in.h>
  7168. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7169. #include <CoreServices/CoreServices.h>
  7170. #endif
  7171. #include <fcntl.h>
  7172. #include <netdb.h>
  7173. #include <arpa/inet.h>
  7174. #include <netinet/tcp.h>
  7175. #endif
  7176. BEGIN_JUCE_NAMESPACE
  7177. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7178. typedef socklen_t juce_socklen_t;
  7179. #else
  7180. typedef int juce_socklen_t;
  7181. #endif
  7182. #if JUCE_WINDOWS
  7183. namespace SocketHelpers
  7184. {
  7185. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7186. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7187. void initWin32Sockets()
  7188. {
  7189. static CriticalSection lock;
  7190. const ScopedLock sl (lock);
  7191. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7192. {
  7193. WSADATA wsaData;
  7194. const WORD wVersionRequested = MAKEWORD (1, 1);
  7195. WSAStartup (wVersionRequested, &wsaData);
  7196. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7197. }
  7198. }
  7199. }
  7200. void juce_shutdownWin32Sockets()
  7201. {
  7202. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7203. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7204. }
  7205. #endif
  7206. namespace SocketHelpers
  7207. {
  7208. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7209. {
  7210. const int sndBufSize = 65536;
  7211. const int rcvBufSize = 65536;
  7212. const int one = 1;
  7213. return handle > 0
  7214. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7215. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7216. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7217. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7218. }
  7219. bool bindSocketToPort (const int handle, const int port) throw()
  7220. {
  7221. if (handle <= 0 || port <= 0)
  7222. return false;
  7223. struct sockaddr_in servTmpAddr;
  7224. zerostruct (servTmpAddr);
  7225. servTmpAddr.sin_family = PF_INET;
  7226. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7227. servTmpAddr.sin_port = htons ((uint16) port);
  7228. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7229. }
  7230. int readSocket (const int handle,
  7231. void* const destBuffer, const int maxBytesToRead,
  7232. bool volatile& connected,
  7233. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7234. {
  7235. int bytesRead = 0;
  7236. while (bytesRead < maxBytesToRead)
  7237. {
  7238. int bytesThisTime;
  7239. #if JUCE_WINDOWS
  7240. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7241. #else
  7242. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7243. && errno == EINTR
  7244. && connected)
  7245. {
  7246. }
  7247. #endif
  7248. if (bytesThisTime <= 0 || ! connected)
  7249. {
  7250. if (bytesRead == 0)
  7251. bytesRead = -1;
  7252. break;
  7253. }
  7254. bytesRead += bytesThisTime;
  7255. if (! blockUntilSpecifiedAmountHasArrived)
  7256. break;
  7257. }
  7258. return bytesRead;
  7259. }
  7260. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7261. {
  7262. struct timeval timeout;
  7263. struct timeval* timeoutp;
  7264. if (timeoutMsecs >= 0)
  7265. {
  7266. timeout.tv_sec = timeoutMsecs / 1000;
  7267. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7268. timeoutp = &timeout;
  7269. }
  7270. else
  7271. {
  7272. timeoutp = 0;
  7273. }
  7274. fd_set rset, wset;
  7275. FD_ZERO (&rset);
  7276. FD_SET (handle, &rset);
  7277. FD_ZERO (&wset);
  7278. FD_SET (handle, &wset);
  7279. fd_set* const prset = forReading ? &rset : 0;
  7280. fd_set* const pwset = forReading ? 0 : &wset;
  7281. #if JUCE_WINDOWS
  7282. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7283. return -1;
  7284. #else
  7285. {
  7286. int result;
  7287. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7288. && errno == EINTR)
  7289. {
  7290. }
  7291. if (result < 0)
  7292. return -1;
  7293. }
  7294. #endif
  7295. {
  7296. int opt;
  7297. juce_socklen_t len = sizeof (opt);
  7298. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7299. || opt != 0)
  7300. return -1;
  7301. }
  7302. if ((forReading && FD_ISSET (handle, &rset))
  7303. || ((! forReading) && FD_ISSET (handle, &wset)))
  7304. return 1;
  7305. return 0;
  7306. }
  7307. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7308. {
  7309. #if JUCE_WINDOWS
  7310. u_long nonBlocking = shouldBlock ? 0 : 1;
  7311. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7312. return false;
  7313. #else
  7314. int socketFlags = fcntl (handle, F_GETFL, 0);
  7315. if (socketFlags == -1)
  7316. return false;
  7317. if (shouldBlock)
  7318. socketFlags &= ~O_NONBLOCK;
  7319. else
  7320. socketFlags |= O_NONBLOCK;
  7321. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7322. return false;
  7323. #endif
  7324. return true;
  7325. }
  7326. bool connectSocket (int volatile& handle,
  7327. const bool isDatagram,
  7328. void** serverAddress,
  7329. const String& hostName,
  7330. const int portNumber,
  7331. const int timeOutMillisecs) throw()
  7332. {
  7333. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7334. if (hostEnt == 0)
  7335. return false;
  7336. struct in_addr targetAddress;
  7337. memcpy (&targetAddress.s_addr,
  7338. *(hostEnt->h_addr_list),
  7339. sizeof (targetAddress.s_addr));
  7340. struct sockaddr_in servTmpAddr;
  7341. zerostruct (servTmpAddr);
  7342. servTmpAddr.sin_family = PF_INET;
  7343. servTmpAddr.sin_addr = targetAddress;
  7344. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7345. if (handle < 0)
  7346. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7347. if (handle < 0)
  7348. return false;
  7349. if (isDatagram)
  7350. {
  7351. *serverAddress = new struct sockaddr_in();
  7352. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7353. return true;
  7354. }
  7355. setSocketBlockingState (handle, false);
  7356. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7357. if (result < 0)
  7358. {
  7359. #if JUCE_WINDOWS
  7360. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7361. #else
  7362. if (errno == EINPROGRESS)
  7363. #endif
  7364. {
  7365. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7366. {
  7367. setSocketBlockingState (handle, true);
  7368. return false;
  7369. }
  7370. }
  7371. }
  7372. setSocketBlockingState (handle, true);
  7373. resetSocketOptions (handle, false, false);
  7374. return true;
  7375. }
  7376. }
  7377. StreamingSocket::StreamingSocket()
  7378. : portNumber (0),
  7379. handle (-1),
  7380. connected (false),
  7381. isListener (false)
  7382. {
  7383. #if JUCE_WINDOWS
  7384. SocketHelpers::initWin32Sockets();
  7385. #endif
  7386. }
  7387. StreamingSocket::StreamingSocket (const String& hostName_,
  7388. const int portNumber_,
  7389. const int handle_)
  7390. : hostName (hostName_),
  7391. portNumber (portNumber_),
  7392. handle (handle_),
  7393. connected (true),
  7394. isListener (false)
  7395. {
  7396. #if JUCE_WINDOWS
  7397. SocketHelpers::initWin32Sockets();
  7398. #endif
  7399. SocketHelpers::resetSocketOptions (handle_, false, false);
  7400. }
  7401. StreamingSocket::~StreamingSocket()
  7402. {
  7403. close();
  7404. }
  7405. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7406. {
  7407. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7408. : -1;
  7409. }
  7410. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7411. {
  7412. if (isListener || ! connected)
  7413. return -1;
  7414. #if JUCE_WINDOWS
  7415. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7416. #else
  7417. int result;
  7418. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7419. && errno == EINTR)
  7420. {
  7421. }
  7422. return result;
  7423. #endif
  7424. }
  7425. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7426. const int timeoutMsecs) const
  7427. {
  7428. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7429. : -1;
  7430. }
  7431. bool StreamingSocket::bindToPort (const int port)
  7432. {
  7433. return SocketHelpers::bindSocketToPort (handle, port);
  7434. }
  7435. bool StreamingSocket::connect (const String& remoteHostName,
  7436. const int remotePortNumber,
  7437. const int timeOutMillisecs)
  7438. {
  7439. if (isListener)
  7440. {
  7441. jassertfalse; // a listener socket can't connect to another one!
  7442. return false;
  7443. }
  7444. if (connected)
  7445. close();
  7446. hostName = remoteHostName;
  7447. portNumber = remotePortNumber;
  7448. isListener = false;
  7449. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7450. remotePortNumber, timeOutMillisecs);
  7451. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7452. {
  7453. close();
  7454. return false;
  7455. }
  7456. return true;
  7457. }
  7458. void StreamingSocket::close()
  7459. {
  7460. #if JUCE_WINDOWS
  7461. if (handle != SOCKET_ERROR || connected)
  7462. closesocket (handle);
  7463. connected = false;
  7464. #else
  7465. if (connected)
  7466. {
  7467. connected = false;
  7468. if (isListener)
  7469. {
  7470. // need to do this to interrupt the accept() function..
  7471. StreamingSocket temp;
  7472. temp.connect ("localhost", portNumber, 1000);
  7473. }
  7474. }
  7475. if (handle != -1)
  7476. ::close (handle);
  7477. #endif
  7478. hostName = String::empty;
  7479. portNumber = 0;
  7480. handle = -1;
  7481. isListener = false;
  7482. }
  7483. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7484. {
  7485. if (connected)
  7486. close();
  7487. hostName = "listener";
  7488. portNumber = newPortNumber;
  7489. isListener = true;
  7490. struct sockaddr_in servTmpAddr;
  7491. zerostruct (servTmpAddr);
  7492. servTmpAddr.sin_family = PF_INET;
  7493. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7494. if (localHostName.isNotEmpty())
  7495. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7496. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7497. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7498. if (handle < 0)
  7499. return false;
  7500. const int reuse = 1;
  7501. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7502. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7503. || listen (handle, SOMAXCONN) < 0)
  7504. {
  7505. close();
  7506. return false;
  7507. }
  7508. connected = true;
  7509. return true;
  7510. }
  7511. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7512. {
  7513. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7514. // prepare this socket as a listener.
  7515. if (connected && isListener)
  7516. {
  7517. struct sockaddr address;
  7518. juce_socklen_t len = sizeof (sockaddr);
  7519. const int newSocket = (int) accept (handle, &address, &len);
  7520. if (newSocket >= 0 && connected)
  7521. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7522. portNumber, newSocket);
  7523. }
  7524. return 0;
  7525. }
  7526. bool StreamingSocket::isLocal() const throw()
  7527. {
  7528. return hostName == "127.0.0.1";
  7529. }
  7530. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7531. : portNumber (0),
  7532. handle (-1),
  7533. connected (true),
  7534. allowBroadcast (allowBroadcast_),
  7535. serverAddress (0)
  7536. {
  7537. #if JUCE_WINDOWS
  7538. SocketHelpers::initWin32Sockets();
  7539. #endif
  7540. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7541. bindToPort (localPortNumber);
  7542. }
  7543. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7544. const int handle_, const int localPortNumber)
  7545. : hostName (hostName_),
  7546. portNumber (portNumber_),
  7547. handle (handle_),
  7548. connected (true),
  7549. allowBroadcast (false),
  7550. serverAddress (0)
  7551. {
  7552. #if JUCE_WINDOWS
  7553. SocketHelpers::initWin32Sockets();
  7554. #endif
  7555. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7556. bindToPort (localPortNumber);
  7557. }
  7558. DatagramSocket::~DatagramSocket()
  7559. {
  7560. close();
  7561. delete static_cast <struct sockaddr_in*> (serverAddress);
  7562. serverAddress = 0;
  7563. }
  7564. void DatagramSocket::close()
  7565. {
  7566. #if JUCE_WINDOWS
  7567. closesocket (handle);
  7568. connected = false;
  7569. #else
  7570. connected = false;
  7571. ::close (handle);
  7572. #endif
  7573. hostName = String::empty;
  7574. portNumber = 0;
  7575. handle = -1;
  7576. }
  7577. bool DatagramSocket::bindToPort (const int port)
  7578. {
  7579. return SocketHelpers::bindSocketToPort (handle, port);
  7580. }
  7581. bool DatagramSocket::connect (const String& remoteHostName,
  7582. const int remotePortNumber,
  7583. const int timeOutMillisecs)
  7584. {
  7585. if (connected)
  7586. close();
  7587. hostName = remoteHostName;
  7588. portNumber = remotePortNumber;
  7589. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7590. remoteHostName, remotePortNumber,
  7591. timeOutMillisecs);
  7592. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7593. {
  7594. close();
  7595. return false;
  7596. }
  7597. return true;
  7598. }
  7599. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7600. {
  7601. struct sockaddr address;
  7602. juce_socklen_t len = sizeof (sockaddr);
  7603. while (waitUntilReady (true, -1) == 1)
  7604. {
  7605. char buf[1];
  7606. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7607. {
  7608. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7609. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7610. -1, -1);
  7611. }
  7612. }
  7613. return 0;
  7614. }
  7615. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7616. const int timeoutMsecs) const
  7617. {
  7618. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7619. : -1;
  7620. }
  7621. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7622. {
  7623. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7624. : -1;
  7625. }
  7626. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7627. {
  7628. // You need to call connect() first to set the server address..
  7629. jassert (serverAddress != 0 && connected);
  7630. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7631. numBytesToWrite, 0,
  7632. (const struct sockaddr*) serverAddress,
  7633. sizeof (struct sockaddr_in))
  7634. : -1;
  7635. }
  7636. bool DatagramSocket::isLocal() const throw()
  7637. {
  7638. return hostName == "127.0.0.1";
  7639. }
  7640. #if JUCE_MSVC
  7641. #pragma warning (pop)
  7642. #endif
  7643. END_JUCE_NAMESPACE
  7644. /*** End of inlined file: juce_Socket.cpp ***/
  7645. /*** Start of inlined file: juce_URL.cpp ***/
  7646. BEGIN_JUCE_NAMESPACE
  7647. URL::URL()
  7648. {
  7649. }
  7650. URL::URL (const String& url_)
  7651. : url (url_)
  7652. {
  7653. int i = url.indexOfChar ('?');
  7654. if (i >= 0)
  7655. {
  7656. do
  7657. {
  7658. const int nextAmp = url.indexOfChar (i + 1, '&');
  7659. const int equalsPos = url.indexOfChar (i + 1, '=');
  7660. if (equalsPos > i + 1)
  7661. {
  7662. if (nextAmp < 0)
  7663. {
  7664. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7665. removeEscapeChars (url.substring (equalsPos + 1)));
  7666. }
  7667. else if (nextAmp > 0 && equalsPos < nextAmp)
  7668. {
  7669. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7670. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7671. }
  7672. }
  7673. i = nextAmp;
  7674. }
  7675. while (i >= 0);
  7676. url = url.upToFirstOccurrenceOf ("?", false, false);
  7677. }
  7678. }
  7679. URL::URL (const URL& other)
  7680. : url (other.url),
  7681. postData (other.postData),
  7682. parameters (other.parameters),
  7683. filesToUpload (other.filesToUpload),
  7684. mimeTypes (other.mimeTypes)
  7685. {
  7686. }
  7687. URL& URL::operator= (const URL& other)
  7688. {
  7689. url = other.url;
  7690. postData = other.postData;
  7691. parameters = other.parameters;
  7692. filesToUpload = other.filesToUpload;
  7693. mimeTypes = other.mimeTypes;
  7694. return *this;
  7695. }
  7696. URL::~URL()
  7697. {
  7698. }
  7699. namespace URLHelpers
  7700. {
  7701. const String getMangledParameters (const StringPairArray& parameters)
  7702. {
  7703. String p;
  7704. for (int i = 0; i < parameters.size(); ++i)
  7705. {
  7706. if (i > 0)
  7707. p << '&';
  7708. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7709. << '='
  7710. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7711. }
  7712. return p;
  7713. }
  7714. int findStartOfDomain (const String& url)
  7715. {
  7716. int i = 0;
  7717. while (CharacterFunctions::isLetterOrDigit (url[i])
  7718. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7719. ++i;
  7720. return url[i] == ':' ? i + 1 : 0;
  7721. }
  7722. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7723. {
  7724. MemoryOutputStream data (postData, false);
  7725. if (url.getFilesToUpload().size() > 0)
  7726. {
  7727. // need to upload some files, so do it as multi-part...
  7728. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7729. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7730. data << "--" << boundary;
  7731. int i;
  7732. for (i = 0; i < url.getParameters().size(); ++i)
  7733. {
  7734. data << "\r\nContent-Disposition: form-data; name=\""
  7735. << url.getParameters().getAllKeys() [i]
  7736. << "\"\r\n\r\n"
  7737. << url.getParameters().getAllValues() [i]
  7738. << "\r\n--"
  7739. << boundary;
  7740. }
  7741. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7742. {
  7743. const File file (url.getFilesToUpload().getAllValues() [i]);
  7744. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7745. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7746. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7747. const String mimeType (url.getMimeTypesOfUploadFiles()
  7748. .getValue (paramName, String::empty));
  7749. if (mimeType.isNotEmpty())
  7750. data << "Content-Type: " << mimeType << "\r\n";
  7751. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7752. << file << "\r\n--" << boundary;
  7753. }
  7754. data << "--\r\n";
  7755. data.flush();
  7756. }
  7757. else
  7758. {
  7759. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7760. data.flush();
  7761. // just a short text attachment, so use simple url encoding..
  7762. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7763. << (int) postData.getSize() << "\r\n";
  7764. }
  7765. }
  7766. }
  7767. const String URL::toString (const bool includeGetParameters) const
  7768. {
  7769. if (includeGetParameters && parameters.size() > 0)
  7770. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7771. else
  7772. return url;
  7773. }
  7774. bool URL::isWellFormed() const
  7775. {
  7776. //xxx TODO
  7777. return url.isNotEmpty();
  7778. }
  7779. const String URL::getDomain() const
  7780. {
  7781. int start = URLHelpers::findStartOfDomain (url);
  7782. while (url[start] == '/')
  7783. ++start;
  7784. const int end1 = url.indexOfChar (start, '/');
  7785. const int end2 = url.indexOfChar (start, ':');
  7786. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7787. : jmin (end1, end2);
  7788. return url.substring (start, end);
  7789. }
  7790. const String URL::getSubPath() const
  7791. {
  7792. int start = URLHelpers::findStartOfDomain (url);
  7793. while (url[start] == '/')
  7794. ++start;
  7795. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7796. return startOfPath <= 0 ? String::empty
  7797. : url.substring (startOfPath);
  7798. }
  7799. const String URL::getScheme() const
  7800. {
  7801. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7802. }
  7803. const URL URL::withNewSubPath (const String& newPath) const
  7804. {
  7805. int start = URLHelpers::findStartOfDomain (url);
  7806. while (url[start] == '/')
  7807. ++start;
  7808. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7809. URL u (*this);
  7810. if (startOfPath > 0)
  7811. u.url = url.substring (0, startOfPath);
  7812. if (! u.url.endsWithChar ('/'))
  7813. u.url << '/';
  7814. if (newPath.startsWithChar ('/'))
  7815. u.url << newPath.substring (1);
  7816. else
  7817. u.url << newPath;
  7818. return u;
  7819. }
  7820. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7821. {
  7822. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7823. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7824. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7825. return true;
  7826. if (possibleURL.containsChar ('@')
  7827. || possibleURL.containsChar (' '))
  7828. return false;
  7829. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7830. .fromLastOccurrenceOf (".", false, false));
  7831. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7832. }
  7833. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7834. {
  7835. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7836. return atSign > 0
  7837. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7838. && (! possibleEmailAddress.endsWithChar ('.'));
  7839. }
  7840. InputStream* URL::createInputStream (const bool usePostCommand,
  7841. OpenStreamProgressCallback* const progressCallback,
  7842. void* const progressCallbackContext,
  7843. const String& extraHeaders,
  7844. const int timeOutMs,
  7845. StringPairArray* const responseHeaders) const
  7846. {
  7847. String headers;
  7848. MemoryBlock headersAndPostData;
  7849. if (usePostCommand)
  7850. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7851. headers += extraHeaders;
  7852. if (! headers.endsWithChar ('\n'))
  7853. headers << "\r\n";
  7854. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7855. progressCallback, progressCallbackContext,
  7856. headers, timeOutMs, responseHeaders);
  7857. }
  7858. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7859. const bool usePostCommand) const
  7860. {
  7861. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7862. if (in != 0)
  7863. {
  7864. in->readIntoMemoryBlock (destData);
  7865. return true;
  7866. }
  7867. return false;
  7868. }
  7869. const String URL::readEntireTextStream (const bool usePostCommand) const
  7870. {
  7871. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7872. if (in != 0)
  7873. return in->readEntireStreamAsString();
  7874. return String::empty;
  7875. }
  7876. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7877. {
  7878. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7879. }
  7880. const URL URL::withParameter (const String& parameterName,
  7881. const String& parameterValue) const
  7882. {
  7883. URL u (*this);
  7884. u.parameters.set (parameterName, parameterValue);
  7885. return u;
  7886. }
  7887. const URL URL::withFileToUpload (const String& parameterName,
  7888. const File& fileToUpload,
  7889. const String& mimeType) const
  7890. {
  7891. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7892. URL u (*this);
  7893. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7894. u.mimeTypes.set (parameterName, mimeType);
  7895. return u;
  7896. }
  7897. const URL URL::withPOSTData (const String& postData_) const
  7898. {
  7899. URL u (*this);
  7900. u.postData = postData_;
  7901. return u;
  7902. }
  7903. const StringPairArray& URL::getParameters() const
  7904. {
  7905. return parameters;
  7906. }
  7907. const StringPairArray& URL::getFilesToUpload() const
  7908. {
  7909. return filesToUpload;
  7910. }
  7911. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7912. {
  7913. return mimeTypes;
  7914. }
  7915. const String URL::removeEscapeChars (const String& s)
  7916. {
  7917. String result (s.replaceCharacter ('+', ' '));
  7918. if (! result.containsChar ('%'))
  7919. return result;
  7920. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7921. // after all the replacements have been made, so that multi-byte chars are handled.
  7922. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7923. for (int i = 0; i < utf8.size(); ++i)
  7924. {
  7925. if (utf8.getUnchecked(i) == '%')
  7926. {
  7927. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7928. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7929. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7930. {
  7931. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7932. utf8.removeRange (i + 1, 2);
  7933. }
  7934. }
  7935. }
  7936. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7937. }
  7938. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7939. {
  7940. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7941. : ",$_-.*!'()");
  7942. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7943. for (int i = 0; i < utf8.size(); ++i)
  7944. {
  7945. const char c = utf8.getUnchecked(i);
  7946. if (! (CharacterFunctions::isLetterOrDigit (c)
  7947. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7948. {
  7949. if (c == ' ')
  7950. {
  7951. utf8.set (i, '+');
  7952. }
  7953. else
  7954. {
  7955. static const char* const hexDigits = "0123456789abcdef";
  7956. utf8.set (i, '%');
  7957. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7958. utf8.insert (++i, hexDigits [c & 15]);
  7959. }
  7960. }
  7961. }
  7962. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7963. }
  7964. bool URL::launchInDefaultBrowser() const
  7965. {
  7966. String u (toString (true));
  7967. if (u.containsChar ('@') && ! u.containsChar (':'))
  7968. u = "mailto:" + u;
  7969. return PlatformUtilities::openDocument (u, String::empty);
  7970. }
  7971. END_JUCE_NAMESPACE
  7972. /*** End of inlined file: juce_URL.cpp ***/
  7973. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7974. BEGIN_JUCE_NAMESPACE
  7975. MACAddress::MACAddress()
  7976. : asInt64 (0)
  7977. {
  7978. }
  7979. MACAddress::MACAddress (const MACAddress& other)
  7980. : asInt64 (other.asInt64)
  7981. {
  7982. }
  7983. MACAddress& MACAddress::operator= (const MACAddress& other)
  7984. {
  7985. asInt64 = other.asInt64;
  7986. return *this;
  7987. }
  7988. MACAddress::MACAddress (const uint8 bytes[6])
  7989. : asInt64 (0)
  7990. {
  7991. memcpy (asBytes, bytes, sizeof (asBytes));
  7992. }
  7993. const String MACAddress::toString() const
  7994. {
  7995. String s;
  7996. s.preallocateStorage (18);
  7997. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7998. {
  7999. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  8000. if (i < numElementsInArray (asBytes) - 1)
  8001. s << '-';
  8002. }
  8003. return s;
  8004. }
  8005. int64 MACAddress::toInt64() const throw()
  8006. {
  8007. int64 n = 0;
  8008. for (int i = numElementsInArray (asBytes); --i >= 0;)
  8009. n = (n << 8) | asBytes[i];
  8010. return n;
  8011. }
  8012. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  8013. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  8014. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  8015. END_JUCE_NAMESPACE
  8016. /*** End of inlined file: juce_MACAddress.cpp ***/
  8017. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  8018. BEGIN_JUCE_NAMESPACE
  8019. namespace
  8020. {
  8021. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  8022. {
  8023. // You need to supply a real stream when creating a BufferedInputStream
  8024. jassert (source != 0);
  8025. requestedSize = jmax (256, requestedSize);
  8026. const int64 sourceSize = source->getTotalLength();
  8027. if (sourceSize >= 0 && sourceSize < requestedSize)
  8028. requestedSize = jmax (32, (int) sourceSize);
  8029. return requestedSize;
  8030. }
  8031. }
  8032. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  8033. const bool deleteSourceWhenDestroyed)
  8034. : source (sourceStream),
  8035. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  8036. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8037. position (sourceStream->getPosition()),
  8038. lastReadPos (0),
  8039. bufferStart (position),
  8040. bufferOverlap (128)
  8041. {
  8042. buffer.malloc (bufferSize);
  8043. }
  8044. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8045. : source (&sourceStream),
  8046. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8047. position (sourceStream.getPosition()),
  8048. lastReadPos (0),
  8049. bufferStart (position),
  8050. bufferOverlap (128)
  8051. {
  8052. buffer.malloc (bufferSize);
  8053. }
  8054. BufferedInputStream::~BufferedInputStream()
  8055. {
  8056. }
  8057. int64 BufferedInputStream::getTotalLength()
  8058. {
  8059. return source->getTotalLength();
  8060. }
  8061. int64 BufferedInputStream::getPosition()
  8062. {
  8063. return position;
  8064. }
  8065. bool BufferedInputStream::setPosition (int64 newPosition)
  8066. {
  8067. position = jmax ((int64) 0, newPosition);
  8068. return true;
  8069. }
  8070. bool BufferedInputStream::isExhausted()
  8071. {
  8072. return (position >= lastReadPos)
  8073. && source->isExhausted();
  8074. }
  8075. void BufferedInputStream::ensureBuffered()
  8076. {
  8077. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8078. if (position < bufferStart || position >= bufferEndOverlap)
  8079. {
  8080. int bytesRead;
  8081. if (position < lastReadPos
  8082. && position >= bufferEndOverlap
  8083. && position >= bufferStart)
  8084. {
  8085. const int bytesToKeep = (int) (lastReadPos - position);
  8086. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8087. bufferStart = position;
  8088. bytesRead = source->read (buffer + bytesToKeep,
  8089. bufferSize - bytesToKeep);
  8090. lastReadPos += bytesRead;
  8091. bytesRead += bytesToKeep;
  8092. }
  8093. else
  8094. {
  8095. bufferStart = position;
  8096. source->setPosition (bufferStart);
  8097. bytesRead = source->read (buffer, bufferSize);
  8098. lastReadPos = bufferStart + bytesRead;
  8099. }
  8100. while (bytesRead < bufferSize)
  8101. buffer [bytesRead++] = 0;
  8102. }
  8103. }
  8104. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8105. {
  8106. if (position >= bufferStart
  8107. && position + maxBytesToRead <= lastReadPos)
  8108. {
  8109. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8110. position += maxBytesToRead;
  8111. return maxBytesToRead;
  8112. }
  8113. else
  8114. {
  8115. if (position < bufferStart || position >= lastReadPos)
  8116. ensureBuffered();
  8117. int bytesRead = 0;
  8118. while (maxBytesToRead > 0)
  8119. {
  8120. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8121. if (bytesAvailable > 0)
  8122. {
  8123. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8124. maxBytesToRead -= bytesAvailable;
  8125. bytesRead += bytesAvailable;
  8126. position += bytesAvailable;
  8127. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8128. }
  8129. const int64 oldLastReadPos = lastReadPos;
  8130. ensureBuffered();
  8131. if (oldLastReadPos == lastReadPos)
  8132. break; // if ensureBuffered() failed to read any more data, bail out
  8133. if (isExhausted())
  8134. break;
  8135. }
  8136. return bytesRead;
  8137. }
  8138. }
  8139. const String BufferedInputStream::readString()
  8140. {
  8141. if (position >= bufferStart
  8142. && position < lastReadPos)
  8143. {
  8144. const int maxChars = (int) (lastReadPos - position);
  8145. const char* const src = buffer + (int) (position - bufferStart);
  8146. for (int i = 0; i < maxChars; ++i)
  8147. {
  8148. if (src[i] == 0)
  8149. {
  8150. position += i + 1;
  8151. return String::fromUTF8 (src, i);
  8152. }
  8153. }
  8154. }
  8155. return InputStream::readString();
  8156. }
  8157. END_JUCE_NAMESPACE
  8158. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8159. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8160. BEGIN_JUCE_NAMESPACE
  8161. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8162. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8163. {
  8164. }
  8165. FileInputSource::~FileInputSource()
  8166. {
  8167. }
  8168. InputStream* FileInputSource::createInputStream()
  8169. {
  8170. return file.createInputStream();
  8171. }
  8172. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8173. {
  8174. return file.getSiblingFile (relatedItemPath).createInputStream();
  8175. }
  8176. int64 FileInputSource::hashCode() const
  8177. {
  8178. int64 h = file.hashCode();
  8179. if (useFileTimeInHashGeneration)
  8180. h ^= file.getLastModificationTime().toMilliseconds();
  8181. return h;
  8182. }
  8183. END_JUCE_NAMESPACE
  8184. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8185. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8186. BEGIN_JUCE_NAMESPACE
  8187. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8188. const size_t sourceDataSize,
  8189. const bool keepInternalCopy)
  8190. : data (static_cast <const char*> (sourceData)),
  8191. dataSize (sourceDataSize),
  8192. position (0)
  8193. {
  8194. if (keepInternalCopy)
  8195. {
  8196. internalCopy.append (data, sourceDataSize);
  8197. data = static_cast <const char*> (internalCopy.getData());
  8198. }
  8199. }
  8200. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8201. const bool keepInternalCopy)
  8202. : data (static_cast <const char*> (sourceData.getData())),
  8203. dataSize (sourceData.getSize()),
  8204. position (0)
  8205. {
  8206. if (keepInternalCopy)
  8207. {
  8208. internalCopy = sourceData;
  8209. data = static_cast <const char*> (internalCopy.getData());
  8210. }
  8211. }
  8212. MemoryInputStream::~MemoryInputStream()
  8213. {
  8214. }
  8215. int64 MemoryInputStream::getTotalLength()
  8216. {
  8217. return dataSize;
  8218. }
  8219. int MemoryInputStream::read (void* const buffer, const int howMany)
  8220. {
  8221. jassert (howMany >= 0);
  8222. const int num = jmin (howMany, (int) (dataSize - position));
  8223. memcpy (buffer, data + position, num);
  8224. position += num;
  8225. return (int) num;
  8226. }
  8227. bool MemoryInputStream::isExhausted()
  8228. {
  8229. return (position >= dataSize);
  8230. }
  8231. bool MemoryInputStream::setPosition (const int64 pos)
  8232. {
  8233. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8234. return true;
  8235. }
  8236. int64 MemoryInputStream::getPosition()
  8237. {
  8238. return position;
  8239. }
  8240. #if JUCE_UNIT_TESTS
  8241. class MemoryStreamTests : public UnitTest
  8242. {
  8243. public:
  8244. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8245. void runTest()
  8246. {
  8247. beginTest ("Basics");
  8248. int randomInt = Random::getSystemRandom().nextInt();
  8249. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8250. double randomDouble = Random::getSystemRandom().nextDouble();
  8251. String randomString;
  8252. for (int i = 50; --i >= 0;)
  8253. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8254. MemoryOutputStream mo;
  8255. mo.writeInt (randomInt);
  8256. mo.writeIntBigEndian (randomInt);
  8257. mo.writeCompressedInt (randomInt);
  8258. mo.writeString (randomString);
  8259. mo.writeInt64 (randomInt64);
  8260. mo.writeInt64BigEndian (randomInt64);
  8261. mo.writeDouble (randomDouble);
  8262. mo.writeDoubleBigEndian (randomDouble);
  8263. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8264. expect (mi.readInt() == randomInt);
  8265. expect (mi.readIntBigEndian() == randomInt);
  8266. expect (mi.readCompressedInt() == randomInt);
  8267. expect (mi.readString() == randomString);
  8268. expect (mi.readInt64() == randomInt64);
  8269. expect (mi.readInt64BigEndian() == randomInt64);
  8270. expect (mi.readDouble() == randomDouble);
  8271. expect (mi.readDoubleBigEndian() == randomDouble);
  8272. }
  8273. };
  8274. static MemoryStreamTests memoryInputStreamUnitTests;
  8275. #endif
  8276. END_JUCE_NAMESPACE
  8277. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8278. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8279. BEGIN_JUCE_NAMESPACE
  8280. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8281. : data (internalBlock),
  8282. position (0),
  8283. size (0)
  8284. {
  8285. internalBlock.setSize (initialSize, false);
  8286. }
  8287. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8288. const bool appendToExistingBlockContent)
  8289. : data (memoryBlockToWriteTo),
  8290. position (0),
  8291. size (0)
  8292. {
  8293. if (appendToExistingBlockContent)
  8294. position = size = memoryBlockToWriteTo.getSize();
  8295. }
  8296. MemoryOutputStream::~MemoryOutputStream()
  8297. {
  8298. flush();
  8299. }
  8300. void MemoryOutputStream::flush()
  8301. {
  8302. if (&data != &internalBlock)
  8303. data.setSize (size, false);
  8304. }
  8305. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8306. {
  8307. data.ensureSize (bytesToPreallocate + 1);
  8308. }
  8309. void MemoryOutputStream::reset() throw()
  8310. {
  8311. position = 0;
  8312. size = 0;
  8313. }
  8314. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8315. {
  8316. if (howMany > 0)
  8317. {
  8318. const size_t storageNeeded = position + howMany;
  8319. if (storageNeeded >= data.getSize())
  8320. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8321. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8322. position += howMany;
  8323. size = jmax (size, position);
  8324. }
  8325. return true;
  8326. }
  8327. const void* MemoryOutputStream::getData() const throw()
  8328. {
  8329. void* const d = data.getData();
  8330. if (data.getSize() > size)
  8331. static_cast <char*> (d) [size] = 0;
  8332. return d;
  8333. }
  8334. bool MemoryOutputStream::setPosition (int64 newPosition)
  8335. {
  8336. if (newPosition <= (int64) size)
  8337. {
  8338. // ok to seek backwards
  8339. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8340. return true;
  8341. }
  8342. else
  8343. {
  8344. // trying to make it bigger isn't a good thing to do..
  8345. return false;
  8346. }
  8347. }
  8348. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8349. {
  8350. // before writing from an input, see if we can preallocate to make it more efficient..
  8351. int64 availableData = source.getTotalLength() - source.getPosition();
  8352. if (availableData > 0)
  8353. {
  8354. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8355. availableData = maxNumBytesToWrite;
  8356. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8357. }
  8358. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8359. }
  8360. const String MemoryOutputStream::toUTF8() const
  8361. {
  8362. return String (static_cast <const char*> (getData()), getDataSize());
  8363. }
  8364. const String MemoryOutputStream::toString() const
  8365. {
  8366. return String::createStringFromData (getData(), (int) getDataSize());
  8367. }
  8368. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8369. {
  8370. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8371. return stream;
  8372. }
  8373. END_JUCE_NAMESPACE
  8374. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8375. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8376. BEGIN_JUCE_NAMESPACE
  8377. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8378. const int64 startPositionInSourceStream_,
  8379. const int64 lengthOfSourceStream_,
  8380. const bool deleteSourceWhenDestroyed)
  8381. : source (sourceStream),
  8382. startPositionInSourceStream (startPositionInSourceStream_),
  8383. lengthOfSourceStream (lengthOfSourceStream_)
  8384. {
  8385. if (deleteSourceWhenDestroyed)
  8386. sourceToDelete = source;
  8387. setPosition (0);
  8388. }
  8389. SubregionStream::~SubregionStream()
  8390. {
  8391. }
  8392. int64 SubregionStream::getTotalLength()
  8393. {
  8394. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8395. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8396. : srcLen;
  8397. }
  8398. int64 SubregionStream::getPosition()
  8399. {
  8400. return source->getPosition() - startPositionInSourceStream;
  8401. }
  8402. bool SubregionStream::setPosition (int64 newPosition)
  8403. {
  8404. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8405. }
  8406. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8407. {
  8408. if (lengthOfSourceStream < 0)
  8409. {
  8410. return source->read (destBuffer, maxBytesToRead);
  8411. }
  8412. else
  8413. {
  8414. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8415. if (maxBytesToRead <= 0)
  8416. return 0;
  8417. return source->read (destBuffer, maxBytesToRead);
  8418. }
  8419. }
  8420. bool SubregionStream::isExhausted()
  8421. {
  8422. if (lengthOfSourceStream >= 0)
  8423. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8424. else
  8425. return source->isExhausted();
  8426. }
  8427. END_JUCE_NAMESPACE
  8428. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8429. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8430. BEGIN_JUCE_NAMESPACE
  8431. PerformanceCounter::PerformanceCounter (const String& name_,
  8432. int runsPerPrintout,
  8433. const File& loggingFile)
  8434. : name (name_),
  8435. numRuns (0),
  8436. runsPerPrint (runsPerPrintout),
  8437. totalTime (0),
  8438. outputFile (loggingFile)
  8439. {
  8440. if (outputFile != File::nonexistent)
  8441. {
  8442. String s ("**** Counter for \"");
  8443. s << name_ << "\" started at: "
  8444. << Time::getCurrentTime().toString (true, true)
  8445. << newLine;
  8446. outputFile.appendText (s, false, false);
  8447. }
  8448. }
  8449. PerformanceCounter::~PerformanceCounter()
  8450. {
  8451. printStatistics();
  8452. }
  8453. void PerformanceCounter::start()
  8454. {
  8455. started = Time::getHighResolutionTicks();
  8456. }
  8457. void PerformanceCounter::stop()
  8458. {
  8459. const int64 now = Time::getHighResolutionTicks();
  8460. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8461. if (++numRuns == runsPerPrint)
  8462. printStatistics();
  8463. }
  8464. void PerformanceCounter::printStatistics()
  8465. {
  8466. if (numRuns > 0)
  8467. {
  8468. String s ("Performance count for \"");
  8469. s << name << "\" - average over " << numRuns << " run(s) = ";
  8470. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8471. if (micros > 10000)
  8472. s << (micros/1000) << " millisecs";
  8473. else
  8474. s << micros << " microsecs";
  8475. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8476. Logger::outputDebugString (s);
  8477. s << newLine;
  8478. if (outputFile != File::nonexistent)
  8479. outputFile.appendText (s, false, false);
  8480. numRuns = 0;
  8481. totalTime = 0;
  8482. }
  8483. }
  8484. END_JUCE_NAMESPACE
  8485. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8486. /*** Start of inlined file: juce_Uuid.cpp ***/
  8487. BEGIN_JUCE_NAMESPACE
  8488. Uuid::Uuid()
  8489. {
  8490. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8491. // to make it very very unlikely that two UUIDs will ever be the same..
  8492. static int64 macAddresses[2];
  8493. static bool hasCheckedMacAddresses = false;
  8494. if (! hasCheckedMacAddresses)
  8495. {
  8496. hasCheckedMacAddresses = true;
  8497. Array<MACAddress> result;
  8498. MACAddress::findAllAddresses (result);
  8499. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8500. macAddresses[i] = result[i].toInt64();
  8501. }
  8502. value.asInt64[0] = macAddresses[0];
  8503. value.asInt64[1] = macAddresses[1];
  8504. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8505. // whose seed will carry over between calls to this method.
  8506. Random r (macAddresses[0] ^ macAddresses[1]
  8507. ^ Random::getSystemRandom().nextInt64());
  8508. for (int i = 4; --i >= 0;)
  8509. {
  8510. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8511. value.asInt[i] ^= r.nextInt();
  8512. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8513. }
  8514. }
  8515. Uuid::~Uuid() throw()
  8516. {
  8517. }
  8518. Uuid::Uuid (const Uuid& other)
  8519. : value (other.value)
  8520. {
  8521. }
  8522. Uuid& Uuid::operator= (const Uuid& other)
  8523. {
  8524. value = other.value;
  8525. return *this;
  8526. }
  8527. bool Uuid::operator== (const Uuid& other) const
  8528. {
  8529. return value.asInt64[0] == other.value.asInt64[0]
  8530. && value.asInt64[1] == other.value.asInt64[1];
  8531. }
  8532. bool Uuid::operator!= (const Uuid& other) const
  8533. {
  8534. return ! operator== (other);
  8535. }
  8536. bool Uuid::isNull() const throw()
  8537. {
  8538. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8539. }
  8540. const String Uuid::toString() const
  8541. {
  8542. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8543. }
  8544. Uuid::Uuid (const String& uuidString)
  8545. {
  8546. operator= (uuidString);
  8547. }
  8548. Uuid& Uuid::operator= (const String& uuidString)
  8549. {
  8550. MemoryBlock mb;
  8551. mb.loadFromHexString (uuidString);
  8552. mb.ensureSize (sizeof (value.asBytes), true);
  8553. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8554. return *this;
  8555. }
  8556. Uuid::Uuid (const uint8* const rawData)
  8557. {
  8558. operator= (rawData);
  8559. }
  8560. Uuid& Uuid::operator= (const uint8* const rawData)
  8561. {
  8562. if (rawData != 0)
  8563. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8564. else
  8565. zeromem (value.asBytes, sizeof (value.asBytes));
  8566. return *this;
  8567. }
  8568. END_JUCE_NAMESPACE
  8569. /*** End of inlined file: juce_Uuid.cpp ***/
  8570. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8571. BEGIN_JUCE_NAMESPACE
  8572. class ZipFile::ZipEntryInfo
  8573. {
  8574. public:
  8575. ZipFile::ZipEntry entry;
  8576. int streamOffset;
  8577. int compressedSize;
  8578. bool compressed;
  8579. };
  8580. class ZipFile::ZipInputStream : public InputStream
  8581. {
  8582. public:
  8583. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8584. : file (file_),
  8585. zipEntryInfo (zei),
  8586. pos (0),
  8587. headerSize (0),
  8588. inputStream (0)
  8589. {
  8590. inputStream = file_.inputStream;
  8591. if (file_.inputSource != 0)
  8592. {
  8593. inputStream = streamToDelete = file.inputSource->createInputStream();
  8594. }
  8595. else
  8596. {
  8597. #if JUCE_DEBUG
  8598. file_.numOpenStreams++;
  8599. #endif
  8600. }
  8601. char buffer [30];
  8602. if (inputStream != 0
  8603. && inputStream->setPosition (zei.streamOffset)
  8604. && inputStream->read (buffer, 30) == 30
  8605. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8606. {
  8607. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8608. + ByteOrder::littleEndianShort (buffer + 28);
  8609. }
  8610. }
  8611. ~ZipInputStream()
  8612. {
  8613. #if JUCE_DEBUG
  8614. if (inputStream != 0 && inputStream == file.inputStream)
  8615. file.numOpenStreams--;
  8616. #endif
  8617. }
  8618. int64 getTotalLength()
  8619. {
  8620. return zipEntryInfo.compressedSize;
  8621. }
  8622. int read (void* buffer, int howMany)
  8623. {
  8624. if (headerSize <= 0)
  8625. return 0;
  8626. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8627. if (inputStream == 0)
  8628. return 0;
  8629. int num;
  8630. if (inputStream == file.inputStream)
  8631. {
  8632. const ScopedLock sl (file.lock);
  8633. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8634. num = inputStream->read (buffer, howMany);
  8635. }
  8636. else
  8637. {
  8638. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8639. num = inputStream->read (buffer, howMany);
  8640. }
  8641. pos += num;
  8642. return num;
  8643. }
  8644. bool isExhausted()
  8645. {
  8646. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8647. }
  8648. int64 getPosition()
  8649. {
  8650. return pos;
  8651. }
  8652. bool setPosition (int64 newPos)
  8653. {
  8654. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8655. return true;
  8656. }
  8657. private:
  8658. ZipFile& file;
  8659. ZipEntryInfo zipEntryInfo;
  8660. int64 pos;
  8661. int headerSize;
  8662. InputStream* inputStream;
  8663. ScopedPointer<InputStream> streamToDelete;
  8664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8665. };
  8666. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8667. : inputStream (source_)
  8668. #if JUCE_DEBUG
  8669. , numOpenStreams (0)
  8670. #endif
  8671. {
  8672. if (deleteStreamWhenDestroyed)
  8673. streamToDelete = inputStream;
  8674. init();
  8675. }
  8676. ZipFile::ZipFile (const File& file)
  8677. : inputStream (0)
  8678. #if JUCE_DEBUG
  8679. , numOpenStreams (0)
  8680. #endif
  8681. {
  8682. inputSource = new FileInputSource (file);
  8683. init();
  8684. }
  8685. ZipFile::ZipFile (InputSource* const inputSource_)
  8686. : inputStream (0),
  8687. inputSource (inputSource_)
  8688. #if JUCE_DEBUG
  8689. , numOpenStreams (0)
  8690. #endif
  8691. {
  8692. init();
  8693. }
  8694. ZipFile::~ZipFile()
  8695. {
  8696. #if JUCE_DEBUG
  8697. entries.clear();
  8698. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8699. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8700. Streams can't be kept open after the file is deleted because they need to share the input
  8701. stream that the file uses to read itself.
  8702. */
  8703. jassert (numOpenStreams == 0);
  8704. #endif
  8705. }
  8706. int ZipFile::getNumEntries() const throw()
  8707. {
  8708. return entries.size();
  8709. }
  8710. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8711. {
  8712. ZipEntryInfo* const zei = entries [index];
  8713. return zei != 0 ? &(zei->entry) : 0;
  8714. }
  8715. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8716. {
  8717. for (int i = 0; i < entries.size(); ++i)
  8718. if (entries.getUnchecked (i)->entry.filename == fileName)
  8719. return i;
  8720. return -1;
  8721. }
  8722. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8723. {
  8724. return getEntry (getIndexOfFileName (fileName));
  8725. }
  8726. InputStream* ZipFile::createStreamForEntry (const int index)
  8727. {
  8728. ZipEntryInfo* const zei = entries[index];
  8729. InputStream* stream = 0;
  8730. if (zei != 0)
  8731. {
  8732. stream = new ZipInputStream (*this, *zei);
  8733. if (zei->compressed)
  8734. {
  8735. stream = new GZIPDecompressorInputStream (stream, true, true,
  8736. zei->entry.uncompressedSize);
  8737. // (much faster to unzip in big blocks using a buffer..)
  8738. stream = new BufferedInputStream (stream, 32768, true);
  8739. }
  8740. }
  8741. return stream;
  8742. }
  8743. class ZipFile::ZipFilenameComparator
  8744. {
  8745. public:
  8746. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8747. {
  8748. return first->entry.filename.compare (second->entry.filename);
  8749. }
  8750. };
  8751. void ZipFile::sortEntriesByFilename()
  8752. {
  8753. ZipFilenameComparator sorter;
  8754. entries.sort (sorter);
  8755. }
  8756. void ZipFile::init()
  8757. {
  8758. ScopedPointer <InputStream> toDelete;
  8759. InputStream* in = inputStream;
  8760. if (inputSource != 0)
  8761. {
  8762. in = inputSource->createInputStream();
  8763. toDelete = in;
  8764. }
  8765. if (in != 0)
  8766. {
  8767. int numEntries = 0;
  8768. int pos = findEndOfZipEntryTable (*in, numEntries);
  8769. if (pos >= 0 && pos < in->getTotalLength())
  8770. {
  8771. const int size = (int) (in->getTotalLength() - pos);
  8772. in->setPosition (pos);
  8773. MemoryBlock headerData;
  8774. if (in->readIntoMemoryBlock (headerData, size) == size)
  8775. {
  8776. pos = 0;
  8777. for (int i = 0; i < numEntries; ++i)
  8778. {
  8779. if (pos + 46 > size)
  8780. break;
  8781. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8782. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8783. if (pos + 46 + fileNameLen > size)
  8784. break;
  8785. ZipEntryInfo* const zei = new ZipEntryInfo();
  8786. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8787. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8788. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8789. const int year = 1980 + (date >> 9);
  8790. const int month = ((date >> 5) & 15) - 1;
  8791. const int day = date & 31;
  8792. const int hours = time >> 11;
  8793. const int minutes = (time >> 5) & 63;
  8794. const int seconds = (time & 31) << 1;
  8795. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8796. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8797. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8798. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8799. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8800. entries.add (zei);
  8801. pos += 46 + fileNameLen
  8802. + ByteOrder::littleEndianShort (buffer + 30)
  8803. + ByteOrder::littleEndianShort (buffer + 32);
  8804. }
  8805. }
  8806. }
  8807. }
  8808. }
  8809. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8810. {
  8811. BufferedInputStream in (input, 8192);
  8812. in.setPosition (in.getTotalLength());
  8813. int64 pos = in.getPosition();
  8814. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8815. char buffer [32];
  8816. zeromem (buffer, sizeof (buffer));
  8817. while (pos > lowestPos)
  8818. {
  8819. in.setPosition (pos - 22);
  8820. pos = in.getPosition();
  8821. memcpy (buffer + 22, buffer, 4);
  8822. if (in.read (buffer, 22) != 22)
  8823. return 0;
  8824. for (int i = 0; i < 22; ++i)
  8825. {
  8826. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8827. {
  8828. in.setPosition (pos + i);
  8829. in.read (buffer, 22);
  8830. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8831. return ByteOrder::littleEndianInt (buffer + 16);
  8832. }
  8833. }
  8834. }
  8835. return 0;
  8836. }
  8837. bool ZipFile::uncompressTo (const File& targetDirectory,
  8838. const bool shouldOverwriteFiles)
  8839. {
  8840. for (int i = 0; i < entries.size(); ++i)
  8841. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8842. return false;
  8843. return true;
  8844. }
  8845. bool ZipFile::uncompressEntry (const int index,
  8846. const File& targetDirectory,
  8847. bool shouldOverwriteFiles)
  8848. {
  8849. const ZipEntryInfo* zei = entries [index];
  8850. if (zei != 0)
  8851. {
  8852. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8853. if (zei->entry.filename.endsWithChar ('/'))
  8854. {
  8855. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8856. }
  8857. else
  8858. {
  8859. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8860. if (in != 0)
  8861. {
  8862. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8863. return false;
  8864. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8865. {
  8866. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8867. if (out != 0)
  8868. {
  8869. out->writeFromInputStream (*in, -1);
  8870. out = 0;
  8871. targetFile.setCreationTime (zei->entry.fileTime);
  8872. targetFile.setLastModificationTime (zei->entry.fileTime);
  8873. targetFile.setLastAccessTime (zei->entry.fileTime);
  8874. return true;
  8875. }
  8876. }
  8877. }
  8878. }
  8879. }
  8880. return false;
  8881. }
  8882. END_JUCE_NAMESPACE
  8883. /*** End of inlined file: juce_ZipFile.cpp ***/
  8884. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8885. #if JUCE_MSVC
  8886. #pragma warning (push)
  8887. #pragma warning (disable: 4514 4996)
  8888. #endif
  8889. #if ! JUCE_ANDROID
  8890. #include <cwctype>
  8891. #endif
  8892. #include <cctype>
  8893. #include <ctime>
  8894. BEGIN_JUCE_NAMESPACE
  8895. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8896. {
  8897. return towupper ((wchar_t) character);
  8898. }
  8899. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8900. {
  8901. return towlower ((wchar_t) character);
  8902. }
  8903. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8904. {
  8905. #if JUCE_WINDOWS
  8906. return iswupper ((wchar_t) character) != 0;
  8907. #else
  8908. return toLowerCase (character) != character;
  8909. #endif
  8910. }
  8911. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8912. {
  8913. #if JUCE_WINDOWS
  8914. return iswlower ((wchar_t) character) != 0;
  8915. #else
  8916. return toUpperCase (character) != character;
  8917. #endif
  8918. }
  8919. bool CharacterFunctions::isWhitespace (const char character) throw()
  8920. {
  8921. return character == ' ' || (character <= 13 && character >= 9);
  8922. }
  8923. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8924. {
  8925. return iswspace ((wchar_t) character) != 0;
  8926. }
  8927. bool CharacterFunctions::isDigit (const char character) throw()
  8928. {
  8929. return (character >= '0' && character <= '9');
  8930. }
  8931. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8932. {
  8933. return iswdigit ((wchar_t) character) != 0;
  8934. }
  8935. bool CharacterFunctions::isLetter (const char character) throw()
  8936. {
  8937. return (character >= 'a' && character <= 'z')
  8938. || (character >= 'A' && character <= 'Z');
  8939. }
  8940. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8941. {
  8942. return iswalpha ((wchar_t) character) != 0;
  8943. }
  8944. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8945. {
  8946. return (character >= 'a' && character <= 'z')
  8947. || (character >= 'A' && character <= 'Z')
  8948. || (character >= '0' && character <= '9');
  8949. }
  8950. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8951. {
  8952. return iswalnum ((wchar_t) character) != 0;
  8953. }
  8954. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8955. {
  8956. unsigned int d = digit - '0';
  8957. if (d < (unsigned int) 10)
  8958. return (int) d;
  8959. d += (unsigned int) ('0' - 'a');
  8960. if (d < (unsigned int) 6)
  8961. return (int) d + 10;
  8962. d += (unsigned int) ('a' - 'A');
  8963. if (d < (unsigned int) 6)
  8964. return (int) d + 10;
  8965. return -1;
  8966. }
  8967. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8968. {
  8969. return (int) strftime (dest, maxChars, format, tm);
  8970. }
  8971. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8972. {
  8973. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  8974. HeapBlock <char> tempDest;
  8975. tempDest.calloc (maxChars + 2);
  8976. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  8977. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  8978. return result;
  8979. #else
  8980. return (int) wcsftime (dest, maxChars, format, tm);
  8981. #endif
  8982. }
  8983. #if JUCE_MSVC
  8984. #pragma warning (pop)
  8985. #endif
  8986. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  8987. {
  8988. if (exponent == 0)
  8989. return value;
  8990. if (value == 0)
  8991. return 0;
  8992. const bool negative = (exponent < 0);
  8993. if (negative)
  8994. exponent = -exponent;
  8995. double result = 1.0, power = 10.0;
  8996. for (int bit = 1; exponent != 0; bit <<= 1)
  8997. {
  8998. if ((exponent & bit) != 0)
  8999. {
  9000. exponent ^= bit;
  9001. result *= power;
  9002. if (exponent == 0)
  9003. break;
  9004. }
  9005. power *= power;
  9006. }
  9007. return negative ? (value / result) : (value * result);
  9008. }
  9009. END_JUCE_NAMESPACE
  9010. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9011. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9012. BEGIN_JUCE_NAMESPACE
  9013. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9014. {
  9015. loadFromText (fileContents);
  9016. }
  9017. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9018. {
  9019. loadFromText (fileToLoad.loadFileAsString());
  9020. }
  9021. LocalisedStrings::~LocalisedStrings()
  9022. {
  9023. }
  9024. const String LocalisedStrings::translate (const String& text) const
  9025. {
  9026. return translations.getValue (text, text);
  9027. }
  9028. namespace
  9029. {
  9030. CriticalSection currentMappingsLock;
  9031. LocalisedStrings* currentMappings = 0;
  9032. int findCloseQuote (const String& text, int startPos)
  9033. {
  9034. juce_wchar lastChar = 0;
  9035. for (;;)
  9036. {
  9037. const juce_wchar c = text [startPos];
  9038. if (c == 0 || (c == '"' && lastChar != '\\'))
  9039. break;
  9040. lastChar = c;
  9041. ++startPos;
  9042. }
  9043. return startPos;
  9044. }
  9045. const String unescapeString (const String& s)
  9046. {
  9047. return s.replace ("\\\"", "\"")
  9048. .replace ("\\\'", "\'")
  9049. .replace ("\\t", "\t")
  9050. .replace ("\\r", "\r")
  9051. .replace ("\\n", "\n");
  9052. }
  9053. }
  9054. void LocalisedStrings::loadFromText (const String& fileContents)
  9055. {
  9056. StringArray lines;
  9057. lines.addLines (fileContents);
  9058. for (int i = 0; i < lines.size(); ++i)
  9059. {
  9060. String line (lines[i].trim());
  9061. if (line.startsWithChar ('"'))
  9062. {
  9063. int closeQuote = findCloseQuote (line, 1);
  9064. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9065. if (originalText.isNotEmpty())
  9066. {
  9067. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9068. closeQuote = findCloseQuote (line, openingQuote + 1);
  9069. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9070. if (newText.isNotEmpty())
  9071. translations.set (originalText, newText);
  9072. }
  9073. }
  9074. else if (line.startsWithIgnoreCase ("language:"))
  9075. {
  9076. languageName = line.substring (9).trim();
  9077. }
  9078. else if (line.startsWithIgnoreCase ("countries:"))
  9079. {
  9080. countryCodes.addTokens (line.substring (10).trim(), true);
  9081. countryCodes.trim();
  9082. countryCodes.removeEmptyStrings();
  9083. }
  9084. }
  9085. }
  9086. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9087. {
  9088. translations.setIgnoresCase (shouldIgnoreCase);
  9089. }
  9090. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9091. {
  9092. const ScopedLock sl (currentMappingsLock);
  9093. delete currentMappings;
  9094. currentMappings = newTranslations;
  9095. }
  9096. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9097. {
  9098. return currentMappings;
  9099. }
  9100. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9101. {
  9102. const ScopedLock sl (currentMappingsLock);
  9103. if (currentMappings != 0)
  9104. return currentMappings->translate (text);
  9105. return text;
  9106. }
  9107. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9108. {
  9109. return translateWithCurrentMappings (String (text));
  9110. }
  9111. END_JUCE_NAMESPACE
  9112. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9113. /*** Start of inlined file: juce_String.cpp ***/
  9114. #if JUCE_MSVC
  9115. #pragma warning (push)
  9116. #pragma warning (disable: 4514 4996)
  9117. #endif
  9118. #include <locale>
  9119. BEGIN_JUCE_NAMESPACE
  9120. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9121. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9122. #endif
  9123. NewLine newLine;
  9124. class StringHolder
  9125. {
  9126. public:
  9127. StringHolder()
  9128. : refCount (0x3fffffff), allocatedNumChars (0)
  9129. {
  9130. text[0] = 0;
  9131. }
  9132. typedef String::CharPointerType CharPointerType;
  9133. static const CharPointerType createUninitialised (const size_t numChars)
  9134. {
  9135. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9136. s->refCount.value = 0;
  9137. s->allocatedNumChars = numChars;
  9138. return CharPointerType (&(s->text[0]));
  9139. }
  9140. template <class CharPointer>
  9141. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9142. {
  9143. if (text.getAddress() == 0 || text.isEmpty())
  9144. return getEmpty();
  9145. const size_t numChars = text.length();
  9146. const CharPointerType dest (createUninitialised (numChars));
  9147. CharPointerType (dest).writeAll (text);
  9148. return dest;
  9149. }
  9150. template <class CharPointer>
  9151. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9152. {
  9153. if (text.getAddress() == 0 || text.isEmpty())
  9154. return getEmpty();
  9155. size_t numChars = text.lengthUpTo (maxChars);
  9156. if (numChars == 0)
  9157. return getEmpty();
  9158. const CharPointerType dest (createUninitialised (numChars));
  9159. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9160. return dest;
  9161. }
  9162. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9163. {
  9164. CharPointerType dest (createUninitialised (numChars));
  9165. copyChars (dest, CharPointerType (src), (int) numChars);
  9166. return dest;
  9167. }
  9168. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9169. {
  9170. const CharPointerType dest (createUninitialised (numChars));
  9171. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9172. return dest;
  9173. }
  9174. static inline const CharPointerType getEmpty() throw()
  9175. {
  9176. return CharPointerType (&(empty.text[0]));
  9177. }
  9178. static void retain (const CharPointerType& text) throw()
  9179. {
  9180. ++(bufferFromText (text)->refCount);
  9181. }
  9182. static inline void release (StringHolder* const b) throw()
  9183. {
  9184. if (--(b->refCount) == -1 && b != &empty)
  9185. delete[] reinterpret_cast <char*> (b);
  9186. }
  9187. static void release (const CharPointerType& text) throw()
  9188. {
  9189. release (bufferFromText (text));
  9190. }
  9191. static CharPointerType makeUnique (const CharPointerType& text)
  9192. {
  9193. StringHolder* const b = bufferFromText (text);
  9194. if (b->refCount.get() <= 0)
  9195. return text;
  9196. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9197. release (b);
  9198. return newText;
  9199. }
  9200. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9201. {
  9202. StringHolder* const b = bufferFromText (text);
  9203. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9204. return text;
  9205. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9206. copyChars (newText, text, b->allocatedNumChars);
  9207. release (b);
  9208. return newText;
  9209. }
  9210. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9211. {
  9212. return bufferFromText (text)->allocatedNumChars;
  9213. }
  9214. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9215. {
  9216. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9217. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9218. CharPointerType (dest + (int) numChars).writeNull();
  9219. }
  9220. Atomic<int> refCount;
  9221. size_t allocatedNumChars;
  9222. juce_wchar text[1];
  9223. static StringHolder empty;
  9224. private:
  9225. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9226. {
  9227. // (Can't use offsetof() here because of warnings about this not being a POD)
  9228. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9229. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9230. }
  9231. };
  9232. StringHolder StringHolder::empty;
  9233. const String String::empty;
  9234. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9235. {
  9236. if (numExtraChars > 0)
  9237. {
  9238. const int oldLen = length();
  9239. const int newTotalLen = oldLen + numExtraChars;
  9240. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9241. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9242. }
  9243. }
  9244. void String::preallocateStorage (const size_t numChars)
  9245. {
  9246. text = StringHolder::makeUniqueWithSize (text, numChars);
  9247. }
  9248. String::String() throw()
  9249. : text (StringHolder::getEmpty())
  9250. {
  9251. }
  9252. String::~String() throw()
  9253. {
  9254. StringHolder::release (text);
  9255. }
  9256. String::String (const String& other) throw()
  9257. : text (other.text)
  9258. {
  9259. StringHolder::retain (text);
  9260. }
  9261. void String::swapWith (String& other) throw()
  9262. {
  9263. swapVariables (text, other.text);
  9264. }
  9265. String& String::operator= (const String& other) throw()
  9266. {
  9267. StringHolder::retain (other.text);
  9268. StringHolder::release (text.atomicSwap (other.text));
  9269. return *this;
  9270. }
  9271. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9272. String::String (const Preallocation& preallocationSize)
  9273. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9274. {
  9275. }
  9276. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9277. : text (0)
  9278. {
  9279. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9280. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9281. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9282. }
  9283. String::String (const char* const t)
  9284. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t)))
  9285. {
  9286. }
  9287. String::String (const juce_wchar* const t)
  9288. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9289. {
  9290. }
  9291. String::String (const CharPointer_UTF8& t)
  9292. : text (StringHolder::createFromCharPointer (t))
  9293. {
  9294. }
  9295. String::String (const CharPointer_UTF16& t)
  9296. : text (StringHolder::createFromCharPointer (t))
  9297. {
  9298. }
  9299. String::String (const CharPointer_UTF32& t)
  9300. : text (StringHolder::createFromCharPointer (t))
  9301. {
  9302. }
  9303. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9304. : text (StringHolder::createFromCharPointer (t, maxChars))
  9305. {
  9306. }
  9307. #if JUCE_WINDOWS
  9308. String::String (const wchar_t* const t)
  9309. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t)))
  9310. {
  9311. }
  9312. String::String (const wchar_t* const t, size_t maxChars)
  9313. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t), maxChars))
  9314. {
  9315. }
  9316. #endif
  9317. String::String (const char* const t, const size_t maxChars)
  9318. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t), maxChars))
  9319. {
  9320. }
  9321. String::String (const juce_wchar* const t, const size_t maxChars)
  9322. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9323. {
  9324. }
  9325. const String String::charToString (const juce_wchar character)
  9326. {
  9327. String result (Preallocation (1));
  9328. result.text[0] = character;
  9329. result.text[1] = 0;
  9330. return result;
  9331. }
  9332. namespace NumberToStringConverters
  9333. {
  9334. // pass in a pointer to the END of a buffer..
  9335. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9336. {
  9337. *--t = 0;
  9338. int64 v = (n >= 0) ? n : -n;
  9339. do
  9340. {
  9341. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9342. v /= 10;
  9343. } while (v > 0);
  9344. if (n < 0)
  9345. *--t = '-';
  9346. return t;
  9347. }
  9348. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9349. {
  9350. *--t = 0;
  9351. do
  9352. {
  9353. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9354. v /= 10;
  9355. } while (v > 0);
  9356. return t;
  9357. }
  9358. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9359. {
  9360. if (n == (int) 0x80000000) // (would cause an overflow)
  9361. return numberToString (t, (int64) n);
  9362. *--t = 0;
  9363. int v = abs (n);
  9364. do
  9365. {
  9366. *--t = (juce_wchar) ('0' + (v % 10));
  9367. v /= 10;
  9368. } while (v > 0);
  9369. if (n < 0)
  9370. *--t = '-';
  9371. return t;
  9372. }
  9373. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9374. {
  9375. *--t = 0;
  9376. do
  9377. {
  9378. *--t = (juce_wchar) ('0' + (v % 10));
  9379. v /= 10;
  9380. } while (v > 0);
  9381. return t;
  9382. }
  9383. juce_wchar getDecimalPoint()
  9384. {
  9385. #if JUCE_VC7_OR_EARLIER
  9386. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9387. #else
  9388. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9389. #endif
  9390. return dp;
  9391. }
  9392. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9393. {
  9394. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9395. {
  9396. char* const end = buffer + numChars;
  9397. char* t = end;
  9398. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9399. *--t = (char) 0;
  9400. while (numDecPlaces >= 0 || v > 0)
  9401. {
  9402. if (numDecPlaces == 0)
  9403. *--t = (char) getDecimalPoint();
  9404. *--t = (char) ('0' + (v % 10));
  9405. v /= 10;
  9406. --numDecPlaces;
  9407. }
  9408. if (n < 0)
  9409. *--t = '-';
  9410. len = end - t - 1;
  9411. return t;
  9412. }
  9413. else
  9414. {
  9415. len = sprintf (buffer, "%.9g", n);
  9416. return buffer;
  9417. }
  9418. }
  9419. template <typename IntegerType>
  9420. const String::CharPointerType createFromInteger (const IntegerType number)
  9421. {
  9422. juce_wchar buffer [32];
  9423. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9424. juce_wchar* const start = numberToString (end, number);
  9425. return StringHolder::createFromFixedLength (start, end - start - 1);
  9426. }
  9427. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9428. {
  9429. char buffer [48];
  9430. size_t len;
  9431. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9432. return StringHolder::createFromFixedLength (start, len);
  9433. }
  9434. }
  9435. String::String (const int number)
  9436. : text (NumberToStringConverters::createFromInteger (number))
  9437. {
  9438. }
  9439. String::String (const unsigned int number)
  9440. : text (NumberToStringConverters::createFromInteger (number))
  9441. {
  9442. }
  9443. String::String (const short number)
  9444. : text (NumberToStringConverters::createFromInteger ((int) number))
  9445. {
  9446. }
  9447. String::String (const unsigned short number)
  9448. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9449. {
  9450. }
  9451. String::String (const int64 number)
  9452. : text (NumberToStringConverters::createFromInteger (number))
  9453. {
  9454. }
  9455. String::String (const uint64 number)
  9456. : text (NumberToStringConverters::createFromInteger (number))
  9457. {
  9458. }
  9459. String::String (const float number, const int numberOfDecimalPlaces)
  9460. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9461. {
  9462. }
  9463. String::String (const double number, const int numberOfDecimalPlaces)
  9464. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9465. {
  9466. }
  9467. int String::length() const throw()
  9468. {
  9469. return (int) text.length();
  9470. }
  9471. int String::hashCode() const throw()
  9472. {
  9473. const juce_wchar* t = text;
  9474. int result = 0;
  9475. while (*t != (juce_wchar) 0)
  9476. result = 31 * result + *t++;
  9477. return result;
  9478. }
  9479. int64 String::hashCode64() const throw()
  9480. {
  9481. const juce_wchar* t = text;
  9482. int64 result = 0;
  9483. while (*t != (juce_wchar) 0)
  9484. result = 101 * result + *t++;
  9485. return result;
  9486. }
  9487. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9488. {
  9489. return string1.compare (string2) == 0;
  9490. }
  9491. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9492. {
  9493. return string1.compare (string2) == 0;
  9494. }
  9495. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9496. {
  9497. return string1.compare (string2) == 0;
  9498. }
  9499. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9500. {
  9501. return string1.getCharPointer().compare (string2) == 0;
  9502. }
  9503. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9504. {
  9505. return string1.getCharPointer().compare (string2) == 0;
  9506. }
  9507. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9508. {
  9509. return string1.getCharPointer().compare (string2) == 0;
  9510. }
  9511. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9512. {
  9513. return string1.compare (string2) != 0;
  9514. }
  9515. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9516. {
  9517. return string1.compare (string2) != 0;
  9518. }
  9519. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9520. {
  9521. return string1.compare (string2) != 0;
  9522. }
  9523. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9524. {
  9525. return string1.getCharPointer().compare (string2) != 0;
  9526. }
  9527. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9528. {
  9529. return string1.getCharPointer().compare (string2) != 0;
  9530. }
  9531. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9532. {
  9533. return string1.getCharPointer().compare (string2) != 0;
  9534. }
  9535. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9536. {
  9537. return string1.compare (string2) > 0;
  9538. }
  9539. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9540. {
  9541. return string1.compare (string2) < 0;
  9542. }
  9543. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9544. {
  9545. return string1.compare (string2) >= 0;
  9546. }
  9547. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9548. {
  9549. return string1.compare (string2) <= 0;
  9550. }
  9551. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9552. {
  9553. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9554. : isEmpty();
  9555. }
  9556. bool String::equalsIgnoreCase (const char* t) const throw()
  9557. {
  9558. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9559. : isEmpty();
  9560. }
  9561. bool String::equalsIgnoreCase (const String& other) const throw()
  9562. {
  9563. return text == other.text
  9564. || text.compareIgnoreCase (other.text) == 0;
  9565. }
  9566. int String::compare (const String& other) const throw()
  9567. {
  9568. return (text == other.text) ? 0 : text.compare (other.text);
  9569. }
  9570. int String::compare (const char* other) const throw()
  9571. {
  9572. return text.compare (CharPointer_UTF8 (other));
  9573. }
  9574. int String::compare (const juce_wchar* other) const throw()
  9575. {
  9576. return text.compare (CharPointer_UTF32 (other));
  9577. }
  9578. int String::compareIgnoreCase (const String& other) const throw()
  9579. {
  9580. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9581. }
  9582. int String::compareLexicographically (const String& other) const throw()
  9583. {
  9584. CharPointerType s1 (text);
  9585. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9586. ++s1;
  9587. CharPointerType s2 (other.text);
  9588. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9589. ++s2;
  9590. return s1.compareIgnoreCase (s2);
  9591. }
  9592. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9593. {
  9594. appendCharPointer (textToAppend.text, maxCharsToTake);
  9595. }
  9596. String& String::operator+= (const juce_wchar* const t)
  9597. {
  9598. appendCharPointer (CharPointer_UTF32 (t));
  9599. return *this;
  9600. }
  9601. String& String::operator+= (const String& other)
  9602. {
  9603. if (isEmpty())
  9604. return operator= (other);
  9605. appendCharPointer (other.text);
  9606. return *this;
  9607. }
  9608. String& String::operator+= (const char ch)
  9609. {
  9610. return operator+= ((juce_wchar) ch);
  9611. }
  9612. String& String::operator+= (const juce_wchar ch)
  9613. {
  9614. const juce_wchar asString[] = { ch, 0 };
  9615. return operator+= (static_cast <const juce_wchar*> (asString));
  9616. }
  9617. #if JUCE_WINDOWS
  9618. String& String::operator+= (wchar_t ch)
  9619. {
  9620. return operator+= ((juce_wchar) ch);
  9621. }
  9622. String& String::operator+= (const wchar_t* t)
  9623. {
  9624. return operator+= (String (t));
  9625. }
  9626. #endif
  9627. String& String::operator+= (const int number)
  9628. {
  9629. juce_wchar buffer [16];
  9630. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9631. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9632. appendFixedLength (start, (int) (end - start));
  9633. return *this;
  9634. }
  9635. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9636. {
  9637. String s (string1);
  9638. return s += string2;
  9639. }
  9640. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9641. {
  9642. String s (string1);
  9643. return s += string2;
  9644. }
  9645. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9646. {
  9647. return String::charToString (string1) + string2;
  9648. }
  9649. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9650. {
  9651. return String::charToString (string1) + string2;
  9652. }
  9653. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9654. {
  9655. return string1 += string2;
  9656. }
  9657. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9658. {
  9659. return string1 += string2;
  9660. }
  9661. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9662. {
  9663. return string1 += string2;
  9664. }
  9665. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9666. {
  9667. return string1 += string2;
  9668. }
  9669. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9670. {
  9671. return string1 += string2;
  9672. }
  9673. #if JUCE_WINDOWS
  9674. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9675. {
  9676. return string1 += string2;
  9677. }
  9678. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9679. {
  9680. string1.appendCharPointer (CharPointer_UTF16 (string2));
  9681. return string1;
  9682. }
  9683. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9684. {
  9685. String s (string1);
  9686. return s += string2;
  9687. }
  9688. #endif
  9689. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9690. {
  9691. return string1 += characterToAppend;
  9692. }
  9693. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9694. {
  9695. return string1 += characterToAppend;
  9696. }
  9697. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9698. {
  9699. return string1 += string2;
  9700. }
  9701. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9702. {
  9703. return string1 += string2;
  9704. }
  9705. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9706. {
  9707. return string1 += string2;
  9708. }
  9709. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9710. {
  9711. return string1 += (int) number;
  9712. }
  9713. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9714. {
  9715. return string1 += number;
  9716. }
  9717. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9718. {
  9719. return string1 += (int) number;
  9720. }
  9721. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9722. {
  9723. return string1 += String (number);
  9724. }
  9725. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9726. {
  9727. return string1 += String (number);
  9728. }
  9729. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9730. {
  9731. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9732. // if lots of large, persistent strings were to be written to streams).
  9733. const int numBytes = text.getNumBytesAsUTF8();
  9734. HeapBlock<char> temp (numBytes + 1);
  9735. text.copyToUTF8 (temp, numBytes + 1);
  9736. stream.write (temp, numBytes);
  9737. return stream;
  9738. }
  9739. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9740. {
  9741. return string1 += NewLine::getDefault();
  9742. }
  9743. int String::indexOfChar (const juce_wchar character) const throw()
  9744. {
  9745. const juce_wchar* t = text;
  9746. for (;;)
  9747. {
  9748. if (*t == character)
  9749. return (int) (t - text);
  9750. if (*t++ == 0)
  9751. return -1;
  9752. }
  9753. }
  9754. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9755. {
  9756. for (int i = length(); --i >= 0;)
  9757. if (text[i] == character)
  9758. return i;
  9759. return -1;
  9760. }
  9761. int String::indexOf (const String& t) const throw()
  9762. {
  9763. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9764. }
  9765. int String::indexOfChar (const int startIndex,
  9766. const juce_wchar character) const throw()
  9767. {
  9768. if (startIndex > 0 && startIndex >= length())
  9769. return -1;
  9770. const juce_wchar* t = text + jmax (0, startIndex);
  9771. for (;;)
  9772. {
  9773. if (*t == character)
  9774. return (int) (t - text);
  9775. if (*t == 0)
  9776. return -1;
  9777. ++t;
  9778. }
  9779. }
  9780. int String::indexOfAnyOf (const String& charactersToLookFor,
  9781. const int startIndex,
  9782. const bool ignoreCase) const throw()
  9783. {
  9784. if (startIndex > 0 && startIndex >= length())
  9785. return -1;
  9786. CharPointerType t (text);
  9787. int i = jmax (0, startIndex);
  9788. t += i;
  9789. while (! t.isEmpty())
  9790. {
  9791. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9792. return i;
  9793. ++i;
  9794. ++t;
  9795. }
  9796. return -1;
  9797. }
  9798. int String::indexOf (const int startIndex, const String& other) const throw()
  9799. {
  9800. if (startIndex > 0 && startIndex >= length())
  9801. return -1;
  9802. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9803. return i >= 0 ? i + startIndex : -1;
  9804. }
  9805. int String::indexOfIgnoreCase (const String& other) const throw()
  9806. {
  9807. if (other.isEmpty())
  9808. return 0;
  9809. const int len = other.length();
  9810. const int end = length() - len;
  9811. for (int i = 0; i <= end; ++i)
  9812. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9813. return i;
  9814. return -1;
  9815. }
  9816. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9817. {
  9818. if (other.isNotEmpty())
  9819. {
  9820. const int len = other.length();
  9821. const int end = length() - len;
  9822. for (int i = jmax (0, startIndex); i <= end; ++i)
  9823. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9824. return i;
  9825. }
  9826. return -1;
  9827. }
  9828. int String::lastIndexOf (const String& other) const throw()
  9829. {
  9830. if (other.isNotEmpty())
  9831. {
  9832. const int len = other.length();
  9833. int i = length() - len;
  9834. if (i >= 0)
  9835. {
  9836. CharPointerType n (text + i);
  9837. while (i >= 0)
  9838. {
  9839. if (n.compareUpTo (other.text, len) == 0)
  9840. return i;
  9841. --n;
  9842. --i;
  9843. }
  9844. }
  9845. }
  9846. return -1;
  9847. }
  9848. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9849. {
  9850. if (other.isNotEmpty())
  9851. {
  9852. const int len = other.length();
  9853. int i = length() - len;
  9854. if (i >= 0)
  9855. {
  9856. CharPointerType n (text + i);
  9857. while (i >= 0)
  9858. {
  9859. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9860. return i;
  9861. --n;
  9862. --i;
  9863. }
  9864. }
  9865. }
  9866. return -1;
  9867. }
  9868. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9869. {
  9870. for (int i = length(); --i >= 0;)
  9871. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9872. return i;
  9873. return -1;
  9874. }
  9875. bool String::contains (const String& other) const throw()
  9876. {
  9877. return indexOf (other) >= 0;
  9878. }
  9879. bool String::containsChar (const juce_wchar character) const throw()
  9880. {
  9881. const juce_wchar* t = text;
  9882. for (;;)
  9883. {
  9884. if (*t == 0)
  9885. return false;
  9886. if (*t == character)
  9887. return true;
  9888. ++t;
  9889. }
  9890. }
  9891. bool String::containsIgnoreCase (const String& t) const throw()
  9892. {
  9893. return indexOfIgnoreCase (t) >= 0;
  9894. }
  9895. int String::indexOfWholeWord (const String& word) const throw()
  9896. {
  9897. if (word.isNotEmpty())
  9898. {
  9899. CharPointerType t (text);
  9900. const int wordLen = word.length();
  9901. const int end = (int) t.length() - wordLen;
  9902. for (int i = 0; i <= end; ++i)
  9903. {
  9904. if (t.compareUpTo (word.text, wordLen) == 0
  9905. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9906. && ! (t + wordLen).isLetterOrDigit())
  9907. return i;
  9908. ++t;
  9909. }
  9910. }
  9911. return -1;
  9912. }
  9913. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9914. {
  9915. if (word.isNotEmpty())
  9916. {
  9917. CharPointerType t (text);
  9918. const int wordLen = word.length();
  9919. const int end = (int) t.length() - wordLen;
  9920. for (int i = 0; i <= end; ++i)
  9921. {
  9922. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  9923. && (i == 0 || ! (t + -1).isLetterOrDigit())
  9924. && ! (t + wordLen).isLetterOrDigit())
  9925. return i;
  9926. ++t;
  9927. }
  9928. }
  9929. return -1;
  9930. }
  9931. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9932. {
  9933. return indexOfWholeWord (wordToLookFor) >= 0;
  9934. }
  9935. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9936. {
  9937. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9938. }
  9939. namespace WildCardHelpers
  9940. {
  9941. int indexOfMatch (const String::CharPointerType& wildcard,
  9942. String::CharPointerType test,
  9943. const bool ignoreCase) throw()
  9944. {
  9945. int start = 0;
  9946. while (! test.isEmpty())
  9947. {
  9948. String::CharPointerType t (test);
  9949. String::CharPointerType w (wildcard);
  9950. for (;;)
  9951. {
  9952. const juce_wchar wc = *w;
  9953. const juce_wchar tc = *t;
  9954. if (wc == tc
  9955. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9956. || (wc == '?' && tc != 0))
  9957. {
  9958. if (wc == 0)
  9959. return start;
  9960. ++t;
  9961. ++w;
  9962. }
  9963. else
  9964. {
  9965. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  9966. return start;
  9967. break;
  9968. }
  9969. }
  9970. ++start;
  9971. ++test;
  9972. }
  9973. return -1;
  9974. }
  9975. }
  9976. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9977. {
  9978. CharPointerType w (wildcard.text);
  9979. CharPointerType t (text);
  9980. for (;;)
  9981. {
  9982. const juce_wchar wc = *w;
  9983. const juce_wchar tc = *t;
  9984. if (wc == tc
  9985. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9986. || (wc == '?' && tc != 0))
  9987. {
  9988. if (wc == 0)
  9989. return true;
  9990. ++w;
  9991. ++t;
  9992. }
  9993. else
  9994. {
  9995. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  9996. }
  9997. }
  9998. }
  9999. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10000. {
  10001. if (numberOfTimesToRepeat <= 0)
  10002. return String::empty;
  10003. const int len = stringToRepeat.length();
  10004. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10005. CharPointerType n (result.text);
  10006. while (--numberOfTimesToRepeat >= 0)
  10007. {
  10008. StringHolder::copyChars (n, stringToRepeat.text, len);
  10009. n += len;
  10010. }
  10011. return result;
  10012. }
  10013. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10014. {
  10015. jassert (padCharacter != 0);
  10016. const int len = length();
  10017. if (len >= minimumLength || padCharacter == 0)
  10018. return *this;
  10019. String result (Preallocation (minimumLength + 1));
  10020. CharPointerType n (result.text);
  10021. minimumLength -= len;
  10022. while (--minimumLength >= 0)
  10023. n.write (padCharacter);
  10024. StringHolder::copyChars (n, text, len);
  10025. return result;
  10026. }
  10027. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10028. {
  10029. jassert (padCharacter != 0);
  10030. const int len = length();
  10031. if (len >= minimumLength || padCharacter == 0)
  10032. return *this;
  10033. String result (*this, (size_t) minimumLength);
  10034. CharPointerType n (result.text + len);
  10035. minimumLength -= len;
  10036. while (--minimumLength >= 0)
  10037. n.write (padCharacter);
  10038. n.writeNull();
  10039. return result;
  10040. }
  10041. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10042. {
  10043. if (index < 0)
  10044. {
  10045. // a negative index to replace from?
  10046. jassertfalse;
  10047. index = 0;
  10048. }
  10049. if (numCharsToReplace < 0)
  10050. {
  10051. // replacing a negative number of characters?
  10052. numCharsToReplace = 0;
  10053. jassertfalse;
  10054. }
  10055. const int len = length();
  10056. if (index + numCharsToReplace > len)
  10057. {
  10058. if (index > len)
  10059. {
  10060. // replacing beyond the end of the string?
  10061. index = len;
  10062. jassertfalse;
  10063. }
  10064. numCharsToReplace = len - index;
  10065. }
  10066. const int newStringLen = stringToInsert.length();
  10067. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10068. if (newTotalLen <= 0)
  10069. return String::empty;
  10070. String result (Preallocation ((size_t) newTotalLen));
  10071. StringHolder::copyChars (result.text, text, index);
  10072. if (newStringLen > 0)
  10073. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10074. const int endStringLen = newTotalLen - (index + newStringLen);
  10075. if (endStringLen > 0)
  10076. StringHolder::copyChars (result.text + (index + newStringLen),
  10077. text + (index + numCharsToReplace),
  10078. endStringLen);
  10079. return result;
  10080. }
  10081. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10082. {
  10083. const int stringToReplaceLen = stringToReplace.length();
  10084. const int stringToInsertLen = stringToInsert.length();
  10085. int i = 0;
  10086. String result (*this);
  10087. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10088. : result.indexOf (i, stringToReplace))) >= 0)
  10089. {
  10090. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10091. i += stringToInsertLen;
  10092. }
  10093. return result;
  10094. }
  10095. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10096. {
  10097. const int index = indexOfChar (charToReplace);
  10098. if (index < 0)
  10099. return *this;
  10100. String result (*this, size_t());
  10101. CharPointerType t (result.text + index);
  10102. while (! t.isEmpty())
  10103. {
  10104. if (*t == charToReplace)
  10105. t.replaceChar (charToInsert);
  10106. ++t;
  10107. }
  10108. return result;
  10109. }
  10110. const String String::replaceCharacters (const String& charactersToReplace,
  10111. const String& charactersToInsertInstead) const
  10112. {
  10113. String result (*this, size_t());
  10114. CharPointerType t (result.text);
  10115. const int len2 = charactersToInsertInstead.length();
  10116. // the two strings passed in are supposed to be the same length!
  10117. jassert (len2 == charactersToReplace.length());
  10118. while (! t.isEmpty())
  10119. {
  10120. const int index = charactersToReplace.indexOfChar (*t);
  10121. if (isPositiveAndBelow (index, len2))
  10122. t.replaceChar (charactersToInsertInstead [index]);
  10123. ++t;
  10124. }
  10125. return result;
  10126. }
  10127. bool String::startsWith (const String& other) const throw()
  10128. {
  10129. return text.compareUpTo (other.text, other.length()) == 0;
  10130. }
  10131. bool String::startsWithIgnoreCase (const String& other) const throw()
  10132. {
  10133. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10134. }
  10135. bool String::startsWithChar (const juce_wchar character) const throw()
  10136. {
  10137. jassert (character != 0); // strings can't contain a null character!
  10138. return text[0] == character;
  10139. }
  10140. bool String::endsWithChar (const juce_wchar character) const throw()
  10141. {
  10142. jassert (character != 0); // strings can't contain a null character!
  10143. return text[0] != 0
  10144. && text [length() - 1] == character;
  10145. }
  10146. bool String::endsWith (const String& other) const throw()
  10147. {
  10148. const int thisLen = length();
  10149. const int otherLen = other.length();
  10150. return thisLen >= otherLen
  10151. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10152. }
  10153. bool String::endsWithIgnoreCase (const String& other) const throw()
  10154. {
  10155. const int thisLen = length();
  10156. const int otherLen = other.length();
  10157. return thisLen >= otherLen
  10158. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10159. }
  10160. const String String::toUpperCase() const
  10161. {
  10162. String result (Preallocation (this->length()));
  10163. CharPointerType dest (result.text);
  10164. CharPointerType src (text);
  10165. for (;;)
  10166. {
  10167. const juce_wchar c = src.toUpperCase();
  10168. dest.write (c);
  10169. if (c == 0)
  10170. break;
  10171. ++src;
  10172. }
  10173. return result;
  10174. }
  10175. const String String::toLowerCase() const
  10176. {
  10177. String result (Preallocation (this->length()));
  10178. CharPointerType dest (result.text);
  10179. CharPointerType src (text);
  10180. for (;;)
  10181. {
  10182. const juce_wchar c = src.toLowerCase();
  10183. dest.write (c);
  10184. if (c == 0)
  10185. break;
  10186. ++src;
  10187. }
  10188. return result;
  10189. }
  10190. juce_wchar& String::operator[] (const int index)
  10191. {
  10192. jassert (isPositiveAndNotGreaterThan (index, length()));
  10193. text = StringHolder::makeUnique (text);
  10194. return text [index];
  10195. }
  10196. juce_wchar String::getLastCharacter() const throw()
  10197. {
  10198. return isEmpty() ? juce_wchar() : text [length() - 1];
  10199. }
  10200. const String String::substring (int start, int end) const
  10201. {
  10202. if (start < 0)
  10203. start = 0;
  10204. else if (end <= start)
  10205. return empty;
  10206. int len = 0;
  10207. while (len <= end && text [len] != 0)
  10208. ++len;
  10209. if (end >= len)
  10210. {
  10211. if (start == 0)
  10212. return *this;
  10213. end = len;
  10214. }
  10215. return String (text + start, end - start);
  10216. }
  10217. const String String::substring (const int start) const
  10218. {
  10219. if (start <= 0)
  10220. return *this;
  10221. const int len = length();
  10222. if (start >= len)
  10223. return empty;
  10224. return String (text + start, len - start);
  10225. }
  10226. const String String::dropLastCharacters (const int numberToDrop) const
  10227. {
  10228. return String (text, jmax (0, length() - numberToDrop));
  10229. }
  10230. const String String::getLastCharacters (const int numCharacters) const
  10231. {
  10232. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10233. }
  10234. const String String::fromFirstOccurrenceOf (const String& sub,
  10235. const bool includeSubString,
  10236. const bool ignoreCase) const
  10237. {
  10238. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10239. : indexOf (sub);
  10240. if (i < 0)
  10241. return empty;
  10242. return substring (includeSubString ? i : i + sub.length());
  10243. }
  10244. const String String::fromLastOccurrenceOf (const String& sub,
  10245. const bool includeSubString,
  10246. const bool ignoreCase) const
  10247. {
  10248. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10249. : lastIndexOf (sub);
  10250. if (i < 0)
  10251. return *this;
  10252. return substring (includeSubString ? i : i + sub.length());
  10253. }
  10254. const String String::upToFirstOccurrenceOf (const String& sub,
  10255. const bool includeSubString,
  10256. const bool ignoreCase) const
  10257. {
  10258. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10259. : indexOf (sub);
  10260. if (i < 0)
  10261. return *this;
  10262. return substring (0, includeSubString ? i + sub.length() : i);
  10263. }
  10264. const String String::upToLastOccurrenceOf (const String& sub,
  10265. const bool includeSubString,
  10266. const bool ignoreCase) const
  10267. {
  10268. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10269. : lastIndexOf (sub);
  10270. if (i < 0)
  10271. return *this;
  10272. return substring (0, includeSubString ? i + sub.length() : i);
  10273. }
  10274. bool String::isQuotedString() const
  10275. {
  10276. const String trimmed (trimStart());
  10277. return trimmed[0] == '"'
  10278. || trimmed[0] == '\'';
  10279. }
  10280. const String String::unquoted() const
  10281. {
  10282. String s (*this);
  10283. if (s.text[0] == '"' || s.text[0] == '\'')
  10284. s = s.substring (1);
  10285. const int lastCharIndex = s.length() - 1;
  10286. if (lastCharIndex >= 0
  10287. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10288. s [lastCharIndex] = 0;
  10289. return s;
  10290. }
  10291. const String String::quoted (const juce_wchar quoteCharacter) const
  10292. {
  10293. if (isEmpty())
  10294. return charToString (quoteCharacter) + quoteCharacter;
  10295. String t (*this);
  10296. if (! t.startsWithChar (quoteCharacter))
  10297. t = charToString (quoteCharacter) + t;
  10298. if (! t.endsWithChar (quoteCharacter))
  10299. t += quoteCharacter;
  10300. return t;
  10301. }
  10302. const String String::trim() const
  10303. {
  10304. if (isEmpty())
  10305. return empty;
  10306. int start = 0;
  10307. while ((text + start).isWhitespace())
  10308. ++start;
  10309. const int len = length();
  10310. int end = len - 1;
  10311. while ((end >= start) && (text + end).isWhitespace())
  10312. --end;
  10313. ++end;
  10314. if (end <= start)
  10315. return empty;
  10316. else if (start > 0 || end < len)
  10317. return String (text + start, end - start);
  10318. return *this;
  10319. }
  10320. const String String::trimStart() const
  10321. {
  10322. if (isEmpty())
  10323. return empty;
  10324. CharPointerType t (text);
  10325. while (t.isWhitespace())
  10326. ++t;
  10327. if (t == text)
  10328. return *this;
  10329. return String (t.getAddress());
  10330. }
  10331. const String String::trimEnd() const
  10332. {
  10333. if (isEmpty())
  10334. return empty;
  10335. CharPointerType endT (text);
  10336. endT = endT.findTerminatingNull() - 1;
  10337. while ((endT.getAddress() >= text) && endT.isWhitespace())
  10338. --endT;
  10339. return String (text, 1 + (int) (endT.getAddress() - text));
  10340. }
  10341. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10342. {
  10343. CharPointerType t (text);
  10344. while (charactersToTrim.containsChar (*t))
  10345. ++t;
  10346. return t == text ? *this : String (t);
  10347. }
  10348. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10349. {
  10350. if (isEmpty())
  10351. return empty;
  10352. const int len = length();
  10353. const juce_wchar* endT = text + (len - 1);
  10354. int numToRemove = 0;
  10355. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10356. {
  10357. ++numToRemove;
  10358. --endT;
  10359. }
  10360. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10361. }
  10362. const String String::retainCharacters (const String& charactersToRetain) const
  10363. {
  10364. if (isEmpty())
  10365. return empty;
  10366. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10367. CharPointerType dst (result.text);
  10368. CharPointerType src (text);
  10369. for (;;)
  10370. {
  10371. const juce_wchar c = src.getAndAdvance();
  10372. if (c == 0)
  10373. break;
  10374. if (charactersToRetain.containsChar (c))
  10375. dst.write (c);
  10376. }
  10377. dst.writeNull();
  10378. return result;
  10379. }
  10380. const String String::removeCharacters (const String& charactersToRemove) const
  10381. {
  10382. if (isEmpty())
  10383. return empty;
  10384. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10385. CharPointerType dst (result.text);
  10386. CharPointerType src (text);
  10387. for (;;)
  10388. {
  10389. const juce_wchar c = src.getAndAdvance();
  10390. if (c == 0)
  10391. break;
  10392. if (! charactersToRemove.containsChar (c))
  10393. dst.write (c);
  10394. }
  10395. dst.writeNull();
  10396. return result;
  10397. }
  10398. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10399. {
  10400. int i = 0;
  10401. for (;;)
  10402. {
  10403. if (! permittedCharacters.containsChar (text[i]))
  10404. break;
  10405. ++i;
  10406. }
  10407. return substring (0, i);
  10408. }
  10409. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10410. {
  10411. const juce_wchar* const t = text;
  10412. int i = 0;
  10413. while (t[i] != 0)
  10414. {
  10415. if (charactersToStopAt.containsChar (t[i]))
  10416. return String (text, i);
  10417. ++i;
  10418. }
  10419. return empty;
  10420. }
  10421. bool String::containsOnly (const String& chars) const throw()
  10422. {
  10423. CharPointerType t (text);
  10424. while (! t.isEmpty())
  10425. if (! chars.containsChar (t.getAndAdvance()))
  10426. return false;
  10427. return true;
  10428. }
  10429. bool String::containsAnyOf (const String& chars) const throw()
  10430. {
  10431. const juce_wchar* t = text;
  10432. while (*t != 0)
  10433. if (chars.containsChar (*t++))
  10434. return true;
  10435. return false;
  10436. }
  10437. bool String::containsNonWhitespaceChars() const throw()
  10438. {
  10439. CharPointerType t (text);
  10440. while (! t.isEmpty())
  10441. {
  10442. if (! t.isWhitespace())
  10443. return true;
  10444. ++t;
  10445. }
  10446. return false;
  10447. }
  10448. const String String::formatted (const juce_wchar* const pf, ... )
  10449. {
  10450. jassert (pf != 0);
  10451. va_list args;
  10452. va_start (args, pf);
  10453. size_t bufferSize = 256;
  10454. String result (Preallocation ((size_t) bufferSize));
  10455. result.text[0] = 0;
  10456. for (;;)
  10457. {
  10458. #if JUCE_LINUX && JUCE_64BIT
  10459. va_list tempArgs;
  10460. va_copy (tempArgs, args);
  10461. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10462. va_end (tempArgs);
  10463. #elif JUCE_WINDOWS
  10464. HeapBlock <wchar_t> temp (bufferSize);
  10465. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10466. if (num > 0)
  10467. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10468. #elif JUCE_ANDROID
  10469. HeapBlock <char> temp (bufferSize);
  10470. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10471. if (num > 0)
  10472. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10473. #else
  10474. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10475. #endif
  10476. if (num > 0)
  10477. return result;
  10478. bufferSize += 256;
  10479. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10480. break; // returns -1 because of an error rather than because it needs more space.
  10481. result.preallocateStorage (bufferSize);
  10482. }
  10483. return empty;
  10484. }
  10485. int String::getIntValue() const throw()
  10486. {
  10487. return text.getIntValue32();
  10488. }
  10489. int String::getTrailingIntValue() const throw()
  10490. {
  10491. int n = 0;
  10492. int mult = 1;
  10493. CharPointerType t (text.findTerminatingNull());
  10494. while ((--t).getAddress() >= text)
  10495. {
  10496. if (! t.isDigit())
  10497. {
  10498. if (*t == '-')
  10499. n = -n;
  10500. break;
  10501. }
  10502. n += mult * (*t - '0');
  10503. mult *= 10;
  10504. }
  10505. return n;
  10506. }
  10507. int64 String::getLargeIntValue() const throw()
  10508. {
  10509. return text.getIntValue64();
  10510. }
  10511. float String::getFloatValue() const throw()
  10512. {
  10513. return (float) getDoubleValue();
  10514. }
  10515. double String::getDoubleValue() const throw()
  10516. {
  10517. return text.getDoubleValue();
  10518. }
  10519. static const char* const hexDigits = "0123456789abcdef";
  10520. const String String::toHexString (const int number)
  10521. {
  10522. juce_wchar buffer[32];
  10523. juce_wchar* const end = buffer + 32;
  10524. juce_wchar* t = end;
  10525. *--t = 0;
  10526. unsigned int v = (unsigned int) number;
  10527. do
  10528. {
  10529. *--t = (juce_wchar) hexDigits [v & 15];
  10530. v >>= 4;
  10531. } while (v != 0);
  10532. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10533. }
  10534. const String String::toHexString (const int64 number)
  10535. {
  10536. juce_wchar buffer[32];
  10537. juce_wchar* const end = buffer + 32;
  10538. juce_wchar* t = end;
  10539. *--t = 0;
  10540. uint64 v = (uint64) number;
  10541. do
  10542. {
  10543. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10544. v >>= 4;
  10545. } while (v != 0);
  10546. return String (t, (int) (((char*) end) - (char*) t));
  10547. }
  10548. const String String::toHexString (const short number)
  10549. {
  10550. return toHexString ((int) (unsigned short) number);
  10551. }
  10552. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10553. {
  10554. if (size <= 0)
  10555. return empty;
  10556. int numChars = (size * 2) + 2;
  10557. if (groupSize > 0)
  10558. numChars += size / groupSize;
  10559. String s (Preallocation ((size_t) numChars));
  10560. CharPointerType dest (s.text);
  10561. for (int i = 0; i < size; ++i)
  10562. {
  10563. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10564. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10565. ++data;
  10566. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10567. dest.write ((juce_wchar) ' ');
  10568. }
  10569. dest.writeNull();
  10570. return s;
  10571. }
  10572. int String::getHexValue32() const throw()
  10573. {
  10574. int result = 0;
  10575. CharPointerType t (text);
  10576. while (! t.isEmpty())
  10577. {
  10578. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10579. if (hexValue >= 0)
  10580. result = (result << 4) | hexValue;
  10581. }
  10582. return result;
  10583. }
  10584. int64 String::getHexValue64() const throw()
  10585. {
  10586. int64 result = 0;
  10587. CharPointerType t (text);
  10588. while (! t.isEmpty())
  10589. {
  10590. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10591. if (hexValue >= 0)
  10592. result = (result << 4) | hexValue;
  10593. }
  10594. return result;
  10595. }
  10596. const String String::createStringFromData (const void* const data_, const int size)
  10597. {
  10598. const uint8* const data = static_cast <const uint8*> (data_);
  10599. if (size <= 0 || data == 0)
  10600. {
  10601. return empty;
  10602. }
  10603. else if (size == 1)
  10604. {
  10605. return charToString ((char) data[0]);
  10606. }
  10607. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10608. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10609. {
  10610. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10611. const int numChars = size / 2 - 1;
  10612. String result;
  10613. result.preallocateStorage (numChars + 2);
  10614. const uint16* const src = (const uint16*) (data + 2);
  10615. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10616. if (bigEndian)
  10617. {
  10618. for (int i = 0; i < numChars; ++i)
  10619. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10620. }
  10621. else
  10622. {
  10623. for (int i = 0; i < numChars; ++i)
  10624. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10625. }
  10626. dst [numChars] = 0;
  10627. return result;
  10628. }
  10629. else
  10630. {
  10631. if (size >= 3
  10632. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10633. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10634. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10635. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10636. return String::fromUTF8 ((const char*) data, size);
  10637. }
  10638. }
  10639. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10640. {
  10641. const int currentLen = length() + 1;
  10642. String& mutableThis = const_cast <String&> (*this);
  10643. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10644. return (mutableThis.text + currentLen).getAddress();
  10645. }
  10646. const CharPointer_UTF8 String::toUTF8() const
  10647. {
  10648. if (isEmpty())
  10649. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10650. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10651. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10652. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10653. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10654. #endif
  10655. CharPointer_UTF8 (extraSpace).writeAll (text);
  10656. return extraSpace;
  10657. }
  10658. CharPointer_UTF16 String::toUTF16() const
  10659. {
  10660. if (isEmpty())
  10661. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10662. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10663. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10664. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10665. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10666. #endif
  10667. CharPointer_UTF16 (extraSpace).writeAll (text);
  10668. return extraSpace;
  10669. }
  10670. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10671. {
  10672. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10673. if (buffer == 0)
  10674. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10675. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10676. }
  10677. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10678. {
  10679. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10680. if (buffer == 0)
  10681. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10682. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10683. }
  10684. int String::getNumBytesAsUTF8() const throw()
  10685. {
  10686. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10687. }
  10688. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10689. {
  10690. if (buffer == 0)
  10691. return empty;
  10692. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10693. : CharPointer_UTF8 (buffer).length());
  10694. String result (Preallocation (len + 1));
  10695. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10696. return result;
  10697. }
  10698. const char* String::toCString() const
  10699. {
  10700. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10701. return toUTF8();
  10702. #else
  10703. if (isEmpty())
  10704. return reinterpret_cast <const char*> (text.getAddress());
  10705. const int len = getNumBytesAsCString();
  10706. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10707. wcstombs (extraSpace, text, len);
  10708. extraSpace [len] = 0;
  10709. return extraSpace;
  10710. #endif
  10711. }
  10712. int String::getNumBytesAsCString() const throw()
  10713. {
  10714. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10715. return getNumBytesAsUTF8();
  10716. #else
  10717. return (int) wcstombs (0, text, 0);
  10718. #endif
  10719. }
  10720. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10721. {
  10722. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10723. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10724. #else
  10725. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10726. if (destBuffer != 0 && numBytes >= 0)
  10727. destBuffer [numBytes] = 0;
  10728. return numBytes;
  10729. #endif
  10730. }
  10731. #if JUCE_MSVC
  10732. #pragma warning (pop)
  10733. #endif
  10734. String::Concatenator::Concatenator (String& stringToAppendTo)
  10735. : result (stringToAppendTo),
  10736. nextIndex (stringToAppendTo.length())
  10737. {
  10738. }
  10739. String::Concatenator::~Concatenator()
  10740. {
  10741. }
  10742. void String::Concatenator::append (const String& s)
  10743. {
  10744. const int len = s.length();
  10745. if (len > 0)
  10746. {
  10747. result.preallocateStorage (nextIndex + len);
  10748. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10749. nextIndex += len;
  10750. }
  10751. }
  10752. #if JUCE_UNIT_TESTS
  10753. class StringTests : public UnitTest
  10754. {
  10755. public:
  10756. StringTests() : UnitTest ("String class") {}
  10757. template <class CharPointerType>
  10758. struct TestUTFConversion
  10759. {
  10760. static void test (UnitTest& test)
  10761. {
  10762. String s (createRandomWideCharString());
  10763. typename CharPointerType::CharType buffer [300];
  10764. memset (buffer, 0xff, sizeof (buffer));
  10765. CharPointerType (buffer).writeAll (s.toUTF32());
  10766. test.expectEquals (String (CharPointerType (buffer)), s);
  10767. memset (buffer, 0xff, sizeof (buffer));
  10768. CharPointerType (buffer).writeAll (s.toUTF16());
  10769. test.expectEquals (String (CharPointerType (buffer)), s);
  10770. memset (buffer, 0xff, sizeof (buffer));
  10771. CharPointerType (buffer).writeAll (s.toUTF8());
  10772. test.expectEquals (String (CharPointerType (buffer)), s);
  10773. }
  10774. };
  10775. static const String createRandomWideCharString()
  10776. {
  10777. juce_wchar buffer [50];
  10778. zerostruct (buffer);
  10779. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10780. {
  10781. if (Random::getSystemRandom().nextBool())
  10782. {
  10783. do
  10784. {
  10785. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10786. }
  10787. while (buffer[i] >= 0xd800 && buffer[i] <= 0xdfff); // (these code-points are illegal in UTF-16)
  10788. }
  10789. else
  10790. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10791. }
  10792. return buffer;
  10793. }
  10794. void runTest()
  10795. {
  10796. {
  10797. beginTest ("Basics");
  10798. expect (String().length() == 0);
  10799. expect (String() == String::empty);
  10800. String s1, s2 ("abcd");
  10801. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10802. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10803. expect (s2.length() == 4);
  10804. s1 = "abcd";
  10805. expect (s2 == s1 && s1 == s2);
  10806. expect (s1 == "abcd" && s1 == L"abcd");
  10807. expect (String ("abcd") == String (L"abcd"));
  10808. expect (String ("abcdefg", 4) == L"abcd");
  10809. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10810. expect (String::charToString ('x') == "x");
  10811. expect (String::charToString (0) == String::empty);
  10812. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10813. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10814. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10815. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10816. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10817. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10818. expect (s1.indexOf (String::empty) == 0);
  10819. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10820. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10821. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10822. expect (s1.containsChar ('a'));
  10823. expect (! s1.containsChar ('x'));
  10824. expect (! s1.containsChar (0));
  10825. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10826. }
  10827. {
  10828. beginTest ("Operations");
  10829. String s ("012345678");
  10830. expect (s.hashCode() != 0);
  10831. expect (s.hashCode64() != 0);
  10832. expect (s.hashCode() != (s + s).hashCode());
  10833. expect (s.hashCode64() != (s + s).hashCode64());
  10834. expect (s.compare (String ("012345678")) == 0);
  10835. expect (s.compare (String ("012345679")) < 0);
  10836. expect (s.compare (String ("012345676")) > 0);
  10837. expect (s.substring (2, 3) == String::charToString (s[2]));
  10838. expect (s.substring (0, 1) == String::charToString (s[0]));
  10839. expect (s.getLastCharacter() == s [s.length() - 1]);
  10840. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10841. expect (s.substring (0, 3) == L"012");
  10842. expect (s.substring (0, 100) == s);
  10843. expect (s.substring (-1, 100) == s);
  10844. expect (s.substring (3) == "345678");
  10845. expect (s.indexOf (L"45") == 4);
  10846. expect (String ("444445").indexOf ("45") == 4);
  10847. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10848. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10849. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10850. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10851. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10852. expect (s.indexOfChar (L'4') == 4);
  10853. expect (s + s == "012345678012345678");
  10854. expect (s.startsWith (s));
  10855. expect (s.startsWith (s.substring (0, 4)));
  10856. expect (s.startsWith (s.dropLastCharacters (4)));
  10857. expect (s.endsWith (s.substring (5)));
  10858. expect (s.endsWith (s));
  10859. expect (s.contains (s.substring (3, 6)));
  10860. expect (s.contains (s.substring (3)));
  10861. expect (s.startsWithChar (s[0]));
  10862. expect (s.endsWithChar (s.getLastCharacter()));
  10863. expect (s [s.length()] == 0);
  10864. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10865. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10866. String s2 ("123");
  10867. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10868. s2 += "xyz";
  10869. expect (s2 == "1234567890xyz");
  10870. beginTest ("Numeric conversions");
  10871. expect (String::empty.getIntValue() == 0);
  10872. expect (String::empty.getDoubleValue() == 0.0);
  10873. expect (String::empty.getFloatValue() == 0.0f);
  10874. expect (s.getIntValue() == 12345678);
  10875. expect (s.getLargeIntValue() == (int64) 12345678);
  10876. expect (s.getDoubleValue() == 12345678.0);
  10877. expect (s.getFloatValue() == 12345678.0f);
  10878. expect (String (-1234).getIntValue() == -1234);
  10879. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10880. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10881. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10882. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10883. expect (s.getHexValue32() == 0x12345678);
  10884. expect (s.getHexValue64() == (int64) 0x12345678);
  10885. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10886. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10887. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10888. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10889. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10890. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10891. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10892. beginTest ("Subsections");
  10893. String s3;
  10894. s3 = "abcdeFGHIJ";
  10895. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10896. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10897. expect (s3.containsIgnoreCase (s3.substring (3)));
  10898. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10899. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10900. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10901. expect (s3.containsAnyOf (L"zzzFs"));
  10902. expect (s3.startsWith ("abcd"));
  10903. expect (s3.startsWithIgnoreCase (L"abCD"));
  10904. expect (s3.startsWith (String::empty));
  10905. expect (s3.startsWithChar ('a'));
  10906. expect (s3.endsWith (String ("HIJ")));
  10907. expect (s3.endsWithIgnoreCase (L"Hij"));
  10908. expect (s3.endsWith (String::empty));
  10909. expect (s3.endsWithChar (L'J'));
  10910. expect (s3.indexOf ("HIJ") == 7);
  10911. expect (s3.indexOf (L"HIJK") == -1);
  10912. expect (s3.indexOfIgnoreCase ("hij") == 7);
  10913. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  10914. String s4 (s3);
  10915. s4.append (String ("xyz123"), 3);
  10916. expect (s4 == s3 + "xyz");
  10917. expect (String (1234) < String (1235));
  10918. expect (String (1235) > String (1234));
  10919. expect (String (1234) >= String (1234));
  10920. expect (String (1234) <= String (1234));
  10921. expect (String (1235) >= String (1234));
  10922. expect (String (1234) <= String (1235));
  10923. String s5 ("word word2 word3");
  10924. expect (s5.containsWholeWord (String ("word2")));
  10925. expect (s5.indexOfWholeWord ("word2") == 5);
  10926. expect (s5.containsWholeWord (L"word"));
  10927. expect (s5.containsWholeWord ("word3"));
  10928. expect (s5.containsWholeWord (s5));
  10929. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  10930. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  10931. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  10932. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  10933. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  10934. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  10935. expect (s5.containsNonWhitespaceChars());
  10936. expect (s5.containsOnly ("ordw23 "));
  10937. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  10938. expect (s5.matchesWildcard (L"wor*", false));
  10939. expect (s5.matchesWildcard ("wOr*", true));
  10940. expect (s5.matchesWildcard (L"*word3", true));
  10941. expect (s5.matchesWildcard ("*word?", true));
  10942. expect (s5.matchesWildcard (L"Word*3", true));
  10943. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  10944. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  10945. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  10946. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  10947. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  10948. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  10949. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  10950. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  10951. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  10952. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  10953. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  10954. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  10955. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  10956. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  10957. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  10958. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  10959. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  10960. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  10961. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  10962. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  10963. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10964. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10965. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  10966. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  10967. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  10968. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  10969. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  10970. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  10971. expect (s5.replace ("Word", "", true) == " 2 3");
  10972. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  10973. expect (s5.replaceCharacter (L'w', 'x') != s5);
  10974. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  10975. expect (s5.replaceCharacters ("wo", "xy") != s5);
  10976. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  10977. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  10978. expect (s5.retainCharacters (String::empty).isEmpty());
  10979. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  10980. expectEquals (s5.removeCharacters (String::empty), s5);
  10981. expect (s5.initialSectionContainingOnly ("word") == L"word");
  10982. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  10983. expect (! s5.isQuotedString());
  10984. expect (s5.quoted().isQuotedString());
  10985. expect (! s5.quoted().unquoted().isQuotedString());
  10986. expect (! String ("x'").isQuotedString());
  10987. expect (String ("'x").isQuotedString());
  10988. String s6 (" \t xyz \t\r\n");
  10989. expectEquals (s6.trim(), String ("xyz"));
  10990. expect (s6.trim().trim() == "xyz");
  10991. expectEquals (s5.trim(), s5);
  10992. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  10993. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  10994. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  10995. expect (s6.trimStart() != s6.trimEnd());
  10996. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  10997. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  10998. }
  10999. {
  11000. beginTest ("UTF conversions");
  11001. TestUTFConversion <CharPointer_UTF32>::test (*this);
  11002. TestUTFConversion <CharPointer_UTF8>::test (*this);
  11003. TestUTFConversion <CharPointer_UTF16>::test (*this);
  11004. }
  11005. {
  11006. beginTest ("StringArray");
  11007. StringArray s;
  11008. for (int i = 5; --i >= 0;)
  11009. s.add (String (i));
  11010. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11011. s.remove (2);
  11012. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11013. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11014. s.clear();
  11015. expectEquals (s.joinIntoString ("x"), String::empty);
  11016. }
  11017. }
  11018. };
  11019. static StringTests stringUnitTests;
  11020. #endif
  11021. END_JUCE_NAMESPACE
  11022. /*** End of inlined file: juce_String.cpp ***/
  11023. /*** Start of inlined file: juce_StringArray.cpp ***/
  11024. BEGIN_JUCE_NAMESPACE
  11025. StringArray::StringArray() throw()
  11026. {
  11027. }
  11028. StringArray::StringArray (const StringArray& other)
  11029. : strings (other.strings)
  11030. {
  11031. }
  11032. StringArray::StringArray (const String& firstValue)
  11033. {
  11034. strings.add (firstValue);
  11035. }
  11036. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11037. const int numberOfStrings)
  11038. {
  11039. for (int i = 0; i < numberOfStrings; ++i)
  11040. strings.add (initialStrings [i]);
  11041. }
  11042. StringArray::StringArray (const char* const* const initialStrings,
  11043. const int numberOfStrings)
  11044. {
  11045. for (int i = 0; i < numberOfStrings; ++i)
  11046. strings.add (initialStrings [i]);
  11047. }
  11048. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11049. {
  11050. int i = 0;
  11051. while (initialStrings[i] != 0)
  11052. strings.add (initialStrings [i++]);
  11053. }
  11054. StringArray::StringArray (const char* const* const initialStrings)
  11055. {
  11056. int i = 0;
  11057. while (initialStrings[i] != 0)
  11058. strings.add (initialStrings [i++]);
  11059. }
  11060. StringArray& StringArray::operator= (const StringArray& other)
  11061. {
  11062. strings = other.strings;
  11063. return *this;
  11064. }
  11065. StringArray::~StringArray()
  11066. {
  11067. }
  11068. bool StringArray::operator== (const StringArray& other) const throw()
  11069. {
  11070. if (other.size() != size())
  11071. return false;
  11072. for (int i = size(); --i >= 0;)
  11073. if (other.strings.getReference(i) != strings.getReference(i))
  11074. return false;
  11075. return true;
  11076. }
  11077. bool StringArray::operator!= (const StringArray& other) const throw()
  11078. {
  11079. return ! operator== (other);
  11080. }
  11081. void StringArray::clear()
  11082. {
  11083. strings.clear();
  11084. }
  11085. const String& StringArray::operator[] (const int index) const throw()
  11086. {
  11087. if (isPositiveAndBelow (index, strings.size()))
  11088. return strings.getReference (index);
  11089. return String::empty;
  11090. }
  11091. String& StringArray::getReference (const int index) throw()
  11092. {
  11093. jassert (isPositiveAndBelow (index, strings.size()));
  11094. return strings.getReference (index);
  11095. }
  11096. void StringArray::add (const String& newString)
  11097. {
  11098. strings.add (newString);
  11099. }
  11100. void StringArray::insert (const int index, const String& newString)
  11101. {
  11102. strings.insert (index, newString);
  11103. }
  11104. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11105. {
  11106. if (! contains (newString, ignoreCase))
  11107. add (newString);
  11108. }
  11109. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11110. {
  11111. if (startIndex < 0)
  11112. {
  11113. jassertfalse;
  11114. startIndex = 0;
  11115. }
  11116. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11117. numElementsToAdd = otherArray.size() - startIndex;
  11118. while (--numElementsToAdd >= 0)
  11119. strings.add (otherArray.strings.getReference (startIndex++));
  11120. }
  11121. void StringArray::set (const int index, const String& newString)
  11122. {
  11123. strings.set (index, newString);
  11124. }
  11125. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11126. {
  11127. if (ignoreCase)
  11128. {
  11129. for (int i = size(); --i >= 0;)
  11130. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11131. return true;
  11132. }
  11133. else
  11134. {
  11135. for (int i = size(); --i >= 0;)
  11136. if (stringToLookFor == strings.getReference(i))
  11137. return true;
  11138. }
  11139. return false;
  11140. }
  11141. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11142. {
  11143. if (i < 0)
  11144. i = 0;
  11145. const int numElements = size();
  11146. if (ignoreCase)
  11147. {
  11148. while (i < numElements)
  11149. {
  11150. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11151. return i;
  11152. ++i;
  11153. }
  11154. }
  11155. else
  11156. {
  11157. while (i < numElements)
  11158. {
  11159. if (stringToLookFor == strings.getReference (i))
  11160. return i;
  11161. ++i;
  11162. }
  11163. }
  11164. return -1;
  11165. }
  11166. void StringArray::remove (const int index)
  11167. {
  11168. strings.remove (index);
  11169. }
  11170. void StringArray::removeString (const String& stringToRemove,
  11171. const bool ignoreCase)
  11172. {
  11173. if (ignoreCase)
  11174. {
  11175. for (int i = size(); --i >= 0;)
  11176. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11177. strings.remove (i);
  11178. }
  11179. else
  11180. {
  11181. for (int i = size(); --i >= 0;)
  11182. if (stringToRemove == strings.getReference (i))
  11183. strings.remove (i);
  11184. }
  11185. }
  11186. void StringArray::removeRange (int startIndex, int numberToRemove)
  11187. {
  11188. strings.removeRange (startIndex, numberToRemove);
  11189. }
  11190. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11191. {
  11192. if (removeWhitespaceStrings)
  11193. {
  11194. for (int i = size(); --i >= 0;)
  11195. if (! strings.getReference(i).containsNonWhitespaceChars())
  11196. strings.remove (i);
  11197. }
  11198. else
  11199. {
  11200. for (int i = size(); --i >= 0;)
  11201. if (strings.getReference(i).isEmpty())
  11202. strings.remove (i);
  11203. }
  11204. }
  11205. void StringArray::trim()
  11206. {
  11207. for (int i = size(); --i >= 0;)
  11208. {
  11209. String& s = strings.getReference(i);
  11210. s = s.trim();
  11211. }
  11212. }
  11213. class InternalStringArrayComparator_CaseSensitive
  11214. {
  11215. public:
  11216. static int compareElements (String& first, String& second) { return first.compare (second); }
  11217. };
  11218. class InternalStringArrayComparator_CaseInsensitive
  11219. {
  11220. public:
  11221. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11222. };
  11223. void StringArray::sort (const bool ignoreCase)
  11224. {
  11225. if (ignoreCase)
  11226. {
  11227. InternalStringArrayComparator_CaseInsensitive comp;
  11228. strings.sort (comp);
  11229. }
  11230. else
  11231. {
  11232. InternalStringArrayComparator_CaseSensitive comp;
  11233. strings.sort (comp);
  11234. }
  11235. }
  11236. void StringArray::move (const int currentIndex, int newIndex) throw()
  11237. {
  11238. strings.move (currentIndex, newIndex);
  11239. }
  11240. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11241. {
  11242. const int last = (numberToJoin < 0) ? size()
  11243. : jmin (size(), start + numberToJoin);
  11244. if (start < 0)
  11245. start = 0;
  11246. if (start >= last)
  11247. return String::empty;
  11248. if (start == last - 1)
  11249. return strings.getReference (start);
  11250. const int separatorLen = separator.length();
  11251. int charsNeeded = separatorLen * (last - start - 1);
  11252. for (int i = start; i < last; ++i)
  11253. charsNeeded += strings.getReference(i).length();
  11254. String result;
  11255. result.preallocateStorage (charsNeeded);
  11256. String::CharPointerType dest (result.getCharPointer());
  11257. while (start < last)
  11258. {
  11259. const String& s = strings.getReference (start);
  11260. if (! s.isEmpty())
  11261. dest.writeAll (s.getCharPointer());
  11262. if (++start < last && separatorLen > 0)
  11263. dest.writeAll (separator.getCharPointer());
  11264. }
  11265. dest.writeNull();
  11266. return result;
  11267. }
  11268. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11269. {
  11270. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11271. }
  11272. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11273. {
  11274. int num = 0;
  11275. if (text.isNotEmpty())
  11276. {
  11277. bool insideQuotes = false;
  11278. juce_wchar currentQuoteChar = 0;
  11279. int i = 0;
  11280. int tokenStart = 0;
  11281. for (;;)
  11282. {
  11283. const juce_wchar c = text[i];
  11284. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11285. if (! isBreak)
  11286. {
  11287. if (quoteCharacters.containsChar (c))
  11288. {
  11289. if (insideQuotes)
  11290. {
  11291. // only break out of quotes-mode if we find a matching quote to the
  11292. // one that we opened with..
  11293. if (currentQuoteChar == c)
  11294. insideQuotes = false;
  11295. }
  11296. else
  11297. {
  11298. insideQuotes = true;
  11299. currentQuoteChar = c;
  11300. }
  11301. }
  11302. }
  11303. else
  11304. {
  11305. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11306. ++num;
  11307. tokenStart = i + 1;
  11308. }
  11309. if (c == 0)
  11310. break;
  11311. ++i;
  11312. }
  11313. }
  11314. return num;
  11315. }
  11316. int StringArray::addLines (const String& sourceText)
  11317. {
  11318. int numLines = 0;
  11319. const juce_wchar* text = sourceText;
  11320. while (*text != 0)
  11321. {
  11322. const juce_wchar* const startOfLine = text;
  11323. while (*text != 0)
  11324. {
  11325. if (*text == '\r')
  11326. {
  11327. ++text;
  11328. if (*text == '\n')
  11329. ++text;
  11330. break;
  11331. }
  11332. if (*text == '\n')
  11333. {
  11334. ++text;
  11335. break;
  11336. }
  11337. ++text;
  11338. }
  11339. const juce_wchar* endOfLine = text;
  11340. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11341. --endOfLine;
  11342. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11343. --endOfLine;
  11344. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11345. ++numLines;
  11346. }
  11347. return numLines;
  11348. }
  11349. void StringArray::removeDuplicates (const bool ignoreCase)
  11350. {
  11351. for (int i = 0; i < size() - 1; ++i)
  11352. {
  11353. const String s (strings.getReference(i));
  11354. int nextIndex = i + 1;
  11355. for (;;)
  11356. {
  11357. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11358. if (nextIndex < 0)
  11359. break;
  11360. strings.remove (nextIndex);
  11361. }
  11362. }
  11363. }
  11364. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11365. const bool appendNumberToFirstInstance,
  11366. const juce_wchar* preNumberString,
  11367. const juce_wchar* postNumberString)
  11368. {
  11369. String defaultPre (" ("), defaultPost (")"); // (these aren't literals because of non-unicode literals on Android)
  11370. if (preNumberString == 0)
  11371. preNumberString = defaultPre;
  11372. if (postNumberString == 0)
  11373. postNumberString = defaultPost;
  11374. for (int i = 0; i < size() - 1; ++i)
  11375. {
  11376. String& s = strings.getReference(i);
  11377. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11378. if (nextIndex >= 0)
  11379. {
  11380. const String original (s);
  11381. int number = 0;
  11382. if (appendNumberToFirstInstance)
  11383. s = original + preNumberString + String (++number) + postNumberString;
  11384. else
  11385. ++number;
  11386. while (nextIndex >= 0)
  11387. {
  11388. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11389. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11390. }
  11391. }
  11392. }
  11393. }
  11394. void StringArray::minimiseStorageOverheads()
  11395. {
  11396. strings.minimiseStorageOverheads();
  11397. }
  11398. END_JUCE_NAMESPACE
  11399. /*** End of inlined file: juce_StringArray.cpp ***/
  11400. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11401. BEGIN_JUCE_NAMESPACE
  11402. StringPairArray::StringPairArray (const bool ignoreCase_)
  11403. : ignoreCase (ignoreCase_)
  11404. {
  11405. }
  11406. StringPairArray::StringPairArray (const StringPairArray& other)
  11407. : keys (other.keys),
  11408. values (other.values),
  11409. ignoreCase (other.ignoreCase)
  11410. {
  11411. }
  11412. StringPairArray::~StringPairArray()
  11413. {
  11414. }
  11415. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11416. {
  11417. keys = other.keys;
  11418. values = other.values;
  11419. return *this;
  11420. }
  11421. bool StringPairArray::operator== (const StringPairArray& other) const
  11422. {
  11423. for (int i = keys.size(); --i >= 0;)
  11424. if (other [keys[i]] != values[i])
  11425. return false;
  11426. return true;
  11427. }
  11428. bool StringPairArray::operator!= (const StringPairArray& other) const
  11429. {
  11430. return ! operator== (other);
  11431. }
  11432. const String& StringPairArray::operator[] (const String& key) const
  11433. {
  11434. return values [keys.indexOf (key, ignoreCase)];
  11435. }
  11436. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11437. {
  11438. const int i = keys.indexOf (key, ignoreCase);
  11439. if (i >= 0)
  11440. return values[i];
  11441. return defaultReturnValue;
  11442. }
  11443. void StringPairArray::set (const String& key, const String& value)
  11444. {
  11445. const int i = keys.indexOf (key, ignoreCase);
  11446. if (i >= 0)
  11447. {
  11448. values.set (i, value);
  11449. }
  11450. else
  11451. {
  11452. keys.add (key);
  11453. values.add (value);
  11454. }
  11455. }
  11456. void StringPairArray::addArray (const StringPairArray& other)
  11457. {
  11458. for (int i = 0; i < other.size(); ++i)
  11459. set (other.keys[i], other.values[i]);
  11460. }
  11461. void StringPairArray::clear()
  11462. {
  11463. keys.clear();
  11464. values.clear();
  11465. }
  11466. void StringPairArray::remove (const String& key)
  11467. {
  11468. remove (keys.indexOf (key, ignoreCase));
  11469. }
  11470. void StringPairArray::remove (const int index)
  11471. {
  11472. keys.remove (index);
  11473. values.remove (index);
  11474. }
  11475. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11476. {
  11477. ignoreCase = shouldIgnoreCase;
  11478. }
  11479. const String StringPairArray::getDescription() const
  11480. {
  11481. String s;
  11482. for (int i = 0; i < keys.size(); ++i)
  11483. {
  11484. s << keys[i] << " = " << values[i];
  11485. if (i < keys.size())
  11486. s << ", ";
  11487. }
  11488. return s;
  11489. }
  11490. void StringPairArray::minimiseStorageOverheads()
  11491. {
  11492. keys.minimiseStorageOverheads();
  11493. values.minimiseStorageOverheads();
  11494. }
  11495. END_JUCE_NAMESPACE
  11496. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11497. /*** Start of inlined file: juce_StringPool.cpp ***/
  11498. BEGIN_JUCE_NAMESPACE
  11499. StringPool::StringPool() throw() {}
  11500. StringPool::~StringPool() {}
  11501. namespace StringPoolHelpers
  11502. {
  11503. template <class StringType>
  11504. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11505. {
  11506. int start = 0;
  11507. int end = strings.size();
  11508. for (;;)
  11509. {
  11510. if (start >= end)
  11511. {
  11512. jassert (start <= end);
  11513. strings.insert (start, newString);
  11514. return strings.getReference (start);
  11515. }
  11516. else
  11517. {
  11518. const String& startString = strings.getReference (start);
  11519. if (startString == newString)
  11520. return startString;
  11521. const int halfway = (start + end) >> 1;
  11522. if (halfway == start)
  11523. {
  11524. if (startString.compare (newString) < 0)
  11525. ++start;
  11526. strings.insert (start, newString);
  11527. return strings.getReference (start);
  11528. }
  11529. const int comp = strings.getReference (halfway).compare (newString);
  11530. if (comp == 0)
  11531. return strings.getReference (halfway);
  11532. else if (comp < 0)
  11533. start = halfway;
  11534. else
  11535. end = halfway;
  11536. }
  11537. }
  11538. }
  11539. }
  11540. const juce_wchar* StringPool::getPooledString (const String& s)
  11541. {
  11542. if (s.isEmpty())
  11543. return String::empty;
  11544. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11545. }
  11546. const juce_wchar* StringPool::getPooledString (const char* const s)
  11547. {
  11548. if (s == 0 || *s == 0)
  11549. return String::empty;
  11550. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11551. }
  11552. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11553. {
  11554. if (s == 0 || *s == 0)
  11555. return String::empty;
  11556. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11557. }
  11558. int StringPool::size() const throw()
  11559. {
  11560. return strings.size();
  11561. }
  11562. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11563. {
  11564. return strings [index];
  11565. }
  11566. END_JUCE_NAMESPACE
  11567. /*** End of inlined file: juce_StringPool.cpp ***/
  11568. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11569. BEGIN_JUCE_NAMESPACE
  11570. XmlDocument::XmlDocument (const String& documentText)
  11571. : originalText (documentText),
  11572. input (0),
  11573. ignoreEmptyTextElements (true)
  11574. {
  11575. }
  11576. XmlDocument::XmlDocument (const File& file)
  11577. : input (0),
  11578. ignoreEmptyTextElements (true),
  11579. inputSource (new FileInputSource (file))
  11580. {
  11581. }
  11582. XmlDocument::~XmlDocument()
  11583. {
  11584. }
  11585. XmlElement* XmlDocument::parse (const File& file)
  11586. {
  11587. XmlDocument doc (file);
  11588. return doc.getDocumentElement();
  11589. }
  11590. XmlElement* XmlDocument::parse (const String& xmlData)
  11591. {
  11592. XmlDocument doc (xmlData);
  11593. return doc.getDocumentElement();
  11594. }
  11595. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11596. {
  11597. inputSource = newSource;
  11598. }
  11599. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11600. {
  11601. ignoreEmptyTextElements = shouldBeIgnored;
  11602. }
  11603. namespace XmlIdentifierChars
  11604. {
  11605. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11606. {
  11607. return CharacterFunctions::isLetterOrDigit (c)
  11608. || c == '_' || c == '-' || c == ':' || c == '.';
  11609. }
  11610. bool isIdentifierChar (const juce_wchar c) throw()
  11611. {
  11612. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11613. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11614. : isIdentifierCharSlow (c);
  11615. }
  11616. /*static void generateIdentifierCharConstants()
  11617. {
  11618. uint32 n[8];
  11619. zerostruct (n);
  11620. for (int i = 0; i < 256; ++i)
  11621. if (isIdentifierCharSlow (i))
  11622. n[i >> 5] |= (1 << (i & 31));
  11623. String s;
  11624. for (int i = 0; i < 8; ++i)
  11625. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11626. DBG (s);
  11627. }*/
  11628. }
  11629. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11630. {
  11631. String textToParse (originalText);
  11632. if (textToParse.isEmpty() && inputSource != 0)
  11633. {
  11634. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11635. if (in != 0)
  11636. {
  11637. MemoryOutputStream data;
  11638. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11639. textToParse = data.toString();
  11640. if (! onlyReadOuterDocumentElement)
  11641. originalText = textToParse;
  11642. }
  11643. }
  11644. input = static_cast <const juce_wchar*> (textToParse);
  11645. lastError = String::empty;
  11646. errorOccurred = false;
  11647. outOfData = false;
  11648. needToLoadDTD = true;
  11649. if (textToParse.isEmpty())
  11650. {
  11651. lastError = "not enough input";
  11652. }
  11653. else
  11654. {
  11655. skipHeader();
  11656. if (input.getAddress() != 0)
  11657. {
  11658. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11659. if (! errorOccurred)
  11660. return result.release();
  11661. }
  11662. else
  11663. {
  11664. lastError = "incorrect xml header";
  11665. }
  11666. }
  11667. return 0;
  11668. }
  11669. const String& XmlDocument::getLastParseError() const throw()
  11670. {
  11671. return lastError;
  11672. }
  11673. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11674. {
  11675. lastError = desc;
  11676. errorOccurred = ! carryOn;
  11677. }
  11678. const String XmlDocument::getFileContents (const String& filename) const
  11679. {
  11680. if (inputSource != 0)
  11681. {
  11682. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11683. if (in != 0)
  11684. return in->readEntireStreamAsString();
  11685. }
  11686. return String::empty;
  11687. }
  11688. juce_wchar XmlDocument::readNextChar() throw()
  11689. {
  11690. if (*input != 0)
  11691. return *input++;
  11692. outOfData = true;
  11693. return 0;
  11694. }
  11695. int XmlDocument::findNextTokenLength() throw()
  11696. {
  11697. int len = 0;
  11698. juce_wchar c = *input;
  11699. while (XmlIdentifierChars::isIdentifierChar (c))
  11700. c = input [++len];
  11701. return len;
  11702. }
  11703. void XmlDocument::skipHeader()
  11704. {
  11705. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11706. if (headerStart >= 0)
  11707. {
  11708. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11709. if (headerEnd < 0)
  11710. return;
  11711. #if JUCE_DEBUG
  11712. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11713. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11714. .fromFirstOccurrenceOf ("=", false, false)
  11715. .fromFirstOccurrenceOf ("\"", false, false)
  11716. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11717. /* If you load an XML document with a non-UTF encoding type, it may have been
  11718. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11719. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11720. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11721. read, use your own code to convert them to a unicode String, and pass that to the
  11722. XML parser.
  11723. */
  11724. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11725. #endif
  11726. input += headerEnd + 2;
  11727. }
  11728. skipNextWhiteSpace();
  11729. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11730. if (docTypeIndex < 0)
  11731. return;
  11732. input += docTypeIndex + 9;
  11733. const CharPointer_UTF32 docType (input);
  11734. int n = 1;
  11735. while (n > 0)
  11736. {
  11737. const juce_wchar c = readNextChar();
  11738. if (outOfData)
  11739. return;
  11740. if (c == '<')
  11741. ++n;
  11742. else if (c == '>')
  11743. --n;
  11744. }
  11745. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11746. }
  11747. void XmlDocument::skipNextWhiteSpace()
  11748. {
  11749. for (;;)
  11750. {
  11751. juce_wchar c = *input;
  11752. while (CharacterFunctions::isWhitespace (c))
  11753. c = *++input;
  11754. if (c == 0)
  11755. {
  11756. outOfData = true;
  11757. break;
  11758. }
  11759. else if (c == '<')
  11760. {
  11761. if (input[1] == '!'
  11762. && input[2] == '-'
  11763. && input[3] == '-')
  11764. {
  11765. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11766. if (closeComment < 0)
  11767. {
  11768. outOfData = true;
  11769. break;
  11770. }
  11771. input += closeComment + 3;
  11772. continue;
  11773. }
  11774. else if (input[1] == '?')
  11775. {
  11776. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11777. if (closeBracket < 0)
  11778. {
  11779. outOfData = true;
  11780. break;
  11781. }
  11782. input += closeBracket + 2;
  11783. continue;
  11784. }
  11785. }
  11786. break;
  11787. }
  11788. }
  11789. void XmlDocument::readQuotedString (String& result)
  11790. {
  11791. const juce_wchar quote = readNextChar();
  11792. while (! outOfData)
  11793. {
  11794. const juce_wchar c = readNextChar();
  11795. if (c == quote)
  11796. break;
  11797. if (c == '&')
  11798. {
  11799. --input;
  11800. readEntity (result);
  11801. }
  11802. else
  11803. {
  11804. --input;
  11805. const CharPointer_UTF32 start (input);
  11806. for (;;)
  11807. {
  11808. const juce_wchar character = *input;
  11809. if (character == quote)
  11810. {
  11811. result.append (start.getAddress(), (int) (input.getAddress() - start.getAddress()));
  11812. ++input;
  11813. return;
  11814. }
  11815. else if (character == '&')
  11816. {
  11817. result.append (start.getAddress(), (int) (input.getAddress() - start.getAddress()));
  11818. break;
  11819. }
  11820. else if (character == 0)
  11821. {
  11822. outOfData = true;
  11823. setLastError ("unmatched quotes", false);
  11824. break;
  11825. }
  11826. ++input;
  11827. }
  11828. }
  11829. }
  11830. }
  11831. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11832. {
  11833. XmlElement* node = 0;
  11834. skipNextWhiteSpace();
  11835. if (outOfData)
  11836. return 0;
  11837. const int openBracket = input.indexOf ((juce_wchar) '<');
  11838. if (openBracket >= 0)
  11839. {
  11840. input += openBracket + 1;
  11841. int tagLen = findNextTokenLength();
  11842. if (tagLen == 0)
  11843. {
  11844. // no tag name - but allow for a gap after the '<' before giving an error
  11845. skipNextWhiteSpace();
  11846. tagLen = findNextTokenLength();
  11847. if (tagLen == 0)
  11848. {
  11849. setLastError ("tag name missing", false);
  11850. return node;
  11851. }
  11852. }
  11853. node = new XmlElement (String (input.getAddress(), tagLen));
  11854. input += tagLen;
  11855. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11856. // look for attributes
  11857. for (;;)
  11858. {
  11859. skipNextWhiteSpace();
  11860. const juce_wchar c = *input;
  11861. // empty tag..
  11862. if (c == '/' && input[1] == '>')
  11863. {
  11864. input += 2;
  11865. break;
  11866. }
  11867. // parse the guts of the element..
  11868. if (c == '>')
  11869. {
  11870. ++input;
  11871. if (alsoParseSubElements)
  11872. readChildElements (node);
  11873. break;
  11874. }
  11875. // get an attribute..
  11876. if (XmlIdentifierChars::isIdentifierChar (c))
  11877. {
  11878. const int attNameLen = findNextTokenLength();
  11879. if (attNameLen > 0)
  11880. {
  11881. const CharPointer_UTF32 attNameStart (input);
  11882. input += attNameLen;
  11883. skipNextWhiteSpace();
  11884. if (readNextChar() == '=')
  11885. {
  11886. skipNextWhiteSpace();
  11887. const juce_wchar nextChar = *input;
  11888. if (nextChar == '"' || nextChar == '\'')
  11889. {
  11890. XmlElement::XmlAttributeNode* const newAtt
  11891. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  11892. String::empty);
  11893. readQuotedString (newAtt->value);
  11894. attributeAppender.append (newAtt);
  11895. continue;
  11896. }
  11897. }
  11898. }
  11899. }
  11900. else
  11901. {
  11902. if (! outOfData)
  11903. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11904. }
  11905. break;
  11906. }
  11907. }
  11908. return node;
  11909. }
  11910. void XmlDocument::readChildElements (XmlElement* parent)
  11911. {
  11912. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  11913. for (;;)
  11914. {
  11915. const CharPointer_UTF32 preWhitespaceInput (input);
  11916. skipNextWhiteSpace();
  11917. if (outOfData)
  11918. {
  11919. setLastError ("unmatched tags", false);
  11920. break;
  11921. }
  11922. if (*input == '<')
  11923. {
  11924. if (input[1] == '/')
  11925. {
  11926. // our close tag..
  11927. const int closeTag = input.indexOf ((juce_wchar) '>');
  11928. if (closeTag >= 0)
  11929. input += closeTag + 1;
  11930. break;
  11931. }
  11932. else if (input[1] == '!'
  11933. && input[2] == '['
  11934. && input[3] == 'C'
  11935. && input[4] == 'D'
  11936. && input[5] == 'A'
  11937. && input[6] == 'T'
  11938. && input[7] == 'A'
  11939. && input[8] == '[')
  11940. {
  11941. input += 9;
  11942. const CharPointer_UTF32 inputStart (input);
  11943. int len = 0;
  11944. for (;;)
  11945. {
  11946. if (*input == 0)
  11947. {
  11948. setLastError ("unterminated CDATA section", false);
  11949. outOfData = true;
  11950. break;
  11951. }
  11952. else if (input[0] == ']'
  11953. && input[1] == ']'
  11954. && input[2] == '>')
  11955. {
  11956. input += 3;
  11957. break;
  11958. }
  11959. ++input;
  11960. ++len;
  11961. }
  11962. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  11963. }
  11964. else
  11965. {
  11966. // this is some other element, so parse and add it..
  11967. XmlElement* const n = readNextElement (true);
  11968. if (n != 0)
  11969. childAppender.append (n);
  11970. else
  11971. return;
  11972. }
  11973. }
  11974. else // must be a character block
  11975. {
  11976. input = preWhitespaceInput; // roll back to include the leading whitespace
  11977. String textElementContent;
  11978. for (;;)
  11979. {
  11980. const juce_wchar c = *input;
  11981. if (c == '<')
  11982. break;
  11983. if (c == 0)
  11984. {
  11985. setLastError ("unmatched tags", false);
  11986. outOfData = true;
  11987. return;
  11988. }
  11989. if (c == '&')
  11990. {
  11991. String entity;
  11992. readEntity (entity);
  11993. if (entity.startsWithChar ('<') && entity [1] != 0)
  11994. {
  11995. const CharPointer_UTF32 oldInput (input);
  11996. const bool oldOutOfData = outOfData;
  11997. input = static_cast <const juce_wchar*> (entity);
  11998. outOfData = false;
  11999. for (;;)
  12000. {
  12001. XmlElement* const n = readNextElement (true);
  12002. if (n == 0)
  12003. break;
  12004. childAppender.append (n);
  12005. }
  12006. input = oldInput;
  12007. outOfData = oldOutOfData;
  12008. }
  12009. else
  12010. {
  12011. textElementContent += entity;
  12012. }
  12013. }
  12014. else
  12015. {
  12016. const CharPointer_UTF32 start (input);
  12017. int len = 0;
  12018. for (;;)
  12019. {
  12020. const juce_wchar nextChar = *input;
  12021. if (nextChar == '<' || nextChar == '&')
  12022. {
  12023. break;
  12024. }
  12025. else if (nextChar == 0)
  12026. {
  12027. setLastError ("unmatched tags", false);
  12028. outOfData = true;
  12029. return;
  12030. }
  12031. ++input;
  12032. ++len;
  12033. }
  12034. textElementContent.append (start.getAddress(), len);
  12035. }
  12036. }
  12037. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12038. {
  12039. childAppender.append (XmlElement::createTextElement (textElementContent));
  12040. }
  12041. }
  12042. }
  12043. }
  12044. void XmlDocument::readEntity (String& result)
  12045. {
  12046. // skip over the ampersand
  12047. ++input;
  12048. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12049. {
  12050. input += 4;
  12051. result += '&';
  12052. }
  12053. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12054. {
  12055. input += 5;
  12056. result += '"';
  12057. }
  12058. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12059. {
  12060. input += 5;
  12061. result += '\'';
  12062. }
  12063. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12064. {
  12065. input += 3;
  12066. result += '<';
  12067. }
  12068. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12069. {
  12070. input += 3;
  12071. result += '>';
  12072. }
  12073. else if (*input == '#')
  12074. {
  12075. int charCode = 0;
  12076. ++input;
  12077. if (*input == 'x' || *input == 'X')
  12078. {
  12079. ++input;
  12080. int numChars = 0;
  12081. while (input[0] != ';')
  12082. {
  12083. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12084. if (hexValue < 0 || ++numChars > 8)
  12085. {
  12086. setLastError ("illegal escape sequence", true);
  12087. break;
  12088. }
  12089. charCode = (charCode << 4) | hexValue;
  12090. ++input;
  12091. }
  12092. ++input;
  12093. }
  12094. else if (input[0] >= '0' && input[0] <= '9')
  12095. {
  12096. int numChars = 0;
  12097. while (input[0] != ';')
  12098. {
  12099. if (++numChars > 12)
  12100. {
  12101. setLastError ("illegal escape sequence", true);
  12102. break;
  12103. }
  12104. charCode = charCode * 10 + (input[0] - '0');
  12105. ++input;
  12106. }
  12107. ++input;
  12108. }
  12109. else
  12110. {
  12111. setLastError ("illegal escape sequence", true);
  12112. result += '&';
  12113. return;
  12114. }
  12115. result << (juce_wchar) charCode;
  12116. }
  12117. else
  12118. {
  12119. const CharPointer_UTF32 entityNameStart (input);
  12120. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12121. if (closingSemiColon < 0)
  12122. {
  12123. outOfData = true;
  12124. result += '&';
  12125. }
  12126. else
  12127. {
  12128. input += closingSemiColon + 1;
  12129. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12130. }
  12131. }
  12132. }
  12133. const String XmlDocument::expandEntity (const String& ent)
  12134. {
  12135. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12136. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12137. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12138. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12139. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12140. if (ent[0] == '#')
  12141. {
  12142. if (ent[1] == 'x' || ent[1] == 'X')
  12143. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12144. if (ent[1] >= '0' && ent[1] <= '9')
  12145. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12146. setLastError ("illegal escape sequence", false);
  12147. return String::charToString ('&');
  12148. }
  12149. return expandExternalEntity (ent);
  12150. }
  12151. const String XmlDocument::expandExternalEntity (const String& entity)
  12152. {
  12153. if (needToLoadDTD)
  12154. {
  12155. if (dtdText.isNotEmpty())
  12156. {
  12157. dtdText = dtdText.trimCharactersAtEnd (">");
  12158. tokenisedDTD.addTokens (dtdText, true);
  12159. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12160. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12161. {
  12162. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12163. tokenisedDTD.clear();
  12164. tokenisedDTD.addTokens (getFileContents (fn), true);
  12165. }
  12166. else
  12167. {
  12168. tokenisedDTD.clear();
  12169. const int openBracket = dtdText.indexOfChar ('[');
  12170. if (openBracket > 0)
  12171. {
  12172. const int closeBracket = dtdText.lastIndexOfChar (']');
  12173. if (closeBracket > openBracket)
  12174. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12175. closeBracket), true);
  12176. }
  12177. }
  12178. for (int i = tokenisedDTD.size(); --i >= 0;)
  12179. {
  12180. if (tokenisedDTD[i].startsWithChar ('%')
  12181. && tokenisedDTD[i].endsWithChar (';'))
  12182. {
  12183. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12184. StringArray newToks;
  12185. newToks.addTokens (parsed, true);
  12186. tokenisedDTD.remove (i);
  12187. for (int j = newToks.size(); --j >= 0;)
  12188. tokenisedDTD.insert (i, newToks[j]);
  12189. }
  12190. }
  12191. }
  12192. needToLoadDTD = false;
  12193. }
  12194. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12195. {
  12196. if (tokenisedDTD[i] == entity)
  12197. {
  12198. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12199. {
  12200. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12201. // check for sub-entities..
  12202. int ampersand = ent.indexOfChar ('&');
  12203. while (ampersand >= 0)
  12204. {
  12205. const int semiColon = ent.indexOf (i + 1, ";");
  12206. if (semiColon < 0)
  12207. {
  12208. setLastError ("entity without terminating semi-colon", false);
  12209. break;
  12210. }
  12211. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12212. ent = ent.substring (0, ampersand)
  12213. + resolved
  12214. + ent.substring (semiColon + 1);
  12215. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12216. }
  12217. return ent;
  12218. }
  12219. }
  12220. }
  12221. setLastError ("unknown entity", true);
  12222. return entity;
  12223. }
  12224. const String XmlDocument::getParameterEntity (const String& entity)
  12225. {
  12226. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12227. {
  12228. if (tokenisedDTD[i] == entity
  12229. && tokenisedDTD [i - 1] == "%"
  12230. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12231. {
  12232. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12233. if (ent.equalsIgnoreCase ("system"))
  12234. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12235. else
  12236. return ent.trim().unquoted();
  12237. }
  12238. }
  12239. return entity;
  12240. }
  12241. END_JUCE_NAMESPACE
  12242. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12243. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12244. BEGIN_JUCE_NAMESPACE
  12245. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12246. : name (other.name),
  12247. value (other.value)
  12248. {
  12249. }
  12250. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12251. : name (name_),
  12252. value (value_)
  12253. {
  12254. #if JUCE_DEBUG
  12255. // this checks whether the attribute name string contains any illegal characters..
  12256. for (const juce_wchar* t = name; *t != 0; ++t)
  12257. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12258. #endif
  12259. }
  12260. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12261. {
  12262. return name.equalsIgnoreCase (nameToMatch);
  12263. }
  12264. XmlElement::XmlElement (const String& tagName_) throw()
  12265. : tagName (tagName_)
  12266. {
  12267. // the tag name mustn't be empty, or it'll look like a text element!
  12268. jassert (tagName_.containsNonWhitespaceChars())
  12269. // The tag can't contain spaces or other characters that would create invalid XML!
  12270. jassert (! tagName_.containsAnyOf (" <>/&"));
  12271. }
  12272. XmlElement::XmlElement (int /*dummy*/) throw()
  12273. {
  12274. }
  12275. XmlElement::XmlElement (const XmlElement& other)
  12276. : tagName (other.tagName)
  12277. {
  12278. copyChildrenAndAttributesFrom (other);
  12279. }
  12280. XmlElement& XmlElement::operator= (const XmlElement& other)
  12281. {
  12282. if (this != &other)
  12283. {
  12284. removeAllAttributes();
  12285. deleteAllChildElements();
  12286. tagName = other.tagName;
  12287. copyChildrenAndAttributesFrom (other);
  12288. }
  12289. return *this;
  12290. }
  12291. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12292. {
  12293. jassert (firstChildElement.get() == 0);
  12294. firstChildElement.addCopyOfList (other.firstChildElement);
  12295. jassert (attributes.get() == 0);
  12296. attributes.addCopyOfList (other.attributes);
  12297. }
  12298. XmlElement::~XmlElement() throw()
  12299. {
  12300. firstChildElement.deleteAll();
  12301. attributes.deleteAll();
  12302. }
  12303. namespace XmlOutputFunctions
  12304. {
  12305. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12306. {
  12307. if ((character >= 'a' && character <= 'z')
  12308. || (character >= 'A' && character <= 'Z')
  12309. || (character >= '0' && character <= '9'))
  12310. return true;
  12311. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12312. do
  12313. {
  12314. if (((juce_wchar) (uint8) *t) == character)
  12315. return true;
  12316. }
  12317. while (*++t != 0);
  12318. return false;
  12319. }
  12320. void generateLegalCharConstants()
  12321. {
  12322. uint8 n[32];
  12323. zerostruct (n);
  12324. for (int i = 0; i < 256; ++i)
  12325. if (isLegalXmlCharSlow (i))
  12326. n[i >> 3] |= (1 << (i & 7));
  12327. String s;
  12328. for (int i = 0; i < 32; ++i)
  12329. s << (int) n[i] << ", ";
  12330. DBG (s);
  12331. }*/
  12332. bool isLegalXmlChar (const uint32 c) throw()
  12333. {
  12334. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12335. return c < sizeof (legalChars) * 8
  12336. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12337. }
  12338. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12339. {
  12340. const juce_wchar* t = text;
  12341. for (;;)
  12342. {
  12343. const juce_wchar character = *t++;
  12344. if (character == 0)
  12345. break;
  12346. if (isLegalXmlChar ((uint32) character))
  12347. {
  12348. outputStream << (char) character;
  12349. }
  12350. else
  12351. {
  12352. switch (character)
  12353. {
  12354. case '&': outputStream << "&amp;"; break;
  12355. case '"': outputStream << "&quot;"; break;
  12356. case '>': outputStream << "&gt;"; break;
  12357. case '<': outputStream << "&lt;"; break;
  12358. case '\n':
  12359. case '\r':
  12360. if (! changeNewLines)
  12361. {
  12362. outputStream << (char) character;
  12363. break;
  12364. }
  12365. // Note: deliberate fall-through here!
  12366. default:
  12367. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12368. break;
  12369. }
  12370. }
  12371. }
  12372. }
  12373. void writeSpaces (OutputStream& out, int numSpaces)
  12374. {
  12375. if (numSpaces > 0)
  12376. {
  12377. const char blanks[] = " ";
  12378. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12379. while (numSpaces > blankSize)
  12380. {
  12381. out.write (blanks, blankSize);
  12382. numSpaces -= blankSize;
  12383. }
  12384. out.write (blanks, numSpaces);
  12385. }
  12386. }
  12387. }
  12388. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12389. const int indentationLevel,
  12390. const int lineWrapLength) const
  12391. {
  12392. using namespace XmlOutputFunctions;
  12393. writeSpaces (outputStream, indentationLevel);
  12394. if (! isTextElement())
  12395. {
  12396. outputStream.writeByte ('<');
  12397. outputStream << tagName;
  12398. {
  12399. const int attIndent = indentationLevel + tagName.length() + 1;
  12400. int lineLen = 0;
  12401. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12402. {
  12403. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12404. {
  12405. outputStream << newLine;
  12406. writeSpaces (outputStream, attIndent);
  12407. lineLen = 0;
  12408. }
  12409. const int64 startPos = outputStream.getPosition();
  12410. outputStream.writeByte (' ');
  12411. outputStream << att->name;
  12412. outputStream.write ("=\"", 2);
  12413. escapeIllegalXmlChars (outputStream, att->value, true);
  12414. outputStream.writeByte ('"');
  12415. lineLen += (int) (outputStream.getPosition() - startPos);
  12416. }
  12417. }
  12418. if (firstChildElement != 0)
  12419. {
  12420. outputStream.writeByte ('>');
  12421. XmlElement* child = firstChildElement;
  12422. bool lastWasTextNode = false;
  12423. while (child != 0)
  12424. {
  12425. if (child->isTextElement())
  12426. {
  12427. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12428. lastWasTextNode = true;
  12429. }
  12430. else
  12431. {
  12432. if (indentationLevel >= 0 && ! lastWasTextNode)
  12433. outputStream << newLine;
  12434. child->writeElementAsText (outputStream,
  12435. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12436. lastWasTextNode = false;
  12437. }
  12438. child = child->getNextElement();
  12439. }
  12440. if (indentationLevel >= 0 && ! lastWasTextNode)
  12441. {
  12442. outputStream << newLine;
  12443. writeSpaces (outputStream, indentationLevel);
  12444. }
  12445. outputStream.write ("</", 2);
  12446. outputStream << tagName;
  12447. outputStream.writeByte ('>');
  12448. }
  12449. else
  12450. {
  12451. outputStream.write ("/>", 2);
  12452. }
  12453. }
  12454. else
  12455. {
  12456. escapeIllegalXmlChars (outputStream, getText(), false);
  12457. }
  12458. }
  12459. const String XmlElement::createDocument (const String& dtdToUse,
  12460. const bool allOnOneLine,
  12461. const bool includeXmlHeader,
  12462. const String& encodingType,
  12463. const int lineWrapLength) const
  12464. {
  12465. MemoryOutputStream mem (2048);
  12466. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12467. return mem.toUTF8();
  12468. }
  12469. void XmlElement::writeToStream (OutputStream& output,
  12470. const String& dtdToUse,
  12471. const bool allOnOneLine,
  12472. const bool includeXmlHeader,
  12473. const String& encodingType,
  12474. const int lineWrapLength) const
  12475. {
  12476. using namespace XmlOutputFunctions;
  12477. if (includeXmlHeader)
  12478. {
  12479. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12480. if (allOnOneLine)
  12481. output.writeByte (' ');
  12482. else
  12483. output << newLine << newLine;
  12484. }
  12485. if (dtdToUse.isNotEmpty())
  12486. {
  12487. output << dtdToUse;
  12488. if (allOnOneLine)
  12489. output.writeByte (' ');
  12490. else
  12491. output << newLine;
  12492. }
  12493. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12494. if (! allOnOneLine)
  12495. output << newLine;
  12496. }
  12497. bool XmlElement::writeToFile (const File& file,
  12498. const String& dtdToUse,
  12499. const String& encodingType,
  12500. const int lineWrapLength) const
  12501. {
  12502. if (file.hasWriteAccess())
  12503. {
  12504. TemporaryFile tempFile (file);
  12505. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12506. if (out != 0)
  12507. {
  12508. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12509. out = 0;
  12510. return tempFile.overwriteTargetFileWithTemporary();
  12511. }
  12512. }
  12513. return false;
  12514. }
  12515. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12516. {
  12517. #if JUCE_DEBUG
  12518. // if debugging, check that the case is actually the same, because
  12519. // valid xml is case-sensitive, and although this lets it pass, it's
  12520. // better not to..
  12521. if (tagName.equalsIgnoreCase (tagNameWanted))
  12522. {
  12523. jassert (tagName == tagNameWanted);
  12524. return true;
  12525. }
  12526. else
  12527. {
  12528. return false;
  12529. }
  12530. #else
  12531. return tagName.equalsIgnoreCase (tagNameWanted);
  12532. #endif
  12533. }
  12534. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12535. {
  12536. XmlElement* e = nextListItem;
  12537. while (e != 0 && ! e->hasTagName (requiredTagName))
  12538. e = e->nextListItem;
  12539. return e;
  12540. }
  12541. int XmlElement::getNumAttributes() const throw()
  12542. {
  12543. return attributes.size();
  12544. }
  12545. const String& XmlElement::getAttributeName (const int index) const throw()
  12546. {
  12547. const XmlAttributeNode* const att = attributes [index];
  12548. return att != 0 ? att->name : String::empty;
  12549. }
  12550. const String& XmlElement::getAttributeValue (const int index) const throw()
  12551. {
  12552. const XmlAttributeNode* const att = attributes [index];
  12553. return att != 0 ? att->value : String::empty;
  12554. }
  12555. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12556. {
  12557. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12558. if (att->hasName (attributeName))
  12559. return true;
  12560. return false;
  12561. }
  12562. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12563. {
  12564. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12565. if (att->hasName (attributeName))
  12566. return att->value;
  12567. return String::empty;
  12568. }
  12569. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12570. {
  12571. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12572. if (att->hasName (attributeName))
  12573. return att->value;
  12574. return defaultReturnValue;
  12575. }
  12576. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12577. {
  12578. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12579. if (att->hasName (attributeName))
  12580. return att->value.getIntValue();
  12581. return defaultReturnValue;
  12582. }
  12583. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12584. {
  12585. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12586. if (att->hasName (attributeName))
  12587. return att->value.getDoubleValue();
  12588. return defaultReturnValue;
  12589. }
  12590. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12591. {
  12592. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12593. {
  12594. if (att->hasName (attributeName))
  12595. {
  12596. juce_wchar firstChar = att->value[0];
  12597. if (CharacterFunctions::isWhitespace (firstChar))
  12598. firstChar = att->value.trimStart() [0];
  12599. return firstChar == '1'
  12600. || firstChar == 't'
  12601. || firstChar == 'y'
  12602. || firstChar == 'T'
  12603. || firstChar == 'Y';
  12604. }
  12605. }
  12606. return defaultReturnValue;
  12607. }
  12608. bool XmlElement::compareAttribute (const String& attributeName,
  12609. const String& stringToCompareAgainst,
  12610. const bool ignoreCase) const throw()
  12611. {
  12612. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12613. if (att->hasName (attributeName))
  12614. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12615. : att->value == stringToCompareAgainst;
  12616. return false;
  12617. }
  12618. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12619. {
  12620. if (attributes == 0)
  12621. {
  12622. attributes = new XmlAttributeNode (attributeName, value);
  12623. }
  12624. else
  12625. {
  12626. XmlAttributeNode* att = attributes;
  12627. for (;;)
  12628. {
  12629. if (att->hasName (attributeName))
  12630. {
  12631. att->value = value;
  12632. break;
  12633. }
  12634. else if (att->nextListItem == 0)
  12635. {
  12636. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12637. break;
  12638. }
  12639. att = att->nextListItem;
  12640. }
  12641. }
  12642. }
  12643. void XmlElement::setAttribute (const String& attributeName, const int number)
  12644. {
  12645. setAttribute (attributeName, String (number));
  12646. }
  12647. void XmlElement::setAttribute (const String& attributeName, const double number)
  12648. {
  12649. setAttribute (attributeName, String (number));
  12650. }
  12651. void XmlElement::removeAttribute (const String& attributeName) throw()
  12652. {
  12653. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12654. while (att->get() != 0)
  12655. {
  12656. if (att->get()->hasName (attributeName))
  12657. {
  12658. delete att->removeNext();
  12659. break;
  12660. }
  12661. att = &(att->get()->nextListItem);
  12662. }
  12663. }
  12664. void XmlElement::removeAllAttributes() throw()
  12665. {
  12666. attributes.deleteAll();
  12667. }
  12668. int XmlElement::getNumChildElements() const throw()
  12669. {
  12670. return firstChildElement.size();
  12671. }
  12672. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12673. {
  12674. return firstChildElement [index].get();
  12675. }
  12676. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12677. {
  12678. XmlElement* child = firstChildElement;
  12679. while (child != 0)
  12680. {
  12681. if (child->hasTagName (childName))
  12682. break;
  12683. child = child->nextListItem;
  12684. }
  12685. return child;
  12686. }
  12687. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12688. {
  12689. if (newNode != 0)
  12690. firstChildElement.append (newNode);
  12691. }
  12692. void XmlElement::insertChildElement (XmlElement* const newNode,
  12693. int indexToInsertAt) throw()
  12694. {
  12695. if (newNode != 0)
  12696. {
  12697. removeChildElement (newNode, false);
  12698. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12699. }
  12700. }
  12701. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12702. {
  12703. XmlElement* const newElement = new XmlElement (childTagName);
  12704. addChildElement (newElement);
  12705. return newElement;
  12706. }
  12707. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12708. XmlElement* const newNode) throw()
  12709. {
  12710. if (newNode != 0)
  12711. {
  12712. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12713. if (p != 0)
  12714. {
  12715. if (currentChildElement != newNode)
  12716. delete p->replaceNext (newNode);
  12717. return true;
  12718. }
  12719. }
  12720. return false;
  12721. }
  12722. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12723. const bool shouldDeleteTheChild) throw()
  12724. {
  12725. if (childToRemove != 0)
  12726. {
  12727. firstChildElement.remove (childToRemove);
  12728. if (shouldDeleteTheChild)
  12729. delete childToRemove;
  12730. }
  12731. }
  12732. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12733. const bool ignoreOrderOfAttributes) const throw()
  12734. {
  12735. if (this != other)
  12736. {
  12737. if (other == 0 || tagName != other->tagName)
  12738. return false;
  12739. if (ignoreOrderOfAttributes)
  12740. {
  12741. int totalAtts = 0;
  12742. const XmlAttributeNode* att = attributes;
  12743. while (att != 0)
  12744. {
  12745. if (! other->compareAttribute (att->name, att->value))
  12746. return false;
  12747. att = att->nextListItem;
  12748. ++totalAtts;
  12749. }
  12750. if (totalAtts != other->getNumAttributes())
  12751. return false;
  12752. }
  12753. else
  12754. {
  12755. const XmlAttributeNode* thisAtt = attributes;
  12756. const XmlAttributeNode* otherAtt = other->attributes;
  12757. for (;;)
  12758. {
  12759. if (thisAtt == 0 || otherAtt == 0)
  12760. {
  12761. if (thisAtt == otherAtt) // both 0, so it's a match
  12762. break;
  12763. return false;
  12764. }
  12765. if (thisAtt->name != otherAtt->name
  12766. || thisAtt->value != otherAtt->value)
  12767. {
  12768. return false;
  12769. }
  12770. thisAtt = thisAtt->nextListItem;
  12771. otherAtt = otherAtt->nextListItem;
  12772. }
  12773. }
  12774. const XmlElement* thisChild = firstChildElement;
  12775. const XmlElement* otherChild = other->firstChildElement;
  12776. for (;;)
  12777. {
  12778. if (thisChild == 0 || otherChild == 0)
  12779. {
  12780. if (thisChild == otherChild) // both 0, so it's a match
  12781. break;
  12782. return false;
  12783. }
  12784. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12785. return false;
  12786. thisChild = thisChild->nextListItem;
  12787. otherChild = otherChild->nextListItem;
  12788. }
  12789. }
  12790. return true;
  12791. }
  12792. void XmlElement::deleteAllChildElements() throw()
  12793. {
  12794. firstChildElement.deleteAll();
  12795. }
  12796. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12797. {
  12798. XmlElement* child = firstChildElement;
  12799. while (child != 0)
  12800. {
  12801. XmlElement* const nextChild = child->nextListItem;
  12802. if (child->hasTagName (name))
  12803. removeChildElement (child, true);
  12804. child = nextChild;
  12805. }
  12806. }
  12807. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12808. {
  12809. return firstChildElement.contains (possibleChild);
  12810. }
  12811. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12812. {
  12813. if (this == elementToLookFor || elementToLookFor == 0)
  12814. return 0;
  12815. XmlElement* child = firstChildElement;
  12816. while (child != 0)
  12817. {
  12818. if (elementToLookFor == child)
  12819. return this;
  12820. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12821. if (found != 0)
  12822. return found;
  12823. child = child->nextListItem;
  12824. }
  12825. return 0;
  12826. }
  12827. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12828. {
  12829. firstChildElement.copyToArray (elems);
  12830. }
  12831. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12832. {
  12833. XmlElement* e = firstChildElement = elems[0];
  12834. for (int i = 1; i < num; ++i)
  12835. {
  12836. e->nextListItem = elems[i];
  12837. e = e->nextListItem;
  12838. }
  12839. e->nextListItem = 0;
  12840. }
  12841. bool XmlElement::isTextElement() const throw()
  12842. {
  12843. return tagName.isEmpty();
  12844. }
  12845. static const String juce_xmltextContentAttributeName ("text");
  12846. const String& XmlElement::getText() const throw()
  12847. {
  12848. jassert (isTextElement()); // you're trying to get the text from an element that
  12849. // isn't actually a text element.. If this contains text sub-nodes, you
  12850. // probably want to use getAllSubText instead.
  12851. return getStringAttribute (juce_xmltextContentAttributeName);
  12852. }
  12853. void XmlElement::setText (const String& newText)
  12854. {
  12855. if (isTextElement())
  12856. setAttribute (juce_xmltextContentAttributeName, newText);
  12857. else
  12858. jassertfalse; // you can only change the text in a text element, not a normal one.
  12859. }
  12860. const String XmlElement::getAllSubText() const
  12861. {
  12862. if (isTextElement())
  12863. return getText();
  12864. String result;
  12865. String::Concatenator concatenator (result);
  12866. const XmlElement* child = firstChildElement;
  12867. while (child != 0)
  12868. {
  12869. concatenator.append (child->getAllSubText());
  12870. child = child->nextListItem;
  12871. }
  12872. return result;
  12873. }
  12874. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12875. const String& defaultReturnValue) const
  12876. {
  12877. const XmlElement* const child = getChildByName (childTagName);
  12878. if (child != 0)
  12879. return child->getAllSubText();
  12880. return defaultReturnValue;
  12881. }
  12882. XmlElement* XmlElement::createTextElement (const String& text)
  12883. {
  12884. XmlElement* const e = new XmlElement ((int) 0);
  12885. e->setAttribute (juce_xmltextContentAttributeName, text);
  12886. return e;
  12887. }
  12888. void XmlElement::addTextElement (const String& text)
  12889. {
  12890. addChildElement (createTextElement (text));
  12891. }
  12892. void XmlElement::deleteAllTextElements() throw()
  12893. {
  12894. XmlElement* child = firstChildElement;
  12895. while (child != 0)
  12896. {
  12897. XmlElement* const next = child->nextListItem;
  12898. if (child->isTextElement())
  12899. removeChildElement (child, true);
  12900. child = next;
  12901. }
  12902. }
  12903. END_JUCE_NAMESPACE
  12904. /*** End of inlined file: juce_XmlElement.cpp ***/
  12905. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12906. BEGIN_JUCE_NAMESPACE
  12907. ReadWriteLock::ReadWriteLock() throw()
  12908. : numWaitingWriters (0),
  12909. numWriters (0),
  12910. writerThreadId (0)
  12911. {
  12912. }
  12913. ReadWriteLock::~ReadWriteLock() throw()
  12914. {
  12915. jassert (readerThreads.size() == 0);
  12916. jassert (numWriters == 0);
  12917. }
  12918. void ReadWriteLock::enterRead() const throw()
  12919. {
  12920. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12921. const ScopedLock sl (accessLock);
  12922. for (;;)
  12923. {
  12924. jassert (readerThreads.size() % 2 == 0);
  12925. int i;
  12926. for (i = 0; i < readerThreads.size(); i += 2)
  12927. if (readerThreads.getUnchecked(i) == threadId)
  12928. break;
  12929. if (i < readerThreads.size()
  12930. || numWriters + numWaitingWriters == 0
  12931. || (threadId == writerThreadId && numWriters > 0))
  12932. {
  12933. if (i < readerThreads.size())
  12934. {
  12935. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12936. }
  12937. else
  12938. {
  12939. readerThreads.add (threadId);
  12940. readerThreads.add ((Thread::ThreadID) 1);
  12941. }
  12942. return;
  12943. }
  12944. const ScopedUnlock ul (accessLock);
  12945. waitEvent.wait (100);
  12946. }
  12947. }
  12948. void ReadWriteLock::exitRead() const throw()
  12949. {
  12950. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12951. const ScopedLock sl (accessLock);
  12952. for (int i = 0; i < readerThreads.size(); i += 2)
  12953. {
  12954. if (readerThreads.getUnchecked(i) == threadId)
  12955. {
  12956. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12957. if (newCount == 0)
  12958. {
  12959. readerThreads.removeRange (i, 2);
  12960. waitEvent.signal();
  12961. }
  12962. else
  12963. {
  12964. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12965. }
  12966. return;
  12967. }
  12968. }
  12969. jassertfalse; // unlocking a lock that wasn't locked..
  12970. }
  12971. void ReadWriteLock::enterWrite() const throw()
  12972. {
  12973. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12974. const ScopedLock sl (accessLock);
  12975. for (;;)
  12976. {
  12977. if (readerThreads.size() + numWriters == 0
  12978. || threadId == writerThreadId
  12979. || (readerThreads.size() == 2
  12980. && readerThreads.getUnchecked(0) == threadId))
  12981. {
  12982. writerThreadId = threadId;
  12983. ++numWriters;
  12984. break;
  12985. }
  12986. ++numWaitingWriters;
  12987. accessLock.exit();
  12988. waitEvent.wait (100);
  12989. accessLock.enter();
  12990. --numWaitingWriters;
  12991. }
  12992. }
  12993. bool ReadWriteLock::tryEnterWrite() const throw()
  12994. {
  12995. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12996. const ScopedLock sl (accessLock);
  12997. if (readerThreads.size() + numWriters == 0
  12998. || threadId == writerThreadId
  12999. || (readerThreads.size() == 2
  13000. && readerThreads.getUnchecked(0) == threadId))
  13001. {
  13002. writerThreadId = threadId;
  13003. ++numWriters;
  13004. return true;
  13005. }
  13006. return false;
  13007. }
  13008. void ReadWriteLock::exitWrite() const throw()
  13009. {
  13010. const ScopedLock sl (accessLock);
  13011. // check this thread actually had the lock..
  13012. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13013. if (--numWriters == 0)
  13014. {
  13015. writerThreadId = 0;
  13016. waitEvent.signal();
  13017. }
  13018. }
  13019. END_JUCE_NAMESPACE
  13020. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13021. /*** Start of inlined file: juce_Thread.cpp ***/
  13022. BEGIN_JUCE_NAMESPACE
  13023. class RunningThreadsList
  13024. {
  13025. public:
  13026. RunningThreadsList()
  13027. {
  13028. }
  13029. void add (Thread* const thread)
  13030. {
  13031. const ScopedLock sl (lock);
  13032. jassert (! threads.contains (thread));
  13033. threads.add (thread);
  13034. }
  13035. void remove (Thread* const thread)
  13036. {
  13037. const ScopedLock sl (lock);
  13038. jassert (threads.contains (thread));
  13039. threads.removeValue (thread);
  13040. }
  13041. int size() const throw()
  13042. {
  13043. return threads.size();
  13044. }
  13045. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13046. {
  13047. const ScopedLock sl (lock);
  13048. for (int i = threads.size(); --i >= 0;)
  13049. {
  13050. Thread* const t = threads.getUnchecked(i);
  13051. if (t->getThreadId() == targetID)
  13052. return t;
  13053. }
  13054. return 0;
  13055. }
  13056. void stopAll (const int timeOutMilliseconds)
  13057. {
  13058. signalAllThreadsToStop();
  13059. for (;;)
  13060. {
  13061. Thread* firstThread = getFirstThread();
  13062. if (firstThread != 0)
  13063. firstThread->stopThread (timeOutMilliseconds);
  13064. else
  13065. break;
  13066. }
  13067. }
  13068. static RunningThreadsList& getInstance()
  13069. {
  13070. static RunningThreadsList runningThreads;
  13071. return runningThreads;
  13072. }
  13073. private:
  13074. Array<Thread*> threads;
  13075. CriticalSection lock;
  13076. void signalAllThreadsToStop()
  13077. {
  13078. const ScopedLock sl (lock);
  13079. for (int i = threads.size(); --i >= 0;)
  13080. threads.getUnchecked(i)->signalThreadShouldExit();
  13081. }
  13082. Thread* getFirstThread() const
  13083. {
  13084. const ScopedLock sl (lock);
  13085. return threads.getFirst();
  13086. }
  13087. };
  13088. void Thread::threadEntryPoint()
  13089. {
  13090. RunningThreadsList::getInstance().add (this);
  13091. JUCE_TRY
  13092. {
  13093. if (threadName_.isNotEmpty())
  13094. setCurrentThreadName (threadName_);
  13095. if (startSuspensionEvent_.wait (10000))
  13096. {
  13097. jassert (getCurrentThreadId() == threadId_);
  13098. if (affinityMask_ != 0)
  13099. setCurrentThreadAffinityMask (affinityMask_);
  13100. run();
  13101. }
  13102. }
  13103. JUCE_CATCH_ALL_ASSERT
  13104. RunningThreadsList::getInstance().remove (this);
  13105. closeThreadHandle();
  13106. }
  13107. // used to wrap the incoming call from the platform-specific code
  13108. void JUCE_API juce_threadEntryPoint (void* userData)
  13109. {
  13110. static_cast <Thread*> (userData)->threadEntryPoint();
  13111. }
  13112. Thread::Thread (const String& threadName)
  13113. : threadName_ (threadName),
  13114. threadHandle_ (0),
  13115. threadId_ (0),
  13116. threadPriority_ (5),
  13117. affinityMask_ (0),
  13118. threadShouldExit_ (false)
  13119. {
  13120. }
  13121. Thread::~Thread()
  13122. {
  13123. /* If your thread class's destructor has been called without first stopping the thread, that
  13124. means that this partially destructed object is still performing some work - and that's
  13125. probably a Bad Thing!
  13126. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13127. your subclass's destructor.
  13128. */
  13129. jassert (! isThreadRunning());
  13130. stopThread (100);
  13131. }
  13132. void Thread::startThread()
  13133. {
  13134. const ScopedLock sl (startStopLock);
  13135. threadShouldExit_ = false;
  13136. if (threadHandle_ == 0)
  13137. {
  13138. launchThread();
  13139. setThreadPriority (threadHandle_, threadPriority_);
  13140. startSuspensionEvent_.signal();
  13141. }
  13142. }
  13143. void Thread::startThread (const int priority)
  13144. {
  13145. const ScopedLock sl (startStopLock);
  13146. if (threadHandle_ == 0)
  13147. {
  13148. threadPriority_ = priority;
  13149. startThread();
  13150. }
  13151. else
  13152. {
  13153. setPriority (priority);
  13154. }
  13155. }
  13156. bool Thread::isThreadRunning() const
  13157. {
  13158. return threadHandle_ != 0;
  13159. }
  13160. void Thread::signalThreadShouldExit()
  13161. {
  13162. threadShouldExit_ = true;
  13163. }
  13164. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13165. {
  13166. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13167. jassert (getThreadId() != getCurrentThreadId());
  13168. const int sleepMsPerIteration = 5;
  13169. int count = timeOutMilliseconds / sleepMsPerIteration;
  13170. while (isThreadRunning())
  13171. {
  13172. if (timeOutMilliseconds > 0 && --count < 0)
  13173. return false;
  13174. sleep (sleepMsPerIteration);
  13175. }
  13176. return true;
  13177. }
  13178. void Thread::stopThread (const int timeOutMilliseconds)
  13179. {
  13180. // agh! You can't stop the thread that's calling this method! How on earth
  13181. // would that work??
  13182. jassert (getCurrentThreadId() != getThreadId());
  13183. const ScopedLock sl (startStopLock);
  13184. if (isThreadRunning())
  13185. {
  13186. signalThreadShouldExit();
  13187. notify();
  13188. if (timeOutMilliseconds != 0)
  13189. waitForThreadToExit (timeOutMilliseconds);
  13190. if (isThreadRunning())
  13191. {
  13192. // very bad karma if this point is reached, as there are bound to be
  13193. // locks and events left in silly states when a thread is killed by force..
  13194. jassertfalse;
  13195. Logger::writeToLog ("!! killing thread by force !!");
  13196. killThread();
  13197. RunningThreadsList::getInstance().remove (this);
  13198. threadHandle_ = 0;
  13199. threadId_ = 0;
  13200. }
  13201. }
  13202. }
  13203. bool Thread::setPriority (const int priority)
  13204. {
  13205. const ScopedLock sl (startStopLock);
  13206. if (setThreadPriority (threadHandle_, priority))
  13207. {
  13208. threadPriority_ = priority;
  13209. return true;
  13210. }
  13211. return false;
  13212. }
  13213. bool Thread::setCurrentThreadPriority (const int priority)
  13214. {
  13215. return setThreadPriority (0, priority);
  13216. }
  13217. void Thread::setAffinityMask (const uint32 affinityMask)
  13218. {
  13219. affinityMask_ = affinityMask;
  13220. }
  13221. bool Thread::wait (const int timeOutMilliseconds) const
  13222. {
  13223. return defaultEvent_.wait (timeOutMilliseconds);
  13224. }
  13225. void Thread::notify() const
  13226. {
  13227. defaultEvent_.signal();
  13228. }
  13229. int Thread::getNumRunningThreads()
  13230. {
  13231. return RunningThreadsList::getInstance().size();
  13232. }
  13233. Thread* Thread::getCurrentThread()
  13234. {
  13235. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13236. }
  13237. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13238. {
  13239. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13240. }
  13241. END_JUCE_NAMESPACE
  13242. /*** End of inlined file: juce_Thread.cpp ***/
  13243. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13244. BEGIN_JUCE_NAMESPACE
  13245. ThreadPoolJob::ThreadPoolJob (const String& name)
  13246. : jobName (name),
  13247. pool (0),
  13248. shouldStop (false),
  13249. isActive (false),
  13250. shouldBeDeleted (false)
  13251. {
  13252. }
  13253. ThreadPoolJob::~ThreadPoolJob()
  13254. {
  13255. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13256. // to remove it first!
  13257. jassert (pool == 0 || ! pool->contains (this));
  13258. }
  13259. const String ThreadPoolJob::getJobName() const
  13260. {
  13261. return jobName;
  13262. }
  13263. void ThreadPoolJob::setJobName (const String& newName)
  13264. {
  13265. jobName = newName;
  13266. }
  13267. void ThreadPoolJob::signalJobShouldExit()
  13268. {
  13269. shouldStop = true;
  13270. }
  13271. class ThreadPool::ThreadPoolThread : public Thread
  13272. {
  13273. public:
  13274. ThreadPoolThread (ThreadPool& pool_)
  13275. : Thread ("Pool"),
  13276. pool (pool_),
  13277. busy (false)
  13278. {
  13279. }
  13280. void run()
  13281. {
  13282. while (! threadShouldExit())
  13283. {
  13284. if (! pool.runNextJob())
  13285. wait (500);
  13286. }
  13287. }
  13288. private:
  13289. ThreadPool& pool;
  13290. bool volatile busy;
  13291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13292. };
  13293. ThreadPool::ThreadPool (const int numThreads,
  13294. const bool startThreadsOnlyWhenNeeded,
  13295. const int stopThreadsWhenNotUsedTimeoutMs)
  13296. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13297. priority (5)
  13298. {
  13299. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13300. for (int i = jmax (1, numThreads); --i >= 0;)
  13301. threads.add (new ThreadPoolThread (*this));
  13302. if (! startThreadsOnlyWhenNeeded)
  13303. for (int i = threads.size(); --i >= 0;)
  13304. threads.getUnchecked(i)->startThread (priority);
  13305. }
  13306. ThreadPool::~ThreadPool()
  13307. {
  13308. removeAllJobs (true, 4000);
  13309. int i;
  13310. for (i = threads.size(); --i >= 0;)
  13311. threads.getUnchecked(i)->signalThreadShouldExit();
  13312. for (i = threads.size(); --i >= 0;)
  13313. threads.getUnchecked(i)->stopThread (500);
  13314. }
  13315. void ThreadPool::addJob (ThreadPoolJob* const job)
  13316. {
  13317. jassert (job != 0);
  13318. jassert (job->pool == 0);
  13319. if (job->pool == 0)
  13320. {
  13321. job->pool = this;
  13322. job->shouldStop = false;
  13323. job->isActive = false;
  13324. {
  13325. const ScopedLock sl (lock);
  13326. jobs.add (job);
  13327. int numRunning = 0;
  13328. for (int i = threads.size(); --i >= 0;)
  13329. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13330. ++numRunning;
  13331. if (numRunning < threads.size())
  13332. {
  13333. bool startedOne = false;
  13334. int n = 1000;
  13335. while (--n >= 0 && ! startedOne)
  13336. {
  13337. for (int i = threads.size(); --i >= 0;)
  13338. {
  13339. if (! threads.getUnchecked(i)->isThreadRunning())
  13340. {
  13341. threads.getUnchecked(i)->startThread (priority);
  13342. startedOne = true;
  13343. break;
  13344. }
  13345. }
  13346. if (! startedOne)
  13347. Thread::sleep (2);
  13348. }
  13349. }
  13350. }
  13351. for (int i = threads.size(); --i >= 0;)
  13352. threads.getUnchecked(i)->notify();
  13353. }
  13354. }
  13355. int ThreadPool::getNumJobs() const
  13356. {
  13357. return jobs.size();
  13358. }
  13359. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13360. {
  13361. const ScopedLock sl (lock);
  13362. return jobs [index];
  13363. }
  13364. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13365. {
  13366. const ScopedLock sl (lock);
  13367. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13368. }
  13369. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13370. {
  13371. const ScopedLock sl (lock);
  13372. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13373. }
  13374. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13375. const int timeOutMs) const
  13376. {
  13377. if (job != 0)
  13378. {
  13379. const uint32 start = Time::getMillisecondCounter();
  13380. while (contains (job))
  13381. {
  13382. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13383. return false;
  13384. jobFinishedSignal.wait (2);
  13385. }
  13386. }
  13387. return true;
  13388. }
  13389. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13390. const bool interruptIfRunning,
  13391. const int timeOutMs)
  13392. {
  13393. bool dontWait = true;
  13394. if (job != 0)
  13395. {
  13396. const ScopedLock sl (lock);
  13397. if (jobs.contains (job))
  13398. {
  13399. if (job->isActive)
  13400. {
  13401. if (interruptIfRunning)
  13402. job->signalJobShouldExit();
  13403. dontWait = false;
  13404. }
  13405. else
  13406. {
  13407. jobs.removeValue (job);
  13408. job->pool = 0;
  13409. }
  13410. }
  13411. }
  13412. return dontWait || waitForJobToFinish (job, timeOutMs);
  13413. }
  13414. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13415. const int timeOutMs,
  13416. const bool deleteInactiveJobs,
  13417. ThreadPool::JobSelector* selectedJobsToRemove)
  13418. {
  13419. Array <ThreadPoolJob*> jobsToWaitFor;
  13420. {
  13421. const ScopedLock sl (lock);
  13422. for (int i = jobs.size(); --i >= 0;)
  13423. {
  13424. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13425. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13426. {
  13427. if (job->isActive)
  13428. {
  13429. jobsToWaitFor.add (job);
  13430. if (interruptRunningJobs)
  13431. job->signalJobShouldExit();
  13432. }
  13433. else
  13434. {
  13435. jobs.remove (i);
  13436. if (deleteInactiveJobs)
  13437. delete job;
  13438. else
  13439. job->pool = 0;
  13440. }
  13441. }
  13442. }
  13443. }
  13444. const uint32 start = Time::getMillisecondCounter();
  13445. for (;;)
  13446. {
  13447. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13448. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13449. jobsToWaitFor.remove (i);
  13450. if (jobsToWaitFor.size() == 0)
  13451. break;
  13452. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13453. return false;
  13454. jobFinishedSignal.wait (20);
  13455. }
  13456. return true;
  13457. }
  13458. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13459. {
  13460. StringArray s;
  13461. const ScopedLock sl (lock);
  13462. for (int i = 0; i < jobs.size(); ++i)
  13463. {
  13464. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13465. if (job->isActive || ! onlyReturnActiveJobs)
  13466. s.add (job->getJobName());
  13467. }
  13468. return s;
  13469. }
  13470. bool ThreadPool::setThreadPriorities (const int newPriority)
  13471. {
  13472. bool ok = true;
  13473. if (priority != newPriority)
  13474. {
  13475. priority = newPriority;
  13476. for (int i = threads.size(); --i >= 0;)
  13477. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13478. ok = false;
  13479. }
  13480. return ok;
  13481. }
  13482. bool ThreadPool::runNextJob()
  13483. {
  13484. ThreadPoolJob* job = 0;
  13485. {
  13486. const ScopedLock sl (lock);
  13487. for (int i = 0; i < jobs.size(); ++i)
  13488. {
  13489. job = jobs[i];
  13490. if (job != 0 && ! (job->isActive || job->shouldStop))
  13491. break;
  13492. job = 0;
  13493. }
  13494. if (job != 0)
  13495. job->isActive = true;
  13496. }
  13497. if (job != 0)
  13498. {
  13499. JUCE_TRY
  13500. {
  13501. ThreadPoolJob::JobStatus result = job->runJob();
  13502. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13503. const ScopedLock sl (lock);
  13504. if (jobs.contains (job))
  13505. {
  13506. job->isActive = false;
  13507. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13508. {
  13509. job->pool = 0;
  13510. job->shouldStop = true;
  13511. jobs.removeValue (job);
  13512. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13513. delete job;
  13514. jobFinishedSignal.signal();
  13515. }
  13516. else
  13517. {
  13518. // move the job to the end of the queue if it wants another go
  13519. jobs.move (jobs.indexOf (job), -1);
  13520. }
  13521. }
  13522. }
  13523. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13524. catch (...)
  13525. {
  13526. const ScopedLock sl (lock);
  13527. jobs.removeValue (job);
  13528. }
  13529. #endif
  13530. }
  13531. else
  13532. {
  13533. if (threadStopTimeout > 0
  13534. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13535. {
  13536. const ScopedLock sl (lock);
  13537. if (jobs.size() == 0)
  13538. for (int i = threads.size(); --i >= 0;)
  13539. threads.getUnchecked(i)->signalThreadShouldExit();
  13540. }
  13541. else
  13542. {
  13543. return false;
  13544. }
  13545. }
  13546. return true;
  13547. }
  13548. END_JUCE_NAMESPACE
  13549. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13550. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13551. BEGIN_JUCE_NAMESPACE
  13552. TimeSliceThread::TimeSliceThread (const String& threadName)
  13553. : Thread (threadName),
  13554. clientBeingCalled (0)
  13555. {
  13556. }
  13557. TimeSliceThread::~TimeSliceThread()
  13558. {
  13559. stopThread (2000);
  13560. }
  13561. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13562. {
  13563. if (client != 0)
  13564. {
  13565. const ScopedLock sl (listLock);
  13566. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13567. clients.addIfNotAlreadyThere (client);
  13568. notify();
  13569. }
  13570. }
  13571. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13572. {
  13573. const ScopedLock sl1 (listLock);
  13574. // if there's a chance we're in the middle of calling this client, we need to
  13575. // also lock the outer lock..
  13576. if (clientBeingCalled == client)
  13577. {
  13578. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13579. const ScopedLock sl2 (callbackLock);
  13580. const ScopedLock sl3 (listLock);
  13581. clients.removeValue (client);
  13582. }
  13583. else
  13584. {
  13585. clients.removeValue (client);
  13586. }
  13587. }
  13588. int TimeSliceThread::getNumClients() const
  13589. {
  13590. return clients.size();
  13591. }
  13592. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13593. {
  13594. const ScopedLock sl (listLock);
  13595. return clients [i];
  13596. }
  13597. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13598. {
  13599. Time soonest;
  13600. TimeSliceClient* client = 0;
  13601. for (int i = clients.size(); --i >= 0;)
  13602. {
  13603. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13604. if (client == 0 || c->nextCallTime < soonest)
  13605. {
  13606. client = c;
  13607. soonest = c->nextCallTime;
  13608. }
  13609. }
  13610. return client;
  13611. }
  13612. void TimeSliceThread::run()
  13613. {
  13614. int index = 0;
  13615. while (! threadShouldExit())
  13616. {
  13617. int timeToWait = 500;
  13618. {
  13619. Time nextClientTime;
  13620. {
  13621. const ScopedLock sl2 (listLock);
  13622. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13623. TimeSliceClient* const firstClient = getNextClient (index);
  13624. if (firstClient != 0)
  13625. nextClientTime = firstClient->nextCallTime;
  13626. }
  13627. const Time now (Time::getCurrentTime());
  13628. if (nextClientTime > now)
  13629. {
  13630. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13631. }
  13632. else
  13633. {
  13634. timeToWait = index == 0 ? 1 : 0;
  13635. const ScopedLock sl (callbackLock);
  13636. {
  13637. const ScopedLock sl2 (listLock);
  13638. clientBeingCalled = getNextClient (index);
  13639. }
  13640. if (clientBeingCalled != 0)
  13641. {
  13642. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13643. const ScopedLock sl2 (listLock);
  13644. if (msUntilNextCall >= 0)
  13645. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13646. else
  13647. clients.removeValue (clientBeingCalled);
  13648. clientBeingCalled = 0;
  13649. }
  13650. }
  13651. }
  13652. if (timeToWait > 0)
  13653. wait (timeToWait);
  13654. }
  13655. }
  13656. END_JUCE_NAMESPACE
  13657. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13658. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13659. BEGIN_JUCE_NAMESPACE
  13660. DeletedAtShutdown::DeletedAtShutdown()
  13661. {
  13662. const ScopedLock sl (getLock());
  13663. getObjects().add (this);
  13664. }
  13665. DeletedAtShutdown::~DeletedAtShutdown()
  13666. {
  13667. const ScopedLock sl (getLock());
  13668. getObjects().removeValue (this);
  13669. }
  13670. void DeletedAtShutdown::deleteAll()
  13671. {
  13672. // make a local copy of the array, so it can't get into a loop if something
  13673. // creates another DeletedAtShutdown object during its destructor.
  13674. Array <DeletedAtShutdown*> localCopy;
  13675. {
  13676. const ScopedLock sl (getLock());
  13677. localCopy = getObjects();
  13678. }
  13679. for (int i = localCopy.size(); --i >= 0;)
  13680. {
  13681. JUCE_TRY
  13682. {
  13683. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13684. // double-check that it's not already been deleted during another object's destructor.
  13685. {
  13686. const ScopedLock sl (getLock());
  13687. if (! getObjects().contains (deletee))
  13688. deletee = 0;
  13689. }
  13690. delete deletee;
  13691. }
  13692. JUCE_CATCH_EXCEPTION
  13693. }
  13694. // if no objects got re-created during shutdown, this should have been emptied by their
  13695. // destructors
  13696. jassert (getObjects().size() == 0);
  13697. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13698. }
  13699. CriticalSection& DeletedAtShutdown::getLock()
  13700. {
  13701. static CriticalSection lock;
  13702. return lock;
  13703. }
  13704. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13705. {
  13706. static Array <DeletedAtShutdown*> objects;
  13707. return objects;
  13708. }
  13709. END_JUCE_NAMESPACE
  13710. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13711. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13712. BEGIN_JUCE_NAMESPACE
  13713. UnitTest::UnitTest (const String& name_)
  13714. : name (name_), runner (0)
  13715. {
  13716. getAllTests().add (this);
  13717. }
  13718. UnitTest::~UnitTest()
  13719. {
  13720. getAllTests().removeValue (this);
  13721. }
  13722. Array<UnitTest*>& UnitTest::getAllTests()
  13723. {
  13724. static Array<UnitTest*> tests;
  13725. return tests;
  13726. }
  13727. void UnitTest::initialise() {}
  13728. void UnitTest::shutdown() {}
  13729. void UnitTest::performTest (UnitTestRunner* const runner_)
  13730. {
  13731. jassert (runner_ != 0);
  13732. runner = runner_;
  13733. initialise();
  13734. runTest();
  13735. shutdown();
  13736. }
  13737. void UnitTest::logMessage (const String& message)
  13738. {
  13739. runner->logMessage (message);
  13740. }
  13741. void UnitTest::beginTest (const String& testName)
  13742. {
  13743. runner->beginNewTest (this, testName);
  13744. }
  13745. void UnitTest::expect (const bool result, const String& failureMessage)
  13746. {
  13747. if (result)
  13748. runner->addPass();
  13749. else
  13750. runner->addFail (failureMessage);
  13751. }
  13752. UnitTestRunner::UnitTestRunner()
  13753. : currentTest (0), assertOnFailure (false)
  13754. {
  13755. }
  13756. UnitTestRunner::~UnitTestRunner()
  13757. {
  13758. }
  13759. int UnitTestRunner::getNumResults() const throw()
  13760. {
  13761. return results.size();
  13762. }
  13763. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  13764. {
  13765. return results [index];
  13766. }
  13767. void UnitTestRunner::resultsUpdated()
  13768. {
  13769. }
  13770. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  13771. {
  13772. results.clear();
  13773. assertOnFailure = assertOnFailure_;
  13774. resultsUpdated();
  13775. for (int i = 0; i < tests.size(); ++i)
  13776. {
  13777. try
  13778. {
  13779. tests.getUnchecked(i)->performTest (this);
  13780. }
  13781. catch (...)
  13782. {
  13783. addFail ("An unhandled exception was thrown!");
  13784. }
  13785. }
  13786. endTest();
  13787. }
  13788. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  13789. {
  13790. runTests (UnitTest::getAllTests(), assertOnFailure_);
  13791. }
  13792. void UnitTestRunner::logMessage (const String& message)
  13793. {
  13794. Logger::writeToLog (message);
  13795. }
  13796. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  13797. {
  13798. endTest();
  13799. currentTest = test;
  13800. TestResult* const r = new TestResult();
  13801. r->unitTestName = test->getName();
  13802. r->subcategoryName = subCategory;
  13803. r->passes = 0;
  13804. r->failures = 0;
  13805. results.add (r);
  13806. logMessage ("-----------------------------------------------------------------");
  13807. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  13808. resultsUpdated();
  13809. }
  13810. void UnitTestRunner::endTest()
  13811. {
  13812. if (results.size() > 0)
  13813. {
  13814. TestResult* const r = results.getLast();
  13815. if (r->failures > 0)
  13816. {
  13817. String m ("FAILED!!");
  13818. m << r->failures << (r->failures == 1 ? "test" : "tests")
  13819. << " failed, out of a total of " << (r->passes + r->failures);
  13820. logMessage (String::empty);
  13821. logMessage (m);
  13822. logMessage (String::empty);
  13823. }
  13824. else
  13825. {
  13826. logMessage ("All tests completed successfully");
  13827. }
  13828. }
  13829. }
  13830. void UnitTestRunner::addPass()
  13831. {
  13832. {
  13833. const ScopedLock sl (results.getLock());
  13834. TestResult* const r = results.getLast();
  13835. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13836. r->passes++;
  13837. String message ("Test ");
  13838. message << (r->failures + r->passes) << " passed";
  13839. logMessage (message);
  13840. }
  13841. resultsUpdated();
  13842. }
  13843. void UnitTestRunner::addFail (const String& failureMessage)
  13844. {
  13845. {
  13846. const ScopedLock sl (results.getLock());
  13847. TestResult* const r = results.getLast();
  13848. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13849. r->failures++;
  13850. String message ("!!! Test ");
  13851. message << (r->failures + r->passes) << " failed";
  13852. if (failureMessage.isNotEmpty())
  13853. message << ": " << failureMessage;
  13854. r->messages.add (message);
  13855. logMessage (message);
  13856. }
  13857. resultsUpdated();
  13858. if (assertOnFailure) { jassertfalse }
  13859. }
  13860. END_JUCE_NAMESPACE
  13861. /*** End of inlined file: juce_UnitTest.cpp ***/
  13862. #endif
  13863. #if JUCE_BUILD_MISC
  13864. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13865. BEGIN_JUCE_NAMESPACE
  13866. class ValueTree::SetPropertyAction : public UndoableAction
  13867. {
  13868. public:
  13869. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13870. const var& newValue_, const var& oldValue_,
  13871. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13872. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13873. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13874. {
  13875. }
  13876. bool perform()
  13877. {
  13878. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13879. if (isDeletingProperty)
  13880. target->removeProperty (name, 0);
  13881. else
  13882. target->setProperty (name, newValue, 0);
  13883. return true;
  13884. }
  13885. bool undo()
  13886. {
  13887. if (isAddingNewProperty)
  13888. target->removeProperty (name, 0);
  13889. else
  13890. target->setProperty (name, oldValue, 0);
  13891. return true;
  13892. }
  13893. int getSizeInUnits()
  13894. {
  13895. return (int) sizeof (*this); //xxx should be more accurate
  13896. }
  13897. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13898. {
  13899. if (! (isAddingNewProperty || isDeletingProperty))
  13900. {
  13901. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13902. if (next != 0 && next->target == target && next->name == name
  13903. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13904. {
  13905. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13906. }
  13907. }
  13908. return 0;
  13909. }
  13910. private:
  13911. const SharedObjectPtr target;
  13912. const Identifier name;
  13913. const var newValue;
  13914. var oldValue;
  13915. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13916. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13917. };
  13918. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13919. {
  13920. public:
  13921. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13922. const SharedObjectPtr& newChild_)
  13923. : target (target_),
  13924. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13925. childIndex (childIndex_),
  13926. isDeleting (newChild_ == 0)
  13927. {
  13928. jassert (child != 0);
  13929. }
  13930. bool perform()
  13931. {
  13932. if (isDeleting)
  13933. target->removeChild (childIndex, 0);
  13934. else
  13935. target->addChild (child, childIndex, 0);
  13936. return true;
  13937. }
  13938. bool undo()
  13939. {
  13940. if (isDeleting)
  13941. {
  13942. target->addChild (child, childIndex, 0);
  13943. }
  13944. else
  13945. {
  13946. // If you hit this, it seems that your object's state is getting confused - probably
  13947. // because you've interleaved some undoable and non-undoable operations?
  13948. jassert (childIndex < target->children.size());
  13949. target->removeChild (childIndex, 0);
  13950. }
  13951. return true;
  13952. }
  13953. int getSizeInUnits()
  13954. {
  13955. return (int) sizeof (*this); //xxx should be more accurate
  13956. }
  13957. private:
  13958. const SharedObjectPtr target, child;
  13959. const int childIndex;
  13960. const bool isDeleting;
  13961. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13962. };
  13963. class ValueTree::MoveChildAction : public UndoableAction
  13964. {
  13965. public:
  13966. MoveChildAction (const SharedObjectPtr& parent_,
  13967. const int startIndex_, const int endIndex_)
  13968. : parent (parent_),
  13969. startIndex (startIndex_),
  13970. endIndex (endIndex_)
  13971. {
  13972. }
  13973. bool perform()
  13974. {
  13975. parent->moveChild (startIndex, endIndex, 0);
  13976. return true;
  13977. }
  13978. bool undo()
  13979. {
  13980. parent->moveChild (endIndex, startIndex, 0);
  13981. return true;
  13982. }
  13983. int getSizeInUnits()
  13984. {
  13985. return (int) sizeof (*this); //xxx should be more accurate
  13986. }
  13987. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13988. {
  13989. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13990. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13991. return new MoveChildAction (parent, startIndex, next->endIndex);
  13992. return 0;
  13993. }
  13994. private:
  13995. const SharedObjectPtr parent;
  13996. const int startIndex, endIndex;
  13997. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  13998. };
  13999. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14000. : type (type_), parent (0)
  14001. {
  14002. }
  14003. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14004. : type (other.type), properties (other.properties), parent (0)
  14005. {
  14006. for (int i = 0; i < other.children.size(); ++i)
  14007. {
  14008. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14009. child->parent = this;
  14010. children.add (child);
  14011. }
  14012. }
  14013. ValueTree::SharedObject::~SharedObject()
  14014. {
  14015. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14016. for (int i = children.size(); --i >= 0;)
  14017. {
  14018. const SharedObjectPtr c (children.getUnchecked(i));
  14019. c->parent = 0;
  14020. children.remove (i);
  14021. c->sendParentChangeMessage();
  14022. }
  14023. }
  14024. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14025. {
  14026. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14027. {
  14028. ValueTree* const v = valueTreesWithListeners[i];
  14029. if (v != 0)
  14030. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14031. }
  14032. }
  14033. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14034. {
  14035. ValueTree tree (this);
  14036. ValueTree::SharedObject* t = this;
  14037. while (t != 0)
  14038. {
  14039. t->sendPropertyChangeMessage (tree, property);
  14040. t = t->parent;
  14041. }
  14042. }
  14043. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14044. {
  14045. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14046. {
  14047. ValueTree* const v = valueTreesWithListeners[i];
  14048. if (v != 0)
  14049. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14050. }
  14051. }
  14052. void ValueTree::SharedObject::sendChildChangeMessage()
  14053. {
  14054. ValueTree tree (this);
  14055. ValueTree::SharedObject* t = this;
  14056. while (t != 0)
  14057. {
  14058. t->sendChildChangeMessage (tree);
  14059. t = t->parent;
  14060. }
  14061. }
  14062. void ValueTree::SharedObject::sendParentChangeMessage()
  14063. {
  14064. ValueTree tree (this);
  14065. int i;
  14066. for (i = children.size(); --i >= 0;)
  14067. {
  14068. SharedObject* const t = children[i];
  14069. if (t != 0)
  14070. t->sendParentChangeMessage();
  14071. }
  14072. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14073. {
  14074. ValueTree* const v = valueTreesWithListeners[i];
  14075. if (v != 0)
  14076. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14077. }
  14078. }
  14079. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14080. {
  14081. return properties [name];
  14082. }
  14083. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14084. {
  14085. return properties.getWithDefault (name, defaultReturnValue);
  14086. }
  14087. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14088. {
  14089. if (undoManager == 0)
  14090. {
  14091. if (properties.set (name, newValue))
  14092. sendPropertyChangeMessage (name);
  14093. }
  14094. else
  14095. {
  14096. var* const existingValue = properties.getVarPointer (name);
  14097. if (existingValue != 0)
  14098. {
  14099. if (*existingValue != newValue)
  14100. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14101. }
  14102. else
  14103. {
  14104. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14105. }
  14106. }
  14107. }
  14108. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14109. {
  14110. return properties.contains (name);
  14111. }
  14112. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14113. {
  14114. if (undoManager == 0)
  14115. {
  14116. if (properties.remove (name))
  14117. sendPropertyChangeMessage (name);
  14118. }
  14119. else
  14120. {
  14121. if (properties.contains (name))
  14122. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14123. }
  14124. }
  14125. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14126. {
  14127. if (undoManager == 0)
  14128. {
  14129. while (properties.size() > 0)
  14130. {
  14131. const Identifier name (properties.getName (properties.size() - 1));
  14132. properties.remove (name);
  14133. sendPropertyChangeMessage (name);
  14134. }
  14135. }
  14136. else
  14137. {
  14138. for (int i = properties.size(); --i >= 0;)
  14139. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14140. }
  14141. }
  14142. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14143. {
  14144. for (int i = 0; i < children.size(); ++i)
  14145. if (children.getUnchecked(i)->type == typeToMatch)
  14146. return ValueTree (children.getUnchecked(i).getObject());
  14147. return ValueTree::invalid;
  14148. }
  14149. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14150. {
  14151. for (int i = 0; i < children.size(); ++i)
  14152. if (children.getUnchecked(i)->type == typeToMatch)
  14153. return ValueTree (children.getUnchecked(i).getObject());
  14154. SharedObject* const newObject = new SharedObject (typeToMatch);
  14155. addChild (newObject, -1, undoManager);
  14156. return ValueTree (newObject);
  14157. }
  14158. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14159. {
  14160. for (int i = 0; i < children.size(); ++i)
  14161. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14162. return ValueTree (children.getUnchecked(i).getObject());
  14163. return ValueTree::invalid;
  14164. }
  14165. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14166. {
  14167. const SharedObject* p = parent;
  14168. while (p != 0)
  14169. {
  14170. if (p == possibleParent)
  14171. return true;
  14172. p = p->parent;
  14173. }
  14174. return false;
  14175. }
  14176. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14177. {
  14178. return children.indexOf (child.object);
  14179. }
  14180. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14181. {
  14182. if (child != 0 && child->parent != this)
  14183. {
  14184. if (child != this && ! isAChildOf (child))
  14185. {
  14186. // You should always make sure that a child is removed from its previous parent before
  14187. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14188. // undomanager should be used when removing it from its current parent..
  14189. jassert (child->parent == 0);
  14190. if (child->parent != 0)
  14191. {
  14192. jassert (child->parent->children.indexOf (child) >= 0);
  14193. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14194. }
  14195. if (undoManager == 0)
  14196. {
  14197. children.insert (index, child);
  14198. child->parent = this;
  14199. sendChildChangeMessage();
  14200. child->sendParentChangeMessage();
  14201. }
  14202. else
  14203. {
  14204. if (index < 0)
  14205. index = children.size();
  14206. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14207. }
  14208. }
  14209. else
  14210. {
  14211. // You're attempting to create a recursive loop! A node
  14212. // can't be a child of one of its own children!
  14213. jassertfalse;
  14214. }
  14215. }
  14216. }
  14217. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14218. {
  14219. const SharedObjectPtr child (children [childIndex]);
  14220. if (child != 0)
  14221. {
  14222. if (undoManager == 0)
  14223. {
  14224. children.remove (childIndex);
  14225. child->parent = 0;
  14226. sendChildChangeMessage();
  14227. child->sendParentChangeMessage();
  14228. }
  14229. else
  14230. {
  14231. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14232. }
  14233. }
  14234. }
  14235. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14236. {
  14237. while (children.size() > 0)
  14238. removeChild (children.size() - 1, undoManager);
  14239. }
  14240. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14241. {
  14242. // The source index must be a valid index!
  14243. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14244. if (currentIndex != newIndex
  14245. && isPositiveAndBelow (currentIndex, children.size()))
  14246. {
  14247. if (undoManager == 0)
  14248. {
  14249. children.move (currentIndex, newIndex);
  14250. sendChildChangeMessage();
  14251. }
  14252. else
  14253. {
  14254. if (! isPositiveAndBelow (newIndex, children.size()))
  14255. newIndex = children.size() - 1;
  14256. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14257. }
  14258. }
  14259. }
  14260. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14261. {
  14262. jassert (newOrder.size() == children.size());
  14263. if (undoManager == 0)
  14264. {
  14265. children = newOrder;
  14266. sendChildChangeMessage();
  14267. }
  14268. else
  14269. {
  14270. for (int i = 0; i < children.size(); ++i)
  14271. {
  14272. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14273. {
  14274. jassert (children.contains (newOrder.getUnchecked(i)));
  14275. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14276. }
  14277. }
  14278. }
  14279. }
  14280. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14281. {
  14282. if (type != other.type
  14283. || properties.size() != other.properties.size()
  14284. || children.size() != other.children.size()
  14285. || properties != other.properties)
  14286. return false;
  14287. for (int i = 0; i < children.size(); ++i)
  14288. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14289. return false;
  14290. return true;
  14291. }
  14292. ValueTree::ValueTree() throw()
  14293. : object (0)
  14294. {
  14295. }
  14296. const ValueTree ValueTree::invalid;
  14297. ValueTree::ValueTree (const Identifier& type_)
  14298. : object (new ValueTree::SharedObject (type_))
  14299. {
  14300. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14301. }
  14302. ValueTree::ValueTree (SharedObject* const object_)
  14303. : object (object_)
  14304. {
  14305. }
  14306. ValueTree::ValueTree (const ValueTree& other)
  14307. : object (other.object)
  14308. {
  14309. }
  14310. ValueTree& ValueTree::operator= (const ValueTree& other)
  14311. {
  14312. if (listeners.size() > 0)
  14313. {
  14314. if (object != 0)
  14315. object->valueTreesWithListeners.removeValue (this);
  14316. if (other.object != 0)
  14317. other.object->valueTreesWithListeners.add (this);
  14318. }
  14319. object = other.object;
  14320. return *this;
  14321. }
  14322. ValueTree::~ValueTree()
  14323. {
  14324. if (listeners.size() > 0 && object != 0)
  14325. object->valueTreesWithListeners.removeValue (this);
  14326. }
  14327. bool ValueTree::operator== (const ValueTree& other) const throw()
  14328. {
  14329. return object == other.object;
  14330. }
  14331. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14332. {
  14333. return object != other.object;
  14334. }
  14335. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14336. {
  14337. return object == other.object
  14338. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14339. }
  14340. ValueTree ValueTree::createCopy() const
  14341. {
  14342. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14343. }
  14344. bool ValueTree::hasType (const Identifier& typeName) const
  14345. {
  14346. return object != 0 && object->type == typeName;
  14347. }
  14348. const Identifier ValueTree::getType() const
  14349. {
  14350. return object != 0 ? object->type : Identifier();
  14351. }
  14352. ValueTree ValueTree::getParent() const
  14353. {
  14354. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14355. }
  14356. ValueTree ValueTree::getSibling (const int delta) const
  14357. {
  14358. if (object == 0 || object->parent == 0)
  14359. return invalid;
  14360. const int index = object->parent->indexOf (*this) + delta;
  14361. return ValueTree (object->parent->children [index].getObject());
  14362. }
  14363. const var& ValueTree::operator[] (const Identifier& name) const
  14364. {
  14365. return object == 0 ? var::null : object->getProperty (name);
  14366. }
  14367. const var& ValueTree::getProperty (const Identifier& name) const
  14368. {
  14369. return object == 0 ? var::null : object->getProperty (name);
  14370. }
  14371. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14372. {
  14373. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14374. }
  14375. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14376. {
  14377. jassert (name.toString().isNotEmpty());
  14378. if (object != 0 && name.toString().isNotEmpty())
  14379. object->setProperty (name, newValue, undoManager);
  14380. }
  14381. bool ValueTree::hasProperty (const Identifier& name) const
  14382. {
  14383. return object != 0 && object->hasProperty (name);
  14384. }
  14385. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14386. {
  14387. if (object != 0)
  14388. object->removeProperty (name, undoManager);
  14389. }
  14390. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14391. {
  14392. if (object != 0)
  14393. object->removeAllProperties (undoManager);
  14394. }
  14395. int ValueTree::getNumProperties() const
  14396. {
  14397. return object == 0 ? 0 : object->properties.size();
  14398. }
  14399. const Identifier ValueTree::getPropertyName (const int index) const
  14400. {
  14401. return object == 0 ? Identifier()
  14402. : object->properties.getName (index);
  14403. }
  14404. class ValueTreePropertyValueSource : public Value::ValueSource,
  14405. public ValueTree::Listener
  14406. {
  14407. public:
  14408. ValueTreePropertyValueSource (const ValueTree& tree_,
  14409. const Identifier& property_,
  14410. UndoManager* const undoManager_)
  14411. : tree (tree_),
  14412. property (property_),
  14413. undoManager (undoManager_)
  14414. {
  14415. tree.addListener (this);
  14416. }
  14417. ~ValueTreePropertyValueSource()
  14418. {
  14419. tree.removeListener (this);
  14420. }
  14421. const var getValue() const
  14422. {
  14423. return tree [property];
  14424. }
  14425. void setValue (const var& newValue)
  14426. {
  14427. tree.setProperty (property, newValue, undoManager);
  14428. }
  14429. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14430. {
  14431. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14432. sendChangeMessage (false);
  14433. }
  14434. void valueTreeChildrenChanged (ValueTree&) {}
  14435. void valueTreeParentChanged (ValueTree&) {}
  14436. private:
  14437. ValueTree tree;
  14438. const Identifier property;
  14439. UndoManager* const undoManager;
  14440. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14441. };
  14442. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14443. {
  14444. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14445. }
  14446. int ValueTree::getNumChildren() const
  14447. {
  14448. return object == 0 ? 0 : object->children.size();
  14449. }
  14450. ValueTree ValueTree::getChild (int index) const
  14451. {
  14452. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14453. }
  14454. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14455. {
  14456. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14457. }
  14458. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14459. {
  14460. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14461. }
  14462. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14463. {
  14464. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14465. }
  14466. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14467. {
  14468. return object != 0 && object->isAChildOf (possibleParent.object);
  14469. }
  14470. int ValueTree::indexOf (const ValueTree& child) const
  14471. {
  14472. return object != 0 ? object->indexOf (child) : -1;
  14473. }
  14474. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14475. {
  14476. if (object != 0)
  14477. object->addChild (child.object, index, undoManager);
  14478. }
  14479. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14480. {
  14481. if (object != 0)
  14482. object->removeChild (childIndex, undoManager);
  14483. }
  14484. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14485. {
  14486. if (object != 0)
  14487. object->removeChild (object->children.indexOf (child.object), undoManager);
  14488. }
  14489. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14490. {
  14491. if (object != 0)
  14492. object->removeAllChildren (undoManager);
  14493. }
  14494. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14495. {
  14496. if (object != 0)
  14497. object->moveChild (currentIndex, newIndex, undoManager);
  14498. }
  14499. void ValueTree::addListener (Listener* listener)
  14500. {
  14501. if (listener != 0)
  14502. {
  14503. if (listeners.size() == 0 && object != 0)
  14504. object->valueTreesWithListeners.add (this);
  14505. listeners.add (listener);
  14506. }
  14507. }
  14508. void ValueTree::removeListener (Listener* listener)
  14509. {
  14510. listeners.remove (listener);
  14511. if (listeners.size() == 0 && object != 0)
  14512. object->valueTreesWithListeners.removeValue (this);
  14513. }
  14514. XmlElement* ValueTree::SharedObject::createXml() const
  14515. {
  14516. XmlElement* const xml = new XmlElement (type.toString());
  14517. properties.copyToXmlAttributes (*xml);
  14518. for (int i = 0; i < children.size(); ++i)
  14519. xml->addChildElement (children.getUnchecked(i)->createXml());
  14520. return xml;
  14521. }
  14522. XmlElement* ValueTree::createXml() const
  14523. {
  14524. return object != 0 ? object->createXml() : 0;
  14525. }
  14526. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14527. {
  14528. ValueTree v (xml.getTagName());
  14529. v.object->properties.setFromXmlAttributes (xml);
  14530. forEachXmlChildElement (xml, e)
  14531. v.addChild (fromXml (*e), -1, 0);
  14532. return v;
  14533. }
  14534. void ValueTree::writeToStream (OutputStream& output)
  14535. {
  14536. output.writeString (getType().toString());
  14537. const int numProps = getNumProperties();
  14538. output.writeCompressedInt (numProps);
  14539. int i;
  14540. for (i = 0; i < numProps; ++i)
  14541. {
  14542. const Identifier name (getPropertyName(i));
  14543. output.writeString (name.toString());
  14544. getProperty(name).writeToStream (output);
  14545. }
  14546. const int numChildren = getNumChildren();
  14547. output.writeCompressedInt (numChildren);
  14548. for (i = 0; i < numChildren; ++i)
  14549. getChild (i).writeToStream (output);
  14550. }
  14551. ValueTree ValueTree::readFromStream (InputStream& input)
  14552. {
  14553. const String type (input.readString());
  14554. if (type.isEmpty())
  14555. return ValueTree::invalid;
  14556. ValueTree v (type);
  14557. const int numProps = input.readCompressedInt();
  14558. if (numProps < 0)
  14559. {
  14560. jassertfalse; // trying to read corrupted data!
  14561. return v;
  14562. }
  14563. int i;
  14564. for (i = 0; i < numProps; ++i)
  14565. {
  14566. const String name (input.readString());
  14567. jassert (name.isNotEmpty());
  14568. const var value (var::readFromStream (input));
  14569. v.object->properties.set (name, value);
  14570. }
  14571. const int numChildren = input.readCompressedInt();
  14572. for (i = 0; i < numChildren; ++i)
  14573. {
  14574. ValueTree child (readFromStream (input));
  14575. v.object->children.add (child.object);
  14576. child.object->parent = v.object;
  14577. }
  14578. return v;
  14579. }
  14580. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14581. {
  14582. MemoryInputStream in (data, numBytes, false);
  14583. return readFromStream (in);
  14584. }
  14585. END_JUCE_NAMESPACE
  14586. /*** End of inlined file: juce_ValueTree.cpp ***/
  14587. /*** Start of inlined file: juce_Value.cpp ***/
  14588. BEGIN_JUCE_NAMESPACE
  14589. Value::ValueSource::ValueSource()
  14590. {
  14591. }
  14592. Value::ValueSource::~ValueSource()
  14593. {
  14594. }
  14595. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14596. {
  14597. if (synchronous)
  14598. {
  14599. for (int i = valuesWithListeners.size(); --i >= 0;)
  14600. {
  14601. Value* const v = valuesWithListeners[i];
  14602. if (v != 0)
  14603. v->callListeners();
  14604. }
  14605. }
  14606. else
  14607. {
  14608. triggerAsyncUpdate();
  14609. }
  14610. }
  14611. void Value::ValueSource::handleAsyncUpdate()
  14612. {
  14613. sendChangeMessage (true);
  14614. }
  14615. class SimpleValueSource : public Value::ValueSource
  14616. {
  14617. public:
  14618. SimpleValueSource()
  14619. {
  14620. }
  14621. SimpleValueSource (const var& initialValue)
  14622. : value (initialValue)
  14623. {
  14624. }
  14625. const var getValue() const
  14626. {
  14627. return value;
  14628. }
  14629. void setValue (const var& newValue)
  14630. {
  14631. if (! newValue.equalsWithSameType (value))
  14632. {
  14633. value = newValue;
  14634. sendChangeMessage (false);
  14635. }
  14636. }
  14637. private:
  14638. var value;
  14639. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14640. };
  14641. Value::Value()
  14642. : value (new SimpleValueSource())
  14643. {
  14644. }
  14645. Value::Value (ValueSource* const value_)
  14646. : value (value_)
  14647. {
  14648. jassert (value_ != 0);
  14649. }
  14650. Value::Value (const var& initialValue)
  14651. : value (new SimpleValueSource (initialValue))
  14652. {
  14653. }
  14654. Value::Value (const Value& other)
  14655. : value (other.value)
  14656. {
  14657. }
  14658. Value& Value::operator= (const Value& other)
  14659. {
  14660. value = other.value;
  14661. return *this;
  14662. }
  14663. Value::~Value()
  14664. {
  14665. if (listeners.size() > 0)
  14666. value->valuesWithListeners.removeValue (this);
  14667. }
  14668. const var Value::getValue() const
  14669. {
  14670. return value->getValue();
  14671. }
  14672. Value::operator const var() const
  14673. {
  14674. return getValue();
  14675. }
  14676. void Value::setValue (const var& newValue)
  14677. {
  14678. value->setValue (newValue);
  14679. }
  14680. const String Value::toString() const
  14681. {
  14682. return value->getValue().toString();
  14683. }
  14684. Value& Value::operator= (const var& newValue)
  14685. {
  14686. value->setValue (newValue);
  14687. return *this;
  14688. }
  14689. void Value::referTo (const Value& valueToReferTo)
  14690. {
  14691. if (valueToReferTo.value != value)
  14692. {
  14693. if (listeners.size() > 0)
  14694. {
  14695. value->valuesWithListeners.removeValue (this);
  14696. valueToReferTo.value->valuesWithListeners.add (this);
  14697. }
  14698. value = valueToReferTo.value;
  14699. callListeners();
  14700. }
  14701. }
  14702. bool Value::refersToSameSourceAs (const Value& other) const
  14703. {
  14704. return value == other.value;
  14705. }
  14706. bool Value::operator== (const Value& other) const
  14707. {
  14708. return value == other.value || value->getValue() == other.getValue();
  14709. }
  14710. bool Value::operator!= (const Value& other) const
  14711. {
  14712. return value != other.value && value->getValue() != other.getValue();
  14713. }
  14714. void Value::addListener (ValueListener* const listener)
  14715. {
  14716. if (listener != 0)
  14717. {
  14718. if (listeners.size() == 0)
  14719. value->valuesWithListeners.add (this);
  14720. listeners.add (listener);
  14721. }
  14722. }
  14723. void Value::removeListener (ValueListener* const listener)
  14724. {
  14725. listeners.remove (listener);
  14726. if (listeners.size() == 0)
  14727. value->valuesWithListeners.removeValue (this);
  14728. }
  14729. void Value::callListeners()
  14730. {
  14731. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14732. listeners.call (&ValueListener::valueChanged, v);
  14733. }
  14734. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14735. {
  14736. return stream << value.toString();
  14737. }
  14738. END_JUCE_NAMESPACE
  14739. /*** End of inlined file: juce_Value.cpp ***/
  14740. /*** Start of inlined file: juce_Application.cpp ***/
  14741. BEGIN_JUCE_NAMESPACE
  14742. #if JUCE_MAC
  14743. extern void juce_initialiseMacMainMenu();
  14744. #endif
  14745. JUCEApplication::JUCEApplication()
  14746. : appReturnValue (0),
  14747. stillInitialising (true)
  14748. {
  14749. jassert (isStandaloneApp() && appInstance == 0);
  14750. appInstance = this;
  14751. }
  14752. JUCEApplication::~JUCEApplication()
  14753. {
  14754. if (appLock != 0)
  14755. {
  14756. appLock->exit();
  14757. appLock = 0;
  14758. }
  14759. jassert (appInstance == this);
  14760. appInstance = 0;
  14761. }
  14762. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14763. JUCEApplication* JUCEApplication::appInstance = 0;
  14764. bool JUCEApplication::moreThanOneInstanceAllowed()
  14765. {
  14766. return true;
  14767. }
  14768. void JUCEApplication::anotherInstanceStarted (const String&)
  14769. {
  14770. }
  14771. void JUCEApplication::systemRequestedQuit()
  14772. {
  14773. quit();
  14774. }
  14775. void JUCEApplication::quit()
  14776. {
  14777. MessageManager::getInstance()->stopDispatchLoop();
  14778. }
  14779. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14780. {
  14781. appReturnValue = newReturnValue;
  14782. }
  14783. void JUCEApplication::actionListenerCallback (const String& message)
  14784. {
  14785. if (message.startsWith (getApplicationName() + "/"))
  14786. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14787. }
  14788. void JUCEApplication::unhandledException (const std::exception*,
  14789. const String&,
  14790. const int)
  14791. {
  14792. jassertfalse;
  14793. }
  14794. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14795. const char* const sourceFile,
  14796. const int lineNumber)
  14797. {
  14798. if (appInstance != 0)
  14799. appInstance->unhandledException (e, sourceFile, lineNumber);
  14800. }
  14801. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14802. {
  14803. return 0;
  14804. }
  14805. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14806. {
  14807. commands.add (StandardApplicationCommandIDs::quit);
  14808. }
  14809. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14810. {
  14811. if (commandID == StandardApplicationCommandIDs::quit)
  14812. {
  14813. result.setInfo (TRANS("Quit"),
  14814. TRANS("Quits the application"),
  14815. "Application",
  14816. 0);
  14817. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14818. }
  14819. }
  14820. bool JUCEApplication::perform (const InvocationInfo& info)
  14821. {
  14822. if (info.commandID == StandardApplicationCommandIDs::quit)
  14823. {
  14824. systemRequestedQuit();
  14825. return true;
  14826. }
  14827. return false;
  14828. }
  14829. bool JUCEApplication::initialiseApp (const String& commandLine)
  14830. {
  14831. commandLineParameters = commandLine.trim();
  14832. #if ! JUCE_IOS
  14833. jassert (appLock == 0); // initialiseApp must only be called once!
  14834. if (! moreThanOneInstanceAllowed())
  14835. {
  14836. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14837. if (! appLock->enter(0))
  14838. {
  14839. appLock = 0;
  14840. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14841. DBG ("Another instance is running - quitting...");
  14842. return false;
  14843. }
  14844. }
  14845. #endif
  14846. // let the app do its setting-up..
  14847. initialise (commandLineParameters);
  14848. #if JUCE_MAC
  14849. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14850. #endif
  14851. // register for broadcast new app messages
  14852. MessageManager::getInstance()->registerBroadcastListener (this);
  14853. stillInitialising = false;
  14854. return true;
  14855. }
  14856. int JUCEApplication::shutdownApp()
  14857. {
  14858. jassert (appInstance == this);
  14859. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14860. JUCE_TRY
  14861. {
  14862. // give the app a chance to clean up..
  14863. shutdown();
  14864. }
  14865. JUCE_CATCH_EXCEPTION
  14866. return getApplicationReturnValue();
  14867. }
  14868. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14869. void JUCEApplication::appWillTerminateByForce()
  14870. {
  14871. {
  14872. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14873. if (app != 0)
  14874. app->shutdownApp();
  14875. }
  14876. shutdownJuce_GUI();
  14877. }
  14878. int JUCEApplication::main (const String& commandLine)
  14879. {
  14880. ScopedJuceInitialiser_GUI libraryInitialiser;
  14881. jassert (createInstance != 0);
  14882. int returnCode = 0;
  14883. {
  14884. const ScopedPointer<JUCEApplication> app (createInstance());
  14885. if (! app->initialiseApp (commandLine))
  14886. return 0;
  14887. JUCE_TRY
  14888. {
  14889. // loop until a quit message is received..
  14890. MessageManager::getInstance()->runDispatchLoop();
  14891. }
  14892. JUCE_CATCH_EXCEPTION
  14893. returnCode = app->shutdownApp();
  14894. }
  14895. return returnCode;
  14896. }
  14897. #if JUCE_IOS
  14898. extern int juce_iOSMain (int argc, const char* argv[]);
  14899. #endif
  14900. #if ! JUCE_WINDOWS
  14901. extern const char* juce_Argv0;
  14902. #endif
  14903. int JUCEApplication::main (int argc, const char* argv[])
  14904. {
  14905. JUCE_AUTORELEASEPOOL
  14906. #if ! JUCE_WINDOWS
  14907. jassert (createInstance != 0);
  14908. juce_Argv0 = argv[0];
  14909. #endif
  14910. #if JUCE_IOS
  14911. return juce_iOSMain (argc, argv);
  14912. #else
  14913. String cmd;
  14914. for (int i = 1; i < argc; ++i)
  14915. cmd << argv[i] << ' ';
  14916. return JUCEApplication::main (cmd);
  14917. #endif
  14918. }
  14919. END_JUCE_NAMESPACE
  14920. /*** End of inlined file: juce_Application.cpp ***/
  14921. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14922. BEGIN_JUCE_NAMESPACE
  14923. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14924. : commandID (commandID_),
  14925. flags (0)
  14926. {
  14927. }
  14928. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14929. const String& description_,
  14930. const String& categoryName_,
  14931. const int flags_) throw()
  14932. {
  14933. shortName = shortName_;
  14934. description = description_;
  14935. categoryName = categoryName_;
  14936. flags = flags_;
  14937. }
  14938. void ApplicationCommandInfo::setActive (const bool b) throw()
  14939. {
  14940. if (b)
  14941. flags &= ~isDisabled;
  14942. else
  14943. flags |= isDisabled;
  14944. }
  14945. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14946. {
  14947. if (b)
  14948. flags |= isTicked;
  14949. else
  14950. flags &= ~isTicked;
  14951. }
  14952. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14953. {
  14954. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14955. }
  14956. END_JUCE_NAMESPACE
  14957. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14958. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14959. BEGIN_JUCE_NAMESPACE
  14960. ApplicationCommandManager::ApplicationCommandManager()
  14961. : firstTarget (0)
  14962. {
  14963. keyMappings = new KeyPressMappingSet (this);
  14964. Desktop::getInstance().addFocusChangeListener (this);
  14965. }
  14966. ApplicationCommandManager::~ApplicationCommandManager()
  14967. {
  14968. Desktop::getInstance().removeFocusChangeListener (this);
  14969. keyMappings = 0;
  14970. }
  14971. void ApplicationCommandManager::clearCommands()
  14972. {
  14973. commands.clear();
  14974. keyMappings->clearAllKeyPresses();
  14975. triggerAsyncUpdate();
  14976. }
  14977. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14978. {
  14979. // zero isn't a valid command ID!
  14980. jassert (newCommand.commandID != 0);
  14981. // the name isn't optional!
  14982. jassert (newCommand.shortName.isNotEmpty());
  14983. if (getCommandForID (newCommand.commandID) == 0)
  14984. {
  14985. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14986. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14987. commands.add (newInfo);
  14988. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14989. triggerAsyncUpdate();
  14990. }
  14991. else
  14992. {
  14993. // trying to re-register the same command with different parameters?
  14994. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14995. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14996. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14997. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14998. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14999. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15000. }
  15001. }
  15002. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15003. {
  15004. if (target != 0)
  15005. {
  15006. Array <CommandID> commandIDs;
  15007. target->getAllCommands (commandIDs);
  15008. for (int i = 0; i < commandIDs.size(); ++i)
  15009. {
  15010. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15011. target->getCommandInfo (info.commandID, info);
  15012. registerCommand (info);
  15013. }
  15014. }
  15015. }
  15016. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15017. {
  15018. for (int i = commands.size(); --i >= 0;)
  15019. {
  15020. if (commands.getUnchecked (i)->commandID == commandID)
  15021. {
  15022. commands.remove (i);
  15023. triggerAsyncUpdate();
  15024. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15025. for (int j = keys.size(); --j >= 0;)
  15026. keyMappings->removeKeyPress (keys.getReference (j));
  15027. }
  15028. }
  15029. }
  15030. void ApplicationCommandManager::commandStatusChanged()
  15031. {
  15032. triggerAsyncUpdate();
  15033. }
  15034. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15035. {
  15036. for (int i = commands.size(); --i >= 0;)
  15037. if (commands.getUnchecked(i)->commandID == commandID)
  15038. return commands.getUnchecked(i);
  15039. return 0;
  15040. }
  15041. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15042. {
  15043. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15044. return (ci != 0) ? ci->shortName : String::empty;
  15045. }
  15046. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15047. {
  15048. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15049. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15050. : String::empty;
  15051. }
  15052. const StringArray ApplicationCommandManager::getCommandCategories() const
  15053. {
  15054. StringArray s;
  15055. for (int i = 0; i < commands.size(); ++i)
  15056. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15057. return s;
  15058. }
  15059. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15060. {
  15061. Array <CommandID> results;
  15062. for (int i = 0; i < commands.size(); ++i)
  15063. if (commands.getUnchecked(i)->categoryName == categoryName)
  15064. results.add (commands.getUnchecked(i)->commandID);
  15065. return results;
  15066. }
  15067. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15068. {
  15069. ApplicationCommandTarget::InvocationInfo info (commandID);
  15070. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15071. return invoke (info, asynchronously);
  15072. }
  15073. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15074. {
  15075. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15076. // manager first..
  15077. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15078. ApplicationCommandInfo commandInfo (0);
  15079. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15080. if (target == 0)
  15081. return false;
  15082. ApplicationCommandTarget::InvocationInfo info (info_);
  15083. info.commandFlags = commandInfo.flags;
  15084. sendListenerInvokeCallback (info);
  15085. const bool ok = target->invoke (info, asynchronously);
  15086. commandStatusChanged();
  15087. return ok;
  15088. }
  15089. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15090. {
  15091. return firstTarget != 0 ? firstTarget
  15092. : findDefaultComponentTarget();
  15093. }
  15094. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15095. {
  15096. firstTarget = newTarget;
  15097. }
  15098. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15099. ApplicationCommandInfo& upToDateInfo)
  15100. {
  15101. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15102. if (target == 0)
  15103. target = JUCEApplication::getInstance();
  15104. if (target != 0)
  15105. target = target->getTargetForCommand (commandID);
  15106. if (target != 0)
  15107. target->getCommandInfo (commandID, upToDateInfo);
  15108. return target;
  15109. }
  15110. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15111. {
  15112. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15113. if (target == 0 && c != 0)
  15114. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15115. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15116. return target;
  15117. }
  15118. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15119. {
  15120. Component* c = Component::getCurrentlyFocusedComponent();
  15121. if (c == 0)
  15122. {
  15123. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15124. if (activeWindow != 0)
  15125. {
  15126. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15127. if (c == 0)
  15128. c = activeWindow;
  15129. }
  15130. }
  15131. if (c == 0 && Process::isForegroundProcess())
  15132. {
  15133. // getting a bit desperate now - try all desktop comps..
  15134. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15135. {
  15136. ApplicationCommandTarget* const target
  15137. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15138. ->getPeer()->getLastFocusedSubcomponent());
  15139. if (target != 0)
  15140. return target;
  15141. }
  15142. }
  15143. if (c != 0)
  15144. {
  15145. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15146. // if we're focused on a ResizableWindow, chances are that it's the content
  15147. // component that really should get the event. And if not, the event will
  15148. // still be passed up to the top level window anyway, so let's send it to the
  15149. // content comp.
  15150. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15151. c = resizableWindow->getContentComponent();
  15152. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15153. if (target != 0)
  15154. return target;
  15155. }
  15156. return JUCEApplication::getInstance();
  15157. }
  15158. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15159. {
  15160. listeners.add (listener);
  15161. }
  15162. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15163. {
  15164. listeners.remove (listener);
  15165. }
  15166. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15167. {
  15168. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15169. }
  15170. void ApplicationCommandManager::handleAsyncUpdate()
  15171. {
  15172. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15173. }
  15174. void ApplicationCommandManager::globalFocusChanged (Component*)
  15175. {
  15176. commandStatusChanged();
  15177. }
  15178. END_JUCE_NAMESPACE
  15179. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15180. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15181. BEGIN_JUCE_NAMESPACE
  15182. ApplicationCommandTarget::ApplicationCommandTarget()
  15183. {
  15184. }
  15185. ApplicationCommandTarget::~ApplicationCommandTarget()
  15186. {
  15187. messageInvoker = 0;
  15188. }
  15189. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15190. {
  15191. if (isCommandActive (info.commandID))
  15192. {
  15193. if (async)
  15194. {
  15195. if (messageInvoker == 0)
  15196. messageInvoker = new CommandTargetMessageInvoker (this);
  15197. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15198. return true;
  15199. }
  15200. else
  15201. {
  15202. const bool success = perform (info);
  15203. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15204. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15205. // returns the command's info.
  15206. return success;
  15207. }
  15208. }
  15209. return false;
  15210. }
  15211. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15212. {
  15213. Component* c = dynamic_cast <Component*> (this);
  15214. if (c != 0)
  15215. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15216. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15217. return 0;
  15218. }
  15219. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15220. {
  15221. ApplicationCommandTarget* target = this;
  15222. int depth = 0;
  15223. while (target != 0)
  15224. {
  15225. Array <CommandID> commandIDs;
  15226. target->getAllCommands (commandIDs);
  15227. if (commandIDs.contains (commandID))
  15228. return target;
  15229. target = target->getNextCommandTarget();
  15230. ++depth;
  15231. jassert (depth < 100); // could be a recursive command chain??
  15232. jassert (target != this); // definitely a recursive command chain!
  15233. if (depth > 100 || target == this)
  15234. break;
  15235. }
  15236. if (target == 0)
  15237. {
  15238. target = JUCEApplication::getInstance();
  15239. if (target != 0)
  15240. {
  15241. Array <CommandID> commandIDs;
  15242. target->getAllCommands (commandIDs);
  15243. if (commandIDs.contains (commandID))
  15244. return target;
  15245. }
  15246. }
  15247. return 0;
  15248. }
  15249. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15250. {
  15251. ApplicationCommandInfo info (commandID);
  15252. info.flags = ApplicationCommandInfo::isDisabled;
  15253. getCommandInfo (commandID, info);
  15254. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15255. }
  15256. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15257. {
  15258. ApplicationCommandTarget* target = this;
  15259. int depth = 0;
  15260. while (target != 0)
  15261. {
  15262. if (target->tryToInvoke (info, async))
  15263. return true;
  15264. target = target->getNextCommandTarget();
  15265. ++depth;
  15266. jassert (depth < 100); // could be a recursive command chain??
  15267. jassert (target != this); // definitely a recursive command chain!
  15268. if (depth > 100 || target == this)
  15269. break;
  15270. }
  15271. if (target == 0)
  15272. {
  15273. target = JUCEApplication::getInstance();
  15274. if (target != 0)
  15275. return target->tryToInvoke (info, async);
  15276. }
  15277. return false;
  15278. }
  15279. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15280. {
  15281. ApplicationCommandTarget::InvocationInfo info (commandID);
  15282. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15283. return invoke (info, asynchronously);
  15284. }
  15285. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15286. : commandID (commandID_),
  15287. commandFlags (0),
  15288. invocationMethod (direct),
  15289. originatingComponent (0),
  15290. isKeyDown (false),
  15291. millisecsSinceKeyPressed (0)
  15292. {
  15293. }
  15294. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15295. : owner (owner_)
  15296. {
  15297. }
  15298. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15299. {
  15300. }
  15301. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15302. {
  15303. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15304. owner->tryToInvoke (*info, false);
  15305. }
  15306. END_JUCE_NAMESPACE
  15307. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15308. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15309. BEGIN_JUCE_NAMESPACE
  15310. juce_ImplementSingleton (ApplicationProperties)
  15311. ApplicationProperties::ApplicationProperties()
  15312. : msBeforeSaving (3000),
  15313. options (PropertiesFile::storeAsBinary),
  15314. commonSettingsAreReadOnly (0),
  15315. processLock (0)
  15316. {
  15317. }
  15318. ApplicationProperties::~ApplicationProperties()
  15319. {
  15320. closeFiles();
  15321. clearSingletonInstance();
  15322. }
  15323. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15324. const String& fileNameSuffix,
  15325. const String& folderName_,
  15326. const int millisecondsBeforeSaving,
  15327. const int propertiesFileOptions,
  15328. InterProcessLock* processLock_)
  15329. {
  15330. appName = applicationName;
  15331. fileSuffix = fileNameSuffix;
  15332. folderName = folderName_;
  15333. msBeforeSaving = millisecondsBeforeSaving;
  15334. options = propertiesFileOptions;
  15335. processLock = processLock_;
  15336. }
  15337. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15338. const bool testCommonSettings,
  15339. const bool showWarningDialogOnFailure)
  15340. {
  15341. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15342. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15343. if (! (userOk && commonOk))
  15344. {
  15345. if (showWarningDialogOnFailure)
  15346. {
  15347. String filenames;
  15348. if (userProps != 0 && ! userOk)
  15349. filenames << '\n' << userProps->getFile().getFullPathName();
  15350. if (commonProps != 0 && ! commonOk)
  15351. filenames << '\n' << commonProps->getFile().getFullPathName();
  15352. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15353. appName + TRANS(" - Unable to save settings"),
  15354. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15355. + appName + TRANS(" needs to be able to write to the following files:\n")
  15356. + filenames
  15357. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15358. }
  15359. return false;
  15360. }
  15361. return true;
  15362. }
  15363. void ApplicationProperties::openFiles()
  15364. {
  15365. // You need to call setStorageParameters() before trying to get hold of the
  15366. // properties!
  15367. jassert (appName.isNotEmpty());
  15368. if (appName.isNotEmpty())
  15369. {
  15370. if (userProps == 0)
  15371. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15372. false, msBeforeSaving, options, processLock);
  15373. if (commonProps == 0)
  15374. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15375. true, msBeforeSaving, options, processLock);
  15376. userProps->setFallbackPropertySet (commonProps);
  15377. }
  15378. }
  15379. PropertiesFile* ApplicationProperties::getUserSettings()
  15380. {
  15381. if (userProps == 0)
  15382. openFiles();
  15383. return userProps;
  15384. }
  15385. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15386. {
  15387. if (commonProps == 0)
  15388. openFiles();
  15389. if (returnUserPropsIfReadOnly)
  15390. {
  15391. if (commonSettingsAreReadOnly == 0)
  15392. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15393. if (commonSettingsAreReadOnly > 0)
  15394. return userProps;
  15395. }
  15396. return commonProps;
  15397. }
  15398. bool ApplicationProperties::saveIfNeeded()
  15399. {
  15400. return (userProps == 0 || userProps->saveIfNeeded())
  15401. && (commonProps == 0 || commonProps->saveIfNeeded());
  15402. }
  15403. void ApplicationProperties::closeFiles()
  15404. {
  15405. userProps = 0;
  15406. commonProps = 0;
  15407. }
  15408. END_JUCE_NAMESPACE
  15409. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15410. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15411. BEGIN_JUCE_NAMESPACE
  15412. namespace PropertyFileConstants
  15413. {
  15414. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15415. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15416. static const char* const fileTag = "PROPERTIES";
  15417. static const char* const valueTag = "VALUE";
  15418. static const char* const nameAttribute = "name";
  15419. static const char* const valueAttribute = "val";
  15420. }
  15421. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15422. const int options_, InterProcessLock* const processLock_)
  15423. : PropertySet (ignoreCaseOfKeyNames),
  15424. file (f),
  15425. timerInterval (millisecondsBeforeSaving),
  15426. options (options_),
  15427. loadedOk (false),
  15428. needsWriting (false),
  15429. processLock (processLock_)
  15430. {
  15431. // You need to correctly specify just one storage format for the file
  15432. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15433. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15434. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15435. ProcessScopedLock pl (createProcessLock());
  15436. if (pl != 0 && ! pl->isLocked())
  15437. return; // locking failure..
  15438. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15439. if (fileStream != 0)
  15440. {
  15441. int magicNumber = fileStream->readInt();
  15442. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15443. {
  15444. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15445. magicNumber = PropertyFileConstants::magicNumber;
  15446. }
  15447. if (magicNumber == PropertyFileConstants::magicNumber)
  15448. {
  15449. loadedOk = true;
  15450. BufferedInputStream in (fileStream.release(), 2048, true);
  15451. int numValues = in.readInt();
  15452. while (--numValues >= 0 && ! in.isExhausted())
  15453. {
  15454. const String key (in.readString());
  15455. const String value (in.readString());
  15456. jassert (key.isNotEmpty());
  15457. if (key.isNotEmpty())
  15458. getAllProperties().set (key, value);
  15459. }
  15460. }
  15461. else
  15462. {
  15463. // Not a binary props file - let's see if it's XML..
  15464. fileStream = 0;
  15465. XmlDocument parser (f);
  15466. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15467. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15468. {
  15469. doc = parser.getDocumentElement();
  15470. if (doc != 0)
  15471. {
  15472. loadedOk = true;
  15473. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15474. {
  15475. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15476. if (name.isNotEmpty())
  15477. {
  15478. getAllProperties().set (name,
  15479. e->getFirstChildElement() != 0
  15480. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15481. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15482. }
  15483. }
  15484. }
  15485. else
  15486. {
  15487. // must be a pretty broken XML file we're trying to parse here,
  15488. // or a sign that this object needs an InterProcessLock,
  15489. // or just a failure reading the file. This last reason is why
  15490. // we don't jassertfalse here.
  15491. }
  15492. }
  15493. }
  15494. }
  15495. else
  15496. {
  15497. loadedOk = ! f.exists();
  15498. }
  15499. }
  15500. PropertiesFile::~PropertiesFile()
  15501. {
  15502. if (! saveIfNeeded())
  15503. jassertfalse;
  15504. }
  15505. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15506. {
  15507. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15508. }
  15509. bool PropertiesFile::saveIfNeeded()
  15510. {
  15511. const ScopedLock sl (getLock());
  15512. return (! needsWriting) || save();
  15513. }
  15514. bool PropertiesFile::needsToBeSaved() const
  15515. {
  15516. const ScopedLock sl (getLock());
  15517. return needsWriting;
  15518. }
  15519. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15520. {
  15521. const ScopedLock sl (getLock());
  15522. needsWriting = needsToBeSaved_;
  15523. }
  15524. bool PropertiesFile::save()
  15525. {
  15526. const ScopedLock sl (getLock());
  15527. stopTimer();
  15528. if (file == File::nonexistent
  15529. || file.isDirectory()
  15530. || ! file.getParentDirectory().createDirectory())
  15531. return false;
  15532. if ((options & storeAsXML) != 0)
  15533. {
  15534. XmlElement doc (PropertyFileConstants::fileTag);
  15535. for (int i = 0; i < getAllProperties().size(); ++i)
  15536. {
  15537. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15538. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15539. // if the value seems to contain xml, store it as such..
  15540. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15541. if (childElement != 0)
  15542. e->addChildElement (childElement);
  15543. else
  15544. e->setAttribute (PropertyFileConstants::valueAttribute,
  15545. getAllProperties().getAllValues() [i]);
  15546. }
  15547. ProcessScopedLock pl (createProcessLock());
  15548. if (pl != 0 && ! pl->isLocked())
  15549. return false; // locking failure..
  15550. if (doc.writeToFile (file, String::empty))
  15551. {
  15552. needsWriting = false;
  15553. return true;
  15554. }
  15555. }
  15556. else
  15557. {
  15558. ProcessScopedLock pl (createProcessLock());
  15559. if (pl != 0 && ! pl->isLocked())
  15560. return false; // locking failure..
  15561. TemporaryFile tempFile (file);
  15562. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15563. if (out != 0)
  15564. {
  15565. if ((options & storeAsCompressedBinary) != 0)
  15566. {
  15567. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15568. out->flush();
  15569. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15570. }
  15571. else
  15572. {
  15573. // have you set up the storage option flags correctly?
  15574. jassert ((options & storeAsBinary) != 0);
  15575. out->writeInt (PropertyFileConstants::magicNumber);
  15576. }
  15577. const int numProperties = getAllProperties().size();
  15578. out->writeInt (numProperties);
  15579. for (int i = 0; i < numProperties; ++i)
  15580. {
  15581. out->writeString (getAllProperties().getAllKeys() [i]);
  15582. out->writeString (getAllProperties().getAllValues() [i]);
  15583. }
  15584. out = 0;
  15585. if (tempFile.overwriteTargetFileWithTemporary())
  15586. {
  15587. needsWriting = false;
  15588. return true;
  15589. }
  15590. }
  15591. }
  15592. return false;
  15593. }
  15594. void PropertiesFile::timerCallback()
  15595. {
  15596. saveIfNeeded();
  15597. }
  15598. void PropertiesFile::propertyChanged()
  15599. {
  15600. sendChangeMessage();
  15601. needsWriting = true;
  15602. if (timerInterval > 0)
  15603. startTimer (timerInterval);
  15604. else if (timerInterval == 0)
  15605. saveIfNeeded();
  15606. }
  15607. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15608. const String& fileNameSuffix,
  15609. const String& folderName,
  15610. const bool commonToAllUsers)
  15611. {
  15612. // mustn't have illegal characters in this name..
  15613. jassert (applicationName == File::createLegalFileName (applicationName));
  15614. #if JUCE_MAC || JUCE_IOS
  15615. File dir (commonToAllUsers ? "/Library/Preferences"
  15616. : "~/Library/Preferences");
  15617. if (folderName.isNotEmpty())
  15618. dir = dir.getChildFile (folderName);
  15619. #elif JUCE_LINUX || JUCE_ANDROID
  15620. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15621. + (folderName.isNotEmpty() ? folderName
  15622. : ("." + applicationName)));
  15623. #elif JUCE_WINDOWS
  15624. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15625. : File::userApplicationDataDirectory));
  15626. if (dir == File::nonexistent)
  15627. return File::nonexistent;
  15628. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15629. : applicationName);
  15630. #endif
  15631. return dir.getChildFile (applicationName)
  15632. .withFileExtension (fileNameSuffix);
  15633. }
  15634. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15635. const String& fileNameSuffix,
  15636. const String& folderName,
  15637. const bool commonToAllUsers,
  15638. const int millisecondsBeforeSaving,
  15639. const int propertiesFileOptions,
  15640. InterProcessLock* processLock_)
  15641. {
  15642. const File file (getDefaultAppSettingsFile (applicationName,
  15643. fileNameSuffix,
  15644. folderName,
  15645. commonToAllUsers));
  15646. jassert (file != File::nonexistent);
  15647. if (file == File::nonexistent)
  15648. return 0;
  15649. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15650. }
  15651. END_JUCE_NAMESPACE
  15652. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15653. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15654. BEGIN_JUCE_NAMESPACE
  15655. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15656. const String& fileWildcard_,
  15657. const String& openFileDialogTitle_,
  15658. const String& saveFileDialogTitle_)
  15659. : changedSinceSave (false),
  15660. fileExtension (fileExtension_),
  15661. fileWildcard (fileWildcard_),
  15662. openFileDialogTitle (openFileDialogTitle_),
  15663. saveFileDialogTitle (saveFileDialogTitle_)
  15664. {
  15665. }
  15666. FileBasedDocument::~FileBasedDocument()
  15667. {
  15668. }
  15669. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15670. {
  15671. if (changedSinceSave != hasChanged)
  15672. {
  15673. changedSinceSave = hasChanged;
  15674. sendChangeMessage();
  15675. }
  15676. }
  15677. void FileBasedDocument::changed()
  15678. {
  15679. changedSinceSave = true;
  15680. sendChangeMessage();
  15681. }
  15682. void FileBasedDocument::setFile (const File& newFile)
  15683. {
  15684. if (documentFile != newFile)
  15685. {
  15686. documentFile = newFile;
  15687. changed();
  15688. }
  15689. }
  15690. bool FileBasedDocument::loadFrom (const File& newFile,
  15691. const bool showMessageOnFailure)
  15692. {
  15693. MouseCursor::showWaitCursor();
  15694. const File oldFile (documentFile);
  15695. documentFile = newFile;
  15696. String error;
  15697. if (newFile.existsAsFile())
  15698. {
  15699. error = loadDocument (newFile);
  15700. if (error.isEmpty())
  15701. {
  15702. setChangedFlag (false);
  15703. MouseCursor::hideWaitCursor();
  15704. setLastDocumentOpened (newFile);
  15705. return true;
  15706. }
  15707. }
  15708. else
  15709. {
  15710. error = "The file doesn't exist";
  15711. }
  15712. documentFile = oldFile;
  15713. MouseCursor::hideWaitCursor();
  15714. if (showMessageOnFailure)
  15715. {
  15716. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15717. TRANS("Failed to open file..."),
  15718. TRANS("There was an error while trying to load the file:\n\n")
  15719. + newFile.getFullPathName()
  15720. + "\n\n"
  15721. + error);
  15722. }
  15723. return false;
  15724. }
  15725. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15726. {
  15727. FileChooser fc (openFileDialogTitle,
  15728. getLastDocumentOpened(),
  15729. fileWildcard);
  15730. if (fc.browseForFileToOpen())
  15731. return loadFrom (fc.getResult(), showMessageOnFailure);
  15732. return false;
  15733. }
  15734. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15735. const bool showMessageOnFailure)
  15736. {
  15737. return saveAs (documentFile,
  15738. false,
  15739. askUserForFileIfNotSpecified,
  15740. showMessageOnFailure);
  15741. }
  15742. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15743. const bool warnAboutOverwritingExistingFiles,
  15744. const bool askUserForFileIfNotSpecified,
  15745. const bool showMessageOnFailure)
  15746. {
  15747. if (newFile == File::nonexistent)
  15748. {
  15749. if (askUserForFileIfNotSpecified)
  15750. {
  15751. return saveAsInteractive (true);
  15752. }
  15753. else
  15754. {
  15755. // can't save to an unspecified file
  15756. jassertfalse;
  15757. return failedToWriteToFile;
  15758. }
  15759. }
  15760. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15761. {
  15762. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15763. TRANS("File already exists"),
  15764. TRANS("There's already a file called:\n\n")
  15765. + newFile.getFullPathName()
  15766. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15767. TRANS("overwrite"),
  15768. TRANS("cancel")))
  15769. {
  15770. return userCancelledSave;
  15771. }
  15772. }
  15773. MouseCursor::showWaitCursor();
  15774. const File oldFile (documentFile);
  15775. documentFile = newFile;
  15776. String error (saveDocument (newFile));
  15777. if (error.isEmpty())
  15778. {
  15779. setChangedFlag (false);
  15780. MouseCursor::hideWaitCursor();
  15781. return savedOk;
  15782. }
  15783. documentFile = oldFile;
  15784. MouseCursor::hideWaitCursor();
  15785. if (showMessageOnFailure)
  15786. {
  15787. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15788. TRANS("Error writing to file..."),
  15789. TRANS("An error occurred while trying to save \"")
  15790. + getDocumentTitle()
  15791. + TRANS("\" to the file:\n\n")
  15792. + newFile.getFullPathName()
  15793. + "\n\n"
  15794. + error);
  15795. }
  15796. return failedToWriteToFile;
  15797. }
  15798. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15799. {
  15800. if (! hasChangedSinceSaved())
  15801. return savedOk;
  15802. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15803. TRANS("Closing document..."),
  15804. TRANS("Do you want to save the changes to \"")
  15805. + getDocumentTitle() + "\"?",
  15806. TRANS("save"),
  15807. TRANS("discard changes"),
  15808. TRANS("cancel"));
  15809. if (r == 1)
  15810. {
  15811. // save changes
  15812. return save (true, true);
  15813. }
  15814. else if (r == 2)
  15815. {
  15816. // discard changes
  15817. return savedOk;
  15818. }
  15819. return userCancelledSave;
  15820. }
  15821. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15822. {
  15823. File f;
  15824. if (documentFile.existsAsFile())
  15825. f = documentFile;
  15826. else
  15827. f = getLastDocumentOpened();
  15828. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15829. if (legalFilename.isEmpty())
  15830. legalFilename = "unnamed";
  15831. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15832. f = f.getSiblingFile (legalFilename);
  15833. else
  15834. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15835. f = f.withFileExtension (fileExtension)
  15836. .getNonexistentSibling (true);
  15837. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15838. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15839. {
  15840. File chosen (fc.getResult());
  15841. if (chosen.getFileExtension().isEmpty())
  15842. {
  15843. chosen = chosen.withFileExtension (fileExtension);
  15844. if (chosen.exists())
  15845. {
  15846. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15847. TRANS("File already exists"),
  15848. TRANS("There's already a file called:")
  15849. + "\n\n" + chosen.getFullPathName()
  15850. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15851. TRANS("overwrite"),
  15852. TRANS("cancel")))
  15853. {
  15854. return userCancelledSave;
  15855. }
  15856. }
  15857. }
  15858. setLastDocumentOpened (chosen);
  15859. return saveAs (chosen, false, false, true);
  15860. }
  15861. return userCancelledSave;
  15862. }
  15863. END_JUCE_NAMESPACE
  15864. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15865. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15866. BEGIN_JUCE_NAMESPACE
  15867. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15868. : maxNumberOfItems (10)
  15869. {
  15870. }
  15871. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15872. {
  15873. }
  15874. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15875. {
  15876. maxNumberOfItems = jmax (1, newMaxNumber);
  15877. while (getNumFiles() > maxNumberOfItems)
  15878. files.remove (getNumFiles() - 1);
  15879. }
  15880. int RecentlyOpenedFilesList::getNumFiles() const
  15881. {
  15882. return files.size();
  15883. }
  15884. const File RecentlyOpenedFilesList::getFile (const int index) const
  15885. {
  15886. return File (files [index]);
  15887. }
  15888. void RecentlyOpenedFilesList::clear()
  15889. {
  15890. files.clear();
  15891. }
  15892. void RecentlyOpenedFilesList::addFile (const File& file)
  15893. {
  15894. const String path (file.getFullPathName());
  15895. files.removeString (path, true);
  15896. files.insert (0, path);
  15897. setMaxNumberOfItems (maxNumberOfItems);
  15898. }
  15899. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15900. {
  15901. for (int i = getNumFiles(); --i >= 0;)
  15902. if (! getFile(i).exists())
  15903. files.remove (i);
  15904. }
  15905. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15906. const int baseItemId,
  15907. const bool showFullPaths,
  15908. const bool dontAddNonExistentFiles,
  15909. const File** filesToAvoid)
  15910. {
  15911. int num = 0;
  15912. for (int i = 0; i < getNumFiles(); ++i)
  15913. {
  15914. const File f (getFile(i));
  15915. if ((! dontAddNonExistentFiles) || f.exists())
  15916. {
  15917. bool needsAvoiding = false;
  15918. if (filesToAvoid != 0)
  15919. {
  15920. const File** avoid = filesToAvoid;
  15921. while (*avoid != 0)
  15922. {
  15923. if (f == **avoid)
  15924. {
  15925. needsAvoiding = true;
  15926. break;
  15927. }
  15928. ++avoid;
  15929. }
  15930. }
  15931. if (! needsAvoiding)
  15932. {
  15933. menuToAddTo.addItem (baseItemId + i,
  15934. showFullPaths ? f.getFullPathName()
  15935. : f.getFileName());
  15936. ++num;
  15937. }
  15938. }
  15939. }
  15940. return num;
  15941. }
  15942. const String RecentlyOpenedFilesList::toString() const
  15943. {
  15944. return files.joinIntoString ("\n");
  15945. }
  15946. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15947. {
  15948. clear();
  15949. files.addLines (stringifiedVersion);
  15950. setMaxNumberOfItems (maxNumberOfItems);
  15951. }
  15952. END_JUCE_NAMESPACE
  15953. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15954. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15955. BEGIN_JUCE_NAMESPACE
  15956. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15957. const int minimumTransactions)
  15958. : totalUnitsStored (0),
  15959. nextIndex (0),
  15960. newTransaction (true),
  15961. reentrancyCheck (false)
  15962. {
  15963. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15964. minimumTransactions);
  15965. }
  15966. UndoManager::~UndoManager()
  15967. {
  15968. clearUndoHistory();
  15969. }
  15970. void UndoManager::clearUndoHistory()
  15971. {
  15972. transactions.clear();
  15973. transactionNames.clear();
  15974. totalUnitsStored = 0;
  15975. nextIndex = 0;
  15976. sendChangeMessage();
  15977. }
  15978. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15979. {
  15980. return totalUnitsStored;
  15981. }
  15982. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15983. const int minimumTransactions)
  15984. {
  15985. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15986. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15987. }
  15988. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15989. {
  15990. if (command_ != 0)
  15991. {
  15992. ScopedPointer<UndoableAction> command (command_);
  15993. if (actionName.isNotEmpty())
  15994. currentTransactionName = actionName;
  15995. if (reentrancyCheck)
  15996. {
  15997. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15998. // undo() methods, or else these actions won't actually get done.
  15999. return false;
  16000. }
  16001. else if (command->perform())
  16002. {
  16003. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16004. if (commandSet != 0 && ! newTransaction)
  16005. {
  16006. UndoableAction* lastAction = commandSet->getLast();
  16007. if (lastAction != 0)
  16008. {
  16009. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16010. if (coalescedAction != 0)
  16011. {
  16012. command = coalescedAction;
  16013. totalUnitsStored -= lastAction->getSizeInUnits();
  16014. commandSet->removeLast();
  16015. }
  16016. }
  16017. }
  16018. else
  16019. {
  16020. commandSet = new OwnedArray<UndoableAction>();
  16021. transactions.insert (nextIndex, commandSet);
  16022. transactionNames.insert (nextIndex, currentTransactionName);
  16023. ++nextIndex;
  16024. }
  16025. totalUnitsStored += command->getSizeInUnits();
  16026. commandSet->add (command.release());
  16027. newTransaction = false;
  16028. while (nextIndex < transactions.size())
  16029. {
  16030. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16031. for (int i = lastSet->size(); --i >= 0;)
  16032. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16033. transactions.removeLast();
  16034. transactionNames.remove (transactionNames.size() - 1);
  16035. }
  16036. while (nextIndex > 0
  16037. && totalUnitsStored > maxNumUnitsToKeep
  16038. && transactions.size() > minimumTransactionsToKeep)
  16039. {
  16040. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16041. for (int i = firstSet->size(); --i >= 0;)
  16042. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16043. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16044. transactions.remove (0);
  16045. transactionNames.remove (0);
  16046. --nextIndex;
  16047. }
  16048. sendChangeMessage();
  16049. return true;
  16050. }
  16051. }
  16052. return false;
  16053. }
  16054. void UndoManager::beginNewTransaction (const String& actionName)
  16055. {
  16056. newTransaction = true;
  16057. currentTransactionName = actionName;
  16058. }
  16059. void UndoManager::setCurrentTransactionName (const String& newName)
  16060. {
  16061. currentTransactionName = newName;
  16062. }
  16063. bool UndoManager::canUndo() const
  16064. {
  16065. return nextIndex > 0;
  16066. }
  16067. bool UndoManager::canRedo() const
  16068. {
  16069. return nextIndex < transactions.size();
  16070. }
  16071. const String UndoManager::getUndoDescription() const
  16072. {
  16073. return transactionNames [nextIndex - 1];
  16074. }
  16075. const String UndoManager::getRedoDescription() const
  16076. {
  16077. return transactionNames [nextIndex];
  16078. }
  16079. bool UndoManager::undo()
  16080. {
  16081. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16082. if (commandSet == 0)
  16083. return false;
  16084. bool failed = false;
  16085. {
  16086. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16087. for (int i = commandSet->size(); --i >= 0;)
  16088. {
  16089. if (! commandSet->getUnchecked(i)->undo())
  16090. {
  16091. jassertfalse;
  16092. failed = true;
  16093. break;
  16094. }
  16095. }
  16096. }
  16097. if (failed)
  16098. clearUndoHistory();
  16099. else
  16100. --nextIndex;
  16101. beginNewTransaction();
  16102. sendChangeMessage();
  16103. return true;
  16104. }
  16105. bool UndoManager::redo()
  16106. {
  16107. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16108. if (commandSet == 0)
  16109. return false;
  16110. bool failed = false;
  16111. {
  16112. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16113. for (int i = 0; i < commandSet->size(); ++i)
  16114. {
  16115. if (! commandSet->getUnchecked(i)->perform())
  16116. {
  16117. jassertfalse;
  16118. failed = true;
  16119. break;
  16120. }
  16121. }
  16122. }
  16123. if (failed)
  16124. clearUndoHistory();
  16125. else
  16126. ++nextIndex;
  16127. beginNewTransaction();
  16128. sendChangeMessage();
  16129. return true;
  16130. }
  16131. bool UndoManager::undoCurrentTransactionOnly()
  16132. {
  16133. return newTransaction ? false : undo();
  16134. }
  16135. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16136. {
  16137. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16138. if (commandSet != 0 && ! newTransaction)
  16139. {
  16140. for (int i = 0; i < commandSet->size(); ++i)
  16141. actionsFound.add (commandSet->getUnchecked(i));
  16142. }
  16143. }
  16144. int UndoManager::getNumActionsInCurrentTransaction() const
  16145. {
  16146. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16147. if (commandSet != 0 && ! newTransaction)
  16148. return commandSet->size();
  16149. return 0;
  16150. }
  16151. END_JUCE_NAMESPACE
  16152. /*** End of inlined file: juce_UndoManager.cpp ***/
  16153. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16154. BEGIN_JUCE_NAMESPACE
  16155. static const char* const aiffFormatName = "AIFF file";
  16156. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16157. class AiffAudioFormatReader : public AudioFormatReader
  16158. {
  16159. public:
  16160. int bytesPerFrame;
  16161. int64 dataChunkStart;
  16162. bool littleEndian;
  16163. AiffAudioFormatReader (InputStream* in)
  16164. : AudioFormatReader (in, TRANS (aiffFormatName))
  16165. {
  16166. if (input->readInt() == chunkName ("FORM"))
  16167. {
  16168. const int len = input->readIntBigEndian();
  16169. const int64 end = input->getPosition() + len;
  16170. const int nextType = input->readInt();
  16171. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16172. {
  16173. bool hasGotVer = false;
  16174. bool hasGotData = false;
  16175. bool hasGotType = false;
  16176. while (input->getPosition() < end)
  16177. {
  16178. const int type = input->readInt();
  16179. const uint32 length = (uint32) input->readIntBigEndian();
  16180. const int64 chunkEnd = input->getPosition() + length;
  16181. if (type == chunkName ("FVER"))
  16182. {
  16183. hasGotVer = true;
  16184. const int ver = input->readIntBigEndian();
  16185. if (ver != 0 && ver != (int) 0xa2805140)
  16186. break;
  16187. }
  16188. else if (type == chunkName ("COMM"))
  16189. {
  16190. hasGotType = true;
  16191. numChannels = (unsigned int) input->readShortBigEndian();
  16192. lengthInSamples = input->readIntBigEndian();
  16193. bitsPerSample = input->readShortBigEndian();
  16194. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16195. unsigned char sampleRateBytes[10];
  16196. input->read (sampleRateBytes, 10);
  16197. const int byte0 = sampleRateBytes[0];
  16198. if ((byte0 & 0x80) != 0
  16199. || byte0 <= 0x3F || byte0 > 0x40
  16200. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16201. break;
  16202. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16203. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16204. sampleRate = (int) sampRate;
  16205. if (length <= 18)
  16206. {
  16207. // some types don't have a chunk large enough to include a compression
  16208. // type, so assume it's just big-endian pcm
  16209. littleEndian = false;
  16210. }
  16211. else
  16212. {
  16213. const int compType = input->readInt();
  16214. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16215. {
  16216. littleEndian = false;
  16217. }
  16218. else if (compType == chunkName ("sowt"))
  16219. {
  16220. littleEndian = true;
  16221. }
  16222. else
  16223. {
  16224. sampleRate = 0;
  16225. break;
  16226. }
  16227. }
  16228. }
  16229. else if (type == chunkName ("SSND"))
  16230. {
  16231. hasGotData = true;
  16232. const int offset = input->readIntBigEndian();
  16233. dataChunkStart = input->getPosition() + 4 + offset;
  16234. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16235. }
  16236. else if ((hasGotVer && hasGotData && hasGotType)
  16237. || chunkEnd < input->getPosition()
  16238. || input->isExhausted())
  16239. {
  16240. break;
  16241. }
  16242. input->setPosition (chunkEnd);
  16243. }
  16244. }
  16245. }
  16246. }
  16247. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16248. int64 startSampleInFile, int numSamples)
  16249. {
  16250. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16251. if (samplesAvailable < numSamples)
  16252. {
  16253. for (int i = numDestChannels; --i >= 0;)
  16254. if (destSamples[i] != 0)
  16255. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16256. numSamples = (int) samplesAvailable;
  16257. }
  16258. if (numSamples <= 0)
  16259. return true;
  16260. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16261. while (numSamples > 0)
  16262. {
  16263. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16264. char tempBuffer [tempBufSize];
  16265. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16266. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16267. if (bytesRead < numThisTime * bytesPerFrame)
  16268. {
  16269. jassert (bytesRead >= 0);
  16270. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16271. }
  16272. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16273. if (littleEndian)
  16274. {
  16275. switch (bitsPerSample)
  16276. {
  16277. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16278. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16279. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16280. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16281. default: jassertfalse; break;
  16282. }
  16283. }
  16284. else
  16285. {
  16286. switch (bitsPerSample)
  16287. {
  16288. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16289. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16290. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16291. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16292. default: jassertfalse; break;
  16293. }
  16294. }
  16295. startOffsetInDestBuffer += numThisTime;
  16296. numSamples -= numThisTime;
  16297. }
  16298. return true;
  16299. }
  16300. private:
  16301. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16302. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16303. };
  16304. class AiffAudioFormatWriter : public AudioFormatWriter
  16305. {
  16306. public:
  16307. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16308. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16309. lengthInSamples (0),
  16310. bytesWritten (0),
  16311. writeFailed (false)
  16312. {
  16313. headerPosition = out->getPosition();
  16314. writeHeader();
  16315. }
  16316. ~AiffAudioFormatWriter()
  16317. {
  16318. if ((bytesWritten & 1) != 0)
  16319. output->writeByte (0);
  16320. writeHeader();
  16321. }
  16322. bool write (const int** data, int numSamples)
  16323. {
  16324. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16325. if (writeFailed)
  16326. return false;
  16327. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16328. tempBlock.ensureSize (bytes, false);
  16329. switch (bitsPerSample)
  16330. {
  16331. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16332. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16333. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16334. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16335. default: jassertfalse; break;
  16336. }
  16337. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16338. || ! output->write (tempBlock.getData(), bytes))
  16339. {
  16340. // failed to write to disk, so let's try writing the header.
  16341. // If it's just run out of disk space, then if it does manage
  16342. // to write the header, we'll still have a useable file..
  16343. writeHeader();
  16344. writeFailed = true;
  16345. return false;
  16346. }
  16347. else
  16348. {
  16349. bytesWritten += bytes;
  16350. lengthInSamples += numSamples;
  16351. return true;
  16352. }
  16353. }
  16354. private:
  16355. MemoryBlock tempBlock;
  16356. uint32 lengthInSamples, bytesWritten;
  16357. int64 headerPosition;
  16358. bool writeFailed;
  16359. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16360. void writeHeader()
  16361. {
  16362. const bool couldSeekOk = output->setPosition (headerPosition);
  16363. (void) couldSeekOk;
  16364. // if this fails, you've given it an output stream that can't seek! It needs
  16365. // to be able to seek back to write the header
  16366. jassert (couldSeekOk);
  16367. const int headerLen = 54;
  16368. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16369. audioBytes += (audioBytes & 1);
  16370. output->writeInt (chunkName ("FORM"));
  16371. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16372. output->writeInt (chunkName ("AIFF"));
  16373. output->writeInt (chunkName ("COMM"));
  16374. output->writeIntBigEndian (18);
  16375. output->writeShortBigEndian ((short) numChannels);
  16376. output->writeIntBigEndian (lengthInSamples);
  16377. output->writeShortBigEndian ((short) bitsPerSample);
  16378. uint8 sampleRateBytes[10];
  16379. zeromem (sampleRateBytes, 10);
  16380. if (sampleRate <= 1)
  16381. {
  16382. sampleRateBytes[0] = 0x3f;
  16383. sampleRateBytes[1] = 0xff;
  16384. sampleRateBytes[2] = 0x80;
  16385. }
  16386. else
  16387. {
  16388. int mask = 0x40000000;
  16389. sampleRateBytes[0] = 0x40;
  16390. if (sampleRate >= mask)
  16391. {
  16392. jassertfalse;
  16393. sampleRateBytes[1] = 0x1d;
  16394. }
  16395. else
  16396. {
  16397. int n = (int) sampleRate;
  16398. int i;
  16399. for (i = 0; i <= 32 ; ++i)
  16400. {
  16401. if ((n & mask) != 0)
  16402. break;
  16403. mask >>= 1;
  16404. }
  16405. n = n << (i + 1);
  16406. sampleRateBytes[1] = (uint8) (29 - i);
  16407. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16408. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16409. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16410. sampleRateBytes[5] = (uint8) (n & 0xff);
  16411. }
  16412. }
  16413. output->write (sampleRateBytes, 10);
  16414. output->writeInt (chunkName ("SSND"));
  16415. output->writeIntBigEndian (audioBytes + 8);
  16416. output->writeInt (0);
  16417. output->writeInt (0);
  16418. jassert (output->getPosition() == headerLen);
  16419. }
  16420. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16421. };
  16422. AiffAudioFormat::AiffAudioFormat()
  16423. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16424. {
  16425. }
  16426. AiffAudioFormat::~AiffAudioFormat()
  16427. {
  16428. }
  16429. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16430. {
  16431. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16432. return Array <int> (rates);
  16433. }
  16434. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16435. {
  16436. const int depths[] = { 8, 16, 24, 0 };
  16437. return Array <int> (depths);
  16438. }
  16439. bool AiffAudioFormat::canDoStereo() { return true; }
  16440. bool AiffAudioFormat::canDoMono() { return true; }
  16441. #if JUCE_MAC
  16442. bool AiffAudioFormat::canHandleFile (const File& f)
  16443. {
  16444. if (AudioFormat::canHandleFile (f))
  16445. return true;
  16446. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16447. return type == 'AIFF' || type == 'AIFC'
  16448. || type == 'aiff' || type == 'aifc';
  16449. }
  16450. #endif
  16451. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16452. {
  16453. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16454. if (w->sampleRate != 0)
  16455. return w.release();
  16456. if (! deleteStreamIfOpeningFails)
  16457. w->input = 0;
  16458. return 0;
  16459. }
  16460. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16461. double sampleRate,
  16462. unsigned int numberOfChannels,
  16463. int bitsPerSample,
  16464. const StringPairArray& /*metadataValues*/,
  16465. int /*qualityOptionIndex*/)
  16466. {
  16467. if (getPossibleBitDepths().contains (bitsPerSample))
  16468. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16469. return 0;
  16470. }
  16471. END_JUCE_NAMESPACE
  16472. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16473. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16474. BEGIN_JUCE_NAMESPACE
  16475. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16476. : formatName (name),
  16477. fileExtensions (extensions)
  16478. {
  16479. }
  16480. AudioFormat::~AudioFormat()
  16481. {
  16482. }
  16483. bool AudioFormat::canHandleFile (const File& f)
  16484. {
  16485. for (int i = 0; i < fileExtensions.size(); ++i)
  16486. if (f.hasFileExtension (fileExtensions[i]))
  16487. return true;
  16488. return false;
  16489. }
  16490. const String& AudioFormat::getFormatName() const { return formatName; }
  16491. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16492. bool AudioFormat::isCompressed() { return false; }
  16493. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16494. END_JUCE_NAMESPACE
  16495. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16496. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16497. BEGIN_JUCE_NAMESPACE
  16498. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16499. const String& formatName_)
  16500. : sampleRate (0),
  16501. bitsPerSample (0),
  16502. lengthInSamples (0),
  16503. numChannels (0),
  16504. usesFloatingPointData (false),
  16505. input (in),
  16506. formatName (formatName_)
  16507. {
  16508. }
  16509. AudioFormatReader::~AudioFormatReader()
  16510. {
  16511. delete input;
  16512. }
  16513. bool AudioFormatReader::read (int* const* destSamples,
  16514. int numDestChannels,
  16515. int64 startSampleInSource,
  16516. int numSamplesToRead,
  16517. const bool fillLeftoverChannelsWithCopies)
  16518. {
  16519. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16520. int startOffsetInDestBuffer = 0;
  16521. if (startSampleInSource < 0)
  16522. {
  16523. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16524. for (int i = numDestChannels; --i >= 0;)
  16525. if (destSamples[i] != 0)
  16526. zeromem (destSamples[i], sizeof (int) * silence);
  16527. startOffsetInDestBuffer += silence;
  16528. numSamplesToRead -= silence;
  16529. startSampleInSource = 0;
  16530. }
  16531. if (numSamplesToRead <= 0)
  16532. return true;
  16533. if (! readSamples (const_cast<int**> (destSamples),
  16534. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16535. startSampleInSource, numSamplesToRead))
  16536. return false;
  16537. if (numDestChannels > (int) numChannels)
  16538. {
  16539. if (fillLeftoverChannelsWithCopies)
  16540. {
  16541. int* lastFullChannel = destSamples[0];
  16542. for (int i = (int) numChannels; --i > 0;)
  16543. {
  16544. if (destSamples[i] != 0)
  16545. {
  16546. lastFullChannel = destSamples[i];
  16547. break;
  16548. }
  16549. }
  16550. if (lastFullChannel != 0)
  16551. for (int i = numChannels; i < numDestChannels; ++i)
  16552. if (destSamples[i] != 0)
  16553. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16554. }
  16555. else
  16556. {
  16557. for (int i = numChannels; i < numDestChannels; ++i)
  16558. if (destSamples[i] != 0)
  16559. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16560. }
  16561. }
  16562. return true;
  16563. }
  16564. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16565. int64 numSamples,
  16566. float& lowestLeft, float& highestLeft,
  16567. float& lowestRight, float& highestRight)
  16568. {
  16569. if (numSamples <= 0)
  16570. {
  16571. lowestLeft = 0;
  16572. lowestRight = 0;
  16573. highestLeft = 0;
  16574. highestRight = 0;
  16575. return;
  16576. }
  16577. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16578. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16579. int* tempBuffer[3];
  16580. tempBuffer[0] = tempSpace.getData();
  16581. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16582. tempBuffer[2] = 0;
  16583. if (usesFloatingPointData)
  16584. {
  16585. float lmin = 1.0e6f;
  16586. float lmax = -lmin;
  16587. float rmin = lmin;
  16588. float rmax = lmax;
  16589. while (numSamples > 0)
  16590. {
  16591. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16592. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16593. numSamples -= numToDo;
  16594. startSampleInFile += numToDo;
  16595. float bufMin, bufMax;
  16596. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16597. lmin = jmin (lmin, bufMin);
  16598. lmax = jmax (lmax, bufMax);
  16599. if (numChannels > 1)
  16600. {
  16601. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16602. rmin = jmin (rmin, bufMin);
  16603. rmax = jmax (rmax, bufMax);
  16604. }
  16605. }
  16606. if (numChannels <= 1)
  16607. {
  16608. rmax = lmax;
  16609. rmin = lmin;
  16610. }
  16611. lowestLeft = lmin;
  16612. highestLeft = lmax;
  16613. lowestRight = rmin;
  16614. highestRight = rmax;
  16615. }
  16616. else
  16617. {
  16618. int lmax = std::numeric_limits<int>::min();
  16619. int lmin = std::numeric_limits<int>::max();
  16620. int rmax = std::numeric_limits<int>::min();
  16621. int rmin = std::numeric_limits<int>::max();
  16622. while (numSamples > 0)
  16623. {
  16624. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16625. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16626. break;
  16627. numSamples -= numToDo;
  16628. startSampleInFile += numToDo;
  16629. for (int j = numChannels; --j >= 0;)
  16630. {
  16631. int bufMin, bufMax;
  16632. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16633. if (j == 0)
  16634. {
  16635. lmax = jmax (lmax, bufMax);
  16636. lmin = jmin (lmin, bufMin);
  16637. }
  16638. else
  16639. {
  16640. rmax = jmax (rmax, bufMax);
  16641. rmin = jmin (rmin, bufMin);
  16642. }
  16643. }
  16644. }
  16645. if (numChannels <= 1)
  16646. {
  16647. rmax = lmax;
  16648. rmin = lmin;
  16649. }
  16650. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16651. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16652. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16653. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16654. }
  16655. }
  16656. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16657. int64 numSamplesToSearch,
  16658. const double magnitudeRangeMinimum,
  16659. const double magnitudeRangeMaximum,
  16660. const int minimumConsecutiveSamples)
  16661. {
  16662. if (numSamplesToSearch == 0)
  16663. return -1;
  16664. const int bufferSize = 4096;
  16665. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16666. int* tempBuffer[3];
  16667. tempBuffer[0] = tempSpace.getData();
  16668. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16669. tempBuffer[2] = 0;
  16670. int consecutive = 0;
  16671. int64 firstMatchPos = -1;
  16672. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16673. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16674. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16675. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16676. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16677. while (numSamplesToSearch != 0)
  16678. {
  16679. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16680. int64 bufferStart = startSample;
  16681. if (numSamplesToSearch < 0)
  16682. bufferStart -= numThisTime;
  16683. if (bufferStart >= (int) lengthInSamples)
  16684. break;
  16685. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16686. int num = numThisTime;
  16687. while (--num >= 0)
  16688. {
  16689. if (numSamplesToSearch < 0)
  16690. --startSample;
  16691. bool matches = false;
  16692. const int index = (int) (startSample - bufferStart);
  16693. if (usesFloatingPointData)
  16694. {
  16695. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16696. if (sample1 >= magnitudeRangeMinimum
  16697. && sample1 <= magnitudeRangeMaximum)
  16698. {
  16699. matches = true;
  16700. }
  16701. else if (numChannels > 1)
  16702. {
  16703. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16704. matches = (sample2 >= magnitudeRangeMinimum
  16705. && sample2 <= magnitudeRangeMaximum);
  16706. }
  16707. }
  16708. else
  16709. {
  16710. const int sample1 = abs (tempBuffer[0] [index]);
  16711. if (sample1 >= intMagnitudeRangeMinimum
  16712. && sample1 <= intMagnitudeRangeMaximum)
  16713. {
  16714. matches = true;
  16715. }
  16716. else if (numChannels > 1)
  16717. {
  16718. const int sample2 = abs (tempBuffer[1][index]);
  16719. matches = (sample2 >= intMagnitudeRangeMinimum
  16720. && sample2 <= intMagnitudeRangeMaximum);
  16721. }
  16722. }
  16723. if (matches)
  16724. {
  16725. if (firstMatchPos < 0)
  16726. firstMatchPos = startSample;
  16727. if (++consecutive >= minimumConsecutiveSamples)
  16728. {
  16729. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16730. return -1;
  16731. return firstMatchPos;
  16732. }
  16733. }
  16734. else
  16735. {
  16736. consecutive = 0;
  16737. firstMatchPos = -1;
  16738. }
  16739. if (numSamplesToSearch > 0)
  16740. ++startSample;
  16741. }
  16742. if (numSamplesToSearch > 0)
  16743. numSamplesToSearch -= numThisTime;
  16744. else
  16745. numSamplesToSearch += numThisTime;
  16746. }
  16747. return -1;
  16748. }
  16749. END_JUCE_NAMESPACE
  16750. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16751. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16752. BEGIN_JUCE_NAMESPACE
  16753. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16754. const String& formatName_,
  16755. const double rate,
  16756. const unsigned int numChannels_,
  16757. const unsigned int bitsPerSample_)
  16758. : sampleRate (rate),
  16759. numChannels (numChannels_),
  16760. bitsPerSample (bitsPerSample_),
  16761. usesFloatingPointData (false),
  16762. output (out),
  16763. formatName (formatName_)
  16764. {
  16765. }
  16766. AudioFormatWriter::~AudioFormatWriter()
  16767. {
  16768. delete output;
  16769. }
  16770. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16771. int64 startSample,
  16772. int64 numSamplesToRead)
  16773. {
  16774. const int bufferSize = 16384;
  16775. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16776. int* buffers [128];
  16777. zerostruct (buffers);
  16778. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16779. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16780. if (numSamplesToRead < 0)
  16781. numSamplesToRead = reader.lengthInSamples;
  16782. while (numSamplesToRead > 0)
  16783. {
  16784. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16785. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16786. return false;
  16787. if (reader.usesFloatingPointData != isFloatingPoint())
  16788. {
  16789. int** bufferChan = buffers;
  16790. while (*bufferChan != 0)
  16791. {
  16792. int* b = *bufferChan++;
  16793. if (isFloatingPoint())
  16794. {
  16795. // int -> float
  16796. const double factor = 1.0 / std::numeric_limits<int>::max();
  16797. for (int i = 0; i < numToDo; ++i)
  16798. ((float*) b)[i] = (float) (factor * b[i]);
  16799. }
  16800. else
  16801. {
  16802. // float -> int
  16803. for (int i = 0; i < numToDo; ++i)
  16804. {
  16805. const double samp = *(const float*) b;
  16806. if (samp <= -1.0)
  16807. *b++ = std::numeric_limits<int>::min();
  16808. else if (samp >= 1.0)
  16809. *b++ = std::numeric_limits<int>::max();
  16810. else
  16811. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16812. }
  16813. }
  16814. }
  16815. }
  16816. if (! write (const_cast<const int**> (buffers), numToDo))
  16817. return false;
  16818. numSamplesToRead -= numToDo;
  16819. startSample += numToDo;
  16820. }
  16821. return true;
  16822. }
  16823. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16824. {
  16825. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16826. while (numSamplesToRead > 0)
  16827. {
  16828. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16829. AudioSourceChannelInfo info;
  16830. info.buffer = &tempBuffer;
  16831. info.startSample = 0;
  16832. info.numSamples = numToDo;
  16833. info.clearActiveBufferRegion();
  16834. source.getNextAudioBlock (info);
  16835. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16836. return false;
  16837. numSamplesToRead -= numToDo;
  16838. }
  16839. return true;
  16840. }
  16841. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16842. {
  16843. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16844. if (numSamples <= 0)
  16845. return true;
  16846. HeapBlock<int> tempBuffer;
  16847. HeapBlock<int*> chans (numChannels + 1);
  16848. chans [numChannels] = 0;
  16849. if (isFloatingPoint())
  16850. {
  16851. for (int i = numChannels; --i >= 0;)
  16852. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  16853. }
  16854. else
  16855. {
  16856. tempBuffer.malloc (numSamples * numChannels);
  16857. for (unsigned int i = 0; i < numChannels; ++i)
  16858. {
  16859. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  16860. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  16861. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  16862. SourceSampleType sourceData (source.getSampleData (i, startSample));
  16863. destData.convertSamples (sourceData, numSamples);
  16864. }
  16865. }
  16866. return write ((const int**) chans.getData(), numSamples);
  16867. }
  16868. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  16869. public AbstractFifo
  16870. {
  16871. public:
  16872. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  16873. : AbstractFifo (bufferSize_),
  16874. buffer (numChannels, bufferSize_),
  16875. timeSliceThread (timeSliceThread_),
  16876. writer (writer_),
  16877. thumbnailToUpdate (0),
  16878. samplesWritten (0),
  16879. isRunning (true)
  16880. {
  16881. timeSliceThread.addTimeSliceClient (this);
  16882. }
  16883. ~Buffer()
  16884. {
  16885. isRunning = false;
  16886. timeSliceThread.removeTimeSliceClient (this);
  16887. while (useTimeSlice() == 0)
  16888. {}
  16889. }
  16890. bool write (const float** data, int numSamples)
  16891. {
  16892. if (numSamples <= 0 || ! isRunning)
  16893. return true;
  16894. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  16895. int start1, size1, start2, size2;
  16896. prepareToWrite (numSamples, start1, size1, start2, size2);
  16897. if (size1 + size2 < numSamples)
  16898. return false;
  16899. for (int i = buffer.getNumChannels(); --i >= 0;)
  16900. {
  16901. buffer.copyFrom (i, start1, data[i], size1);
  16902. buffer.copyFrom (i, start2, data[i] + size1, size2);
  16903. }
  16904. finishedWrite (size1 + size2);
  16905. timeSliceThread.notify();
  16906. return true;
  16907. }
  16908. int useTimeSlice()
  16909. {
  16910. const int numToDo = getTotalSize() / 4;
  16911. int start1, size1, start2, size2;
  16912. prepareToRead (numToDo, start1, size1, start2, size2);
  16913. if (size1 <= 0)
  16914. return 10;
  16915. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  16916. const ScopedLock sl (thumbnailLock);
  16917. if (thumbnailToUpdate != 0)
  16918. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  16919. samplesWritten += size1;
  16920. if (size2 > 0)
  16921. {
  16922. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  16923. if (thumbnailToUpdate != 0)
  16924. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  16925. samplesWritten += size2;
  16926. }
  16927. finishedRead (size1 + size2);
  16928. return 0;
  16929. }
  16930. void setThumbnail (AudioThumbnail* thumb)
  16931. {
  16932. if (thumb != 0)
  16933. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  16934. const ScopedLock sl (thumbnailLock);
  16935. thumbnailToUpdate = thumb;
  16936. samplesWritten = 0;
  16937. }
  16938. private:
  16939. AudioSampleBuffer buffer;
  16940. TimeSliceThread& timeSliceThread;
  16941. ScopedPointer<AudioFormatWriter> writer;
  16942. CriticalSection thumbnailLock;
  16943. AudioThumbnail* thumbnailToUpdate;
  16944. int64 samplesWritten;
  16945. volatile bool isRunning;
  16946. JUCE_DECLARE_NON_COPYABLE (Buffer);
  16947. };
  16948. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  16949. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  16950. {
  16951. }
  16952. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  16953. {
  16954. }
  16955. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  16956. {
  16957. return buffer->write (data, numSamples);
  16958. }
  16959. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  16960. {
  16961. buffer->setThumbnail (thumb);
  16962. }
  16963. END_JUCE_NAMESPACE
  16964. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  16965. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16966. BEGIN_JUCE_NAMESPACE
  16967. AudioFormatManager::AudioFormatManager()
  16968. : defaultFormatIndex (0)
  16969. {
  16970. }
  16971. AudioFormatManager::~AudioFormatManager()
  16972. {
  16973. }
  16974. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  16975. {
  16976. jassert (newFormat != 0);
  16977. if (newFormat != 0)
  16978. {
  16979. #if JUCE_DEBUG
  16980. for (int i = getNumKnownFormats(); --i >= 0;)
  16981. {
  16982. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16983. {
  16984. jassertfalse; // trying to add the same format twice!
  16985. }
  16986. }
  16987. #endif
  16988. if (makeThisTheDefaultFormat)
  16989. defaultFormatIndex = getNumKnownFormats();
  16990. knownFormats.add (newFormat);
  16991. }
  16992. }
  16993. void AudioFormatManager::registerBasicFormats()
  16994. {
  16995. #if JUCE_MAC
  16996. registerFormat (new AiffAudioFormat(), true);
  16997. registerFormat (new WavAudioFormat(), false);
  16998. #else
  16999. registerFormat (new WavAudioFormat(), true);
  17000. registerFormat (new AiffAudioFormat(), false);
  17001. #endif
  17002. #if JUCE_USE_FLAC
  17003. registerFormat (new FlacAudioFormat(), false);
  17004. #endif
  17005. #if JUCE_USE_OGGVORBIS
  17006. registerFormat (new OggVorbisAudioFormat(), false);
  17007. #endif
  17008. }
  17009. void AudioFormatManager::clearFormats()
  17010. {
  17011. knownFormats.clear();
  17012. defaultFormatIndex = 0;
  17013. }
  17014. int AudioFormatManager::getNumKnownFormats() const
  17015. {
  17016. return knownFormats.size();
  17017. }
  17018. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17019. {
  17020. return knownFormats [index];
  17021. }
  17022. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17023. {
  17024. return getKnownFormat (defaultFormatIndex);
  17025. }
  17026. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17027. {
  17028. String e (fileExtension);
  17029. if (! e.startsWithChar ('.'))
  17030. e = "." + e;
  17031. for (int i = 0; i < getNumKnownFormats(); ++i)
  17032. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17033. return getKnownFormat(i);
  17034. return 0;
  17035. }
  17036. const String AudioFormatManager::getWildcardForAllFormats() const
  17037. {
  17038. StringArray allExtensions;
  17039. int i;
  17040. for (i = 0; i < getNumKnownFormats(); ++i)
  17041. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17042. allExtensions.trim();
  17043. allExtensions.removeEmptyStrings();
  17044. String s;
  17045. for (i = 0; i < allExtensions.size(); ++i)
  17046. {
  17047. s << '*';
  17048. if (! allExtensions[i].startsWithChar ('.'))
  17049. s << '.';
  17050. s << allExtensions[i];
  17051. if (i < allExtensions.size() - 1)
  17052. s << ';';
  17053. }
  17054. return s;
  17055. }
  17056. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17057. {
  17058. // you need to actually register some formats before the manager can
  17059. // use them to open a file!
  17060. jassert (getNumKnownFormats() > 0);
  17061. for (int i = 0; i < getNumKnownFormats(); ++i)
  17062. {
  17063. AudioFormat* const af = getKnownFormat(i);
  17064. if (af->canHandleFile (file))
  17065. {
  17066. InputStream* const in = file.createInputStream();
  17067. if (in != 0)
  17068. {
  17069. AudioFormatReader* const r = af->createReaderFor (in, true);
  17070. if (r != 0)
  17071. return r;
  17072. }
  17073. }
  17074. }
  17075. return 0;
  17076. }
  17077. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17078. {
  17079. // you need to actually register some formats before the manager can
  17080. // use them to open a file!
  17081. jassert (getNumKnownFormats() > 0);
  17082. ScopedPointer <InputStream> in (audioFileStream);
  17083. if (in != 0)
  17084. {
  17085. const int64 originalStreamPos = in->getPosition();
  17086. for (int i = 0; i < getNumKnownFormats(); ++i)
  17087. {
  17088. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17089. if (r != 0)
  17090. {
  17091. in.release();
  17092. return r;
  17093. }
  17094. in->setPosition (originalStreamPos);
  17095. // the stream that is passed-in must be capable of being repositioned so
  17096. // that all the formats can have a go at opening it.
  17097. jassert (in->getPosition() == originalStreamPos);
  17098. }
  17099. }
  17100. return 0;
  17101. }
  17102. END_JUCE_NAMESPACE
  17103. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17104. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17105. BEGIN_JUCE_NAMESPACE
  17106. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17107. const int64 startSample_,
  17108. const int64 length_,
  17109. const bool deleteSourceWhenDeleted_)
  17110. : AudioFormatReader (0, source_->getFormatName()),
  17111. source (source_),
  17112. startSample (startSample_),
  17113. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17114. {
  17115. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17116. sampleRate = source->sampleRate;
  17117. bitsPerSample = source->bitsPerSample;
  17118. lengthInSamples = length;
  17119. numChannels = source->numChannels;
  17120. usesFloatingPointData = source->usesFloatingPointData;
  17121. }
  17122. AudioSubsectionReader::~AudioSubsectionReader()
  17123. {
  17124. if (deleteSourceWhenDeleted)
  17125. delete source;
  17126. }
  17127. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17128. int64 startSampleInFile, int numSamples)
  17129. {
  17130. if (startSampleInFile + numSamples > length)
  17131. {
  17132. for (int i = numDestChannels; --i >= 0;)
  17133. if (destSamples[i] != 0)
  17134. zeromem (destSamples[i], sizeof (int) * numSamples);
  17135. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17136. if (numSamples <= 0)
  17137. return true;
  17138. }
  17139. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17140. startSampleInFile + startSample, numSamples);
  17141. }
  17142. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17143. int64 numSamples,
  17144. float& lowestLeft,
  17145. float& highestLeft,
  17146. float& lowestRight,
  17147. float& highestRight)
  17148. {
  17149. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17150. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17151. source->readMaxLevels (startSampleInFile + startSample,
  17152. numSamples,
  17153. lowestLeft,
  17154. highestLeft,
  17155. lowestRight,
  17156. highestRight);
  17157. }
  17158. END_JUCE_NAMESPACE
  17159. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17160. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17161. BEGIN_JUCE_NAMESPACE
  17162. struct AudioThumbnail::MinMaxValue
  17163. {
  17164. char minValue;
  17165. char maxValue;
  17166. MinMaxValue() : minValue (0), maxValue (0)
  17167. {
  17168. }
  17169. inline void set (const char newMin, const char newMax) throw()
  17170. {
  17171. minValue = newMin;
  17172. maxValue = newMax;
  17173. }
  17174. inline void setFloat (const float newMin, const float newMax) throw()
  17175. {
  17176. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17177. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17178. if (maxValue == minValue)
  17179. maxValue = (char) jmin (127, maxValue + 1);
  17180. }
  17181. inline bool isNonZero() const throw()
  17182. {
  17183. return maxValue > minValue;
  17184. }
  17185. inline int getPeak() const throw()
  17186. {
  17187. return jmax (std::abs ((int) minValue),
  17188. std::abs ((int) maxValue));
  17189. }
  17190. inline void read (InputStream& input)
  17191. {
  17192. minValue = input.readByte();
  17193. maxValue = input.readByte();
  17194. }
  17195. inline void write (OutputStream& output)
  17196. {
  17197. output.writeByte (minValue);
  17198. output.writeByte (maxValue);
  17199. }
  17200. };
  17201. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17202. {
  17203. public:
  17204. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17205. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17206. hashCode (hash), owner (owner_), reader (newReader)
  17207. {
  17208. }
  17209. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17210. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17211. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17212. {
  17213. }
  17214. ~LevelDataSource()
  17215. {
  17216. owner.cache.removeTimeSliceClient (this);
  17217. }
  17218. enum { timeBeforeDeletingReader = 1000 };
  17219. void initialise (int64 numSamplesFinished_)
  17220. {
  17221. const ScopedLock sl (readerLock);
  17222. numSamplesFinished = numSamplesFinished_;
  17223. createReader();
  17224. if (reader != 0)
  17225. {
  17226. lengthInSamples = reader->lengthInSamples;
  17227. numChannels = reader->numChannels;
  17228. sampleRate = reader->sampleRate;
  17229. if (lengthInSamples <= 0 || isFullyLoaded())
  17230. reader = 0;
  17231. else
  17232. owner.cache.addTimeSliceClient (this);
  17233. }
  17234. }
  17235. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17236. {
  17237. const ScopedLock sl (readerLock);
  17238. if (reader == 0)
  17239. {
  17240. createReader();
  17241. if (reader != 0)
  17242. owner.cache.addTimeSliceClient (this);
  17243. }
  17244. if (reader != 0)
  17245. {
  17246. float l[4] = { 0 };
  17247. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17248. levels.clearQuick();
  17249. levels.addArray ((const float*) l, 4);
  17250. }
  17251. }
  17252. void releaseResources()
  17253. {
  17254. const ScopedLock sl (readerLock);
  17255. reader = 0;
  17256. }
  17257. int useTimeSlice()
  17258. {
  17259. if (isFullyLoaded())
  17260. {
  17261. if (reader != 0 && source != 0)
  17262. releaseResources();
  17263. return -1;
  17264. }
  17265. bool justFinished = false;
  17266. {
  17267. const ScopedLock sl (readerLock);
  17268. createReader();
  17269. if (reader != 0)
  17270. {
  17271. if (! readNextBlock())
  17272. return 0;
  17273. justFinished = true;
  17274. }
  17275. }
  17276. if (justFinished)
  17277. owner.cache.storeThumb (owner, hashCode);
  17278. return timeBeforeDeletingReader;
  17279. }
  17280. bool isFullyLoaded() const throw()
  17281. {
  17282. return numSamplesFinished >= lengthInSamples;
  17283. }
  17284. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17285. {
  17286. return (int) (originalSample / owner.samplesPerThumbSample);
  17287. }
  17288. int64 lengthInSamples, numSamplesFinished;
  17289. double sampleRate;
  17290. int numChannels;
  17291. int64 hashCode;
  17292. private:
  17293. AudioThumbnail& owner;
  17294. ScopedPointer <InputSource> source;
  17295. ScopedPointer <AudioFormatReader> reader;
  17296. CriticalSection readerLock;
  17297. void createReader()
  17298. {
  17299. if (reader == 0 && source != 0)
  17300. {
  17301. InputStream* audioFileStream = source->createInputStream();
  17302. if (audioFileStream != 0)
  17303. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17304. }
  17305. }
  17306. bool readNextBlock()
  17307. {
  17308. jassert (reader != 0);
  17309. if (! isFullyLoaded())
  17310. {
  17311. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17312. if (numToDo > 0)
  17313. {
  17314. int64 startSample = numSamplesFinished;
  17315. const int firstThumbIndex = sampleToThumbSample (startSample);
  17316. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17317. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17318. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17319. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17320. for (int i = 0; i < numThumbSamps; ++i)
  17321. {
  17322. float lowestLeft, highestLeft, lowestRight, highestRight;
  17323. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17324. lowestLeft, highestLeft, lowestRight, highestRight);
  17325. levels[0][i].setFloat (lowestLeft, highestLeft);
  17326. levels[1][i].setFloat (lowestRight, highestRight);
  17327. }
  17328. {
  17329. const ScopedUnlock su (readerLock);
  17330. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17331. }
  17332. numSamplesFinished += numToDo;
  17333. }
  17334. }
  17335. return isFullyLoaded();
  17336. }
  17337. };
  17338. class AudioThumbnail::ThumbData
  17339. {
  17340. public:
  17341. ThumbData (const int numThumbSamples)
  17342. : peakLevel (-1)
  17343. {
  17344. ensureSize (numThumbSamples);
  17345. }
  17346. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17347. {
  17348. jassert (thumbSampleIndex < data.size());
  17349. return data.getRawDataPointer() + thumbSampleIndex;
  17350. }
  17351. int getSize() const throw()
  17352. {
  17353. return data.size();
  17354. }
  17355. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17356. {
  17357. if (startSample >= 0)
  17358. {
  17359. endSample = jmin (endSample, data.size() - 1);
  17360. char mx = -128;
  17361. char mn = 127;
  17362. while (startSample <= endSample)
  17363. {
  17364. const MinMaxValue& v = data.getReference (startSample);
  17365. if (v.minValue < mn) mn = v.minValue;
  17366. if (v.maxValue > mx) mx = v.maxValue;
  17367. ++startSample;
  17368. }
  17369. if (mn <= mx)
  17370. {
  17371. result.set (mn, mx);
  17372. return;
  17373. }
  17374. }
  17375. result.set (1, 0);
  17376. }
  17377. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17378. {
  17379. resetPeak();
  17380. if (startIndex + numValues > data.size())
  17381. ensureSize (startIndex + numValues);
  17382. MinMaxValue* const dest = getData (startIndex);
  17383. for (int i = 0; i < numValues; ++i)
  17384. dest[i] = source[i];
  17385. }
  17386. void resetPeak()
  17387. {
  17388. peakLevel = -1;
  17389. }
  17390. int getPeak()
  17391. {
  17392. if (peakLevel < 0)
  17393. {
  17394. for (int i = 0; i < data.size(); ++i)
  17395. {
  17396. const int peak = data[i].getPeak();
  17397. if (peak > peakLevel)
  17398. peakLevel = peak;
  17399. }
  17400. }
  17401. return peakLevel;
  17402. }
  17403. private:
  17404. Array <MinMaxValue> data;
  17405. int peakLevel;
  17406. void ensureSize (const int thumbSamples)
  17407. {
  17408. const int extraNeeded = thumbSamples - data.size();
  17409. if (extraNeeded > 0)
  17410. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17411. }
  17412. };
  17413. class AudioThumbnail::CachedWindow
  17414. {
  17415. public:
  17416. CachedWindow()
  17417. : cachedStart (0), cachedTimePerPixel (0),
  17418. numChannelsCached (0), numSamplesCached (0),
  17419. cacheNeedsRefilling (true)
  17420. {
  17421. }
  17422. void invalidate()
  17423. {
  17424. cacheNeedsRefilling = true;
  17425. }
  17426. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17427. const double startTime, const double endTime,
  17428. const int channelNum, const float verticalZoomFactor,
  17429. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17430. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17431. {
  17432. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17433. numChannels, samplesPerThumbSample, levelData, channels);
  17434. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17435. {
  17436. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17437. if (! clip.isEmpty())
  17438. {
  17439. const float topY = (float) area.getY();
  17440. const float bottomY = (float) area.getBottom();
  17441. const float midY = (topY + bottomY) * 0.5f;
  17442. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17443. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17444. int x = clip.getX();
  17445. for (int w = clip.getWidth(); --w >= 0;)
  17446. {
  17447. if (cacheData->isNonZero())
  17448. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17449. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17450. ++x;
  17451. ++cacheData;
  17452. }
  17453. }
  17454. }
  17455. }
  17456. private:
  17457. Array <MinMaxValue> data;
  17458. double cachedStart, cachedTimePerPixel;
  17459. int numChannelsCached, numSamplesCached;
  17460. bool cacheNeedsRefilling;
  17461. void refillCache (const int numSamples, double startTime, const double endTime,
  17462. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17463. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17464. {
  17465. const double timePerPixel = (endTime - startTime) / numSamples;
  17466. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17467. {
  17468. invalidate();
  17469. return;
  17470. }
  17471. if (numSamples == numSamplesCached
  17472. && numChannelsCached == numChannels
  17473. && startTime == cachedStart
  17474. && timePerPixel == cachedTimePerPixel
  17475. && ! cacheNeedsRefilling)
  17476. {
  17477. return;
  17478. }
  17479. numSamplesCached = numSamples;
  17480. numChannelsCached = numChannels;
  17481. cachedStart = startTime;
  17482. cachedTimePerPixel = timePerPixel;
  17483. cacheNeedsRefilling = false;
  17484. ensureSize (numSamples);
  17485. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17486. {
  17487. int sample = roundToInt (startTime * sampleRate);
  17488. Array<float> levels;
  17489. int i;
  17490. for (i = 0; i < numSamples; ++i)
  17491. {
  17492. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17493. if (sample >= 0)
  17494. {
  17495. if (sample >= levelData->lengthInSamples)
  17496. break;
  17497. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17498. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17499. for (int chan = 0; chan < numChans; ++chan)
  17500. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17501. levels.getUnchecked (chan * 2 + 1));
  17502. }
  17503. startTime += timePerPixel;
  17504. sample = nextSample;
  17505. }
  17506. numSamplesCached = i;
  17507. }
  17508. else
  17509. {
  17510. jassert (channels.size() == numChannelsCached);
  17511. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17512. {
  17513. ThumbData* channelData = channels.getUnchecked (channelNum);
  17514. MinMaxValue* cacheData = getData (channelNum, 0);
  17515. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17516. startTime = cachedStart;
  17517. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17518. for (int i = numSamples; --i >= 0;)
  17519. {
  17520. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17521. channelData->getMinMax (sample, nextSample, *cacheData);
  17522. ++cacheData;
  17523. startTime += timePerPixel;
  17524. sample = nextSample;
  17525. }
  17526. }
  17527. }
  17528. }
  17529. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17530. {
  17531. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17532. return data.getRawDataPointer() + channelNum * numSamplesCached
  17533. + cacheIndex;
  17534. }
  17535. void ensureSize (const int numSamples)
  17536. {
  17537. const int itemsRequired = numSamples * numChannelsCached;
  17538. if (data.size() < itemsRequired)
  17539. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17540. }
  17541. };
  17542. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17543. AudioFormatManager& formatManagerToUse_,
  17544. AudioThumbnailCache& cacheToUse)
  17545. : formatManagerToUse (formatManagerToUse_),
  17546. cache (cacheToUse),
  17547. window (new CachedWindow()),
  17548. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17549. totalSamples (0),
  17550. numChannels (0),
  17551. sampleRate (0)
  17552. {
  17553. }
  17554. AudioThumbnail::~AudioThumbnail()
  17555. {
  17556. clear();
  17557. }
  17558. void AudioThumbnail::clear()
  17559. {
  17560. source = 0;
  17561. const ScopedLock sl (lock);
  17562. window->invalidate();
  17563. channels.clear();
  17564. totalSamples = numSamplesFinished = 0;
  17565. numChannels = 0;
  17566. sampleRate = 0;
  17567. sendChangeMessage();
  17568. }
  17569. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17570. {
  17571. clear();
  17572. numChannels = newNumChannels;
  17573. sampleRate = newSampleRate;
  17574. totalSamples = totalSamplesInSource;
  17575. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17576. }
  17577. void AudioThumbnail::createChannels (const int length)
  17578. {
  17579. while (channels.size() < numChannels)
  17580. channels.add (new ThumbData (length));
  17581. }
  17582. void AudioThumbnail::loadFrom (InputStream& input)
  17583. {
  17584. clear();
  17585. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17586. return;
  17587. samplesPerThumbSample = input.readInt();
  17588. totalSamples = input.readInt64(); // Total number of source samples.
  17589. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17590. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17591. numChannels = input.readInt(); // Number of audio channels.
  17592. sampleRate = input.readInt(); // Source sample rate.
  17593. input.skipNextBytes (16); // reserved area
  17594. createChannels (numThumbnailSamples);
  17595. for (int i = 0; i < numThumbnailSamples; ++i)
  17596. for (int chan = 0; chan < numChannels; ++chan)
  17597. channels.getUnchecked(chan)->getData(i)->read (input);
  17598. }
  17599. void AudioThumbnail::saveTo (OutputStream& output) const
  17600. {
  17601. const ScopedLock sl (lock);
  17602. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17603. output.write ("jatm", 4);
  17604. output.writeInt (samplesPerThumbSample);
  17605. output.writeInt64 (totalSamples);
  17606. output.writeInt64 (numSamplesFinished);
  17607. output.writeInt (numThumbnailSamples);
  17608. output.writeInt (numChannels);
  17609. output.writeInt ((int) sampleRate);
  17610. output.writeInt64 (0);
  17611. output.writeInt64 (0);
  17612. for (int i = 0; i < numThumbnailSamples; ++i)
  17613. for (int chan = 0; chan < numChannels; ++chan)
  17614. channels.getUnchecked(chan)->getData(i)->write (output);
  17615. }
  17616. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17617. {
  17618. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17619. numSamplesFinished = 0;
  17620. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17621. {
  17622. source = newSource; // (make sure this isn't done before loadThumb is called)
  17623. source->lengthInSamples = totalSamples;
  17624. source->sampleRate = sampleRate;
  17625. source->numChannels = numChannels;
  17626. source->numSamplesFinished = numSamplesFinished;
  17627. }
  17628. else
  17629. {
  17630. source = newSource; // (make sure this isn't done before loadThumb is called)
  17631. const ScopedLock sl (lock);
  17632. source->initialise (numSamplesFinished);
  17633. totalSamples = source->lengthInSamples;
  17634. sampleRate = source->sampleRate;
  17635. numChannels = source->numChannels;
  17636. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17637. }
  17638. return sampleRate > 0 && totalSamples > 0;
  17639. }
  17640. bool AudioThumbnail::setSource (InputSource* const newSource)
  17641. {
  17642. clear();
  17643. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17644. }
  17645. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17646. {
  17647. clear();
  17648. if (newReader != 0)
  17649. setDataSource (new LevelDataSource (*this, newReader, hash));
  17650. }
  17651. int64 AudioThumbnail::getHashCode() const
  17652. {
  17653. return source == 0 ? 0 : source->hashCode;
  17654. }
  17655. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17656. int startOffsetInBuffer, int numSamples)
  17657. {
  17658. jassert (startSample >= 0);
  17659. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17660. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17661. const int numToDo = lastThumbIndex - firstThumbIndex;
  17662. if (numToDo > 0)
  17663. {
  17664. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17665. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17666. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17667. for (int chan = 0; chan < numChans; ++chan)
  17668. {
  17669. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17670. MinMaxValue* const dest = thumbData + numToDo * chan;
  17671. thumbChannels [chan] = dest;
  17672. for (int i = 0; i < numToDo; ++i)
  17673. {
  17674. float low, high;
  17675. const int start = i * samplesPerThumbSample;
  17676. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17677. dest[i].setFloat (low, high);
  17678. }
  17679. }
  17680. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17681. }
  17682. }
  17683. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17684. {
  17685. const ScopedLock sl (lock);
  17686. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17687. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17688. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17689. totalSamples = jmax (numSamplesFinished, totalSamples);
  17690. window->invalidate();
  17691. sendChangeMessage();
  17692. }
  17693. int AudioThumbnail::getNumChannels() const throw()
  17694. {
  17695. return numChannels;
  17696. }
  17697. double AudioThumbnail::getTotalLength() const throw()
  17698. {
  17699. return totalSamples / sampleRate;
  17700. }
  17701. bool AudioThumbnail::isFullyLoaded() const throw()
  17702. {
  17703. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17704. }
  17705. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17706. {
  17707. return numSamplesFinished;
  17708. }
  17709. float AudioThumbnail::getApproximatePeak() const
  17710. {
  17711. int peak = 0;
  17712. for (int i = channels.size(); --i >= 0;)
  17713. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17714. return jlimit (0, 127, peak) / 127.0f;
  17715. }
  17716. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17717. double endTime, int channelNum, float verticalZoomFactor)
  17718. {
  17719. const ScopedLock sl (lock);
  17720. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17721. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17722. }
  17723. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17724. double endTimeSeconds, float verticalZoomFactor)
  17725. {
  17726. for (int i = 0; i < numChannels; ++i)
  17727. {
  17728. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17729. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17730. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17731. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17732. }
  17733. }
  17734. END_JUCE_NAMESPACE
  17735. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17736. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17737. BEGIN_JUCE_NAMESPACE
  17738. struct ThumbnailCacheEntry
  17739. {
  17740. int64 hash;
  17741. uint32 lastUsed;
  17742. MemoryBlock data;
  17743. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17744. };
  17745. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17746. : TimeSliceThread ("thumb cache"),
  17747. maxNumThumbsToStore (maxNumThumbsToStore_)
  17748. {
  17749. startThread (2);
  17750. }
  17751. AudioThumbnailCache::~AudioThumbnailCache()
  17752. {
  17753. }
  17754. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17755. {
  17756. for (int i = thumbs.size(); --i >= 0;)
  17757. if (thumbs.getUnchecked(i)->hash == hash)
  17758. return thumbs.getUnchecked(i);
  17759. return 0;
  17760. }
  17761. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17762. {
  17763. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17764. if (te != 0)
  17765. {
  17766. te->lastUsed = Time::getMillisecondCounter();
  17767. MemoryInputStream in (te->data, false);
  17768. thumb.loadFrom (in);
  17769. return true;
  17770. }
  17771. return false;
  17772. }
  17773. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17774. const int64 hashCode)
  17775. {
  17776. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17777. if (te == 0)
  17778. {
  17779. te = new ThumbnailCacheEntry();
  17780. te->hash = hashCode;
  17781. if (thumbs.size() < maxNumThumbsToStore)
  17782. {
  17783. thumbs.add (te);
  17784. }
  17785. else
  17786. {
  17787. int oldest = 0;
  17788. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17789. for (int i = thumbs.size(); --i >= 0;)
  17790. {
  17791. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17792. {
  17793. oldest = i;
  17794. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17795. }
  17796. }
  17797. thumbs.set (oldest, te);
  17798. }
  17799. }
  17800. te->lastUsed = Time::getMillisecondCounter();
  17801. MemoryOutputStream out (te->data, false);
  17802. thumb.saveTo (out);
  17803. }
  17804. void AudioThumbnailCache::clear()
  17805. {
  17806. thumbs.clear();
  17807. }
  17808. END_JUCE_NAMESPACE
  17809. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17810. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17811. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17812. #if ! JUCE_WINDOWS
  17813. #include <QuickTime/Movies.h>
  17814. #include <QuickTime/QTML.h>
  17815. #include <QuickTime/QuickTimeComponents.h>
  17816. #include <QuickTime/MediaHandlers.h>
  17817. #include <QuickTime/ImageCodec.h>
  17818. #else
  17819. #if JUCE_MSVC
  17820. #pragma warning (push)
  17821. #pragma warning (disable : 4100)
  17822. #endif
  17823. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17824. add its header directory to your include path.
  17825. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17826. flag in juce_Config.h
  17827. */
  17828. #include <Movies.h>
  17829. #include <QTML.h>
  17830. #include <QuickTimeComponents.h>
  17831. #include <MediaHandlers.h>
  17832. #include <ImageCodec.h>
  17833. #if JUCE_MSVC
  17834. #pragma warning (pop)
  17835. #endif
  17836. #endif
  17837. BEGIN_JUCE_NAMESPACE
  17838. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17839. static const char* const quickTimeFormatName = "QuickTime file";
  17840. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17841. class QTAudioReader : public AudioFormatReader
  17842. {
  17843. public:
  17844. QTAudioReader (InputStream* const input_, const int trackNum_)
  17845. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17846. ok (false),
  17847. movie (0),
  17848. trackNum (trackNum_),
  17849. lastSampleRead (0),
  17850. lastThreadId (0),
  17851. extractor (0),
  17852. dataHandle (0)
  17853. {
  17854. JUCE_AUTORELEASEPOOL
  17855. bufferList.calloc (256, 1);
  17856. #if JUCE_WINDOWS
  17857. if (InitializeQTML (0) != noErr)
  17858. return;
  17859. #endif
  17860. if (EnterMovies() != noErr)
  17861. return;
  17862. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17863. if (! opened)
  17864. return;
  17865. {
  17866. const int numTracks = GetMovieTrackCount (movie);
  17867. int trackCount = 0;
  17868. for (int i = 1; i <= numTracks; ++i)
  17869. {
  17870. track = GetMovieIndTrack (movie, i);
  17871. media = GetTrackMedia (track);
  17872. OSType mediaType;
  17873. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17874. if (mediaType == SoundMediaType
  17875. && trackCount++ == trackNum_)
  17876. {
  17877. ok = true;
  17878. break;
  17879. }
  17880. }
  17881. }
  17882. if (! ok)
  17883. return;
  17884. ok = false;
  17885. lengthInSamples = GetMediaDecodeDuration (media);
  17886. usesFloatingPointData = false;
  17887. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17888. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17889. / GetMediaTimeScale (media);
  17890. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17891. unsigned long output_layout_size;
  17892. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17893. kQTPropertyClass_MovieAudioExtraction_Audio,
  17894. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17895. 0, &output_layout_size, 0);
  17896. if (err != noErr)
  17897. return;
  17898. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17899. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17900. err = MovieAudioExtractionGetProperty (extractor,
  17901. kQTPropertyClass_MovieAudioExtraction_Audio,
  17902. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17903. output_layout_size, qt_audio_channel_layout, 0);
  17904. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17905. err = MovieAudioExtractionSetProperty (extractor,
  17906. kQTPropertyClass_MovieAudioExtraction_Audio,
  17907. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17908. output_layout_size,
  17909. qt_audio_channel_layout);
  17910. err = MovieAudioExtractionGetProperty (extractor,
  17911. kQTPropertyClass_MovieAudioExtraction_Audio,
  17912. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17913. sizeof (inputStreamDesc),
  17914. &inputStreamDesc, 0);
  17915. if (err != noErr)
  17916. return;
  17917. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17918. | kAudioFormatFlagIsPacked
  17919. | kAudioFormatFlagsNativeEndian;
  17920. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17921. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17922. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17923. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17924. err = MovieAudioExtractionSetProperty (extractor,
  17925. kQTPropertyClass_MovieAudioExtraction_Audio,
  17926. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17927. sizeof (inputStreamDesc),
  17928. &inputStreamDesc);
  17929. if (err != noErr)
  17930. return;
  17931. Boolean allChannelsDiscrete = false;
  17932. err = MovieAudioExtractionSetProperty (extractor,
  17933. kQTPropertyClass_MovieAudioExtraction_Movie,
  17934. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17935. sizeof (allChannelsDiscrete),
  17936. &allChannelsDiscrete);
  17937. if (err != noErr)
  17938. return;
  17939. bufferList->mNumberBuffers = 1;
  17940. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17941. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  17942. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17943. bufferList->mBuffers[0].mData = dataBuffer;
  17944. sampleRate = inputStreamDesc.mSampleRate;
  17945. bitsPerSample = 16;
  17946. numChannels = inputStreamDesc.mChannelsPerFrame;
  17947. detachThread();
  17948. ok = true;
  17949. }
  17950. ~QTAudioReader()
  17951. {
  17952. JUCE_AUTORELEASEPOOL
  17953. checkThreadIsAttached();
  17954. if (dataHandle != 0)
  17955. DisposeHandle (dataHandle);
  17956. if (extractor != 0)
  17957. {
  17958. MovieAudioExtractionEnd (extractor);
  17959. extractor = 0;
  17960. }
  17961. DisposeMovie (movie);
  17962. #if JUCE_MAC
  17963. ExitMoviesOnThread ();
  17964. #endif
  17965. }
  17966. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17967. int64 startSampleInFile, int numSamples)
  17968. {
  17969. JUCE_AUTORELEASEPOOL
  17970. checkThreadIsAttached();
  17971. bool ok = true;
  17972. while (numSamples > 0)
  17973. {
  17974. if (lastSampleRead != startSampleInFile)
  17975. {
  17976. TimeRecord time;
  17977. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17978. time.base = 0;
  17979. time.value.hi = 0;
  17980. time.value.lo = (UInt32) startSampleInFile;
  17981. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17982. kQTPropertyClass_MovieAudioExtraction_Movie,
  17983. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17984. sizeof (time), &time);
  17985. if (err != noErr)
  17986. {
  17987. ok = false;
  17988. break;
  17989. }
  17990. }
  17991. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  17992. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  17993. UInt32 outFlags = 0;
  17994. UInt32 actualNumFrames = framesToDo;
  17995. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  17996. if (err != noErr)
  17997. {
  17998. ok = false;
  17999. break;
  18000. }
  18001. lastSampleRead = startSampleInFile + actualNumFrames;
  18002. const int samplesReceived = actualNumFrames;
  18003. for (int j = numDestChannels; --j >= 0;)
  18004. {
  18005. if (destSamples[j] != 0)
  18006. {
  18007. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18008. for (int i = 0; i < samplesReceived; ++i)
  18009. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18010. }
  18011. }
  18012. startOffsetInDestBuffer += samplesReceived;
  18013. startSampleInFile += samplesReceived;
  18014. numSamples -= samplesReceived;
  18015. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18016. {
  18017. for (int j = numDestChannels; --j >= 0;)
  18018. if (destSamples[j] != 0)
  18019. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18020. break;
  18021. }
  18022. }
  18023. detachThread();
  18024. return ok;
  18025. }
  18026. bool ok;
  18027. private:
  18028. Movie movie;
  18029. Media media;
  18030. Track track;
  18031. const int trackNum;
  18032. double trackUnitsPerFrame;
  18033. int samplesPerFrame;
  18034. int64 lastSampleRead;
  18035. Thread::ThreadID lastThreadId;
  18036. MovieAudioExtractionRef extractor;
  18037. AudioStreamBasicDescription inputStreamDesc;
  18038. HeapBlock <AudioBufferList> bufferList;
  18039. HeapBlock <char> dataBuffer;
  18040. Handle dataHandle;
  18041. void checkThreadIsAttached()
  18042. {
  18043. #if JUCE_MAC
  18044. if (Thread::getCurrentThreadId() != lastThreadId)
  18045. EnterMoviesOnThread (0);
  18046. AttachMovieToCurrentThread (movie);
  18047. #endif
  18048. }
  18049. void detachThread()
  18050. {
  18051. #if JUCE_MAC
  18052. DetachMovieFromCurrentThread (movie);
  18053. #endif
  18054. }
  18055. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18056. };
  18057. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18058. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18059. {
  18060. }
  18061. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18062. {
  18063. }
  18064. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18065. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18066. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18067. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18068. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18069. const bool deleteStreamIfOpeningFails)
  18070. {
  18071. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18072. if (r->ok)
  18073. return r.release();
  18074. if (! deleteStreamIfOpeningFails)
  18075. r->input = 0;
  18076. return 0;
  18077. }
  18078. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18079. double /*sampleRateToUse*/,
  18080. unsigned int /*numberOfChannels*/,
  18081. int /*bitsPerSample*/,
  18082. const StringPairArray& /*metadataValues*/,
  18083. int /*qualityOptionIndex*/)
  18084. {
  18085. jassertfalse; // not yet implemented!
  18086. return 0;
  18087. }
  18088. END_JUCE_NAMESPACE
  18089. #endif
  18090. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18091. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18092. BEGIN_JUCE_NAMESPACE
  18093. static const char* const wavFormatName = "WAV file";
  18094. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18095. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18096. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18097. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18098. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18099. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18100. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18101. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18102. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18103. const String& originator,
  18104. const String& originatorRef,
  18105. const Time& date,
  18106. const int64 timeReferenceSamples,
  18107. const String& codingHistory)
  18108. {
  18109. StringPairArray m;
  18110. m.set (bwavDescription, description);
  18111. m.set (bwavOriginator, originator);
  18112. m.set (bwavOriginatorRef, originatorRef);
  18113. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18114. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18115. m.set (bwavTimeReference, String (timeReferenceSamples));
  18116. m.set (bwavCodingHistory, codingHistory);
  18117. return m;
  18118. }
  18119. namespace WavFileHelpers
  18120. {
  18121. #if JUCE_MSVC
  18122. #pragma pack (push, 1)
  18123. #define PACKED
  18124. #elif JUCE_GCC
  18125. #define PACKED __attribute__((packed))
  18126. #else
  18127. #define PACKED
  18128. #endif
  18129. struct BWAVChunk
  18130. {
  18131. char description [256];
  18132. char originator [32];
  18133. char originatorRef [32];
  18134. char originationDate [10];
  18135. char originationTime [8];
  18136. uint32 timeRefLow;
  18137. uint32 timeRefHigh;
  18138. uint16 version;
  18139. uint8 umid[64];
  18140. uint8 reserved[190];
  18141. char codingHistory[1];
  18142. void copyTo (StringPairArray& values) const
  18143. {
  18144. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18145. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18146. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18147. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18148. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18149. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18150. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18151. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18152. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18153. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18154. }
  18155. static MemoryBlock createFrom (const StringPairArray& values)
  18156. {
  18157. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18158. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18159. data.fillWith (0);
  18160. BWAVChunk* b = (BWAVChunk*) data.getData();
  18161. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18162. // as they get called in the right order..
  18163. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18164. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18165. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18166. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18167. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18168. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18169. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18170. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18171. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18172. if (b->description[0] != 0
  18173. || b->originator[0] != 0
  18174. || b->originationDate[0] != 0
  18175. || b->originationTime[0] != 0
  18176. || b->codingHistory[0] != 0
  18177. || time != 0)
  18178. {
  18179. return data;
  18180. }
  18181. return MemoryBlock();
  18182. }
  18183. } PACKED;
  18184. struct SMPLChunk
  18185. {
  18186. struct SampleLoop
  18187. {
  18188. uint32 identifier;
  18189. uint32 type;
  18190. uint32 start;
  18191. uint32 end;
  18192. uint32 fraction;
  18193. uint32 playCount;
  18194. } PACKED;
  18195. uint32 manufacturer;
  18196. uint32 product;
  18197. uint32 samplePeriod;
  18198. uint32 midiUnityNote;
  18199. uint32 midiPitchFraction;
  18200. uint32 smpteFormat;
  18201. uint32 smpteOffset;
  18202. uint32 numSampleLoops;
  18203. uint32 samplerData;
  18204. SampleLoop loops[1];
  18205. void copyTo (StringPairArray& values, const int totalSize) const
  18206. {
  18207. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18208. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18209. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18210. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18211. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18212. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18213. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18214. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18215. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18216. for (uint32 i = 0; i < numSampleLoops; ++i)
  18217. {
  18218. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18219. break;
  18220. const String prefix ("Loop" + String(i));
  18221. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18222. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18223. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18224. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18225. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18226. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18227. }
  18228. }
  18229. static MemoryBlock createFrom (const StringPairArray& values)
  18230. {
  18231. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18232. if (numLoops <= 0)
  18233. return MemoryBlock();
  18234. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18235. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18236. data.fillWith (0);
  18237. SMPLChunk* s = (SMPLChunk*) data.getData();
  18238. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18239. // as they get called in the right order..
  18240. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18241. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18242. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18243. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18244. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18245. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18246. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18247. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18248. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18249. for (int i = 0; i < numLoops; ++i)
  18250. {
  18251. const String prefix ("Loop" + String(i));
  18252. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18253. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18254. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18255. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18256. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18257. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18258. }
  18259. return data;
  18260. }
  18261. } PACKED;
  18262. struct ExtensibleWavSubFormat
  18263. {
  18264. uint32 data1;
  18265. uint16 data2;
  18266. uint16 data3;
  18267. uint8 data4[8];
  18268. } PACKED;
  18269. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18270. {
  18271. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18272. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18273. uint32 dataSizeLow; // low 4 byte size of data chunk
  18274. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18275. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18276. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18277. uint32 tableLength; // number of valid entries in array 'table'
  18278. } PACKED;
  18279. #if JUCE_MSVC
  18280. #pragma pack (pop)
  18281. #endif
  18282. #undef PACKED
  18283. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18284. }
  18285. class WavAudioFormatReader : public AudioFormatReader
  18286. {
  18287. public:
  18288. WavAudioFormatReader (InputStream* const in)
  18289. : AudioFormatReader (in, TRANS (wavFormatName)),
  18290. bwavChunkStart (0),
  18291. bwavSize (0),
  18292. dataLength (0),
  18293. isRF64 (false)
  18294. {
  18295. using namespace WavFileHelpers;
  18296. uint64 len = 0;
  18297. int64 end = 0;
  18298. bool hasGotType = false;
  18299. bool hasGotData = false;
  18300. const int firstChunkType = input->readInt();
  18301. if (firstChunkType == chunkName ("RF64"))
  18302. {
  18303. input->skipNextBytes (4); // size is -1 for RF64
  18304. isRF64 = true;
  18305. }
  18306. else if (firstChunkType == chunkName ("RIFF"))
  18307. {
  18308. len = (uint64) input->readInt();
  18309. end = input->getPosition() + len;
  18310. }
  18311. else
  18312. {
  18313. return;
  18314. }
  18315. const int64 startOfRIFFChunk = input->getPosition();
  18316. if (input->readInt() == chunkName ("WAVE"))
  18317. {
  18318. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18319. {
  18320. uint32 length = (uint32) input->readInt();
  18321. if (length < 28)
  18322. {
  18323. return;
  18324. }
  18325. else
  18326. {
  18327. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18328. len = input->readInt64();
  18329. end = startOfRIFFChunk + len;
  18330. dataLength = input->readInt64();
  18331. input->setPosition (chunkEnd);
  18332. }
  18333. }
  18334. while (input->getPosition() < end && ! input->isExhausted())
  18335. {
  18336. const int chunkType = input->readInt();
  18337. uint32 length = (uint32) input->readInt();
  18338. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18339. if (chunkType == chunkName ("fmt "))
  18340. {
  18341. // read the format chunk
  18342. const unsigned short format = input->readShort();
  18343. const short numChans = input->readShort();
  18344. sampleRate = input->readInt();
  18345. const int bytesPerSec = input->readInt();
  18346. numChannels = numChans;
  18347. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18348. bitsPerSample = 8 * bytesPerFrame / numChans;
  18349. if (format == 3)
  18350. {
  18351. usesFloatingPointData = true;
  18352. }
  18353. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18354. {
  18355. if (length < 40) // too short
  18356. {
  18357. bytesPerFrame = 0;
  18358. }
  18359. else
  18360. {
  18361. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18362. ExtensibleWavSubFormat subFormat;
  18363. subFormat.data1 = input->readInt();
  18364. subFormat.data2 = input->readShort();
  18365. subFormat.data3 = input->readShort();
  18366. input->read (subFormat.data4, sizeof (subFormat.data4));
  18367. const ExtensibleWavSubFormat pcmFormat
  18368. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18369. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18370. {
  18371. const ExtensibleWavSubFormat ambisonicFormat
  18372. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18373. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18374. bytesPerFrame = 0;
  18375. }
  18376. }
  18377. }
  18378. else if (format != 1)
  18379. {
  18380. bytesPerFrame = 0;
  18381. }
  18382. hasGotType = true;
  18383. }
  18384. else if (chunkType == chunkName ("data"))
  18385. {
  18386. // get the data chunk's position
  18387. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18388. dataLength = length;
  18389. dataChunkStart = input->getPosition();
  18390. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18391. hasGotData = true;
  18392. }
  18393. else if (chunkType == chunkName ("bext"))
  18394. {
  18395. bwavChunkStart = input->getPosition();
  18396. bwavSize = length;
  18397. // Broadcast-wav extension chunk..
  18398. HeapBlock <BWAVChunk> bwav;
  18399. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18400. input->read (bwav, length);
  18401. bwav->copyTo (metadataValues);
  18402. }
  18403. else if (chunkType == chunkName ("smpl"))
  18404. {
  18405. HeapBlock <SMPLChunk> smpl;
  18406. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18407. input->read (smpl, length);
  18408. smpl->copyTo (metadataValues, length);
  18409. }
  18410. else if (chunkEnd <= input->getPosition())
  18411. {
  18412. break;
  18413. }
  18414. input->setPosition (chunkEnd);
  18415. }
  18416. }
  18417. }
  18418. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18419. int64 startSampleInFile, int numSamples)
  18420. {
  18421. jassert (destSamples != 0);
  18422. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18423. if (samplesAvailable < numSamples)
  18424. {
  18425. for (int i = numDestChannels; --i >= 0;)
  18426. if (destSamples[i] != 0)
  18427. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18428. numSamples = (int) samplesAvailable;
  18429. }
  18430. if (numSamples <= 0)
  18431. return true;
  18432. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18433. while (numSamples > 0)
  18434. {
  18435. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18436. char tempBuffer [tempBufSize];
  18437. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18438. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18439. if (bytesRead < numThisTime * bytesPerFrame)
  18440. {
  18441. jassert (bytesRead >= 0);
  18442. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18443. }
  18444. switch (bitsPerSample)
  18445. {
  18446. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18447. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18448. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18449. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18450. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18451. default: jassertfalse; break;
  18452. }
  18453. startOffsetInDestBuffer += numThisTime;
  18454. numSamples -= numThisTime;
  18455. }
  18456. return true;
  18457. }
  18458. int64 bwavChunkStart, bwavSize;
  18459. private:
  18460. ScopedPointer<AudioData::Converter> converter;
  18461. int bytesPerFrame;
  18462. int64 dataChunkStart, dataLength;
  18463. bool isRF64;
  18464. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18465. };
  18466. class WavAudioFormatWriter : public AudioFormatWriter
  18467. {
  18468. public:
  18469. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18470. const unsigned int numChannels_, const int bits,
  18471. const StringPairArray& metadataValues)
  18472. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18473. lengthInSamples (0),
  18474. bytesWritten (0),
  18475. writeFailed (false),
  18476. isRF64 (false)
  18477. {
  18478. using namespace WavFileHelpers;
  18479. if (metadataValues.size() > 0)
  18480. {
  18481. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18482. smplChunk = SMPLChunk::createFrom (metadataValues);
  18483. }
  18484. headerPosition = out->getPosition();
  18485. writeHeader();
  18486. }
  18487. ~WavAudioFormatWriter()
  18488. {
  18489. if ((bytesWritten & 1) != 0) // pad to an even length
  18490. {
  18491. ++bytesWritten;
  18492. output->writeByte (0);
  18493. }
  18494. writeHeader();
  18495. }
  18496. bool write (const int** data, int numSamples)
  18497. {
  18498. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18499. if (writeFailed)
  18500. return false;
  18501. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18502. tempBlock.ensureSize (bytes, false);
  18503. switch (bitsPerSample)
  18504. {
  18505. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18506. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18507. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18508. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18509. default: jassertfalse; break;
  18510. }
  18511. if (! output->write (tempBlock.getData(), bytes))
  18512. {
  18513. // failed to write to disk, so let's try writing the header.
  18514. // If it's just run out of disk space, then if it does manage
  18515. // to write the header, we'll still have a useable file..
  18516. writeHeader();
  18517. writeFailed = true;
  18518. return false;
  18519. }
  18520. else
  18521. {
  18522. bytesWritten += bytes;
  18523. lengthInSamples += numSamples;
  18524. return true;
  18525. }
  18526. }
  18527. private:
  18528. ScopedPointer<AudioData::Converter> converter;
  18529. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18530. uint64 lengthInSamples, bytesWritten;
  18531. int64 headerPosition;
  18532. bool writeFailed, isRF64;
  18533. static int getChannelMask (const int numChannels) throw()
  18534. {
  18535. switch (numChannels)
  18536. {
  18537. case 1: return 0;
  18538. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18539. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18540. 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
  18541. default: break;
  18542. }
  18543. return 0;
  18544. }
  18545. void writeHeader()
  18546. {
  18547. using namespace WavFileHelpers;
  18548. const bool seekedOk = output->setPosition (headerPosition);
  18549. (void) seekedOk;
  18550. // if this fails, you've given it an output stream that can't seek! It needs
  18551. // to be able to seek back to write the header
  18552. jassert (seekedOk);
  18553. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18554. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18555. int64 riffChunkSize = 4 /* 'WAVE' */ + 8 + 40 /* WAVEFORMATEX */
  18556. + 8 + audioDataSize + (audioDataSize & 1)
  18557. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18558. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18559. + (8 + 28); // (JUNK chunk)
  18560. riffChunkSize += (riffChunkSize & 0x1);
  18561. isRF64 = (riffChunkSize > 0xffffffff);
  18562. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18563. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18564. output->writeInt (chunkName ("WAVE"));
  18565. if (! isRF64)
  18566. {
  18567. // write Junk chunk
  18568. output->writeInt (chunkName ("JUNK"));
  18569. output->writeInt (28);
  18570. output->writeRepeatedByte (0, 28);
  18571. }
  18572. else
  18573. {
  18574. // write ds64 chunk
  18575. output->writeInt (chunkName ("ds64"));
  18576. output->writeInt (28); // chunk size for uncompressed data (no table)
  18577. output->writeInt64 (riffChunkSize);
  18578. output->writeInt64 (audioDataSize);
  18579. output->writeRepeatedByte (0, 12);
  18580. }
  18581. output->writeInt (chunkName ("fmt "));
  18582. output->writeInt (40); // WAVEFORMATEX chunk size
  18583. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18584. output->writeShort ((short) numChannels);
  18585. output->writeInt ((int) sampleRate);
  18586. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18587. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18588. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18589. output->writeShort (22); // cbSize (size of the extension)
  18590. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18591. output->writeInt (getChannelMask (numChannels));
  18592. const ExtensibleWavSubFormat pcmFormat
  18593. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18594. const ExtensibleWavSubFormat IEEEFloatFormat
  18595. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18596. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18597. output->writeInt ((int) subFormat.data1);
  18598. output->writeShort ((short) subFormat.data2);
  18599. output->writeShort ((short) subFormat.data3);
  18600. output->write (subFormat.data4, sizeof (subFormat.data4));
  18601. if (bwavChunk.getSize() > 0)
  18602. {
  18603. output->writeInt (chunkName ("bext"));
  18604. output->writeInt ((int) bwavChunk.getSize());
  18605. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18606. }
  18607. if (smplChunk.getSize() > 0)
  18608. {
  18609. output->writeInt (chunkName ("smpl"));
  18610. output->writeInt ((int) smplChunk.getSize());
  18611. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18612. }
  18613. output->writeInt (chunkName ("data"));
  18614. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18615. usesFloatingPointData = (bitsPerSample == 32);
  18616. }
  18617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18618. };
  18619. WavAudioFormat::WavAudioFormat()
  18620. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18621. {
  18622. }
  18623. WavAudioFormat::~WavAudioFormat()
  18624. {
  18625. }
  18626. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18627. {
  18628. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18629. return Array <int> (rates);
  18630. }
  18631. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18632. {
  18633. const int depths[] = { 8, 16, 24, 32, 0 };
  18634. return Array <int> (depths);
  18635. }
  18636. bool WavAudioFormat::canDoStereo() { return true; }
  18637. bool WavAudioFormat::canDoMono() { return true; }
  18638. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18639. const bool deleteStreamIfOpeningFails)
  18640. {
  18641. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18642. if (r->sampleRate != 0)
  18643. return r.release();
  18644. if (! deleteStreamIfOpeningFails)
  18645. r->input = 0;
  18646. return 0;
  18647. }
  18648. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18649. unsigned int numChannels, int bitsPerSample,
  18650. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18651. {
  18652. if (getPossibleBitDepths().contains (bitsPerSample))
  18653. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18654. return 0;
  18655. }
  18656. namespace WavFileHelpers
  18657. {
  18658. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18659. {
  18660. TemporaryFile tempFile (file);
  18661. WavAudioFormat wav;
  18662. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18663. if (reader != 0)
  18664. {
  18665. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18666. if (outStream != 0)
  18667. {
  18668. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18669. reader->numChannels, reader->bitsPerSample,
  18670. metadata, 0));
  18671. if (writer != 0)
  18672. {
  18673. outStream.release();
  18674. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18675. writer = 0;
  18676. reader = 0;
  18677. return ok && tempFile.overwriteTargetFileWithTemporary();
  18678. }
  18679. }
  18680. }
  18681. return false;
  18682. }
  18683. }
  18684. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18685. {
  18686. using namespace WavFileHelpers;
  18687. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18688. if (reader != 0)
  18689. {
  18690. const int64 bwavPos = reader->bwavChunkStart;
  18691. const int64 bwavSize = reader->bwavSize;
  18692. reader = 0;
  18693. if (bwavSize > 0)
  18694. {
  18695. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18696. if (chunk.getSize() <= (size_t) bwavSize)
  18697. {
  18698. // the new one will fit in the space available, so write it directly..
  18699. const int64 oldSize = wavFile.getSize();
  18700. {
  18701. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18702. out->setPosition (bwavPos);
  18703. out->write (chunk.getData(), (int) chunk.getSize());
  18704. out->setPosition (oldSize);
  18705. }
  18706. jassert (wavFile.getSize() == oldSize);
  18707. return true;
  18708. }
  18709. }
  18710. }
  18711. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18712. }
  18713. END_JUCE_NAMESPACE
  18714. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18715. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18716. #if JUCE_USE_CDREADER
  18717. BEGIN_JUCE_NAMESPACE
  18718. int AudioCDReader::getNumTracks() const
  18719. {
  18720. return trackStartSamples.size() - 1;
  18721. }
  18722. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18723. {
  18724. return trackStartSamples [trackNum];
  18725. }
  18726. const Array<int>& AudioCDReader::getTrackOffsets() const
  18727. {
  18728. return trackStartSamples;
  18729. }
  18730. int AudioCDReader::getCDDBId()
  18731. {
  18732. int checksum = 0;
  18733. const int numTracks = getNumTracks();
  18734. for (int i = 0; i < numTracks; ++i)
  18735. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18736. checksum += offset % 10;
  18737. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18738. // CCLLLLTT: checksum, length, tracks
  18739. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18740. }
  18741. END_JUCE_NAMESPACE
  18742. #endif
  18743. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18744. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18745. BEGIN_JUCE_NAMESPACE
  18746. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18747. const bool deleteReaderWhenThisIsDeleted)
  18748. : reader (reader_),
  18749. deleteReader (deleteReaderWhenThisIsDeleted),
  18750. nextPlayPos (0),
  18751. looping (false)
  18752. {
  18753. jassert (reader != 0);
  18754. }
  18755. AudioFormatReaderSource::~AudioFormatReaderSource()
  18756. {
  18757. releaseResources();
  18758. if (deleteReader)
  18759. delete reader;
  18760. }
  18761. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18762. {
  18763. nextPlayPos = newPosition;
  18764. }
  18765. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18766. {
  18767. looping = shouldLoop;
  18768. }
  18769. int64 AudioFormatReaderSource::getNextReadPosition() const
  18770. {
  18771. return looping ? nextPlayPos % reader->lengthInSamples
  18772. : nextPlayPos;
  18773. }
  18774. int64 AudioFormatReaderSource::getTotalLength() const
  18775. {
  18776. return reader->lengthInSamples;
  18777. }
  18778. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18779. double /*sampleRate*/)
  18780. {
  18781. }
  18782. void AudioFormatReaderSource::releaseResources()
  18783. {
  18784. }
  18785. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18786. {
  18787. if (info.numSamples > 0)
  18788. {
  18789. const int64 start = nextPlayPos;
  18790. if (looping)
  18791. {
  18792. const int newStart = start % (int) reader->lengthInSamples;
  18793. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18794. if (newEnd > newStart)
  18795. {
  18796. info.buffer->readFromAudioReader (reader,
  18797. info.startSample,
  18798. newEnd - newStart,
  18799. newStart,
  18800. true, true);
  18801. }
  18802. else
  18803. {
  18804. const int endSamps = (int) reader->lengthInSamples - newStart;
  18805. info.buffer->readFromAudioReader (reader,
  18806. info.startSample,
  18807. endSamps,
  18808. newStart,
  18809. true, true);
  18810. info.buffer->readFromAudioReader (reader,
  18811. info.startSample + endSamps,
  18812. newEnd,
  18813. 0,
  18814. true, true);
  18815. }
  18816. nextPlayPos = newEnd;
  18817. }
  18818. else
  18819. {
  18820. info.buffer->readFromAudioReader (reader,
  18821. info.startSample,
  18822. info.numSamples,
  18823. start,
  18824. true, true);
  18825. nextPlayPos += info.numSamples;
  18826. }
  18827. }
  18828. }
  18829. END_JUCE_NAMESPACE
  18830. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18831. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18832. BEGIN_JUCE_NAMESPACE
  18833. AudioSourcePlayer::AudioSourcePlayer()
  18834. : source (0),
  18835. sampleRate (0),
  18836. bufferSize (0),
  18837. tempBuffer (2, 8),
  18838. lastGain (1.0f),
  18839. gain (1.0f)
  18840. {
  18841. }
  18842. AudioSourcePlayer::~AudioSourcePlayer()
  18843. {
  18844. setSource (0);
  18845. }
  18846. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18847. {
  18848. if (source != newSource)
  18849. {
  18850. AudioSource* const oldSource = source;
  18851. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18852. newSource->prepareToPlay (bufferSize, sampleRate);
  18853. {
  18854. const ScopedLock sl (readLock);
  18855. source = newSource;
  18856. }
  18857. if (oldSource != 0)
  18858. oldSource->releaseResources();
  18859. }
  18860. }
  18861. void AudioSourcePlayer::setGain (const float newGain) throw()
  18862. {
  18863. gain = newGain;
  18864. }
  18865. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18866. int totalNumInputChannels,
  18867. float** outputChannelData,
  18868. int totalNumOutputChannels,
  18869. int numSamples)
  18870. {
  18871. // these should have been prepared by audioDeviceAboutToStart()...
  18872. jassert (sampleRate > 0 && bufferSize > 0);
  18873. const ScopedLock sl (readLock);
  18874. if (source != 0)
  18875. {
  18876. AudioSourceChannelInfo info;
  18877. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18878. // messy stuff needed to compact the channels down into an array
  18879. // of non-zero pointers..
  18880. for (i = 0; i < totalNumInputChannels; ++i)
  18881. {
  18882. if (inputChannelData[i] != 0)
  18883. {
  18884. inputChans [numInputs++] = inputChannelData[i];
  18885. if (numInputs >= numElementsInArray (inputChans))
  18886. break;
  18887. }
  18888. }
  18889. for (i = 0; i < totalNumOutputChannels; ++i)
  18890. {
  18891. if (outputChannelData[i] != 0)
  18892. {
  18893. outputChans [numOutputs++] = outputChannelData[i];
  18894. if (numOutputs >= numElementsInArray (outputChans))
  18895. break;
  18896. }
  18897. }
  18898. if (numInputs > numOutputs)
  18899. {
  18900. // if there aren't enough output channels for the number of
  18901. // inputs, we need to create some temporary extra ones (can't
  18902. // use the input data in case it gets written to)
  18903. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18904. false, false, true);
  18905. for (i = 0; i < numOutputs; ++i)
  18906. {
  18907. channels[numActiveChans] = outputChans[i];
  18908. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18909. ++numActiveChans;
  18910. }
  18911. for (i = numOutputs; i < numInputs; ++i)
  18912. {
  18913. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18914. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18915. ++numActiveChans;
  18916. }
  18917. }
  18918. else
  18919. {
  18920. for (i = 0; i < numInputs; ++i)
  18921. {
  18922. channels[numActiveChans] = outputChans[i];
  18923. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18924. ++numActiveChans;
  18925. }
  18926. for (i = numInputs; i < numOutputs; ++i)
  18927. {
  18928. channels[numActiveChans] = outputChans[i];
  18929. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18930. ++numActiveChans;
  18931. }
  18932. }
  18933. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18934. info.buffer = &buffer;
  18935. info.startSample = 0;
  18936. info.numSamples = numSamples;
  18937. source->getNextAudioBlock (info);
  18938. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18939. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18940. lastGain = gain;
  18941. }
  18942. else
  18943. {
  18944. for (int i = 0; i < totalNumOutputChannels; ++i)
  18945. if (outputChannelData[i] != 0)
  18946. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18947. }
  18948. }
  18949. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18950. {
  18951. sampleRate = device->getCurrentSampleRate();
  18952. bufferSize = device->getCurrentBufferSizeSamples();
  18953. zeromem (channels, sizeof (channels));
  18954. if (source != 0)
  18955. source->prepareToPlay (bufferSize, sampleRate);
  18956. }
  18957. void AudioSourcePlayer::audioDeviceStopped()
  18958. {
  18959. if (source != 0)
  18960. source->releaseResources();
  18961. sampleRate = 0.0;
  18962. bufferSize = 0;
  18963. tempBuffer.setSize (2, 8);
  18964. }
  18965. END_JUCE_NAMESPACE
  18966. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18967. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18968. BEGIN_JUCE_NAMESPACE
  18969. AudioTransportSource::AudioTransportSource()
  18970. : source (0),
  18971. resamplerSource (0),
  18972. bufferingSource (0),
  18973. positionableSource (0),
  18974. masterSource (0),
  18975. gain (1.0f),
  18976. lastGain (1.0f),
  18977. playing (false),
  18978. stopped (true),
  18979. sampleRate (44100.0),
  18980. sourceSampleRate (0.0),
  18981. blockSize (128),
  18982. readAheadBufferSize (0),
  18983. isPrepared (false),
  18984. inputStreamEOF (false)
  18985. {
  18986. }
  18987. AudioTransportSource::~AudioTransportSource()
  18988. {
  18989. setSource (0);
  18990. releaseResources();
  18991. }
  18992. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18993. int readAheadBufferSize_,
  18994. double sourceSampleRateToCorrectFor,
  18995. int maxNumChannels)
  18996. {
  18997. if (source == newSource)
  18998. {
  18999. if (source == 0)
  19000. return;
  19001. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19002. }
  19003. readAheadBufferSize = readAheadBufferSize_;
  19004. sourceSampleRate = sourceSampleRateToCorrectFor;
  19005. ResamplingAudioSource* newResamplerSource = 0;
  19006. BufferingAudioSource* newBufferingSource = 0;
  19007. PositionableAudioSource* newPositionableSource = 0;
  19008. AudioSource* newMasterSource = 0;
  19009. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19010. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19011. AudioSource* oldMasterSource = masterSource;
  19012. if (newSource != 0)
  19013. {
  19014. newPositionableSource = newSource;
  19015. if (readAheadBufferSize_ > 0)
  19016. newPositionableSource = newBufferingSource
  19017. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19018. newPositionableSource->setNextReadPosition (0);
  19019. if (sourceSampleRateToCorrectFor != 0)
  19020. newMasterSource = newResamplerSource
  19021. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19022. else
  19023. newMasterSource = newPositionableSource;
  19024. if (isPrepared)
  19025. {
  19026. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19027. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19028. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19029. }
  19030. }
  19031. {
  19032. const ScopedLock sl (callbackLock);
  19033. source = newSource;
  19034. resamplerSource = newResamplerSource;
  19035. bufferingSource = newBufferingSource;
  19036. masterSource = newMasterSource;
  19037. positionableSource = newPositionableSource;
  19038. playing = false;
  19039. }
  19040. if (oldMasterSource != 0)
  19041. oldMasterSource->releaseResources();
  19042. }
  19043. void AudioTransportSource::start()
  19044. {
  19045. if ((! playing) && masterSource != 0)
  19046. {
  19047. {
  19048. const ScopedLock sl (callbackLock);
  19049. playing = true;
  19050. stopped = false;
  19051. inputStreamEOF = false;
  19052. }
  19053. sendChangeMessage();
  19054. }
  19055. }
  19056. void AudioTransportSource::stop()
  19057. {
  19058. if (playing)
  19059. {
  19060. {
  19061. const ScopedLock sl (callbackLock);
  19062. playing = false;
  19063. }
  19064. int n = 500;
  19065. while (--n >= 0 && ! stopped)
  19066. Thread::sleep (2);
  19067. sendChangeMessage();
  19068. }
  19069. }
  19070. void AudioTransportSource::setPosition (double newPosition)
  19071. {
  19072. if (sampleRate > 0.0)
  19073. setNextReadPosition ((int64) (newPosition * sampleRate));
  19074. }
  19075. double AudioTransportSource::getCurrentPosition() const
  19076. {
  19077. if (sampleRate > 0.0)
  19078. return getNextReadPosition() / sampleRate;
  19079. else
  19080. return 0.0;
  19081. }
  19082. double AudioTransportSource::getLengthInSeconds() const
  19083. {
  19084. return getTotalLength() / sampleRate;
  19085. }
  19086. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19087. {
  19088. if (positionableSource != 0)
  19089. {
  19090. if (sampleRate > 0 && sourceSampleRate > 0)
  19091. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19092. positionableSource->setNextReadPosition (newPosition);
  19093. }
  19094. }
  19095. int64 AudioTransportSource::getNextReadPosition() const
  19096. {
  19097. if (positionableSource != 0)
  19098. {
  19099. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19100. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19101. }
  19102. return 0;
  19103. }
  19104. int64 AudioTransportSource::getTotalLength() const
  19105. {
  19106. const ScopedLock sl (callbackLock);
  19107. if (positionableSource != 0)
  19108. {
  19109. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19110. return (int64) (positionableSource->getTotalLength() * ratio);
  19111. }
  19112. return 0;
  19113. }
  19114. bool AudioTransportSource::isLooping() const
  19115. {
  19116. const ScopedLock sl (callbackLock);
  19117. return positionableSource != 0
  19118. && positionableSource->isLooping();
  19119. }
  19120. void AudioTransportSource::setGain (const float newGain) throw()
  19121. {
  19122. gain = newGain;
  19123. }
  19124. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19125. double sampleRate_)
  19126. {
  19127. const ScopedLock sl (callbackLock);
  19128. sampleRate = sampleRate_;
  19129. blockSize = samplesPerBlockExpected;
  19130. if (masterSource != 0)
  19131. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19132. if (resamplerSource != 0 && sourceSampleRate != 0)
  19133. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19134. isPrepared = true;
  19135. }
  19136. void AudioTransportSource::releaseResources()
  19137. {
  19138. const ScopedLock sl (callbackLock);
  19139. if (masterSource != 0)
  19140. masterSource->releaseResources();
  19141. isPrepared = false;
  19142. }
  19143. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19144. {
  19145. const ScopedLock sl (callbackLock);
  19146. inputStreamEOF = false;
  19147. if (masterSource != 0 && ! stopped)
  19148. {
  19149. masterSource->getNextAudioBlock (info);
  19150. if (! playing)
  19151. {
  19152. // just stopped playing, so fade out the last block..
  19153. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19154. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19155. if (info.numSamples > 256)
  19156. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19157. }
  19158. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19159. && ! positionableSource->isLooping())
  19160. {
  19161. playing = false;
  19162. inputStreamEOF = true;
  19163. sendChangeMessage();
  19164. }
  19165. stopped = ! playing;
  19166. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19167. {
  19168. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19169. lastGain, gain);
  19170. }
  19171. }
  19172. else
  19173. {
  19174. info.clearActiveBufferRegion();
  19175. stopped = true;
  19176. }
  19177. lastGain = gain;
  19178. }
  19179. END_JUCE_NAMESPACE
  19180. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19181. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19182. BEGIN_JUCE_NAMESPACE
  19183. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19184. public Thread,
  19185. private Timer
  19186. {
  19187. public:
  19188. SharedBufferingAudioSourceThread()
  19189. : Thread ("Audio Buffer")
  19190. {
  19191. }
  19192. ~SharedBufferingAudioSourceThread()
  19193. {
  19194. stopThread (10000);
  19195. clearSingletonInstance();
  19196. }
  19197. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19198. void addSource (BufferingAudioSource* source)
  19199. {
  19200. const ScopedLock sl (lock);
  19201. if (! sources.contains (source))
  19202. {
  19203. sources.add (source);
  19204. startThread();
  19205. stopTimer();
  19206. }
  19207. notify();
  19208. }
  19209. void removeSource (BufferingAudioSource* source)
  19210. {
  19211. const ScopedLock sl (lock);
  19212. sources.removeValue (source);
  19213. if (sources.size() == 0)
  19214. startTimer (5000);
  19215. }
  19216. private:
  19217. Array <BufferingAudioSource*> sources;
  19218. CriticalSection lock;
  19219. void run()
  19220. {
  19221. while (! threadShouldExit())
  19222. {
  19223. bool busy = false;
  19224. for (int i = sources.size(); --i >= 0;)
  19225. {
  19226. if (threadShouldExit())
  19227. return;
  19228. const ScopedLock sl (lock);
  19229. BufferingAudioSource* const b = sources[i];
  19230. if (b != 0 && b->readNextBufferChunk())
  19231. busy = true;
  19232. }
  19233. if (! busy)
  19234. wait (500);
  19235. }
  19236. }
  19237. void timerCallback()
  19238. {
  19239. stopTimer();
  19240. if (sources.size() == 0)
  19241. deleteInstance();
  19242. }
  19243. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19244. };
  19245. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19246. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19247. const bool deleteSourceWhenDeleted_,
  19248. int numberOfSamplesToBuffer_)
  19249. : source (source_),
  19250. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19251. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19252. buffer (2, 0),
  19253. bufferValidStart (0),
  19254. bufferValidEnd (0),
  19255. nextPlayPos (0),
  19256. wasSourceLooping (false)
  19257. {
  19258. jassert (source_ != 0);
  19259. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19260. // not using a larger buffer..
  19261. }
  19262. BufferingAudioSource::~BufferingAudioSource()
  19263. {
  19264. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19265. if (thread != 0)
  19266. thread->removeSource (this);
  19267. if (deleteSourceWhenDeleted)
  19268. delete source;
  19269. }
  19270. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19271. {
  19272. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19273. sampleRate = sampleRate_;
  19274. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19275. buffer.clear();
  19276. bufferValidStart = 0;
  19277. bufferValidEnd = 0;
  19278. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19279. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19280. buffer.getNumSamples() / 2))
  19281. {
  19282. SharedBufferingAudioSourceThread::getInstance()->notify();
  19283. Thread::sleep (5);
  19284. }
  19285. }
  19286. void BufferingAudioSource::releaseResources()
  19287. {
  19288. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19289. if (thread != 0)
  19290. thread->removeSource (this);
  19291. buffer.setSize (2, 0);
  19292. source->releaseResources();
  19293. }
  19294. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19295. {
  19296. const ScopedLock sl (bufferStartPosLock);
  19297. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19298. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19299. if (validStart == validEnd)
  19300. {
  19301. // total cache miss
  19302. info.clearActiveBufferRegion();
  19303. }
  19304. else
  19305. {
  19306. if (validStart > 0)
  19307. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19308. if (validEnd < info.numSamples)
  19309. info.buffer->clear (info.startSample + validEnd,
  19310. info.numSamples - validEnd); // partial cache miss at end
  19311. if (validStart < validEnd)
  19312. {
  19313. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19314. {
  19315. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19316. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19317. if (startBufferIndex < endBufferIndex)
  19318. {
  19319. info.buffer->copyFrom (chan, info.startSample + validStart,
  19320. buffer,
  19321. chan, startBufferIndex,
  19322. validEnd - validStart);
  19323. }
  19324. else
  19325. {
  19326. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19327. info.buffer->copyFrom (chan, info.startSample + validStart,
  19328. buffer,
  19329. chan, startBufferIndex,
  19330. initialSize);
  19331. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19332. buffer,
  19333. chan, 0,
  19334. (validEnd - validStart) - initialSize);
  19335. }
  19336. }
  19337. }
  19338. nextPlayPos += info.numSamples;
  19339. if (source->isLooping() && nextPlayPos > 0)
  19340. nextPlayPos %= source->getTotalLength();
  19341. }
  19342. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19343. if (thread != 0)
  19344. thread->notify();
  19345. }
  19346. int64 BufferingAudioSource::getNextReadPosition() const
  19347. {
  19348. return (source->isLooping() && nextPlayPos > 0)
  19349. ? nextPlayPos % source->getTotalLength()
  19350. : nextPlayPos;
  19351. }
  19352. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19353. {
  19354. const ScopedLock sl (bufferStartPosLock);
  19355. nextPlayPos = newPosition;
  19356. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19357. if (thread != 0)
  19358. thread->notify();
  19359. }
  19360. bool BufferingAudioSource::readNextBufferChunk()
  19361. {
  19362. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19363. {
  19364. const ScopedLock sl (bufferStartPosLock);
  19365. if (wasSourceLooping != isLooping())
  19366. {
  19367. wasSourceLooping = isLooping();
  19368. bufferValidStart = 0;
  19369. bufferValidEnd = 0;
  19370. }
  19371. newBVS = jmax ((int64) 0, nextPlayPos);
  19372. newBVE = newBVS + buffer.getNumSamples() - 4;
  19373. sectionToReadStart = 0;
  19374. sectionToReadEnd = 0;
  19375. const int maxChunkSize = 2048;
  19376. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19377. {
  19378. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19379. sectionToReadStart = newBVS;
  19380. sectionToReadEnd = newBVE;
  19381. bufferValidStart = 0;
  19382. bufferValidEnd = 0;
  19383. }
  19384. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19385. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19386. {
  19387. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19388. sectionToReadStart = bufferValidEnd;
  19389. sectionToReadEnd = newBVE;
  19390. bufferValidStart = newBVS;
  19391. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19392. }
  19393. }
  19394. if (sectionToReadStart != sectionToReadEnd)
  19395. {
  19396. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19397. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19398. if (bufferIndexStart < bufferIndexEnd)
  19399. {
  19400. readBufferSection (sectionToReadStart,
  19401. (int) (sectionToReadEnd - sectionToReadStart),
  19402. bufferIndexStart);
  19403. }
  19404. else
  19405. {
  19406. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19407. readBufferSection (sectionToReadStart,
  19408. initialSize,
  19409. bufferIndexStart);
  19410. readBufferSection (sectionToReadStart + initialSize,
  19411. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19412. 0);
  19413. }
  19414. const ScopedLock sl2 (bufferStartPosLock);
  19415. bufferValidStart = newBVS;
  19416. bufferValidEnd = newBVE;
  19417. return true;
  19418. }
  19419. else
  19420. {
  19421. return false;
  19422. }
  19423. }
  19424. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19425. {
  19426. if (source->getNextReadPosition() != start)
  19427. source->setNextReadPosition (start);
  19428. AudioSourceChannelInfo info;
  19429. info.buffer = &buffer;
  19430. info.startSample = bufferOffset;
  19431. info.numSamples = length;
  19432. source->getNextAudioBlock (info);
  19433. }
  19434. END_JUCE_NAMESPACE
  19435. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19436. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19437. BEGIN_JUCE_NAMESPACE
  19438. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19439. const bool deleteSourceWhenDeleted_)
  19440. : requiredNumberOfChannels (2),
  19441. source (source_),
  19442. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19443. buffer (2, 16)
  19444. {
  19445. remappedInfo.buffer = &buffer;
  19446. remappedInfo.startSample = 0;
  19447. }
  19448. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19449. {
  19450. if (deleteSourceWhenDeleted)
  19451. delete source;
  19452. }
  19453. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19454. {
  19455. const ScopedLock sl (lock);
  19456. requiredNumberOfChannels = requiredNumberOfChannels_;
  19457. }
  19458. void ChannelRemappingAudioSource::clearAllMappings()
  19459. {
  19460. const ScopedLock sl (lock);
  19461. remappedInputs.clear();
  19462. remappedOutputs.clear();
  19463. }
  19464. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19465. {
  19466. const ScopedLock sl (lock);
  19467. while (remappedInputs.size() < destIndex)
  19468. remappedInputs.add (-1);
  19469. remappedInputs.set (destIndex, sourceIndex);
  19470. }
  19471. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19472. {
  19473. const ScopedLock sl (lock);
  19474. while (remappedOutputs.size() < sourceIndex)
  19475. remappedOutputs.add (-1);
  19476. remappedOutputs.set (sourceIndex, destIndex);
  19477. }
  19478. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19479. {
  19480. const ScopedLock sl (lock);
  19481. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19482. return remappedInputs.getUnchecked (inputChannelIndex);
  19483. return -1;
  19484. }
  19485. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19486. {
  19487. const ScopedLock sl (lock);
  19488. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19489. return remappedOutputs .getUnchecked (outputChannelIndex);
  19490. return -1;
  19491. }
  19492. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19493. {
  19494. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19495. }
  19496. void ChannelRemappingAudioSource::releaseResources()
  19497. {
  19498. source->releaseResources();
  19499. }
  19500. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19501. {
  19502. const ScopedLock sl (lock);
  19503. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19504. const int numChans = bufferToFill.buffer->getNumChannels();
  19505. int i;
  19506. for (i = 0; i < buffer.getNumChannels(); ++i)
  19507. {
  19508. const int remappedChan = getRemappedInputChannel (i);
  19509. if (remappedChan >= 0 && remappedChan < numChans)
  19510. {
  19511. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19512. remappedChan,
  19513. bufferToFill.startSample,
  19514. bufferToFill.numSamples);
  19515. }
  19516. else
  19517. {
  19518. buffer.clear (i, 0, bufferToFill.numSamples);
  19519. }
  19520. }
  19521. remappedInfo.numSamples = bufferToFill.numSamples;
  19522. source->getNextAudioBlock (remappedInfo);
  19523. bufferToFill.clearActiveBufferRegion();
  19524. for (i = 0; i < requiredNumberOfChannels; ++i)
  19525. {
  19526. const int remappedChan = getRemappedOutputChannel (i);
  19527. if (remappedChan >= 0 && remappedChan < numChans)
  19528. {
  19529. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19530. buffer, i, 0, bufferToFill.numSamples);
  19531. }
  19532. }
  19533. }
  19534. XmlElement* ChannelRemappingAudioSource::createXml() const
  19535. {
  19536. XmlElement* e = new XmlElement ("MAPPINGS");
  19537. String ins, outs;
  19538. int i;
  19539. const ScopedLock sl (lock);
  19540. for (i = 0; i < remappedInputs.size(); ++i)
  19541. ins << remappedInputs.getUnchecked(i) << ' ';
  19542. for (i = 0; i < remappedOutputs.size(); ++i)
  19543. outs << remappedOutputs.getUnchecked(i) << ' ';
  19544. e->setAttribute ("inputs", ins.trimEnd());
  19545. e->setAttribute ("outputs", outs.trimEnd());
  19546. return e;
  19547. }
  19548. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19549. {
  19550. if (e.hasTagName ("MAPPINGS"))
  19551. {
  19552. const ScopedLock sl (lock);
  19553. clearAllMappings();
  19554. StringArray ins, outs;
  19555. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19556. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19557. int i;
  19558. for (i = 0; i < ins.size(); ++i)
  19559. remappedInputs.add (ins[i].getIntValue());
  19560. for (i = 0; i < outs.size(); ++i)
  19561. remappedOutputs.add (outs[i].getIntValue());
  19562. }
  19563. }
  19564. END_JUCE_NAMESPACE
  19565. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19566. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19567. BEGIN_JUCE_NAMESPACE
  19568. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19569. const bool deleteInputWhenDeleted_)
  19570. : input (inputSource),
  19571. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19572. {
  19573. jassert (inputSource != 0);
  19574. for (int i = 2; --i >= 0;)
  19575. iirFilters.add (new IIRFilter());
  19576. }
  19577. IIRFilterAudioSource::~IIRFilterAudioSource()
  19578. {
  19579. if (deleteInputWhenDeleted)
  19580. delete input;
  19581. }
  19582. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19583. {
  19584. for (int i = iirFilters.size(); --i >= 0;)
  19585. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19586. }
  19587. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19588. {
  19589. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19590. for (int i = iirFilters.size(); --i >= 0;)
  19591. iirFilters.getUnchecked(i)->reset();
  19592. }
  19593. void IIRFilterAudioSource::releaseResources()
  19594. {
  19595. input->releaseResources();
  19596. }
  19597. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19598. {
  19599. input->getNextAudioBlock (bufferToFill);
  19600. const int numChannels = bufferToFill.buffer->getNumChannels();
  19601. while (numChannels > iirFilters.size())
  19602. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19603. for (int i = 0; i < numChannels; ++i)
  19604. iirFilters.getUnchecked(i)
  19605. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19606. bufferToFill.numSamples);
  19607. }
  19608. END_JUCE_NAMESPACE
  19609. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19610. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19611. BEGIN_JUCE_NAMESPACE
  19612. MixerAudioSource::MixerAudioSource()
  19613. : tempBuffer (2, 0),
  19614. currentSampleRate (0.0),
  19615. bufferSizeExpected (0)
  19616. {
  19617. }
  19618. MixerAudioSource::~MixerAudioSource()
  19619. {
  19620. removeAllInputs();
  19621. }
  19622. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19623. {
  19624. if (input != 0 && ! inputs.contains (input))
  19625. {
  19626. double localRate;
  19627. int localBufferSize;
  19628. {
  19629. const ScopedLock sl (lock);
  19630. localRate = currentSampleRate;
  19631. localBufferSize = bufferSizeExpected;
  19632. }
  19633. if (localRate != 0.0)
  19634. input->prepareToPlay (localBufferSize, localRate);
  19635. const ScopedLock sl (lock);
  19636. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19637. inputs.add (input);
  19638. }
  19639. }
  19640. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19641. {
  19642. if (input != 0)
  19643. {
  19644. int index;
  19645. {
  19646. const ScopedLock sl (lock);
  19647. index = inputs.indexOf (input);
  19648. if (index >= 0)
  19649. {
  19650. inputsToDelete.shiftBits (index, 1);
  19651. inputs.remove (index);
  19652. }
  19653. }
  19654. if (index >= 0)
  19655. {
  19656. input->releaseResources();
  19657. if (deleteInput)
  19658. delete input;
  19659. }
  19660. }
  19661. }
  19662. void MixerAudioSource::removeAllInputs()
  19663. {
  19664. OwnedArray<AudioSource> toDelete;
  19665. {
  19666. const ScopedLock sl (lock);
  19667. for (int i = inputs.size(); --i >= 0;)
  19668. if (inputsToDelete[i])
  19669. toDelete.add (inputs.getUnchecked(i));
  19670. }
  19671. }
  19672. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19673. {
  19674. tempBuffer.setSize (2, samplesPerBlockExpected);
  19675. const ScopedLock sl (lock);
  19676. currentSampleRate = sampleRate;
  19677. bufferSizeExpected = samplesPerBlockExpected;
  19678. for (int i = inputs.size(); --i >= 0;)
  19679. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19680. }
  19681. void MixerAudioSource::releaseResources()
  19682. {
  19683. const ScopedLock sl (lock);
  19684. for (int i = inputs.size(); --i >= 0;)
  19685. inputs.getUnchecked(i)->releaseResources();
  19686. tempBuffer.setSize (2, 0);
  19687. currentSampleRate = 0;
  19688. bufferSizeExpected = 0;
  19689. }
  19690. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19691. {
  19692. const ScopedLock sl (lock);
  19693. if (inputs.size() > 0)
  19694. {
  19695. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19696. if (inputs.size() > 1)
  19697. {
  19698. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19699. info.buffer->getNumSamples());
  19700. AudioSourceChannelInfo info2;
  19701. info2.buffer = &tempBuffer;
  19702. info2.numSamples = info.numSamples;
  19703. info2.startSample = 0;
  19704. for (int i = 1; i < inputs.size(); ++i)
  19705. {
  19706. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19707. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19708. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19709. }
  19710. }
  19711. }
  19712. else
  19713. {
  19714. info.clearActiveBufferRegion();
  19715. }
  19716. }
  19717. END_JUCE_NAMESPACE
  19718. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19719. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19720. BEGIN_JUCE_NAMESPACE
  19721. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19722. const bool deleteInputWhenDeleted_,
  19723. const int numChannels_)
  19724. : input (inputSource),
  19725. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19726. ratio (1.0),
  19727. lastRatio (1.0),
  19728. buffer (numChannels_, 0),
  19729. sampsInBuffer (0),
  19730. numChannels (numChannels_)
  19731. {
  19732. jassert (input != 0);
  19733. }
  19734. ResamplingAudioSource::~ResamplingAudioSource()
  19735. {
  19736. if (deleteInputWhenDeleted)
  19737. delete input;
  19738. }
  19739. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19740. {
  19741. jassert (samplesInPerOutputSample > 0);
  19742. const ScopedLock sl (ratioLock);
  19743. ratio = jmax (0.0, samplesInPerOutputSample);
  19744. }
  19745. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19746. double sampleRate)
  19747. {
  19748. const ScopedLock sl (ratioLock);
  19749. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19750. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19751. buffer.clear();
  19752. sampsInBuffer = 0;
  19753. bufferPos = 0;
  19754. subSampleOffset = 0.0;
  19755. filterStates.calloc (numChannels);
  19756. srcBuffers.calloc (numChannels);
  19757. destBuffers.calloc (numChannels);
  19758. createLowPass (ratio);
  19759. resetFilters();
  19760. }
  19761. void ResamplingAudioSource::releaseResources()
  19762. {
  19763. input->releaseResources();
  19764. buffer.setSize (numChannels, 0);
  19765. }
  19766. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19767. {
  19768. double localRatio;
  19769. {
  19770. const ScopedLock sl (ratioLock);
  19771. localRatio = ratio;
  19772. }
  19773. if (lastRatio != localRatio)
  19774. {
  19775. createLowPass (localRatio);
  19776. lastRatio = localRatio;
  19777. }
  19778. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19779. int bufferSize = buffer.getNumSamples();
  19780. if (bufferSize < sampsNeeded + 8)
  19781. {
  19782. bufferPos %= bufferSize;
  19783. bufferSize = sampsNeeded + 32;
  19784. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19785. }
  19786. bufferPos %= bufferSize;
  19787. int endOfBufferPos = bufferPos + sampsInBuffer;
  19788. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19789. while (sampsNeeded > sampsInBuffer)
  19790. {
  19791. endOfBufferPos %= bufferSize;
  19792. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19793. bufferSize - endOfBufferPos);
  19794. AudioSourceChannelInfo readInfo;
  19795. readInfo.buffer = &buffer;
  19796. readInfo.numSamples = numToDo;
  19797. readInfo.startSample = endOfBufferPos;
  19798. input->getNextAudioBlock (readInfo);
  19799. if (localRatio > 1.0001)
  19800. {
  19801. // for down-sampling, pre-apply the filter..
  19802. for (int i = channelsToProcess; --i >= 0;)
  19803. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19804. }
  19805. sampsInBuffer += numToDo;
  19806. endOfBufferPos += numToDo;
  19807. }
  19808. for (int channel = 0; channel < channelsToProcess; ++channel)
  19809. {
  19810. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19811. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19812. }
  19813. int nextPos = (bufferPos + 1) % bufferSize;
  19814. for (int m = info.numSamples; --m >= 0;)
  19815. {
  19816. const float alpha = (float) subSampleOffset;
  19817. const float invAlpha = 1.0f - alpha;
  19818. for (int channel = 0; channel < channelsToProcess; ++channel)
  19819. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19820. subSampleOffset += localRatio;
  19821. jassert (sampsInBuffer > 0);
  19822. while (subSampleOffset >= 1.0)
  19823. {
  19824. if (++bufferPos >= bufferSize)
  19825. bufferPos = 0;
  19826. --sampsInBuffer;
  19827. nextPos = (bufferPos + 1) % bufferSize;
  19828. subSampleOffset -= 1.0;
  19829. }
  19830. }
  19831. if (localRatio < 0.9999)
  19832. {
  19833. // for up-sampling, apply the filter after transposing..
  19834. for (int i = channelsToProcess; --i >= 0;)
  19835. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19836. }
  19837. else if (localRatio <= 1.0001)
  19838. {
  19839. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19840. for (int i = channelsToProcess; --i >= 0;)
  19841. {
  19842. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19843. FilterState& fs = filterStates[i];
  19844. if (info.numSamples > 1)
  19845. {
  19846. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19847. }
  19848. else
  19849. {
  19850. fs.y2 = fs.y1;
  19851. fs.x2 = fs.x1;
  19852. }
  19853. fs.y1 = fs.x1 = *endOfBuffer;
  19854. }
  19855. }
  19856. jassert (sampsInBuffer >= 0);
  19857. }
  19858. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19859. {
  19860. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19861. : 0.5 * frequencyRatio;
  19862. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  19863. const double nSquared = n * n;
  19864. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19865. setFilterCoefficients (c1,
  19866. c1 * 2.0f,
  19867. c1,
  19868. 1.0,
  19869. c1 * 2.0 * (1.0 - nSquared),
  19870. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19871. }
  19872. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19873. {
  19874. const double a = 1.0 / c4;
  19875. c1 *= a;
  19876. c2 *= a;
  19877. c3 *= a;
  19878. c5 *= a;
  19879. c6 *= a;
  19880. coefficients[0] = c1;
  19881. coefficients[1] = c2;
  19882. coefficients[2] = c3;
  19883. coefficients[3] = c4;
  19884. coefficients[4] = c5;
  19885. coefficients[5] = c6;
  19886. }
  19887. void ResamplingAudioSource::resetFilters()
  19888. {
  19889. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19890. }
  19891. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19892. {
  19893. while (--num >= 0)
  19894. {
  19895. const double in = *samples;
  19896. double out = coefficients[0] * in
  19897. + coefficients[1] * fs.x1
  19898. + coefficients[2] * fs.x2
  19899. - coefficients[4] * fs.y1
  19900. - coefficients[5] * fs.y2;
  19901. #if JUCE_INTEL
  19902. if (! (out < -1.0e-8 || out > 1.0e-8))
  19903. out = 0;
  19904. #endif
  19905. fs.x2 = fs.x1;
  19906. fs.x1 = in;
  19907. fs.y2 = fs.y1;
  19908. fs.y1 = out;
  19909. *samples++ = (float) out;
  19910. }
  19911. }
  19912. END_JUCE_NAMESPACE
  19913. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19914. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19915. BEGIN_JUCE_NAMESPACE
  19916. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19917. : frequency (1000.0),
  19918. sampleRate (44100.0),
  19919. currentPhase (0.0),
  19920. phasePerSample (0.0),
  19921. amplitude (0.5f)
  19922. {
  19923. }
  19924. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19925. {
  19926. }
  19927. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19928. {
  19929. amplitude = newAmplitude;
  19930. }
  19931. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19932. {
  19933. frequency = newFrequencyHz;
  19934. phasePerSample = 0.0;
  19935. }
  19936. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19937. double sampleRate_)
  19938. {
  19939. currentPhase = 0.0;
  19940. phasePerSample = 0.0;
  19941. sampleRate = sampleRate_;
  19942. }
  19943. void ToneGeneratorAudioSource::releaseResources()
  19944. {
  19945. }
  19946. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19947. {
  19948. if (phasePerSample == 0.0)
  19949. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19950. for (int i = 0; i < info.numSamples; ++i)
  19951. {
  19952. const float sample = amplitude * (float) std::sin (currentPhase);
  19953. currentPhase += phasePerSample;
  19954. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19955. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19956. }
  19957. }
  19958. END_JUCE_NAMESPACE
  19959. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19960. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19961. BEGIN_JUCE_NAMESPACE
  19962. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19963. : sampleRate (0),
  19964. bufferSize (0),
  19965. useDefaultInputChannels (true),
  19966. useDefaultOutputChannels (true)
  19967. {
  19968. }
  19969. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19970. {
  19971. return outputDeviceName == other.outputDeviceName
  19972. && inputDeviceName == other.inputDeviceName
  19973. && sampleRate == other.sampleRate
  19974. && bufferSize == other.bufferSize
  19975. && inputChannels == other.inputChannels
  19976. && useDefaultInputChannels == other.useDefaultInputChannels
  19977. && outputChannels == other.outputChannels
  19978. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19979. }
  19980. AudioDeviceManager::AudioDeviceManager()
  19981. : currentAudioDevice (0),
  19982. numInputChansNeeded (0),
  19983. numOutputChansNeeded (2),
  19984. listNeedsScanning (true),
  19985. useInputNames (false),
  19986. inputLevelMeasurementEnabledCount (0),
  19987. inputLevel (0),
  19988. tempBuffer (2, 2),
  19989. defaultMidiOutput (0),
  19990. cpuUsageMs (0),
  19991. timeToCpuScale (0)
  19992. {
  19993. callbackHandler.owner = this;
  19994. }
  19995. AudioDeviceManager::~AudioDeviceManager()
  19996. {
  19997. currentAudioDevice = 0;
  19998. defaultMidiOutput = 0;
  19999. }
  20000. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20001. {
  20002. if (availableDeviceTypes.size() == 0)
  20003. {
  20004. createAudioDeviceTypes (availableDeviceTypes);
  20005. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20006. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20007. if (availableDeviceTypes.size() > 0)
  20008. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20009. }
  20010. }
  20011. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20012. {
  20013. scanDevicesIfNeeded();
  20014. return availableDeviceTypes;
  20015. }
  20016. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20017. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20018. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20019. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20020. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20021. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20022. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20023. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20024. {
  20025. (void) list; // (to avoid 'unused param' warnings)
  20026. #if JUCE_WINDOWS
  20027. #if JUCE_WASAPI
  20028. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20029. list.add (juce_createAudioIODeviceType_WASAPI());
  20030. #endif
  20031. #if JUCE_DIRECTSOUND
  20032. list.add (juce_createAudioIODeviceType_DirectSound());
  20033. #endif
  20034. #if JUCE_ASIO
  20035. list.add (juce_createAudioIODeviceType_ASIO());
  20036. #endif
  20037. #endif
  20038. #if JUCE_MAC
  20039. list.add (juce_createAudioIODeviceType_CoreAudio());
  20040. #endif
  20041. #if JUCE_IOS
  20042. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20043. #endif
  20044. #if JUCE_LINUX && JUCE_ALSA
  20045. list.add (juce_createAudioIODeviceType_ALSA());
  20046. #endif
  20047. #if JUCE_LINUX && JUCE_JACK
  20048. list.add (juce_createAudioIODeviceType_JACK());
  20049. #endif
  20050. }
  20051. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20052. const int numOutputChannelsNeeded,
  20053. const XmlElement* const e,
  20054. const bool selectDefaultDeviceOnFailure,
  20055. const String& preferredDefaultDeviceName,
  20056. const AudioDeviceSetup* preferredSetupOptions)
  20057. {
  20058. scanDevicesIfNeeded();
  20059. numInputChansNeeded = numInputChannelsNeeded;
  20060. numOutputChansNeeded = numOutputChannelsNeeded;
  20061. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20062. {
  20063. lastExplicitSettings = new XmlElement (*e);
  20064. String error;
  20065. AudioDeviceSetup setup;
  20066. if (preferredSetupOptions != 0)
  20067. setup = *preferredSetupOptions;
  20068. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20069. {
  20070. setup.inputDeviceName = setup.outputDeviceName
  20071. = e->getStringAttribute ("audioDeviceName");
  20072. }
  20073. else
  20074. {
  20075. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20076. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20077. }
  20078. currentDeviceType = e->getStringAttribute ("deviceType");
  20079. if (currentDeviceType.isEmpty())
  20080. {
  20081. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20082. if (type != 0)
  20083. currentDeviceType = type->getTypeName();
  20084. else if (availableDeviceTypes.size() > 0)
  20085. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20086. }
  20087. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20088. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20089. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20090. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20091. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20092. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20093. error = setAudioDeviceSetup (setup, true);
  20094. midiInsFromXml.clear();
  20095. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20096. midiInsFromXml.add (c->getStringAttribute ("name"));
  20097. const StringArray allMidiIns (MidiInput::getDevices());
  20098. for (int i = allMidiIns.size(); --i >= 0;)
  20099. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20100. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20101. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20102. false, preferredDefaultDeviceName);
  20103. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20104. return error;
  20105. }
  20106. else
  20107. {
  20108. AudioDeviceSetup setup;
  20109. if (preferredSetupOptions != 0)
  20110. {
  20111. setup = *preferredSetupOptions;
  20112. }
  20113. else if (preferredDefaultDeviceName.isNotEmpty())
  20114. {
  20115. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20116. {
  20117. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20118. StringArray outs (type->getDeviceNames (false));
  20119. int i;
  20120. for (i = 0; i < outs.size(); ++i)
  20121. {
  20122. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20123. {
  20124. setup.outputDeviceName = outs[i];
  20125. break;
  20126. }
  20127. }
  20128. StringArray ins (type->getDeviceNames (true));
  20129. for (i = 0; i < ins.size(); ++i)
  20130. {
  20131. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20132. {
  20133. setup.inputDeviceName = ins[i];
  20134. break;
  20135. }
  20136. }
  20137. }
  20138. }
  20139. insertDefaultDeviceNames (setup);
  20140. return setAudioDeviceSetup (setup, false);
  20141. }
  20142. }
  20143. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20144. {
  20145. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20146. if (type != 0)
  20147. {
  20148. if (setup.outputDeviceName.isEmpty())
  20149. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20150. if (setup.inputDeviceName.isEmpty())
  20151. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20152. }
  20153. }
  20154. XmlElement* AudioDeviceManager::createStateXml() const
  20155. {
  20156. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20157. }
  20158. void AudioDeviceManager::scanDevicesIfNeeded()
  20159. {
  20160. if (listNeedsScanning)
  20161. {
  20162. listNeedsScanning = false;
  20163. createDeviceTypesIfNeeded();
  20164. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20165. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20166. }
  20167. }
  20168. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20169. {
  20170. scanDevicesIfNeeded();
  20171. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20172. {
  20173. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20174. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20175. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20176. {
  20177. return type;
  20178. }
  20179. }
  20180. return 0;
  20181. }
  20182. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20183. {
  20184. setup = currentSetup;
  20185. }
  20186. void AudioDeviceManager::deleteCurrentDevice()
  20187. {
  20188. currentAudioDevice = 0;
  20189. currentSetup.inputDeviceName = String::empty;
  20190. currentSetup.outputDeviceName = String::empty;
  20191. }
  20192. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20193. const bool treatAsChosenDevice)
  20194. {
  20195. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20196. {
  20197. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20198. && currentDeviceType != type)
  20199. {
  20200. currentDeviceType = type;
  20201. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20202. insertDefaultDeviceNames (s);
  20203. setAudioDeviceSetup (s, treatAsChosenDevice);
  20204. sendChangeMessage();
  20205. break;
  20206. }
  20207. }
  20208. }
  20209. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20210. {
  20211. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20212. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20213. return availableDeviceTypes[i];
  20214. return availableDeviceTypes[0];
  20215. }
  20216. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20217. const bool treatAsChosenDevice)
  20218. {
  20219. jassert (&newSetup != &currentSetup); // this will have no effect
  20220. if (newSetup == currentSetup && currentAudioDevice != 0)
  20221. return String::empty;
  20222. if (! (newSetup == currentSetup))
  20223. sendChangeMessage();
  20224. stopDevice();
  20225. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20226. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20227. String error;
  20228. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20229. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20230. {
  20231. deleteCurrentDevice();
  20232. if (treatAsChosenDevice)
  20233. updateXml();
  20234. return String::empty;
  20235. }
  20236. if (currentSetup.inputDeviceName != newInputDeviceName
  20237. || currentSetup.outputDeviceName != newOutputDeviceName
  20238. || currentAudioDevice == 0)
  20239. {
  20240. deleteCurrentDevice();
  20241. scanDevicesIfNeeded();
  20242. if (newOutputDeviceName.isNotEmpty()
  20243. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20244. {
  20245. return "No such device: " + newOutputDeviceName;
  20246. }
  20247. if (newInputDeviceName.isNotEmpty()
  20248. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20249. {
  20250. return "No such device: " + newInputDeviceName;
  20251. }
  20252. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20253. if (currentAudioDevice == 0)
  20254. 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!";
  20255. else
  20256. error = currentAudioDevice->getLastError();
  20257. if (error.isNotEmpty())
  20258. {
  20259. deleteCurrentDevice();
  20260. return error;
  20261. }
  20262. if (newSetup.useDefaultInputChannels)
  20263. {
  20264. inputChannels.clear();
  20265. inputChannels.setRange (0, numInputChansNeeded, true);
  20266. }
  20267. if (newSetup.useDefaultOutputChannels)
  20268. {
  20269. outputChannels.clear();
  20270. outputChannels.setRange (0, numOutputChansNeeded, true);
  20271. }
  20272. if (newInputDeviceName.isEmpty())
  20273. inputChannels.clear();
  20274. if (newOutputDeviceName.isEmpty())
  20275. outputChannels.clear();
  20276. }
  20277. if (! newSetup.useDefaultInputChannels)
  20278. inputChannels = newSetup.inputChannels;
  20279. if (! newSetup.useDefaultOutputChannels)
  20280. outputChannels = newSetup.outputChannels;
  20281. currentSetup = newSetup;
  20282. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20283. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20284. error = currentAudioDevice->open (inputChannels,
  20285. outputChannels,
  20286. currentSetup.sampleRate,
  20287. currentSetup.bufferSize);
  20288. if (error.isEmpty())
  20289. {
  20290. currentDeviceType = currentAudioDevice->getTypeName();
  20291. currentAudioDevice->start (&callbackHandler);
  20292. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20293. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20294. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20295. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20296. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20297. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20298. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20299. if (treatAsChosenDevice)
  20300. updateXml();
  20301. }
  20302. else
  20303. {
  20304. deleteCurrentDevice();
  20305. }
  20306. return error;
  20307. }
  20308. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20309. {
  20310. jassert (currentAudioDevice != 0);
  20311. if (rate > 0)
  20312. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20313. if (currentAudioDevice->getSampleRate (i) == rate)
  20314. return rate;
  20315. double lowestAbove44 = 0.0;
  20316. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20317. {
  20318. const double sr = currentAudioDevice->getSampleRate (i);
  20319. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20320. lowestAbove44 = sr;
  20321. }
  20322. if (lowestAbove44 > 0.0)
  20323. return lowestAbove44;
  20324. return currentAudioDevice->getSampleRate (0);
  20325. }
  20326. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20327. {
  20328. jassert (currentAudioDevice != 0);
  20329. if (bufferSize > 0)
  20330. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20331. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20332. return bufferSize;
  20333. return currentAudioDevice->getDefaultBufferSize();
  20334. }
  20335. void AudioDeviceManager::stopDevice()
  20336. {
  20337. if (currentAudioDevice != 0)
  20338. currentAudioDevice->stop();
  20339. testSound = 0;
  20340. }
  20341. void AudioDeviceManager::closeAudioDevice()
  20342. {
  20343. stopDevice();
  20344. currentAudioDevice = 0;
  20345. }
  20346. void AudioDeviceManager::restartLastAudioDevice()
  20347. {
  20348. if (currentAudioDevice == 0)
  20349. {
  20350. if (currentSetup.inputDeviceName.isEmpty()
  20351. && currentSetup.outputDeviceName.isEmpty())
  20352. {
  20353. // This method will only reload the last device that was running
  20354. // before closeAudioDevice() was called - you need to actually open
  20355. // one first, with setAudioDevice().
  20356. jassertfalse;
  20357. return;
  20358. }
  20359. AudioDeviceSetup s (currentSetup);
  20360. setAudioDeviceSetup (s, false);
  20361. }
  20362. }
  20363. void AudioDeviceManager::updateXml()
  20364. {
  20365. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20366. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20367. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20368. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20369. if (currentAudioDevice != 0)
  20370. {
  20371. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20372. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20373. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20374. if (! currentSetup.useDefaultInputChannels)
  20375. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20376. if (! currentSetup.useDefaultOutputChannels)
  20377. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20378. }
  20379. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20380. {
  20381. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20382. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20383. }
  20384. if (midiInsFromXml.size() > 0)
  20385. {
  20386. // Add any midi devices that have been enabled before, but which aren't currently
  20387. // open because the device has been disconnected.
  20388. const StringArray availableMidiDevices (MidiInput::getDevices());
  20389. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20390. {
  20391. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20392. {
  20393. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20394. m->setAttribute ("name", midiInsFromXml[i]);
  20395. }
  20396. }
  20397. }
  20398. if (defaultMidiOutputName.isNotEmpty())
  20399. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20400. }
  20401. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20402. {
  20403. {
  20404. const ScopedLock sl (audioCallbackLock);
  20405. if (callbacks.contains (newCallback))
  20406. return;
  20407. }
  20408. if (currentAudioDevice != 0 && newCallback != 0)
  20409. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20410. const ScopedLock sl (audioCallbackLock);
  20411. callbacks.add (newCallback);
  20412. }
  20413. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20414. {
  20415. if (callbackToRemove != 0)
  20416. {
  20417. bool needsDeinitialising = currentAudioDevice != 0;
  20418. {
  20419. const ScopedLock sl (audioCallbackLock);
  20420. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20421. callbacks.removeValue (callbackToRemove);
  20422. }
  20423. if (needsDeinitialising)
  20424. callbackToRemove->audioDeviceStopped();
  20425. }
  20426. }
  20427. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20428. int numInputChannels,
  20429. float** outputChannelData,
  20430. int numOutputChannels,
  20431. int numSamples)
  20432. {
  20433. const ScopedLock sl (audioCallbackLock);
  20434. if (inputLevelMeasurementEnabledCount > 0)
  20435. {
  20436. for (int j = 0; j < numSamples; ++j)
  20437. {
  20438. float s = 0;
  20439. for (int i = 0; i < numInputChannels; ++i)
  20440. s += std::abs (inputChannelData[i][j]);
  20441. s /= numInputChannels;
  20442. const double decayFactor = 0.99992;
  20443. if (s > inputLevel)
  20444. inputLevel = s;
  20445. else if (inputLevel > 0.001f)
  20446. inputLevel *= decayFactor;
  20447. else
  20448. inputLevel = 0;
  20449. }
  20450. }
  20451. if (callbacks.size() > 0)
  20452. {
  20453. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20454. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20455. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20456. outputChannelData, numOutputChannels, numSamples);
  20457. float** const tempChans = tempBuffer.getArrayOfChannels();
  20458. for (int i = callbacks.size(); --i > 0;)
  20459. {
  20460. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20461. tempChans, numOutputChannels, numSamples);
  20462. for (int chan = 0; chan < numOutputChannels; ++chan)
  20463. {
  20464. const float* const src = tempChans [chan];
  20465. float* const dst = outputChannelData [chan];
  20466. if (src != 0 && dst != 0)
  20467. for (int j = 0; j < numSamples; ++j)
  20468. dst[j] += src[j];
  20469. }
  20470. }
  20471. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20472. const double filterAmount = 0.2;
  20473. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20474. }
  20475. else
  20476. {
  20477. for (int i = 0; i < numOutputChannels; ++i)
  20478. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20479. }
  20480. if (testSound != 0)
  20481. {
  20482. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20483. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20484. for (int i = 0; i < numOutputChannels; ++i)
  20485. for (int j = 0; j < numSamps; ++j)
  20486. outputChannelData [i][j] += src[j];
  20487. testSoundPosition += numSamps;
  20488. if (testSoundPosition >= testSound->getNumSamples())
  20489. testSound = 0;
  20490. }
  20491. }
  20492. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20493. {
  20494. cpuUsageMs = 0;
  20495. const double sampleRate = device->getCurrentSampleRate();
  20496. const int blockSize = device->getCurrentBufferSizeSamples();
  20497. if (sampleRate > 0.0 && blockSize > 0)
  20498. {
  20499. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20500. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20501. }
  20502. {
  20503. const ScopedLock sl (audioCallbackLock);
  20504. for (int i = callbacks.size(); --i >= 0;)
  20505. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20506. }
  20507. sendChangeMessage();
  20508. }
  20509. void AudioDeviceManager::audioDeviceStoppedInt()
  20510. {
  20511. cpuUsageMs = 0;
  20512. timeToCpuScale = 0;
  20513. sendChangeMessage();
  20514. const ScopedLock sl (audioCallbackLock);
  20515. for (int i = callbacks.size(); --i >= 0;)
  20516. callbacks.getUnchecked(i)->audioDeviceStopped();
  20517. }
  20518. double AudioDeviceManager::getCpuUsage() const
  20519. {
  20520. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20521. }
  20522. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20523. const bool enabled)
  20524. {
  20525. if (enabled != isMidiInputEnabled (name))
  20526. {
  20527. if (enabled)
  20528. {
  20529. const int index = MidiInput::getDevices().indexOf (name);
  20530. if (index >= 0)
  20531. {
  20532. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20533. if (min != 0)
  20534. {
  20535. enabledMidiInputs.add (min);
  20536. min->start();
  20537. }
  20538. }
  20539. }
  20540. else
  20541. {
  20542. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20543. if (enabledMidiInputs[i]->getName() == name)
  20544. enabledMidiInputs.remove (i);
  20545. }
  20546. updateXml();
  20547. sendChangeMessage();
  20548. }
  20549. }
  20550. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20551. {
  20552. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20553. if (enabledMidiInputs[i]->getName() == name)
  20554. return true;
  20555. return false;
  20556. }
  20557. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20558. MidiInputCallback* callbackToAdd)
  20559. {
  20560. removeMidiInputCallback (name, callbackToAdd);
  20561. if (name.isEmpty())
  20562. {
  20563. midiCallbacks.add (callbackToAdd);
  20564. midiCallbackDevices.add (String::empty);
  20565. }
  20566. else
  20567. {
  20568. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20569. {
  20570. if (enabledMidiInputs[i]->getName() == name)
  20571. {
  20572. const ScopedLock sl (midiCallbackLock);
  20573. midiCallbacks.add (callbackToAdd);
  20574. midiCallbackDevices.add (enabledMidiInputs[i]->getName());
  20575. break;
  20576. }
  20577. }
  20578. }
  20579. }
  20580. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* /*callback*/)
  20581. {
  20582. const ScopedLock sl (midiCallbackLock);
  20583. for (int i = midiCallbacks.size(); --i >= 0;)
  20584. {
  20585. if (midiCallbackDevices[i] == name)
  20586. {
  20587. midiCallbacks.remove (i);
  20588. midiCallbackDevices.remove (i);
  20589. }
  20590. }
  20591. }
  20592. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20593. const MidiMessage& message)
  20594. {
  20595. if (! message.isActiveSense())
  20596. {
  20597. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20598. const ScopedLock sl (midiCallbackLock);
  20599. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20600. {
  20601. const String name (midiCallbackDevices[i]);
  20602. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20603. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20604. }
  20605. }
  20606. }
  20607. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20608. {
  20609. if (defaultMidiOutputName != deviceName)
  20610. {
  20611. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20612. {
  20613. const ScopedLock sl (audioCallbackLock);
  20614. oldCallbacks = callbacks;
  20615. callbacks.clear();
  20616. }
  20617. if (currentAudioDevice != 0)
  20618. for (int i = oldCallbacks.size(); --i >= 0;)
  20619. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20620. defaultMidiOutput = 0;
  20621. defaultMidiOutputName = deviceName;
  20622. if (deviceName.isNotEmpty())
  20623. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20624. if (currentAudioDevice != 0)
  20625. for (int i = oldCallbacks.size(); --i >= 0;)
  20626. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20627. {
  20628. const ScopedLock sl (audioCallbackLock);
  20629. callbacks = oldCallbacks;
  20630. }
  20631. updateXml();
  20632. sendChangeMessage();
  20633. }
  20634. }
  20635. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20636. int numInputChannels,
  20637. float** outputChannelData,
  20638. int numOutputChannels,
  20639. int numSamples)
  20640. {
  20641. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20642. }
  20643. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20644. {
  20645. owner->audioDeviceAboutToStartInt (device);
  20646. }
  20647. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20648. {
  20649. owner->audioDeviceStoppedInt();
  20650. }
  20651. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20652. {
  20653. owner->handleIncomingMidiMessageInt (source, message);
  20654. }
  20655. void AudioDeviceManager::playTestSound()
  20656. {
  20657. { // cunningly nested to swap, unlock and delete in that order.
  20658. ScopedPointer <AudioSampleBuffer> oldSound;
  20659. {
  20660. const ScopedLock sl (audioCallbackLock);
  20661. oldSound = testSound;
  20662. }
  20663. }
  20664. testSoundPosition = 0;
  20665. if (currentAudioDevice != 0)
  20666. {
  20667. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20668. const int soundLength = (int) sampleRate;
  20669. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20670. float* samples = newSound->getSampleData (0);
  20671. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20672. const float amplitude = 0.5f;
  20673. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20674. for (int i = 0; i < soundLength; ++i)
  20675. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20676. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20677. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20678. const ScopedLock sl (audioCallbackLock);
  20679. testSound = newSound;
  20680. }
  20681. }
  20682. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20683. {
  20684. const ScopedLock sl (audioCallbackLock);
  20685. if (enableMeasurement)
  20686. ++inputLevelMeasurementEnabledCount;
  20687. else
  20688. --inputLevelMeasurementEnabledCount;
  20689. inputLevel = 0;
  20690. }
  20691. double AudioDeviceManager::getCurrentInputLevel() const
  20692. {
  20693. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20694. return inputLevel;
  20695. }
  20696. END_JUCE_NAMESPACE
  20697. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20698. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20699. BEGIN_JUCE_NAMESPACE
  20700. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20701. : name (deviceName),
  20702. typeName (typeName_)
  20703. {
  20704. }
  20705. AudioIODevice::~AudioIODevice()
  20706. {
  20707. }
  20708. bool AudioIODevice::hasControlPanel() const
  20709. {
  20710. return false;
  20711. }
  20712. bool AudioIODevice::showControlPanel()
  20713. {
  20714. jassertfalse; // this should only be called for devices which return true from
  20715. // their hasControlPanel() method.
  20716. return false;
  20717. }
  20718. END_JUCE_NAMESPACE
  20719. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20720. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20721. BEGIN_JUCE_NAMESPACE
  20722. AudioIODeviceType::AudioIODeviceType (const String& name)
  20723. : typeName (name)
  20724. {
  20725. }
  20726. AudioIODeviceType::~AudioIODeviceType()
  20727. {
  20728. }
  20729. END_JUCE_NAMESPACE
  20730. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20731. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20732. BEGIN_JUCE_NAMESPACE
  20733. MidiOutput::MidiOutput()
  20734. : Thread ("midi out"),
  20735. internal (0),
  20736. firstMessage (0)
  20737. {
  20738. }
  20739. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20740. const double sampleNumber)
  20741. : message (data, len, sampleNumber)
  20742. {
  20743. }
  20744. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20745. const double millisecondCounterToStartAt,
  20746. double samplesPerSecondForBuffer)
  20747. {
  20748. // You've got to call startBackgroundThread() for this to actually work..
  20749. jassert (isThreadRunning());
  20750. // this needs to be a value in the future - RTFM for this method!
  20751. jassert (millisecondCounterToStartAt > 0);
  20752. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20753. MidiBuffer::Iterator i (buffer);
  20754. const uint8* data;
  20755. int len, time;
  20756. while (i.getNextEvent (data, len, time))
  20757. {
  20758. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20759. PendingMessage* const m
  20760. = new PendingMessage (data, len, eventTime);
  20761. const ScopedLock sl (lock);
  20762. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20763. {
  20764. m->next = firstMessage;
  20765. firstMessage = m;
  20766. }
  20767. else
  20768. {
  20769. PendingMessage* mm = firstMessage;
  20770. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20771. mm = mm->next;
  20772. m->next = mm->next;
  20773. mm->next = m;
  20774. }
  20775. }
  20776. notify();
  20777. }
  20778. void MidiOutput::clearAllPendingMessages()
  20779. {
  20780. const ScopedLock sl (lock);
  20781. while (firstMessage != 0)
  20782. {
  20783. PendingMessage* const m = firstMessage;
  20784. firstMessage = firstMessage->next;
  20785. delete m;
  20786. }
  20787. }
  20788. void MidiOutput::startBackgroundThread()
  20789. {
  20790. startThread (9);
  20791. }
  20792. void MidiOutput::stopBackgroundThread()
  20793. {
  20794. stopThread (5000);
  20795. }
  20796. void MidiOutput::run()
  20797. {
  20798. while (! threadShouldExit())
  20799. {
  20800. uint32 now = Time::getMillisecondCounter();
  20801. uint32 eventTime = 0;
  20802. uint32 timeToWait = 500;
  20803. PendingMessage* message;
  20804. {
  20805. const ScopedLock sl (lock);
  20806. message = firstMessage;
  20807. if (message != 0)
  20808. {
  20809. eventTime = roundToInt (message->message.getTimeStamp());
  20810. if (eventTime > now + 20)
  20811. {
  20812. timeToWait = eventTime - (now + 20);
  20813. message = 0;
  20814. }
  20815. else
  20816. {
  20817. firstMessage = message->next;
  20818. }
  20819. }
  20820. }
  20821. if (message != 0)
  20822. {
  20823. if (eventTime > now)
  20824. {
  20825. Time::waitForMillisecondCounter (eventTime);
  20826. if (threadShouldExit())
  20827. break;
  20828. }
  20829. if (eventTime > now - 200)
  20830. sendMessageNow (message->message);
  20831. delete message;
  20832. }
  20833. else
  20834. {
  20835. jassert (timeToWait < 1000 * 30);
  20836. wait (timeToWait);
  20837. }
  20838. }
  20839. clearAllPendingMessages();
  20840. }
  20841. END_JUCE_NAMESPACE
  20842. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20843. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20844. BEGIN_JUCE_NAMESPACE
  20845. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20846. {
  20847. const double maxVal = (double) 0x7fff;
  20848. char* intData = static_cast <char*> (dest);
  20849. if (dest != (void*) source || destBytesPerSample <= 4)
  20850. {
  20851. for (int i = 0; i < numSamples; ++i)
  20852. {
  20853. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20854. intData += destBytesPerSample;
  20855. }
  20856. }
  20857. else
  20858. {
  20859. intData += destBytesPerSample * numSamples;
  20860. for (int i = numSamples; --i >= 0;)
  20861. {
  20862. intData -= destBytesPerSample;
  20863. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20864. }
  20865. }
  20866. }
  20867. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20868. {
  20869. const double maxVal = (double) 0x7fff;
  20870. char* intData = static_cast <char*> (dest);
  20871. if (dest != (void*) source || destBytesPerSample <= 4)
  20872. {
  20873. for (int i = 0; i < numSamples; ++i)
  20874. {
  20875. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20876. intData += destBytesPerSample;
  20877. }
  20878. }
  20879. else
  20880. {
  20881. intData += destBytesPerSample * numSamples;
  20882. for (int i = numSamples; --i >= 0;)
  20883. {
  20884. intData -= destBytesPerSample;
  20885. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20886. }
  20887. }
  20888. }
  20889. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20890. {
  20891. const double maxVal = (double) 0x7fffff;
  20892. char* intData = static_cast <char*> (dest);
  20893. if (dest != (void*) source || destBytesPerSample <= 4)
  20894. {
  20895. for (int i = 0; i < numSamples; ++i)
  20896. {
  20897. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20898. intData += destBytesPerSample;
  20899. }
  20900. }
  20901. else
  20902. {
  20903. intData += destBytesPerSample * numSamples;
  20904. for (int i = numSamples; --i >= 0;)
  20905. {
  20906. intData -= destBytesPerSample;
  20907. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20908. }
  20909. }
  20910. }
  20911. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20912. {
  20913. const double maxVal = (double) 0x7fffff;
  20914. char* intData = static_cast <char*> (dest);
  20915. if (dest != (void*) source || destBytesPerSample <= 4)
  20916. {
  20917. for (int i = 0; i < numSamples; ++i)
  20918. {
  20919. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20920. intData += destBytesPerSample;
  20921. }
  20922. }
  20923. else
  20924. {
  20925. intData += destBytesPerSample * numSamples;
  20926. for (int i = numSamples; --i >= 0;)
  20927. {
  20928. intData -= destBytesPerSample;
  20929. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20930. }
  20931. }
  20932. }
  20933. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20934. {
  20935. const double maxVal = (double) 0x7fffffff;
  20936. char* intData = static_cast <char*> (dest);
  20937. if (dest != (void*) source || destBytesPerSample <= 4)
  20938. {
  20939. for (int i = 0; i < numSamples; ++i)
  20940. {
  20941. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20942. intData += destBytesPerSample;
  20943. }
  20944. }
  20945. else
  20946. {
  20947. intData += destBytesPerSample * numSamples;
  20948. for (int i = numSamples; --i >= 0;)
  20949. {
  20950. intData -= destBytesPerSample;
  20951. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20952. }
  20953. }
  20954. }
  20955. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20956. {
  20957. const double maxVal = (double) 0x7fffffff;
  20958. char* intData = static_cast <char*> (dest);
  20959. if (dest != (void*) source || destBytesPerSample <= 4)
  20960. {
  20961. for (int i = 0; i < numSamples; ++i)
  20962. {
  20963. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20964. intData += destBytesPerSample;
  20965. }
  20966. }
  20967. else
  20968. {
  20969. intData += destBytesPerSample * numSamples;
  20970. for (int i = numSamples; --i >= 0;)
  20971. {
  20972. intData -= destBytesPerSample;
  20973. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20974. }
  20975. }
  20976. }
  20977. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20978. {
  20979. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20980. char* d = static_cast <char*> (dest);
  20981. for (int i = 0; i < numSamples; ++i)
  20982. {
  20983. *(float*) d = source[i];
  20984. #if JUCE_BIG_ENDIAN
  20985. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20986. #endif
  20987. d += destBytesPerSample;
  20988. }
  20989. }
  20990. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20991. {
  20992. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20993. char* d = static_cast <char*> (dest);
  20994. for (int i = 0; i < numSamples; ++i)
  20995. {
  20996. *(float*) d = source[i];
  20997. #if JUCE_LITTLE_ENDIAN
  20998. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20999. #endif
  21000. d += destBytesPerSample;
  21001. }
  21002. }
  21003. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21004. {
  21005. const float scale = 1.0f / 0x7fff;
  21006. const char* intData = static_cast <const char*> (source);
  21007. if (source != (void*) dest || srcBytesPerSample >= 4)
  21008. {
  21009. for (int i = 0; i < numSamples; ++i)
  21010. {
  21011. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21012. intData += srcBytesPerSample;
  21013. }
  21014. }
  21015. else
  21016. {
  21017. intData += srcBytesPerSample * numSamples;
  21018. for (int i = numSamples; --i >= 0;)
  21019. {
  21020. intData -= srcBytesPerSample;
  21021. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21022. }
  21023. }
  21024. }
  21025. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21026. {
  21027. const float scale = 1.0f / 0x7fff;
  21028. const char* intData = static_cast <const char*> (source);
  21029. if (source != (void*) dest || srcBytesPerSample >= 4)
  21030. {
  21031. for (int i = 0; i < numSamples; ++i)
  21032. {
  21033. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21034. intData += srcBytesPerSample;
  21035. }
  21036. }
  21037. else
  21038. {
  21039. intData += srcBytesPerSample * numSamples;
  21040. for (int i = numSamples; --i >= 0;)
  21041. {
  21042. intData -= srcBytesPerSample;
  21043. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21044. }
  21045. }
  21046. }
  21047. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21048. {
  21049. const float scale = 1.0f / 0x7fffff;
  21050. const char* intData = static_cast <const char*> (source);
  21051. if (source != (void*) dest || srcBytesPerSample >= 4)
  21052. {
  21053. for (int i = 0; i < numSamples; ++i)
  21054. {
  21055. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21056. intData += srcBytesPerSample;
  21057. }
  21058. }
  21059. else
  21060. {
  21061. intData += srcBytesPerSample * numSamples;
  21062. for (int i = numSamples; --i >= 0;)
  21063. {
  21064. intData -= srcBytesPerSample;
  21065. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21066. }
  21067. }
  21068. }
  21069. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21070. {
  21071. const float scale = 1.0f / 0x7fffff;
  21072. const char* intData = static_cast <const char*> (source);
  21073. if (source != (void*) dest || srcBytesPerSample >= 4)
  21074. {
  21075. for (int i = 0; i < numSamples; ++i)
  21076. {
  21077. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21078. intData += srcBytesPerSample;
  21079. }
  21080. }
  21081. else
  21082. {
  21083. intData += srcBytesPerSample * numSamples;
  21084. for (int i = numSamples; --i >= 0;)
  21085. {
  21086. intData -= srcBytesPerSample;
  21087. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21088. }
  21089. }
  21090. }
  21091. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21092. {
  21093. const float scale = 1.0f / 0x7fffffff;
  21094. const char* intData = static_cast <const char*> (source);
  21095. if (source != (void*) dest || srcBytesPerSample >= 4)
  21096. {
  21097. for (int i = 0; i < numSamples; ++i)
  21098. {
  21099. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21100. intData += srcBytesPerSample;
  21101. }
  21102. }
  21103. else
  21104. {
  21105. intData += srcBytesPerSample * numSamples;
  21106. for (int i = numSamples; --i >= 0;)
  21107. {
  21108. intData -= srcBytesPerSample;
  21109. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21110. }
  21111. }
  21112. }
  21113. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21114. {
  21115. const float scale = 1.0f / 0x7fffffff;
  21116. const char* intData = static_cast <const char*> (source);
  21117. if (source != (void*) dest || srcBytesPerSample >= 4)
  21118. {
  21119. for (int i = 0; i < numSamples; ++i)
  21120. {
  21121. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21122. intData += srcBytesPerSample;
  21123. }
  21124. }
  21125. else
  21126. {
  21127. intData += srcBytesPerSample * numSamples;
  21128. for (int i = numSamples; --i >= 0;)
  21129. {
  21130. intData -= srcBytesPerSample;
  21131. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21132. }
  21133. }
  21134. }
  21135. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21136. {
  21137. const char* s = static_cast <const char*> (source);
  21138. for (int i = 0; i < numSamples; ++i)
  21139. {
  21140. dest[i] = *(float*)s;
  21141. #if JUCE_BIG_ENDIAN
  21142. uint32* const d = (uint32*) (dest + i);
  21143. *d = ByteOrder::swap (*d);
  21144. #endif
  21145. s += srcBytesPerSample;
  21146. }
  21147. }
  21148. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21149. {
  21150. const char* s = static_cast <const char*> (source);
  21151. for (int i = 0; i < numSamples; ++i)
  21152. {
  21153. dest[i] = *(float*)s;
  21154. #if JUCE_LITTLE_ENDIAN
  21155. uint32* const d = (uint32*) (dest + i);
  21156. *d = ByteOrder::swap (*d);
  21157. #endif
  21158. s += srcBytesPerSample;
  21159. }
  21160. }
  21161. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21162. const float* const source,
  21163. void* const dest,
  21164. const int numSamples)
  21165. {
  21166. switch (destFormat)
  21167. {
  21168. case int16LE:
  21169. convertFloatToInt16LE (source, dest, numSamples);
  21170. break;
  21171. case int16BE:
  21172. convertFloatToInt16BE (source, dest, numSamples);
  21173. break;
  21174. case int24LE:
  21175. convertFloatToInt24LE (source, dest, numSamples);
  21176. break;
  21177. case int24BE:
  21178. convertFloatToInt24BE (source, dest, numSamples);
  21179. break;
  21180. case int32LE:
  21181. convertFloatToInt32LE (source, dest, numSamples);
  21182. break;
  21183. case int32BE:
  21184. convertFloatToInt32BE (source, dest, numSamples);
  21185. break;
  21186. case float32LE:
  21187. convertFloatToFloat32LE (source, dest, numSamples);
  21188. break;
  21189. case float32BE:
  21190. convertFloatToFloat32BE (source, dest, numSamples);
  21191. break;
  21192. default:
  21193. jassertfalse;
  21194. break;
  21195. }
  21196. }
  21197. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21198. const void* const source,
  21199. float* const dest,
  21200. const int numSamples)
  21201. {
  21202. switch (sourceFormat)
  21203. {
  21204. case int16LE:
  21205. convertInt16LEToFloat (source, dest, numSamples);
  21206. break;
  21207. case int16BE:
  21208. convertInt16BEToFloat (source, dest, numSamples);
  21209. break;
  21210. case int24LE:
  21211. convertInt24LEToFloat (source, dest, numSamples);
  21212. break;
  21213. case int24BE:
  21214. convertInt24BEToFloat (source, dest, numSamples);
  21215. break;
  21216. case int32LE:
  21217. convertInt32LEToFloat (source, dest, numSamples);
  21218. break;
  21219. case int32BE:
  21220. convertInt32BEToFloat (source, dest, numSamples);
  21221. break;
  21222. case float32LE:
  21223. convertFloat32LEToFloat (source, dest, numSamples);
  21224. break;
  21225. case float32BE:
  21226. convertFloat32BEToFloat (source, dest, numSamples);
  21227. break;
  21228. default:
  21229. jassertfalse;
  21230. break;
  21231. }
  21232. }
  21233. void AudioDataConverters::interleaveSamples (const float** const source,
  21234. float* const dest,
  21235. const int numSamples,
  21236. const int numChannels)
  21237. {
  21238. for (int chan = 0; chan < numChannels; ++chan)
  21239. {
  21240. int i = chan;
  21241. const float* src = source [chan];
  21242. for (int j = 0; j < numSamples; ++j)
  21243. {
  21244. dest [i] = src [j];
  21245. i += numChannels;
  21246. }
  21247. }
  21248. }
  21249. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21250. float** const dest,
  21251. const int numSamples,
  21252. const int numChannels)
  21253. {
  21254. for (int chan = 0; chan < numChannels; ++chan)
  21255. {
  21256. int i = chan;
  21257. float* dst = dest [chan];
  21258. for (int j = 0; j < numSamples; ++j)
  21259. {
  21260. dst [j] = source [i];
  21261. i += numChannels;
  21262. }
  21263. }
  21264. }
  21265. #if JUCE_UNIT_TESTS
  21266. class AudioConversionTests : public UnitTest
  21267. {
  21268. public:
  21269. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21270. template <class F1, class E1, class F2, class E2>
  21271. struct Test5
  21272. {
  21273. static void test (UnitTest& unitTest)
  21274. {
  21275. test (unitTest, false);
  21276. test (unitTest, true);
  21277. }
  21278. static void test (UnitTest& unitTest, bool inPlace)
  21279. {
  21280. const int numSamples = 2048;
  21281. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21282. {
  21283. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21284. bool clippingFailed = false;
  21285. for (int i = 0; i < numSamples / 2; ++i)
  21286. {
  21287. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21288. if (! d.isFloatingPoint())
  21289. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21290. ++d;
  21291. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21292. ++d;
  21293. }
  21294. unitTest.expect (! clippingFailed);
  21295. }
  21296. // convert data from the source to dest format..
  21297. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21298. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21299. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21300. // ..and back again..
  21301. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21302. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21303. if (! inPlace)
  21304. zerostruct (reversed);
  21305. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21306. {
  21307. int biggestDiff = 0;
  21308. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21309. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21310. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21311. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21312. for (int i = 0; i < numSamples; ++i)
  21313. {
  21314. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21315. ++d1;
  21316. ++d2;
  21317. }
  21318. unitTest.expect (biggestDiff <= errorMargin);
  21319. }
  21320. }
  21321. };
  21322. template <class F1, class E1, class FormatType>
  21323. struct Test3
  21324. {
  21325. static void test (UnitTest& unitTest)
  21326. {
  21327. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21328. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21329. }
  21330. };
  21331. template <class FormatType, class Endianness>
  21332. struct Test2
  21333. {
  21334. static void test (UnitTest& unitTest)
  21335. {
  21336. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21337. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21338. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21339. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21340. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21341. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21342. }
  21343. };
  21344. template <class FormatType>
  21345. struct Test1
  21346. {
  21347. static void test (UnitTest& unitTest)
  21348. {
  21349. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21350. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21351. }
  21352. };
  21353. void runTest()
  21354. {
  21355. beginTest ("Round-trip conversion");
  21356. Test1 <AudioData::Int8>::test (*this);
  21357. Test1 <AudioData::Int16>::test (*this);
  21358. Test1 <AudioData::Int24>::test (*this);
  21359. Test1 <AudioData::Int32>::test (*this);
  21360. Test1 <AudioData::Float32>::test (*this);
  21361. }
  21362. };
  21363. static AudioConversionTests audioConversionUnitTests;
  21364. #endif
  21365. END_JUCE_NAMESPACE
  21366. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21367. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21368. BEGIN_JUCE_NAMESPACE
  21369. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21370. const int numSamples) throw()
  21371. : numChannels (numChannels_),
  21372. size (numSamples)
  21373. {
  21374. jassert (numSamples >= 0);
  21375. jassert (numChannels_ > 0);
  21376. allocateData();
  21377. }
  21378. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21379. : numChannels (other.numChannels),
  21380. size (other.size)
  21381. {
  21382. allocateData();
  21383. const size_t numBytes = size * sizeof (float);
  21384. for (int i = 0; i < numChannels; ++i)
  21385. memcpy (channels[i], other.channels[i], numBytes);
  21386. }
  21387. void AudioSampleBuffer::allocateData()
  21388. {
  21389. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21390. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21391. allocatedData.malloc (allocatedBytes);
  21392. channels = reinterpret_cast <float**> (allocatedData.getData());
  21393. float* chan = (float*) (allocatedData + channelListSize);
  21394. for (int i = 0; i < numChannels; ++i)
  21395. {
  21396. channels[i] = chan;
  21397. chan += size;
  21398. }
  21399. channels [numChannels] = 0;
  21400. }
  21401. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21402. const int numChannels_,
  21403. const int numSamples) throw()
  21404. : numChannels (numChannels_),
  21405. size (numSamples),
  21406. allocatedBytes (0)
  21407. {
  21408. jassert (numChannels_ > 0);
  21409. allocateChannels (dataToReferTo);
  21410. }
  21411. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21412. const int newNumChannels,
  21413. const int newNumSamples) throw()
  21414. {
  21415. jassert (newNumChannels > 0);
  21416. allocatedBytes = 0;
  21417. allocatedData.free();
  21418. numChannels = newNumChannels;
  21419. size = newNumSamples;
  21420. allocateChannels (dataToReferTo);
  21421. }
  21422. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21423. {
  21424. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21425. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21426. {
  21427. channels = static_cast <float**> (preallocatedChannelSpace);
  21428. }
  21429. else
  21430. {
  21431. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21432. channels = reinterpret_cast <float**> (allocatedData.getData());
  21433. }
  21434. for (int i = 0; i < numChannels; ++i)
  21435. {
  21436. // you have to pass in the same number of valid pointers as numChannels
  21437. jassert (dataToReferTo[i] != 0);
  21438. channels[i] = dataToReferTo[i];
  21439. }
  21440. channels [numChannels] = 0;
  21441. }
  21442. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21443. {
  21444. if (this != &other)
  21445. {
  21446. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21447. const size_t numBytes = size * sizeof (float);
  21448. for (int i = 0; i < numChannels; ++i)
  21449. memcpy (channels[i], other.channels[i], numBytes);
  21450. }
  21451. return *this;
  21452. }
  21453. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21454. {
  21455. }
  21456. void AudioSampleBuffer::setSize (const int newNumChannels,
  21457. const int newNumSamples,
  21458. const bool keepExistingContent,
  21459. const bool clearExtraSpace,
  21460. const bool avoidReallocating) throw()
  21461. {
  21462. jassert (newNumChannels > 0);
  21463. if (newNumSamples != size || newNumChannels != numChannels)
  21464. {
  21465. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21466. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21467. if (keepExistingContent)
  21468. {
  21469. HeapBlock <char> newData;
  21470. newData.allocate (newTotalBytes, clearExtraSpace);
  21471. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21472. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21473. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21474. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21475. for (int i = 0; i < numChansToCopy; ++i)
  21476. {
  21477. memcpy (newChan, channels[i], numBytesToCopy);
  21478. newChannels[i] = newChan;
  21479. newChan += newNumSamples;
  21480. }
  21481. allocatedData.swapWith (newData);
  21482. allocatedBytes = (int) newTotalBytes;
  21483. channels = newChannels;
  21484. }
  21485. else
  21486. {
  21487. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21488. {
  21489. if (clearExtraSpace)
  21490. zeromem (allocatedData, newTotalBytes);
  21491. }
  21492. else
  21493. {
  21494. allocatedBytes = newTotalBytes;
  21495. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21496. channels = reinterpret_cast <float**> (allocatedData.getData());
  21497. }
  21498. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21499. for (int i = 0; i < newNumChannels; ++i)
  21500. {
  21501. channels[i] = chan;
  21502. chan += newNumSamples;
  21503. }
  21504. }
  21505. channels [newNumChannels] = 0;
  21506. size = newNumSamples;
  21507. numChannels = newNumChannels;
  21508. }
  21509. }
  21510. void AudioSampleBuffer::clear() throw()
  21511. {
  21512. for (int i = 0; i < numChannels; ++i)
  21513. zeromem (channels[i], size * sizeof (float));
  21514. }
  21515. void AudioSampleBuffer::clear (const int startSample,
  21516. const int numSamples) throw()
  21517. {
  21518. jassert (startSample >= 0 && startSample + numSamples <= size);
  21519. for (int i = 0; i < numChannels; ++i)
  21520. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21521. }
  21522. void AudioSampleBuffer::clear (const int channel,
  21523. const int startSample,
  21524. const int numSamples) throw()
  21525. {
  21526. jassert (isPositiveAndBelow (channel, numChannels));
  21527. jassert (startSample >= 0 && startSample + numSamples <= size);
  21528. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21529. }
  21530. void AudioSampleBuffer::applyGain (const int channel,
  21531. const int startSample,
  21532. int numSamples,
  21533. const float gain) throw()
  21534. {
  21535. jassert (isPositiveAndBelow (channel, numChannels));
  21536. jassert (startSample >= 0 && startSample + numSamples <= size);
  21537. if (gain != 1.0f)
  21538. {
  21539. float* d = channels [channel] + startSample;
  21540. if (gain == 0.0f)
  21541. {
  21542. zeromem (d, sizeof (float) * numSamples);
  21543. }
  21544. else
  21545. {
  21546. while (--numSamples >= 0)
  21547. *d++ *= gain;
  21548. }
  21549. }
  21550. }
  21551. void AudioSampleBuffer::applyGainRamp (const int channel,
  21552. const int startSample,
  21553. int numSamples,
  21554. float startGain,
  21555. float endGain) throw()
  21556. {
  21557. if (startGain == endGain)
  21558. {
  21559. applyGain (channel, startSample, numSamples, startGain);
  21560. }
  21561. else
  21562. {
  21563. jassert (isPositiveAndBelow (channel, numChannels));
  21564. jassert (startSample >= 0 && startSample + numSamples <= size);
  21565. const float increment = (endGain - startGain) / numSamples;
  21566. float* d = channels [channel] + startSample;
  21567. while (--numSamples >= 0)
  21568. {
  21569. *d++ *= startGain;
  21570. startGain += increment;
  21571. }
  21572. }
  21573. }
  21574. void AudioSampleBuffer::applyGain (const int startSample,
  21575. const int numSamples,
  21576. const float gain) throw()
  21577. {
  21578. for (int i = 0; i < numChannels; ++i)
  21579. applyGain (i, startSample, numSamples, gain);
  21580. }
  21581. void AudioSampleBuffer::addFrom (const int destChannel,
  21582. const int destStartSample,
  21583. const AudioSampleBuffer& source,
  21584. const int sourceChannel,
  21585. const int sourceStartSample,
  21586. int numSamples,
  21587. const float gain) throw()
  21588. {
  21589. jassert (&source != this || sourceChannel != destChannel);
  21590. jassert (isPositiveAndBelow (destChannel, numChannels));
  21591. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21592. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21593. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21594. if (gain != 0.0f && numSamples > 0)
  21595. {
  21596. float* d = channels [destChannel] + destStartSample;
  21597. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21598. if (gain != 1.0f)
  21599. {
  21600. while (--numSamples >= 0)
  21601. *d++ += gain * *s++;
  21602. }
  21603. else
  21604. {
  21605. while (--numSamples >= 0)
  21606. *d++ += *s++;
  21607. }
  21608. }
  21609. }
  21610. void AudioSampleBuffer::addFrom (const int destChannel,
  21611. const int destStartSample,
  21612. const float* source,
  21613. int numSamples,
  21614. const float gain) throw()
  21615. {
  21616. jassert (isPositiveAndBelow (destChannel, numChannels));
  21617. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21618. jassert (source != 0);
  21619. if (gain != 0.0f && numSamples > 0)
  21620. {
  21621. float* d = channels [destChannel] + destStartSample;
  21622. if (gain != 1.0f)
  21623. {
  21624. while (--numSamples >= 0)
  21625. *d++ += gain * *source++;
  21626. }
  21627. else
  21628. {
  21629. while (--numSamples >= 0)
  21630. *d++ += *source++;
  21631. }
  21632. }
  21633. }
  21634. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21635. const int destStartSample,
  21636. const float* source,
  21637. int numSamples,
  21638. float startGain,
  21639. const float endGain) throw()
  21640. {
  21641. jassert (isPositiveAndBelow (destChannel, numChannels));
  21642. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21643. jassert (source != 0);
  21644. if (startGain == endGain)
  21645. {
  21646. addFrom (destChannel,
  21647. destStartSample,
  21648. source,
  21649. numSamples,
  21650. startGain);
  21651. }
  21652. else
  21653. {
  21654. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21655. {
  21656. const float increment = (endGain - startGain) / numSamples;
  21657. float* d = channels [destChannel] + destStartSample;
  21658. while (--numSamples >= 0)
  21659. {
  21660. *d++ += startGain * *source++;
  21661. startGain += increment;
  21662. }
  21663. }
  21664. }
  21665. }
  21666. void AudioSampleBuffer::copyFrom (const int destChannel,
  21667. const int destStartSample,
  21668. const AudioSampleBuffer& source,
  21669. const int sourceChannel,
  21670. const int sourceStartSample,
  21671. int numSamples) throw()
  21672. {
  21673. jassert (&source != this || sourceChannel != destChannel);
  21674. jassert (isPositiveAndBelow (destChannel, numChannels));
  21675. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21676. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21677. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21678. if (numSamples > 0)
  21679. {
  21680. memcpy (channels [destChannel] + destStartSample,
  21681. source.channels [sourceChannel] + sourceStartSample,
  21682. sizeof (float) * numSamples);
  21683. }
  21684. }
  21685. void AudioSampleBuffer::copyFrom (const int destChannel,
  21686. const int destStartSample,
  21687. const float* source,
  21688. int numSamples) throw()
  21689. {
  21690. jassert (isPositiveAndBelow (destChannel, numChannels));
  21691. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21692. jassert (source != 0);
  21693. if (numSamples > 0)
  21694. {
  21695. memcpy (channels [destChannel] + destStartSample,
  21696. source,
  21697. sizeof (float) * numSamples);
  21698. }
  21699. }
  21700. void AudioSampleBuffer::copyFrom (const int destChannel,
  21701. const int destStartSample,
  21702. const float* source,
  21703. int numSamples,
  21704. const float gain) throw()
  21705. {
  21706. jassert (isPositiveAndBelow (destChannel, numChannels));
  21707. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21708. jassert (source != 0);
  21709. if (numSamples > 0)
  21710. {
  21711. float* d = channels [destChannel] + destStartSample;
  21712. if (gain != 1.0f)
  21713. {
  21714. if (gain == 0)
  21715. {
  21716. zeromem (d, sizeof (float) * numSamples);
  21717. }
  21718. else
  21719. {
  21720. while (--numSamples >= 0)
  21721. *d++ = gain * *source++;
  21722. }
  21723. }
  21724. else
  21725. {
  21726. memcpy (d, source, sizeof (float) * numSamples);
  21727. }
  21728. }
  21729. }
  21730. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21731. const int destStartSample,
  21732. const float* source,
  21733. int numSamples,
  21734. float startGain,
  21735. float endGain) throw()
  21736. {
  21737. jassert (isPositiveAndBelow (destChannel, numChannels));
  21738. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21739. jassert (source != 0);
  21740. if (startGain == endGain)
  21741. {
  21742. copyFrom (destChannel,
  21743. destStartSample,
  21744. source,
  21745. numSamples,
  21746. startGain);
  21747. }
  21748. else
  21749. {
  21750. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21751. {
  21752. const float increment = (endGain - startGain) / numSamples;
  21753. float* d = channels [destChannel] + destStartSample;
  21754. while (--numSamples >= 0)
  21755. {
  21756. *d++ = startGain * *source++;
  21757. startGain += increment;
  21758. }
  21759. }
  21760. }
  21761. }
  21762. void AudioSampleBuffer::findMinMax (const int channel,
  21763. const int startSample,
  21764. int numSamples,
  21765. float& minVal,
  21766. float& maxVal) const throw()
  21767. {
  21768. jassert (isPositiveAndBelow (channel, numChannels));
  21769. jassert (startSample >= 0 && startSample + numSamples <= size);
  21770. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21771. }
  21772. float AudioSampleBuffer::getMagnitude (const int channel,
  21773. const int startSample,
  21774. const int numSamples) const throw()
  21775. {
  21776. jassert (isPositiveAndBelow (channel, numChannels));
  21777. jassert (startSample >= 0 && startSample + numSamples <= size);
  21778. float mn, mx;
  21779. findMinMax (channel, startSample, numSamples, mn, mx);
  21780. return jmax (mn, -mn, mx, -mx);
  21781. }
  21782. float AudioSampleBuffer::getMagnitude (const int startSample,
  21783. const int numSamples) const throw()
  21784. {
  21785. float mag = 0.0f;
  21786. for (int i = 0; i < numChannels; ++i)
  21787. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21788. return mag;
  21789. }
  21790. float AudioSampleBuffer::getRMSLevel (const int channel,
  21791. const int startSample,
  21792. const int numSamples) const throw()
  21793. {
  21794. jassert (isPositiveAndBelow (channel, numChannels));
  21795. jassert (startSample >= 0 && startSample + numSamples <= size);
  21796. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21797. return 0.0f;
  21798. const float* const data = channels [channel] + startSample;
  21799. double sum = 0.0;
  21800. for (int i = 0; i < numSamples; ++i)
  21801. {
  21802. const float sample = data [i];
  21803. sum += sample * sample;
  21804. }
  21805. return (float) std::sqrt (sum / numSamples);
  21806. }
  21807. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21808. const int startSample,
  21809. const int numSamples,
  21810. const int64 readerStartSample,
  21811. const bool useLeftChan,
  21812. const bool useRightChan)
  21813. {
  21814. jassert (reader != 0);
  21815. jassert (startSample >= 0 && startSample + numSamples <= size);
  21816. if (numSamples > 0)
  21817. {
  21818. int* chans[3];
  21819. if (useLeftChan == useRightChan)
  21820. {
  21821. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21822. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21823. }
  21824. else if (useLeftChan || (reader->numChannels == 1))
  21825. {
  21826. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21827. chans[1] = 0;
  21828. }
  21829. else if (useRightChan)
  21830. {
  21831. chans[0] = 0;
  21832. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21833. }
  21834. chans[2] = 0;
  21835. reader->read (chans, 2, readerStartSample, numSamples, true);
  21836. if (! reader->usesFloatingPointData)
  21837. {
  21838. for (int j = 0; j < 2; ++j)
  21839. {
  21840. float* const d = reinterpret_cast <float*> (chans[j]);
  21841. if (d != 0)
  21842. {
  21843. const float multiplier = 1.0f / 0x7fffffff;
  21844. for (int i = 0; i < numSamples; ++i)
  21845. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  21846. }
  21847. }
  21848. }
  21849. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21850. {
  21851. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21852. memcpy (getSampleData (1, startSample),
  21853. getSampleData (0, startSample),
  21854. sizeof (float) * numSamples);
  21855. }
  21856. }
  21857. }
  21858. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21859. const int startSample,
  21860. const int numSamples) const
  21861. {
  21862. jassert (writer != 0);
  21863. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  21864. }
  21865. END_JUCE_NAMESPACE
  21866. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21867. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21868. BEGIN_JUCE_NAMESPACE
  21869. IIRFilter::IIRFilter()
  21870. : active (false)
  21871. {
  21872. reset();
  21873. }
  21874. IIRFilter::IIRFilter (const IIRFilter& other)
  21875. : active (other.active)
  21876. {
  21877. const ScopedLock sl (other.processLock);
  21878. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21879. reset();
  21880. }
  21881. IIRFilter::~IIRFilter()
  21882. {
  21883. }
  21884. void IIRFilter::reset() throw()
  21885. {
  21886. const ScopedLock sl (processLock);
  21887. x1 = 0;
  21888. x2 = 0;
  21889. y1 = 0;
  21890. y2 = 0;
  21891. }
  21892. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21893. {
  21894. float out = coefficients[0] * in
  21895. + coefficients[1] * x1
  21896. + coefficients[2] * x2
  21897. - coefficients[4] * y1
  21898. - coefficients[5] * y2;
  21899. #if JUCE_INTEL
  21900. if (! (out < -1.0e-8 || out > 1.0e-8))
  21901. out = 0;
  21902. #endif
  21903. x2 = x1;
  21904. x1 = in;
  21905. y2 = y1;
  21906. y1 = out;
  21907. return out;
  21908. }
  21909. void IIRFilter::processSamples (float* const samples,
  21910. const int numSamples) throw()
  21911. {
  21912. const ScopedLock sl (processLock);
  21913. if (active)
  21914. {
  21915. for (int i = 0; i < numSamples; ++i)
  21916. {
  21917. const float in = samples[i];
  21918. float out = coefficients[0] * in
  21919. + coefficients[1] * x1
  21920. + coefficients[2] * x2
  21921. - coefficients[4] * y1
  21922. - coefficients[5] * y2;
  21923. #if JUCE_INTEL
  21924. if (! (out < -1.0e-8 || out > 1.0e-8))
  21925. out = 0;
  21926. #endif
  21927. x2 = x1;
  21928. x1 = in;
  21929. y2 = y1;
  21930. y1 = out;
  21931. samples[i] = out;
  21932. }
  21933. }
  21934. }
  21935. void IIRFilter::makeLowPass (const double sampleRate,
  21936. const double frequency) throw()
  21937. {
  21938. jassert (sampleRate > 0);
  21939. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21940. const double nSquared = n * n;
  21941. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21942. setCoefficients (c1,
  21943. c1 * 2.0f,
  21944. c1,
  21945. 1.0,
  21946. c1 * 2.0 * (1.0 - nSquared),
  21947. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21948. }
  21949. void IIRFilter::makeHighPass (const double sampleRate,
  21950. const double frequency) throw()
  21951. {
  21952. const double n = tan (double_Pi * frequency / sampleRate);
  21953. const double nSquared = n * n;
  21954. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21955. setCoefficients (c1,
  21956. c1 * -2.0f,
  21957. c1,
  21958. 1.0,
  21959. c1 * 2.0 * (nSquared - 1.0),
  21960. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21961. }
  21962. void IIRFilter::makeLowShelf (const double sampleRate,
  21963. const double cutOffFrequency,
  21964. const double Q,
  21965. const float gainFactor) throw()
  21966. {
  21967. jassert (sampleRate > 0);
  21968. jassert (Q > 0);
  21969. const double A = jmax (0.0f, gainFactor);
  21970. const double aminus1 = A - 1.0;
  21971. const double aplus1 = A + 1.0;
  21972. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21973. const double coso = std::cos (omega);
  21974. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21975. const double aminus1TimesCoso = aminus1 * coso;
  21976. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21977. A * 2.0 * (aminus1 - aplus1 * coso),
  21978. A * (aplus1 - aminus1TimesCoso - beta),
  21979. aplus1 + aminus1TimesCoso + beta,
  21980. -2.0 * (aminus1 + aplus1 * coso),
  21981. aplus1 + aminus1TimesCoso - beta);
  21982. }
  21983. void IIRFilter::makeHighShelf (const double sampleRate,
  21984. const double cutOffFrequency,
  21985. const double Q,
  21986. const float gainFactor) throw()
  21987. {
  21988. jassert (sampleRate > 0);
  21989. jassert (Q > 0);
  21990. const double A = jmax (0.0f, gainFactor);
  21991. const double aminus1 = A - 1.0;
  21992. const double aplus1 = A + 1.0;
  21993. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21994. const double coso = std::cos (omega);
  21995. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21996. const double aminus1TimesCoso = aminus1 * coso;
  21997. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21998. A * -2.0 * (aminus1 + aplus1 * coso),
  21999. A * (aplus1 + aminus1TimesCoso - beta),
  22000. aplus1 - aminus1TimesCoso + beta,
  22001. 2.0 * (aminus1 - aplus1 * coso),
  22002. aplus1 - aminus1TimesCoso - beta);
  22003. }
  22004. void IIRFilter::makeBandPass (const double sampleRate,
  22005. const double centreFrequency,
  22006. const double Q,
  22007. const float gainFactor) throw()
  22008. {
  22009. jassert (sampleRate > 0);
  22010. jassert (Q > 0);
  22011. const double A = jmax (0.0f, gainFactor);
  22012. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22013. const double alpha = 0.5 * std::sin (omega) / Q;
  22014. const double c2 = -2.0 * std::cos (omega);
  22015. const double alphaTimesA = alpha * A;
  22016. const double alphaOverA = alpha / A;
  22017. setCoefficients (1.0 + alphaTimesA,
  22018. c2,
  22019. 1.0 - alphaTimesA,
  22020. 1.0 + alphaOverA,
  22021. c2,
  22022. 1.0 - alphaOverA);
  22023. }
  22024. void IIRFilter::makeInactive() throw()
  22025. {
  22026. const ScopedLock sl (processLock);
  22027. active = false;
  22028. }
  22029. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22030. {
  22031. const ScopedLock sl (processLock);
  22032. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22033. active = other.active;
  22034. }
  22035. void IIRFilter::setCoefficients (double c1,
  22036. double c2,
  22037. double c3,
  22038. double c4,
  22039. double c5,
  22040. double c6) throw()
  22041. {
  22042. const double a = 1.0 / c4;
  22043. c1 *= a;
  22044. c2 *= a;
  22045. c3 *= a;
  22046. c5 *= a;
  22047. c6 *= a;
  22048. const ScopedLock sl (processLock);
  22049. coefficients[0] = (float) c1;
  22050. coefficients[1] = (float) c2;
  22051. coefficients[2] = (float) c3;
  22052. coefficients[3] = (float) c4;
  22053. coefficients[4] = (float) c5;
  22054. coefficients[5] = (float) c6;
  22055. active = true;
  22056. }
  22057. END_JUCE_NAMESPACE
  22058. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22059. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22060. BEGIN_JUCE_NAMESPACE
  22061. MidiBuffer::MidiBuffer() throw()
  22062. : bytesUsed (0)
  22063. {
  22064. }
  22065. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22066. : bytesUsed (0)
  22067. {
  22068. addEvent (message, 0);
  22069. }
  22070. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22071. : data (other.data),
  22072. bytesUsed (other.bytesUsed)
  22073. {
  22074. }
  22075. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22076. {
  22077. bytesUsed = other.bytesUsed;
  22078. data = other.data;
  22079. return *this;
  22080. }
  22081. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22082. {
  22083. data.swapWith (other.data);
  22084. swapVariables <int> (bytesUsed, other.bytesUsed);
  22085. }
  22086. MidiBuffer::~MidiBuffer()
  22087. {
  22088. }
  22089. inline uint8* MidiBuffer::getData() const throw()
  22090. {
  22091. return static_cast <uint8*> (data.getData());
  22092. }
  22093. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22094. {
  22095. return *static_cast <const int*> (d);
  22096. }
  22097. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22098. {
  22099. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22100. }
  22101. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22102. {
  22103. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22104. }
  22105. void MidiBuffer::clear() throw()
  22106. {
  22107. bytesUsed = 0;
  22108. }
  22109. void MidiBuffer::clear (const int startSample, const int numSamples)
  22110. {
  22111. uint8* const start = findEventAfter (getData(), startSample - 1);
  22112. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22113. if (end > start)
  22114. {
  22115. const int bytesToMove = bytesUsed - (int) (end - getData());
  22116. if (bytesToMove > 0)
  22117. memmove (start, end, bytesToMove);
  22118. bytesUsed -= (int) (end - start);
  22119. }
  22120. }
  22121. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22122. {
  22123. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22124. }
  22125. namespace MidiBufferHelpers
  22126. {
  22127. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22128. {
  22129. unsigned int byte = (unsigned int) *data;
  22130. int size = 0;
  22131. if (byte == 0xf0 || byte == 0xf7)
  22132. {
  22133. const uint8* d = data + 1;
  22134. while (d < data + maxBytes)
  22135. if (*d++ == 0xf7)
  22136. break;
  22137. size = (int) (d - data);
  22138. }
  22139. else if (byte == 0xff)
  22140. {
  22141. int n;
  22142. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22143. size = jmin (maxBytes, n + 2 + bytesLeft);
  22144. }
  22145. else if (byte >= 0x80)
  22146. {
  22147. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22148. }
  22149. return size;
  22150. }
  22151. }
  22152. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22153. {
  22154. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22155. if (numBytes > 0)
  22156. {
  22157. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22158. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22159. uint8* d = findEventAfter (getData(), sampleNumber);
  22160. const int bytesToMove = bytesUsed - (int) (d - getData());
  22161. if (bytesToMove > 0)
  22162. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22163. *reinterpret_cast <int*> (d) = sampleNumber;
  22164. d += sizeof (int);
  22165. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22166. d += sizeof (uint16);
  22167. memcpy (d, newData, numBytes);
  22168. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22169. }
  22170. }
  22171. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22172. const int startSample,
  22173. const int numSamples,
  22174. const int sampleDeltaToAdd)
  22175. {
  22176. Iterator i (otherBuffer);
  22177. i.setNextSamplePosition (startSample);
  22178. const uint8* eventData;
  22179. int eventSize, position;
  22180. while (i.getNextEvent (eventData, eventSize, position)
  22181. && (position < startSample + numSamples || numSamples < 0))
  22182. {
  22183. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22184. }
  22185. }
  22186. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22187. {
  22188. data.ensureSize (minimumNumBytes);
  22189. }
  22190. bool MidiBuffer::isEmpty() const throw()
  22191. {
  22192. return bytesUsed == 0;
  22193. }
  22194. int MidiBuffer::getNumEvents() const throw()
  22195. {
  22196. int n = 0;
  22197. const uint8* d = getData();
  22198. const uint8* const end = d + bytesUsed;
  22199. while (d < end)
  22200. {
  22201. d += getEventTotalSize (d);
  22202. ++n;
  22203. }
  22204. return n;
  22205. }
  22206. int MidiBuffer::getFirstEventTime() const throw()
  22207. {
  22208. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22209. }
  22210. int MidiBuffer::getLastEventTime() const throw()
  22211. {
  22212. if (bytesUsed == 0)
  22213. return 0;
  22214. const uint8* d = getData();
  22215. const uint8* const endData = d + bytesUsed;
  22216. for (;;)
  22217. {
  22218. const uint8* const nextOne = d + getEventTotalSize (d);
  22219. if (nextOne >= endData)
  22220. return getEventTime (d);
  22221. d = nextOne;
  22222. }
  22223. }
  22224. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22225. {
  22226. const uint8* const endData = getData() + bytesUsed;
  22227. while (d < endData && getEventTime (d) <= samplePosition)
  22228. d += getEventTotalSize (d);
  22229. return d;
  22230. }
  22231. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22232. : buffer (buffer_),
  22233. data (buffer_.getData())
  22234. {
  22235. }
  22236. MidiBuffer::Iterator::~Iterator() throw()
  22237. {
  22238. }
  22239. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22240. {
  22241. data = buffer.getData();
  22242. const uint8* dataEnd = data + buffer.bytesUsed;
  22243. while (data < dataEnd && getEventTime (data) < samplePosition)
  22244. data += getEventTotalSize (data);
  22245. }
  22246. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22247. {
  22248. if (data >= buffer.getData() + buffer.bytesUsed)
  22249. return false;
  22250. samplePosition = getEventTime (data);
  22251. numBytes = getEventDataSize (data);
  22252. data += sizeof (int) + sizeof (uint16);
  22253. midiData = data;
  22254. data += numBytes;
  22255. return true;
  22256. }
  22257. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22258. {
  22259. if (data >= buffer.getData() + buffer.bytesUsed)
  22260. return false;
  22261. samplePosition = getEventTime (data);
  22262. const int numBytes = getEventDataSize (data);
  22263. data += sizeof (int) + sizeof (uint16);
  22264. result = MidiMessage (data, numBytes, samplePosition);
  22265. data += numBytes;
  22266. return true;
  22267. }
  22268. END_JUCE_NAMESPACE
  22269. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22270. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22271. BEGIN_JUCE_NAMESPACE
  22272. namespace MidiFileHelpers
  22273. {
  22274. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22275. {
  22276. unsigned int buffer = v & 0x7F;
  22277. while ((v >>= 7) != 0)
  22278. {
  22279. buffer <<= 8;
  22280. buffer |= ((v & 0x7F) | 0x80);
  22281. }
  22282. for (;;)
  22283. {
  22284. out.writeByte ((char) buffer);
  22285. if (buffer & 0x80)
  22286. buffer >>= 8;
  22287. else
  22288. break;
  22289. }
  22290. }
  22291. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22292. {
  22293. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22294. data += 4;
  22295. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22296. {
  22297. bool ok = false;
  22298. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22299. {
  22300. for (int i = 0; i < 8; ++i)
  22301. {
  22302. ch = ByteOrder::bigEndianInt (data);
  22303. data += 4;
  22304. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22305. {
  22306. ok = true;
  22307. break;
  22308. }
  22309. }
  22310. }
  22311. if (! ok)
  22312. return false;
  22313. }
  22314. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22315. data += 4;
  22316. fileType = (short) ByteOrder::bigEndianShort (data);
  22317. data += 2;
  22318. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22319. data += 2;
  22320. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22321. data += 2;
  22322. bytesRemaining -= 6;
  22323. data += bytesRemaining;
  22324. return true;
  22325. }
  22326. double convertTicksToSeconds (const double time,
  22327. const MidiMessageSequence& tempoEvents,
  22328. const int timeFormat)
  22329. {
  22330. if (timeFormat > 0)
  22331. {
  22332. int numer = 4, denom = 4;
  22333. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22334. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22335. double secsPerTick = 0.5 * tickLen;
  22336. const int numEvents = tempoEvents.getNumEvents();
  22337. for (int i = 0; i < numEvents; ++i)
  22338. {
  22339. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22340. if (time <= m.getTimeStamp())
  22341. break;
  22342. if (timeFormat > 0)
  22343. {
  22344. correctedTempoTime = correctedTempoTime
  22345. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22346. }
  22347. else
  22348. {
  22349. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22350. }
  22351. tempoTime = m.getTimeStamp();
  22352. if (m.isTempoMetaEvent())
  22353. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22354. else if (m.isTimeSignatureMetaEvent())
  22355. m.getTimeSignatureInfo (numer, denom);
  22356. while (i + 1 < numEvents)
  22357. {
  22358. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22359. if (m2.getTimeStamp() == tempoTime)
  22360. {
  22361. ++i;
  22362. if (m2.isTempoMetaEvent())
  22363. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22364. else if (m2.isTimeSignatureMetaEvent())
  22365. m2.getTimeSignatureInfo (numer, denom);
  22366. }
  22367. else
  22368. {
  22369. break;
  22370. }
  22371. }
  22372. }
  22373. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22374. }
  22375. else
  22376. {
  22377. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22378. }
  22379. }
  22380. // a comparator that puts all the note-offs before note-ons that have the same time
  22381. struct Sorter
  22382. {
  22383. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22384. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22385. {
  22386. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22387. if (diff == 0)
  22388. {
  22389. if (first->message.isNoteOff() && second->message.isNoteOn())
  22390. return -1;
  22391. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22392. return 1;
  22393. else
  22394. return 0;
  22395. }
  22396. else
  22397. {
  22398. return (diff > 0) ? 1 : -1;
  22399. }
  22400. }
  22401. };
  22402. }
  22403. MidiFile::MidiFile()
  22404. : timeFormat ((short) (unsigned short) 0xe728)
  22405. {
  22406. }
  22407. MidiFile::~MidiFile()
  22408. {
  22409. clear();
  22410. }
  22411. void MidiFile::clear()
  22412. {
  22413. tracks.clear();
  22414. }
  22415. int MidiFile::getNumTracks() const throw()
  22416. {
  22417. return tracks.size();
  22418. }
  22419. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22420. {
  22421. return tracks [index];
  22422. }
  22423. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22424. {
  22425. tracks.add (new MidiMessageSequence (trackSequence));
  22426. }
  22427. short MidiFile::getTimeFormat() const throw()
  22428. {
  22429. return timeFormat;
  22430. }
  22431. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22432. {
  22433. timeFormat = (short) ticks;
  22434. }
  22435. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22436. const int subframeResolution) throw()
  22437. {
  22438. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22439. }
  22440. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22441. {
  22442. for (int i = tracks.size(); --i >= 0;)
  22443. {
  22444. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22445. for (int j = 0; j < numEvents; ++j)
  22446. {
  22447. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22448. if (m.isTempoMetaEvent())
  22449. tempoChangeEvents.addEvent (m);
  22450. }
  22451. }
  22452. }
  22453. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22454. {
  22455. for (int i = tracks.size(); --i >= 0;)
  22456. {
  22457. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22458. for (int j = 0; j < numEvents; ++j)
  22459. {
  22460. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22461. if (m.isTimeSignatureMetaEvent())
  22462. timeSigEvents.addEvent (m);
  22463. }
  22464. }
  22465. }
  22466. double MidiFile::getLastTimestamp() const
  22467. {
  22468. double t = 0.0;
  22469. for (int i = tracks.size(); --i >= 0;)
  22470. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22471. return t;
  22472. }
  22473. bool MidiFile::readFrom (InputStream& sourceStream)
  22474. {
  22475. clear();
  22476. MemoryBlock data;
  22477. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22478. // (put a sanity-check on the file size, as midi files are generally small)
  22479. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22480. {
  22481. size_t size = data.getSize();
  22482. const uint8* d = static_cast <const uint8*> (data.getData());
  22483. short fileType, expectedTracks;
  22484. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22485. {
  22486. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22487. int track = 0;
  22488. while (size > 0 && track < expectedTracks)
  22489. {
  22490. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22491. d += 4;
  22492. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22493. d += 4;
  22494. if (chunkSize <= 0)
  22495. break;
  22496. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22497. {
  22498. readNextTrack (d, chunkSize);
  22499. }
  22500. size -= chunkSize + 8;
  22501. d += chunkSize;
  22502. ++track;
  22503. }
  22504. return true;
  22505. }
  22506. }
  22507. return false;
  22508. }
  22509. void MidiFile::readNextTrack (const uint8* data, int size)
  22510. {
  22511. double time = 0;
  22512. char lastStatusByte = 0;
  22513. MidiMessageSequence result;
  22514. while (size > 0)
  22515. {
  22516. int bytesUsed;
  22517. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22518. data += bytesUsed;
  22519. size -= bytesUsed;
  22520. time += delay;
  22521. int messSize = 0;
  22522. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22523. if (messSize <= 0)
  22524. break;
  22525. size -= messSize;
  22526. data += messSize;
  22527. result.addEvent (mm);
  22528. const char firstByte = *(mm.getRawData());
  22529. if ((firstByte & 0xf0) != 0xf0)
  22530. lastStatusByte = firstByte;
  22531. }
  22532. // use a sort that puts all the note-offs before note-ons that have the same time
  22533. MidiFileHelpers::Sorter sorter;
  22534. result.list.sort (sorter, true);
  22535. result.updateMatchedPairs();
  22536. addTrack (result);
  22537. }
  22538. void MidiFile::convertTimestampTicksToSeconds()
  22539. {
  22540. MidiMessageSequence tempoEvents;
  22541. findAllTempoEvents (tempoEvents);
  22542. findAllTimeSigEvents (tempoEvents);
  22543. for (int i = 0; i < tracks.size(); ++i)
  22544. {
  22545. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22546. for (int j = ms.getNumEvents(); --j >= 0;)
  22547. {
  22548. MidiMessage& m = ms.getEventPointer(j)->message;
  22549. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22550. tempoEvents,
  22551. timeFormat));
  22552. }
  22553. }
  22554. }
  22555. bool MidiFile::writeTo (OutputStream& out)
  22556. {
  22557. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22558. out.writeIntBigEndian (6);
  22559. out.writeShortBigEndian (1); // type
  22560. out.writeShortBigEndian ((short) tracks.size());
  22561. out.writeShortBigEndian (timeFormat);
  22562. for (int i = 0; i < tracks.size(); ++i)
  22563. writeTrack (out, i);
  22564. out.flush();
  22565. return true;
  22566. }
  22567. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22568. {
  22569. MemoryOutputStream out;
  22570. const MidiMessageSequence& ms = *tracks[trackNum];
  22571. int lastTick = 0;
  22572. char lastStatusByte = 0;
  22573. for (int i = 0; i < ms.getNumEvents(); ++i)
  22574. {
  22575. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22576. const int tick = roundToInt (mm.getTimeStamp());
  22577. const int delta = jmax (0, tick - lastTick);
  22578. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22579. lastTick = tick;
  22580. const char statusByte = *(mm.getRawData());
  22581. if ((statusByte == lastStatusByte)
  22582. && ((statusByte & 0xf0) != 0xf0)
  22583. && i > 0
  22584. && mm.getRawDataSize() > 1)
  22585. {
  22586. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22587. }
  22588. else
  22589. {
  22590. out.write (mm.getRawData(), mm.getRawDataSize());
  22591. }
  22592. lastStatusByte = statusByte;
  22593. }
  22594. out.writeByte (0);
  22595. const MidiMessage m (MidiMessage::endOfTrack());
  22596. out.write (m.getRawData(),
  22597. m.getRawDataSize());
  22598. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22599. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22600. mainOut.write (out.getData(), (int) out.getDataSize());
  22601. }
  22602. END_JUCE_NAMESPACE
  22603. /*** End of inlined file: juce_MidiFile.cpp ***/
  22604. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22605. BEGIN_JUCE_NAMESPACE
  22606. MidiKeyboardState::MidiKeyboardState()
  22607. {
  22608. zerostruct (noteStates);
  22609. }
  22610. MidiKeyboardState::~MidiKeyboardState()
  22611. {
  22612. }
  22613. void MidiKeyboardState::reset()
  22614. {
  22615. const ScopedLock sl (lock);
  22616. zerostruct (noteStates);
  22617. eventsToAdd.clear();
  22618. }
  22619. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22620. {
  22621. jassert (midiChannel >= 0 && midiChannel <= 16);
  22622. return isPositiveAndBelow (n, (int) 128)
  22623. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22624. }
  22625. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22626. {
  22627. return isPositiveAndBelow (n, (int) 128)
  22628. && (noteStates[n] & midiChannelMask) != 0;
  22629. }
  22630. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22631. {
  22632. jassert (midiChannel >= 0 && midiChannel <= 16);
  22633. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22634. const ScopedLock sl (lock);
  22635. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22636. {
  22637. const int timeNow = (int) Time::getMillisecondCounter();
  22638. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22639. eventsToAdd.clear (0, timeNow - 500);
  22640. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22641. }
  22642. }
  22643. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22644. {
  22645. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22646. {
  22647. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22648. for (int i = listeners.size(); --i >= 0;)
  22649. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22650. }
  22651. }
  22652. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22653. {
  22654. const ScopedLock sl (lock);
  22655. if (isNoteOn (midiChannel, midiNoteNumber))
  22656. {
  22657. const int timeNow = (int) Time::getMillisecondCounter();
  22658. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22659. eventsToAdd.clear (0, timeNow - 500);
  22660. noteOffInternal (midiChannel, midiNoteNumber);
  22661. }
  22662. }
  22663. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22664. {
  22665. if (isNoteOn (midiChannel, midiNoteNumber))
  22666. {
  22667. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22668. for (int i = listeners.size(); --i >= 0;)
  22669. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22670. }
  22671. }
  22672. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22673. {
  22674. const ScopedLock sl (lock);
  22675. if (midiChannel <= 0)
  22676. {
  22677. for (int i = 1; i <= 16; ++i)
  22678. allNotesOff (i);
  22679. }
  22680. else
  22681. {
  22682. for (int i = 0; i < 128; ++i)
  22683. noteOff (midiChannel, i);
  22684. }
  22685. }
  22686. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22687. {
  22688. if (message.isNoteOn())
  22689. {
  22690. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22691. }
  22692. else if (message.isNoteOff())
  22693. {
  22694. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22695. }
  22696. else if (message.isAllNotesOff())
  22697. {
  22698. for (int i = 0; i < 128; ++i)
  22699. noteOffInternal (message.getChannel(), i);
  22700. }
  22701. }
  22702. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22703. const int startSample,
  22704. const int numSamples,
  22705. const bool injectIndirectEvents)
  22706. {
  22707. MidiBuffer::Iterator i (buffer);
  22708. MidiMessage message (0xf4, 0.0);
  22709. int time;
  22710. const ScopedLock sl (lock);
  22711. while (i.getNextEvent (message, time))
  22712. processNextMidiEvent (message);
  22713. if (injectIndirectEvents)
  22714. {
  22715. MidiBuffer::Iterator i2 (eventsToAdd);
  22716. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22717. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22718. while (i2.getNextEvent (message, time))
  22719. {
  22720. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22721. buffer.addEvent (message, startSample + pos);
  22722. }
  22723. }
  22724. eventsToAdd.clear();
  22725. }
  22726. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22727. {
  22728. const ScopedLock sl (lock);
  22729. listeners.addIfNotAlreadyThere (listener);
  22730. }
  22731. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22732. {
  22733. const ScopedLock sl (lock);
  22734. listeners.removeValue (listener);
  22735. }
  22736. END_JUCE_NAMESPACE
  22737. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22738. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22739. BEGIN_JUCE_NAMESPACE
  22740. namespace MidiHelpers
  22741. {
  22742. inline uint8 initialByte (const int type, const int channel) throw()
  22743. {
  22744. return (uint8) (type | jlimit (0, 15, channel - 1));
  22745. }
  22746. inline uint8 validVelocity (const int v) throw()
  22747. {
  22748. return (uint8) jlimit (0, 127, v);
  22749. }
  22750. }
  22751. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22752. {
  22753. numBytesUsed = 0;
  22754. int v = 0;
  22755. int i;
  22756. do
  22757. {
  22758. i = (int) *data++;
  22759. if (++numBytesUsed > 6)
  22760. break;
  22761. v = (v << 7) + (i & 0x7f);
  22762. } while (i & 0x80);
  22763. return v;
  22764. }
  22765. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22766. {
  22767. // this method only works for valid starting bytes of a short midi message
  22768. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22769. static const char messageLengths[] =
  22770. {
  22771. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22772. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22773. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22774. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22775. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22776. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22777. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22778. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22779. };
  22780. return messageLengths [firstByte & 0x7f];
  22781. }
  22782. MidiMessage::MidiMessage() throw()
  22783. : timeStamp (0),
  22784. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22785. size (2)
  22786. {
  22787. data[0] = 0xf0;
  22788. data[1] = 0xf7;
  22789. }
  22790. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22791. : timeStamp (t),
  22792. size (dataSize)
  22793. {
  22794. jassert (dataSize > 0);
  22795. if (dataSize <= 4)
  22796. data = static_cast<uint8*> (preallocatedData.asBytes);
  22797. else
  22798. data = new uint8 [dataSize];
  22799. memcpy (data, d, dataSize);
  22800. // check that the length matches the data..
  22801. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22802. }
  22803. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22804. : timeStamp (t),
  22805. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22806. size (1)
  22807. {
  22808. data[0] = (uint8) byte1;
  22809. // check that the length matches the data..
  22810. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22811. }
  22812. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22813. : timeStamp (t),
  22814. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22815. size (2)
  22816. {
  22817. data[0] = (uint8) byte1;
  22818. data[1] = (uint8) byte2;
  22819. // check that the length matches the data..
  22820. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22821. }
  22822. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22823. : timeStamp (t),
  22824. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22825. size (3)
  22826. {
  22827. data[0] = (uint8) byte1;
  22828. data[1] = (uint8) byte2;
  22829. data[2] = (uint8) byte3;
  22830. // check that the length matches the data..
  22831. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22832. }
  22833. MidiMessage::MidiMessage (const MidiMessage& other)
  22834. : timeStamp (other.timeStamp),
  22835. size (other.size)
  22836. {
  22837. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22838. {
  22839. data = new uint8 [size];
  22840. memcpy (data, other.data, size);
  22841. }
  22842. else
  22843. {
  22844. data = static_cast<uint8*> (preallocatedData.asBytes);
  22845. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22846. }
  22847. }
  22848. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22849. : timeStamp (newTimeStamp),
  22850. size (other.size)
  22851. {
  22852. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22853. {
  22854. data = new uint8 [size];
  22855. memcpy (data, other.data, size);
  22856. }
  22857. else
  22858. {
  22859. data = static_cast<uint8*> (preallocatedData.asBytes);
  22860. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22861. }
  22862. }
  22863. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22864. : timeStamp (t),
  22865. data (static_cast<uint8*> (preallocatedData.asBytes))
  22866. {
  22867. const uint8* src = static_cast <const uint8*> (src_);
  22868. unsigned int byte = (unsigned int) *src;
  22869. if (byte < 0x80)
  22870. {
  22871. byte = (unsigned int) (uint8) lastStatusByte;
  22872. numBytesUsed = -1;
  22873. }
  22874. else
  22875. {
  22876. numBytesUsed = 0;
  22877. --sz;
  22878. ++src;
  22879. }
  22880. if (byte >= 0x80)
  22881. {
  22882. if (byte == 0xf0)
  22883. {
  22884. const uint8* d = src;
  22885. bool haveReadAllLengthBytes = false;
  22886. while (d < src + sz)
  22887. {
  22888. if (*d >= 0x80)
  22889. {
  22890. if (*d == 0xf7)
  22891. {
  22892. ++d; // include the trailing 0xf7 when we hit it
  22893. break;
  22894. }
  22895. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  22896. break; // bytes, assume it's the end of the sysex
  22897. ++d;
  22898. continue;
  22899. }
  22900. haveReadAllLengthBytes = true;
  22901. ++d;
  22902. }
  22903. size = 1 + (int) (d - src);
  22904. data = new uint8 [size];
  22905. *data = (uint8) byte;
  22906. memcpy (data + 1, src, size - 1);
  22907. }
  22908. else if (byte == 0xff)
  22909. {
  22910. int n;
  22911. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22912. size = jmin (sz + 1, n + 2 + bytesLeft);
  22913. data = new uint8 [size];
  22914. *data = (uint8) byte;
  22915. memcpy (data + 1, src, size - 1);
  22916. }
  22917. else
  22918. {
  22919. preallocatedData.asInt32 = 0;
  22920. size = getMessageLengthFromFirstByte ((uint8) byte);
  22921. data[0] = (uint8) byte;
  22922. if (size > 1)
  22923. {
  22924. data[1] = src[0];
  22925. if (size > 2)
  22926. data[2] = src[1];
  22927. }
  22928. }
  22929. numBytesUsed += size;
  22930. }
  22931. else
  22932. {
  22933. preallocatedData.asInt32 = 0;
  22934. size = 0;
  22935. }
  22936. }
  22937. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22938. {
  22939. if (this != &other)
  22940. {
  22941. timeStamp = other.timeStamp;
  22942. size = other.size;
  22943. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22944. delete[] data;
  22945. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22946. {
  22947. data = new uint8 [size];
  22948. memcpy (data, other.data, size);
  22949. }
  22950. else
  22951. {
  22952. data = static_cast<uint8*> (preallocatedData.asBytes);
  22953. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22954. }
  22955. }
  22956. return *this;
  22957. }
  22958. MidiMessage::~MidiMessage()
  22959. {
  22960. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22961. delete[] data;
  22962. }
  22963. int MidiMessage::getChannel() const throw()
  22964. {
  22965. if ((data[0] & 0xf0) != 0xf0)
  22966. return (data[0] & 0xf) + 1;
  22967. else
  22968. return 0;
  22969. }
  22970. bool MidiMessage::isForChannel (const int channel) const throw()
  22971. {
  22972. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22973. return ((data[0] & 0xf) == channel - 1)
  22974. && ((data[0] & 0xf0) != 0xf0);
  22975. }
  22976. void MidiMessage::setChannel (const int channel) throw()
  22977. {
  22978. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22979. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22980. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  22981. | (uint8)(channel - 1));
  22982. }
  22983. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22984. {
  22985. return ((data[0] & 0xf0) == 0x90)
  22986. && (returnTrueForVelocity0 || data[2] != 0);
  22987. }
  22988. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22989. {
  22990. return ((data[0] & 0xf0) == 0x80)
  22991. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22992. }
  22993. bool MidiMessage::isNoteOnOrOff() const throw()
  22994. {
  22995. const int d = data[0] & 0xf0;
  22996. return (d == 0x90) || (d == 0x80);
  22997. }
  22998. int MidiMessage::getNoteNumber() const throw()
  22999. {
  23000. return data[1];
  23001. }
  23002. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23003. {
  23004. if (isNoteOnOrOff())
  23005. data[1] = newNoteNumber & 127;
  23006. }
  23007. uint8 MidiMessage::getVelocity() const throw()
  23008. {
  23009. if (isNoteOnOrOff())
  23010. return data[2];
  23011. else
  23012. return 0;
  23013. }
  23014. float MidiMessage::getFloatVelocity() const throw()
  23015. {
  23016. return getVelocity() * (1.0f / 127.0f);
  23017. }
  23018. void MidiMessage::setVelocity (const float newVelocity) throw()
  23019. {
  23020. if (isNoteOnOrOff())
  23021. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23022. }
  23023. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23024. {
  23025. if (isNoteOnOrOff())
  23026. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23027. }
  23028. bool MidiMessage::isAftertouch() const throw()
  23029. {
  23030. return (data[0] & 0xf0) == 0xa0;
  23031. }
  23032. int MidiMessage::getAfterTouchValue() const throw()
  23033. {
  23034. return data[2];
  23035. }
  23036. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23037. const int noteNum,
  23038. const int aftertouchValue) throw()
  23039. {
  23040. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23041. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23042. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23043. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23044. noteNum & 0x7f,
  23045. aftertouchValue & 0x7f);
  23046. }
  23047. bool MidiMessage::isChannelPressure() const throw()
  23048. {
  23049. return (data[0] & 0xf0) == 0xd0;
  23050. }
  23051. int MidiMessage::getChannelPressureValue() const throw()
  23052. {
  23053. jassert (isChannelPressure());
  23054. return data[1];
  23055. }
  23056. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23057. const int pressure) throw()
  23058. {
  23059. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23060. jassert (isPositiveAndBelow (pressure, (int) 128));
  23061. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23062. }
  23063. bool MidiMessage::isProgramChange() const throw()
  23064. {
  23065. return (data[0] & 0xf0) == 0xc0;
  23066. }
  23067. int MidiMessage::getProgramChangeNumber() const throw()
  23068. {
  23069. return data[1];
  23070. }
  23071. const MidiMessage MidiMessage::programChange (const int channel,
  23072. const int programNumber) throw()
  23073. {
  23074. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23075. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23076. }
  23077. bool MidiMessage::isPitchWheel() const throw()
  23078. {
  23079. return (data[0] & 0xf0) == 0xe0;
  23080. }
  23081. int MidiMessage::getPitchWheelValue() const throw()
  23082. {
  23083. return data[1] | (data[2] << 7);
  23084. }
  23085. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23086. const int position) throw()
  23087. {
  23088. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23089. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23090. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23091. }
  23092. bool MidiMessage::isController() const throw()
  23093. {
  23094. return (data[0] & 0xf0) == 0xb0;
  23095. }
  23096. int MidiMessage::getControllerNumber() const throw()
  23097. {
  23098. jassert (isController());
  23099. return data[1];
  23100. }
  23101. int MidiMessage::getControllerValue() const throw()
  23102. {
  23103. jassert (isController());
  23104. return data[2];
  23105. }
  23106. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23107. {
  23108. // the channel must be between 1 and 16 inclusive
  23109. jassert (channel > 0 && channel <= 16);
  23110. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23111. }
  23112. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23113. {
  23114. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23115. }
  23116. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23117. {
  23118. jassert (channel > 0 && channel <= 16);
  23119. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23120. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23121. }
  23122. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23123. {
  23124. jassert (channel > 0 && channel <= 16);
  23125. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23126. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23127. }
  23128. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23129. {
  23130. return controllerEvent (channel, 123, 0);
  23131. }
  23132. bool MidiMessage::isAllNotesOff() const throw()
  23133. {
  23134. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23135. }
  23136. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23137. {
  23138. return controllerEvent (channel, 120, 0);
  23139. }
  23140. bool MidiMessage::isAllSoundOff() const throw()
  23141. {
  23142. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23143. }
  23144. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23145. {
  23146. return controllerEvent (channel, 121, 0);
  23147. }
  23148. const MidiMessage MidiMessage::masterVolume (const float volume)
  23149. {
  23150. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23151. uint8 buf[8];
  23152. buf[0] = 0xf0;
  23153. buf[1] = 0x7f;
  23154. buf[2] = 0x7f;
  23155. buf[3] = 0x04;
  23156. buf[4] = 0x01;
  23157. buf[5] = (uint8) (vol & 0x7f);
  23158. buf[6] = (uint8) (vol >> 7);
  23159. buf[7] = 0xf7;
  23160. return MidiMessage (buf, 8);
  23161. }
  23162. bool MidiMessage::isSysEx() const throw()
  23163. {
  23164. return *data == 0xf0;
  23165. }
  23166. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23167. {
  23168. HeapBlock<uint8> m (dataSize + 2);
  23169. m[0] = 0xf0;
  23170. memcpy (m + 1, sysexData, dataSize);
  23171. m[dataSize + 1] = 0xf7;
  23172. return MidiMessage (m, dataSize + 2);
  23173. }
  23174. const uint8* MidiMessage::getSysExData() const throw()
  23175. {
  23176. return isSysEx() ? getRawData() + 1 : 0;
  23177. }
  23178. int MidiMessage::getSysExDataSize() const throw()
  23179. {
  23180. return isSysEx() ? size - 2 : 0;
  23181. }
  23182. bool MidiMessage::isMetaEvent() const throw()
  23183. {
  23184. return *data == 0xff;
  23185. }
  23186. bool MidiMessage::isActiveSense() const throw()
  23187. {
  23188. return *data == 0xfe;
  23189. }
  23190. int MidiMessage::getMetaEventType() const throw()
  23191. {
  23192. return *data != 0xff ? -1 : data[1];
  23193. }
  23194. int MidiMessage::getMetaEventLength() const throw()
  23195. {
  23196. if (*data == 0xff)
  23197. {
  23198. int n;
  23199. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23200. }
  23201. return 0;
  23202. }
  23203. const uint8* MidiMessage::getMetaEventData() const throw()
  23204. {
  23205. int n;
  23206. const uint8* d = data + 2;
  23207. readVariableLengthVal (d, n);
  23208. return d + n;
  23209. }
  23210. bool MidiMessage::isTrackMetaEvent() const throw()
  23211. {
  23212. return getMetaEventType() == 0;
  23213. }
  23214. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23215. {
  23216. return getMetaEventType() == 47;
  23217. }
  23218. bool MidiMessage::isTextMetaEvent() const throw()
  23219. {
  23220. const int t = getMetaEventType();
  23221. return t > 0 && t < 16;
  23222. }
  23223. const String MidiMessage::getTextFromTextMetaEvent() const
  23224. {
  23225. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23226. }
  23227. bool MidiMessage::isTrackNameEvent() const throw()
  23228. {
  23229. return (data[1] == 3) && (*data == 0xff);
  23230. }
  23231. bool MidiMessage::isTempoMetaEvent() const throw()
  23232. {
  23233. return (data[1] == 81) && (*data == 0xff);
  23234. }
  23235. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23236. {
  23237. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23238. }
  23239. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23240. {
  23241. return data[3] + 1;
  23242. }
  23243. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23244. {
  23245. if (! isTempoMetaEvent())
  23246. return 0.0;
  23247. const uint8* const d = getMetaEventData();
  23248. return (((unsigned int) d[0] << 16)
  23249. | ((unsigned int) d[1] << 8)
  23250. | d[2])
  23251. / 1000000.0;
  23252. }
  23253. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23254. {
  23255. if (timeFormat > 0)
  23256. {
  23257. if (! isTempoMetaEvent())
  23258. return 0.5 / timeFormat;
  23259. return getTempoSecondsPerQuarterNote() / timeFormat;
  23260. }
  23261. else
  23262. {
  23263. const int frameCode = (-timeFormat) >> 8;
  23264. double framesPerSecond;
  23265. switch (frameCode)
  23266. {
  23267. case 24: framesPerSecond = 24.0; break;
  23268. case 25: framesPerSecond = 25.0; break;
  23269. case 29: framesPerSecond = 29.97; break;
  23270. case 30: framesPerSecond = 30.0; break;
  23271. default: framesPerSecond = 30.0; break;
  23272. }
  23273. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23274. }
  23275. }
  23276. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23277. {
  23278. uint8 d[8];
  23279. d[0] = 0xff;
  23280. d[1] = 81;
  23281. d[2] = 3;
  23282. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23283. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23284. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23285. return MidiMessage (d, 6, 0.0);
  23286. }
  23287. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23288. {
  23289. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23290. }
  23291. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23292. {
  23293. if (isTimeSignatureMetaEvent())
  23294. {
  23295. const uint8* const d = getMetaEventData();
  23296. numerator = d[0];
  23297. denominator = 1 << d[1];
  23298. }
  23299. else
  23300. {
  23301. numerator = 4;
  23302. denominator = 4;
  23303. }
  23304. }
  23305. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23306. {
  23307. uint8 d[8];
  23308. d[0] = 0xff;
  23309. d[1] = 0x58;
  23310. d[2] = 0x04;
  23311. d[3] = (uint8) numerator;
  23312. int n = 1;
  23313. int powerOfTwo = 0;
  23314. while (n < denominator)
  23315. {
  23316. n <<= 1;
  23317. ++powerOfTwo;
  23318. }
  23319. d[4] = (uint8) powerOfTwo;
  23320. d[5] = 0x01;
  23321. d[6] = 96;
  23322. return MidiMessage (d, 7, 0.0);
  23323. }
  23324. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23325. {
  23326. uint8 d[8];
  23327. d[0] = 0xff;
  23328. d[1] = 0x20;
  23329. d[2] = 0x01;
  23330. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23331. return MidiMessage (d, 4, 0.0);
  23332. }
  23333. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23334. {
  23335. return getMetaEventType() == 89;
  23336. }
  23337. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23338. {
  23339. return (int) *getMetaEventData();
  23340. }
  23341. const MidiMessage MidiMessage::endOfTrack() throw()
  23342. {
  23343. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23344. }
  23345. bool MidiMessage::isSongPositionPointer() const throw()
  23346. {
  23347. return *data == 0xf2;
  23348. }
  23349. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23350. {
  23351. return data[1] | (data[2] << 7);
  23352. }
  23353. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23354. {
  23355. return MidiMessage (0xf2,
  23356. positionInMidiBeats & 127,
  23357. (positionInMidiBeats >> 7) & 127);
  23358. }
  23359. bool MidiMessage::isMidiStart() const throw()
  23360. {
  23361. return *data == 0xfa;
  23362. }
  23363. const MidiMessage MidiMessage::midiStart() throw()
  23364. {
  23365. return MidiMessage (0xfa);
  23366. }
  23367. bool MidiMessage::isMidiContinue() const throw()
  23368. {
  23369. return *data == 0xfb;
  23370. }
  23371. const MidiMessage MidiMessage::midiContinue() throw()
  23372. {
  23373. return MidiMessage (0xfb);
  23374. }
  23375. bool MidiMessage::isMidiStop() const throw()
  23376. {
  23377. return *data == 0xfc;
  23378. }
  23379. const MidiMessage MidiMessage::midiStop() throw()
  23380. {
  23381. return MidiMessage (0xfc);
  23382. }
  23383. bool MidiMessage::isMidiClock() const throw()
  23384. {
  23385. return *data == 0xf8;
  23386. }
  23387. const MidiMessage MidiMessage::midiClock() throw()
  23388. {
  23389. return MidiMessage (0xf8);
  23390. }
  23391. bool MidiMessage::isQuarterFrame() const throw()
  23392. {
  23393. return *data == 0xf1;
  23394. }
  23395. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23396. {
  23397. return ((int) data[1]) >> 4;
  23398. }
  23399. int MidiMessage::getQuarterFrameValue() const throw()
  23400. {
  23401. return ((int) data[1]) & 0x0f;
  23402. }
  23403. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23404. const int value) throw()
  23405. {
  23406. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23407. }
  23408. bool MidiMessage::isFullFrame() const throw()
  23409. {
  23410. return data[0] == 0xf0
  23411. && data[1] == 0x7f
  23412. && size >= 10
  23413. && data[3] == 0x01
  23414. && data[4] == 0x01;
  23415. }
  23416. void MidiMessage::getFullFrameParameters (int& hours,
  23417. int& minutes,
  23418. int& seconds,
  23419. int& frames,
  23420. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23421. {
  23422. jassert (isFullFrame());
  23423. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23424. hours = data[5] & 0x1f;
  23425. minutes = data[6];
  23426. seconds = data[7];
  23427. frames = data[8];
  23428. }
  23429. const MidiMessage MidiMessage::fullFrame (const int hours,
  23430. const int minutes,
  23431. const int seconds,
  23432. const int frames,
  23433. MidiMessage::SmpteTimecodeType timecodeType)
  23434. {
  23435. uint8 d[10];
  23436. d[0] = 0xf0;
  23437. d[1] = 0x7f;
  23438. d[2] = 0x7f;
  23439. d[3] = 0x01;
  23440. d[4] = 0x01;
  23441. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23442. d[6] = (uint8) minutes;
  23443. d[7] = (uint8) seconds;
  23444. d[8] = (uint8) frames;
  23445. d[9] = 0xf7;
  23446. return MidiMessage (d, 10, 0.0);
  23447. }
  23448. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23449. {
  23450. return data[0] == 0xf0
  23451. && data[1] == 0x7f
  23452. && data[3] == 0x06
  23453. && size > 5;
  23454. }
  23455. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23456. {
  23457. jassert (isMidiMachineControlMessage());
  23458. return (MidiMachineControlCommand) data[4];
  23459. }
  23460. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23461. {
  23462. uint8 d[6];
  23463. d[0] = 0xf0;
  23464. d[1] = 0x7f;
  23465. d[2] = 0x00;
  23466. d[3] = 0x06;
  23467. d[4] = (uint8) command;
  23468. d[5] = 0xf7;
  23469. return MidiMessage (d, 6, 0.0);
  23470. }
  23471. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23472. int& minutes,
  23473. int& seconds,
  23474. int& frames) const throw()
  23475. {
  23476. if (size >= 12
  23477. && data[0] == 0xf0
  23478. && data[1] == 0x7f
  23479. && data[3] == 0x06
  23480. && data[4] == 0x44
  23481. && data[5] == 0x06
  23482. && data[6] == 0x01)
  23483. {
  23484. hours = data[7] % 24; // (that some machines send out hours > 24)
  23485. minutes = data[8];
  23486. seconds = data[9];
  23487. frames = data[10];
  23488. return true;
  23489. }
  23490. return false;
  23491. }
  23492. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23493. int minutes,
  23494. int seconds,
  23495. int frames)
  23496. {
  23497. uint8 d[12];
  23498. d[0] = 0xf0;
  23499. d[1] = 0x7f;
  23500. d[2] = 0x00;
  23501. d[3] = 0x06;
  23502. d[4] = 0x44;
  23503. d[5] = 0x06;
  23504. d[6] = 0x01;
  23505. d[7] = (uint8) hours;
  23506. d[8] = (uint8) minutes;
  23507. d[9] = (uint8) seconds;
  23508. d[10] = (uint8) frames;
  23509. d[11] = 0xf7;
  23510. return MidiMessage (d, 12, 0.0);
  23511. }
  23512. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23513. {
  23514. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23515. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23516. if (isPositiveAndBelow (note, (int) 128))
  23517. {
  23518. String s (useSharps ? sharpNoteNames [note % 12]
  23519. : flatNoteNames [note % 12]);
  23520. if (includeOctaveNumber)
  23521. s << (note / 12 + (octaveNumForMiddleC - 5));
  23522. return s;
  23523. }
  23524. return String::empty;
  23525. }
  23526. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23527. {
  23528. noteNumber -= 12 * 6 + 9; // now 0 = A
  23529. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23530. }
  23531. const String MidiMessage::getGMInstrumentName (const int n)
  23532. {
  23533. const char* names[] =
  23534. {
  23535. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23536. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23537. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23538. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23539. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23540. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23541. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23542. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23543. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23544. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23545. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23546. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23547. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23548. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23549. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23550. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23551. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23552. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23553. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23554. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23555. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23556. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23557. "Applause", "Gunshot"
  23558. };
  23559. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23560. }
  23561. const String MidiMessage::getGMInstrumentBankName (const int n)
  23562. {
  23563. const char* names[] =
  23564. {
  23565. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23566. "Bass", "Strings", "Ensemble", "Brass",
  23567. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23568. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23569. };
  23570. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23571. }
  23572. const String MidiMessage::getRhythmInstrumentName (const int n)
  23573. {
  23574. const char* names[] =
  23575. {
  23576. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23577. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23578. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23579. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23580. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23581. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23582. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23583. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23584. "Mute Triangle", "Open Triangle"
  23585. };
  23586. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23587. }
  23588. const String MidiMessage::getControllerName (const int n)
  23589. {
  23590. const char* names[] =
  23591. {
  23592. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23593. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23594. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23595. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23596. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23597. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23598. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23599. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23600. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23601. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23602. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23603. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23604. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23605. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23606. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23607. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23608. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23609. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23610. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23612. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23613. "Poly Operation"
  23614. };
  23615. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23616. }
  23617. END_JUCE_NAMESPACE
  23618. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23619. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23620. BEGIN_JUCE_NAMESPACE
  23621. MidiMessageCollector::MidiMessageCollector()
  23622. : lastCallbackTime (0),
  23623. sampleRate (44100.0001)
  23624. {
  23625. }
  23626. MidiMessageCollector::~MidiMessageCollector()
  23627. {
  23628. }
  23629. void MidiMessageCollector::reset (const double sampleRate_)
  23630. {
  23631. jassert (sampleRate_ > 0);
  23632. const ScopedLock sl (midiCallbackLock);
  23633. sampleRate = sampleRate_;
  23634. incomingMessages.clear();
  23635. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23636. }
  23637. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23638. {
  23639. // you need to call reset() to set the correct sample rate before using this object
  23640. jassert (sampleRate != 44100.0001);
  23641. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23642. // for details of what the number should be.
  23643. jassert (message.getTimeStamp() != 0);
  23644. const ScopedLock sl (midiCallbackLock);
  23645. const int sampleNumber
  23646. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23647. incomingMessages.addEvent (message, sampleNumber);
  23648. // if the messages don't get used for over a second, we'd better
  23649. // get rid of any old ones to avoid the queue getting too big
  23650. if (sampleNumber > sampleRate)
  23651. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23652. }
  23653. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23654. const int numSamples)
  23655. {
  23656. // you need to call reset() to set the correct sample rate before using this object
  23657. jassert (sampleRate != 44100.0001);
  23658. const double timeNow = Time::getMillisecondCounterHiRes();
  23659. const double msElapsed = timeNow - lastCallbackTime;
  23660. const ScopedLock sl (midiCallbackLock);
  23661. lastCallbackTime = timeNow;
  23662. if (! incomingMessages.isEmpty())
  23663. {
  23664. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23665. int startSample = 0;
  23666. int scale = 1 << 16;
  23667. const uint8* midiData;
  23668. int numBytes, samplePosition;
  23669. MidiBuffer::Iterator iter (incomingMessages);
  23670. if (numSourceSamples > numSamples)
  23671. {
  23672. // if our list of events is longer than the buffer we're being
  23673. // asked for, scale them down to squeeze them all in..
  23674. const int maxBlockLengthToUse = numSamples << 5;
  23675. if (numSourceSamples > maxBlockLengthToUse)
  23676. {
  23677. startSample = numSourceSamples - maxBlockLengthToUse;
  23678. numSourceSamples = maxBlockLengthToUse;
  23679. iter.setNextSamplePosition (startSample);
  23680. }
  23681. scale = (numSamples << 10) / numSourceSamples;
  23682. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23683. {
  23684. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23685. destBuffer.addEvent (midiData, numBytes,
  23686. jlimit (0, numSamples - 1, samplePosition));
  23687. }
  23688. }
  23689. else
  23690. {
  23691. // if our event list is shorter than the number we need, put them
  23692. // towards the end of the buffer
  23693. startSample = numSamples - numSourceSamples;
  23694. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23695. {
  23696. destBuffer.addEvent (midiData, numBytes,
  23697. jlimit (0, numSamples - 1, samplePosition + startSample));
  23698. }
  23699. }
  23700. incomingMessages.clear();
  23701. }
  23702. }
  23703. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23704. {
  23705. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23706. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23707. addMessageToQueue (m);
  23708. }
  23709. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23710. {
  23711. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23712. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23713. addMessageToQueue (m);
  23714. }
  23715. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23716. {
  23717. addMessageToQueue (message);
  23718. }
  23719. END_JUCE_NAMESPACE
  23720. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23721. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23722. BEGIN_JUCE_NAMESPACE
  23723. MidiMessageSequence::MidiMessageSequence()
  23724. {
  23725. }
  23726. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23727. {
  23728. list.ensureStorageAllocated (other.list.size());
  23729. for (int i = 0; i < other.list.size(); ++i)
  23730. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23731. }
  23732. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23733. {
  23734. MidiMessageSequence otherCopy (other);
  23735. swapWith (otherCopy);
  23736. return *this;
  23737. }
  23738. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23739. {
  23740. list.swapWithArray (other.list);
  23741. }
  23742. MidiMessageSequence::~MidiMessageSequence()
  23743. {
  23744. }
  23745. void MidiMessageSequence::clear()
  23746. {
  23747. list.clear();
  23748. }
  23749. int MidiMessageSequence::getNumEvents() const
  23750. {
  23751. return list.size();
  23752. }
  23753. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23754. {
  23755. return list [index];
  23756. }
  23757. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23758. {
  23759. const MidiEventHolder* const meh = list [index];
  23760. if (meh != 0 && meh->noteOffObject != 0)
  23761. return meh->noteOffObject->message.getTimeStamp();
  23762. else
  23763. return 0.0;
  23764. }
  23765. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23766. {
  23767. const MidiEventHolder* const meh = list [index];
  23768. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23769. }
  23770. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23771. {
  23772. return list.indexOf (event);
  23773. }
  23774. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23775. {
  23776. const int numEvents = list.size();
  23777. int i;
  23778. for (i = 0; i < numEvents; ++i)
  23779. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23780. break;
  23781. return i;
  23782. }
  23783. double MidiMessageSequence::getStartTime() const
  23784. {
  23785. if (list.size() > 0)
  23786. return list.getUnchecked(0)->message.getTimeStamp();
  23787. else
  23788. return 0;
  23789. }
  23790. double MidiMessageSequence::getEndTime() const
  23791. {
  23792. if (list.size() > 0)
  23793. return list.getLast()->message.getTimeStamp();
  23794. else
  23795. return 0;
  23796. }
  23797. double MidiMessageSequence::getEventTime (const int index) const
  23798. {
  23799. if (isPositiveAndBelow (index, list.size()))
  23800. return list.getUnchecked (index)->message.getTimeStamp();
  23801. return 0.0;
  23802. }
  23803. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23804. double timeAdjustment)
  23805. {
  23806. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23807. timeAdjustment += newMessage.getTimeStamp();
  23808. newOne->message.setTimeStamp (timeAdjustment);
  23809. int i;
  23810. for (i = list.size(); --i >= 0;)
  23811. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23812. break;
  23813. list.insert (i + 1, newOne);
  23814. }
  23815. void MidiMessageSequence::deleteEvent (const int index,
  23816. const bool deleteMatchingNoteUp)
  23817. {
  23818. if (isPositiveAndBelow (index, list.size()))
  23819. {
  23820. if (deleteMatchingNoteUp)
  23821. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23822. list.remove (index);
  23823. }
  23824. }
  23825. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23826. double timeAdjustment,
  23827. double firstAllowableTime,
  23828. double endOfAllowableDestTimes)
  23829. {
  23830. firstAllowableTime -= timeAdjustment;
  23831. endOfAllowableDestTimes -= timeAdjustment;
  23832. for (int i = 0; i < other.list.size(); ++i)
  23833. {
  23834. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23835. const double t = m.getTimeStamp();
  23836. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23837. {
  23838. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23839. newOne->message.setTimeStamp (timeAdjustment + t);
  23840. list.add (newOne);
  23841. }
  23842. }
  23843. sort();
  23844. }
  23845. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23846. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23847. {
  23848. const double diff = first->message.getTimeStamp()
  23849. - second->message.getTimeStamp();
  23850. return (diff > 0) - (diff < 0);
  23851. }
  23852. void MidiMessageSequence::sort()
  23853. {
  23854. list.sort (*this, true);
  23855. }
  23856. void MidiMessageSequence::updateMatchedPairs()
  23857. {
  23858. for (int i = 0; i < list.size(); ++i)
  23859. {
  23860. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23861. if (m1.isNoteOn())
  23862. {
  23863. list.getUnchecked(i)->noteOffObject = 0;
  23864. const int note = m1.getNoteNumber();
  23865. const int chan = m1.getChannel();
  23866. const int len = list.size();
  23867. for (int j = i + 1; j < len; ++j)
  23868. {
  23869. const MidiMessage& m = list.getUnchecked(j)->message;
  23870. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23871. {
  23872. if (m.isNoteOff())
  23873. {
  23874. list.getUnchecked(i)->noteOffObject = list[j];
  23875. break;
  23876. }
  23877. else if (m.isNoteOn())
  23878. {
  23879. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23880. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23881. list.getUnchecked(i)->noteOffObject = list[j];
  23882. break;
  23883. }
  23884. }
  23885. }
  23886. }
  23887. }
  23888. }
  23889. void MidiMessageSequence::addTimeToMessages (const double delta)
  23890. {
  23891. for (int i = list.size(); --i >= 0;)
  23892. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23893. + delta);
  23894. }
  23895. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23896. MidiMessageSequence& destSequence,
  23897. const bool alsoIncludeMetaEvents) const
  23898. {
  23899. for (int i = 0; i < list.size(); ++i)
  23900. {
  23901. const MidiMessage& mm = list.getUnchecked(i)->message;
  23902. if (mm.isForChannel (channelNumberToExtract)
  23903. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23904. {
  23905. destSequence.addEvent (mm);
  23906. }
  23907. }
  23908. }
  23909. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23910. {
  23911. for (int i = 0; i < list.size(); ++i)
  23912. {
  23913. const MidiMessage& mm = list.getUnchecked(i)->message;
  23914. if (mm.isSysEx())
  23915. destSequence.addEvent (mm);
  23916. }
  23917. }
  23918. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23919. {
  23920. for (int i = list.size(); --i >= 0;)
  23921. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23922. list.remove(i);
  23923. }
  23924. void MidiMessageSequence::deleteSysExMessages()
  23925. {
  23926. for (int i = list.size(); --i >= 0;)
  23927. if (list.getUnchecked(i)->message.isSysEx())
  23928. list.remove(i);
  23929. }
  23930. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23931. const double time,
  23932. OwnedArray<MidiMessage>& dest)
  23933. {
  23934. bool doneProg = false;
  23935. bool donePitchWheel = false;
  23936. Array <int> doneControllers;
  23937. doneControllers.ensureStorageAllocated (32);
  23938. for (int i = list.size(); --i >= 0;)
  23939. {
  23940. const MidiMessage& mm = list.getUnchecked(i)->message;
  23941. if (mm.isForChannel (channelNumber)
  23942. && mm.getTimeStamp() <= time)
  23943. {
  23944. if (mm.isProgramChange())
  23945. {
  23946. if (! doneProg)
  23947. {
  23948. dest.add (new MidiMessage (mm, 0.0));
  23949. doneProg = true;
  23950. }
  23951. }
  23952. else if (mm.isController())
  23953. {
  23954. if (! doneControllers.contains (mm.getControllerNumber()))
  23955. {
  23956. dest.add (new MidiMessage (mm, 0.0));
  23957. doneControllers.add (mm.getControllerNumber());
  23958. }
  23959. }
  23960. else if (mm.isPitchWheel())
  23961. {
  23962. if (! donePitchWheel)
  23963. {
  23964. dest.add (new MidiMessage (mm, 0.0));
  23965. donePitchWheel = true;
  23966. }
  23967. }
  23968. }
  23969. }
  23970. }
  23971. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23972. : message (message_),
  23973. noteOffObject (0)
  23974. {
  23975. }
  23976. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23977. {
  23978. }
  23979. END_JUCE_NAMESPACE
  23980. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23981. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23982. BEGIN_JUCE_NAMESPACE
  23983. AudioPluginFormat::AudioPluginFormat() throw()
  23984. {
  23985. }
  23986. AudioPluginFormat::~AudioPluginFormat()
  23987. {
  23988. }
  23989. END_JUCE_NAMESPACE
  23990. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23991. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23992. BEGIN_JUCE_NAMESPACE
  23993. AudioPluginFormatManager::AudioPluginFormatManager()
  23994. {
  23995. }
  23996. AudioPluginFormatManager::~AudioPluginFormatManager()
  23997. {
  23998. clearSingletonInstance();
  23999. }
  24000. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24001. void AudioPluginFormatManager::addDefaultFormats()
  24002. {
  24003. #if JUCE_DEBUG
  24004. // you should only call this method once!
  24005. for (int i = formats.size(); --i >= 0;)
  24006. {
  24007. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24008. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24009. #endif
  24010. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24011. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24012. #endif
  24013. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24014. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24015. #endif
  24016. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24017. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24018. #endif
  24019. }
  24020. #endif
  24021. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24022. formats.add (new AudioUnitPluginFormat());
  24023. #endif
  24024. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24025. formats.add (new VSTPluginFormat());
  24026. #endif
  24027. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24028. formats.add (new DirectXPluginFormat());
  24029. #endif
  24030. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24031. formats.add (new LADSPAPluginFormat());
  24032. #endif
  24033. }
  24034. int AudioPluginFormatManager::getNumFormats()
  24035. {
  24036. return formats.size();
  24037. }
  24038. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24039. {
  24040. return formats [index];
  24041. }
  24042. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24043. {
  24044. formats.add (format);
  24045. }
  24046. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24047. String& errorMessage) const
  24048. {
  24049. AudioPluginInstance* result = 0;
  24050. for (int i = 0; i < formats.size(); ++i)
  24051. {
  24052. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24053. if (result != 0)
  24054. break;
  24055. }
  24056. if (result == 0)
  24057. {
  24058. if (! doesPluginStillExist (description))
  24059. errorMessage = TRANS ("This plug-in file no longer exists");
  24060. else
  24061. errorMessage = TRANS ("This plug-in failed to load correctly");
  24062. }
  24063. return result;
  24064. }
  24065. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24066. {
  24067. for (int i = 0; i < formats.size(); ++i)
  24068. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24069. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24070. return false;
  24071. }
  24072. END_JUCE_NAMESPACE
  24073. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24074. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24075. #define JUCE_PLUGIN_HOST 1
  24076. BEGIN_JUCE_NAMESPACE
  24077. AudioPluginInstance::AudioPluginInstance()
  24078. {
  24079. }
  24080. AudioPluginInstance::~AudioPluginInstance()
  24081. {
  24082. }
  24083. void* AudioPluginInstance::getPlatformSpecificData()
  24084. {
  24085. return 0;
  24086. }
  24087. END_JUCE_NAMESPACE
  24088. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24089. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24090. BEGIN_JUCE_NAMESPACE
  24091. KnownPluginList::KnownPluginList()
  24092. {
  24093. }
  24094. KnownPluginList::~KnownPluginList()
  24095. {
  24096. }
  24097. void KnownPluginList::clear()
  24098. {
  24099. if (types.size() > 0)
  24100. {
  24101. types.clear();
  24102. sendChangeMessage();
  24103. }
  24104. }
  24105. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24106. {
  24107. for (int i = 0; i < types.size(); ++i)
  24108. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24109. return types.getUnchecked(i);
  24110. return 0;
  24111. }
  24112. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24113. {
  24114. for (int i = 0; i < types.size(); ++i)
  24115. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24116. return types.getUnchecked(i);
  24117. return 0;
  24118. }
  24119. bool KnownPluginList::addType (const PluginDescription& type)
  24120. {
  24121. for (int i = types.size(); --i >= 0;)
  24122. {
  24123. if (types.getUnchecked(i)->isDuplicateOf (type))
  24124. {
  24125. // strange - found a duplicate plugin with different info..
  24126. jassert (types.getUnchecked(i)->name == type.name);
  24127. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24128. *types.getUnchecked(i) = type;
  24129. return false;
  24130. }
  24131. }
  24132. types.add (new PluginDescription (type));
  24133. sendChangeMessage();
  24134. return true;
  24135. }
  24136. void KnownPluginList::removeType (const int index)
  24137. {
  24138. types.remove (index);
  24139. sendChangeMessage();
  24140. }
  24141. namespace
  24142. {
  24143. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24144. {
  24145. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24146. return File (fileOrIdentifier).getLastModificationTime();
  24147. return Time();
  24148. }
  24149. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24150. {
  24151. return t1 != t2 || t1 == Time();
  24152. }
  24153. }
  24154. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24155. {
  24156. if (getTypeForFile (fileOrIdentifier) == 0)
  24157. return false;
  24158. for (int i = types.size(); --i >= 0;)
  24159. {
  24160. const PluginDescription* const d = types.getUnchecked(i);
  24161. if (d->fileOrIdentifier == fileOrIdentifier
  24162. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24163. {
  24164. return false;
  24165. }
  24166. }
  24167. return true;
  24168. }
  24169. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24170. const bool dontRescanIfAlreadyInList,
  24171. OwnedArray <PluginDescription>& typesFound,
  24172. AudioPluginFormat& format)
  24173. {
  24174. bool addedOne = false;
  24175. if (dontRescanIfAlreadyInList
  24176. && getTypeForFile (fileOrIdentifier) != 0)
  24177. {
  24178. bool needsRescanning = false;
  24179. for (int i = types.size(); --i >= 0;)
  24180. {
  24181. const PluginDescription* const d = types.getUnchecked(i);
  24182. if (d->fileOrIdentifier == fileOrIdentifier)
  24183. {
  24184. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24185. needsRescanning = true;
  24186. else
  24187. typesFound.add (new PluginDescription (*d));
  24188. }
  24189. }
  24190. if (! needsRescanning)
  24191. return false;
  24192. }
  24193. OwnedArray <PluginDescription> found;
  24194. format.findAllTypesForFile (found, fileOrIdentifier);
  24195. for (int i = 0; i < found.size(); ++i)
  24196. {
  24197. PluginDescription* const desc = found.getUnchecked(i);
  24198. jassert (desc != 0);
  24199. if (addType (*desc))
  24200. addedOne = true;
  24201. typesFound.add (new PluginDescription (*desc));
  24202. }
  24203. return addedOne;
  24204. }
  24205. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24206. OwnedArray <PluginDescription>& typesFound)
  24207. {
  24208. for (int i = 0; i < files.size(); ++i)
  24209. {
  24210. bool loaded = false;
  24211. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24212. {
  24213. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24214. if (scanAndAddFile (files[i], true, typesFound, *format))
  24215. loaded = true;
  24216. }
  24217. if (! loaded)
  24218. {
  24219. const File f (files[i]);
  24220. if (f.isDirectory())
  24221. {
  24222. StringArray s;
  24223. {
  24224. Array<File> subFiles;
  24225. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24226. for (int j = 0; j < subFiles.size(); ++j)
  24227. s.add (subFiles.getReference(j).getFullPathName());
  24228. }
  24229. scanAndAddDragAndDroppedFiles (s, typesFound);
  24230. }
  24231. }
  24232. }
  24233. }
  24234. class PluginSorter
  24235. {
  24236. public:
  24237. KnownPluginList::SortMethod method;
  24238. PluginSorter() throw() {}
  24239. int compareElements (const PluginDescription* const first,
  24240. const PluginDescription* const second) const
  24241. {
  24242. int diff = 0;
  24243. if (method == KnownPluginList::sortByCategory)
  24244. diff = first->category.compareLexicographically (second->category);
  24245. else if (method == KnownPluginList::sortByManufacturer)
  24246. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24247. else if (method == KnownPluginList::sortByFileSystemLocation)
  24248. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24249. .upToLastOccurrenceOf ("/", false, false)
  24250. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24251. .upToLastOccurrenceOf ("/", false, false));
  24252. if (diff == 0)
  24253. diff = first->name.compareLexicographically (second->name);
  24254. return diff;
  24255. }
  24256. };
  24257. void KnownPluginList::sort (const SortMethod method)
  24258. {
  24259. if (method != defaultOrder)
  24260. {
  24261. PluginSorter sorter;
  24262. sorter.method = method;
  24263. types.sort (sorter, true);
  24264. sendChangeMessage();
  24265. }
  24266. }
  24267. XmlElement* KnownPluginList::createXml() const
  24268. {
  24269. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24270. for (int i = 0; i < types.size(); ++i)
  24271. e->addChildElement (types.getUnchecked(i)->createXml());
  24272. return e;
  24273. }
  24274. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24275. {
  24276. clear();
  24277. if (xml.hasTagName ("KNOWNPLUGINS"))
  24278. {
  24279. forEachXmlChildElement (xml, e)
  24280. {
  24281. PluginDescription info;
  24282. if (info.loadFromXml (*e))
  24283. addType (info);
  24284. }
  24285. }
  24286. }
  24287. const int menuIdBase = 0x324503f4;
  24288. // This is used to turn a bunch of paths into a nested menu structure.
  24289. struct PluginFilesystemTree
  24290. {
  24291. private:
  24292. String folder;
  24293. OwnedArray <PluginFilesystemTree> subFolders;
  24294. Array <PluginDescription*> plugins;
  24295. void addPlugin (PluginDescription* const pd, const String& path)
  24296. {
  24297. if (path.isEmpty())
  24298. {
  24299. plugins.add (pd);
  24300. }
  24301. else
  24302. {
  24303. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24304. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24305. for (int i = subFolders.size(); --i >= 0;)
  24306. {
  24307. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24308. {
  24309. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24310. return;
  24311. }
  24312. }
  24313. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24314. newFolder->folder = firstSubFolder;
  24315. subFolders.add (newFolder);
  24316. newFolder->addPlugin (pd, remainingPath);
  24317. }
  24318. }
  24319. // removes any deeply nested folders that don't contain any actual plugins
  24320. void optimise()
  24321. {
  24322. for (int i = subFolders.size(); --i >= 0;)
  24323. {
  24324. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24325. sub->optimise();
  24326. if (sub->plugins.size() == 0)
  24327. {
  24328. for (int j = 0; j < sub->subFolders.size(); ++j)
  24329. subFolders.add (sub->subFolders.getUnchecked(j));
  24330. sub->subFolders.clear (false);
  24331. subFolders.remove (i);
  24332. }
  24333. }
  24334. }
  24335. public:
  24336. void buildTree (const Array <PluginDescription*>& allPlugins)
  24337. {
  24338. for (int i = 0; i < allPlugins.size(); ++i)
  24339. {
  24340. String path (allPlugins.getUnchecked(i)
  24341. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24342. .upToLastOccurrenceOf ("/", false, false));
  24343. if (path.substring (1, 2) == ":")
  24344. path = path.substring (2);
  24345. addPlugin (allPlugins.getUnchecked(i), path);
  24346. }
  24347. optimise();
  24348. }
  24349. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24350. {
  24351. int i;
  24352. for (i = 0; i < subFolders.size(); ++i)
  24353. {
  24354. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24355. PopupMenu subMenu;
  24356. sub->addToMenu (subMenu, allPlugins);
  24357. #if JUCE_MAC
  24358. // avoid the special AU formatting nonsense on Mac..
  24359. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24360. #else
  24361. m.addSubMenu (sub->folder, subMenu);
  24362. #endif
  24363. }
  24364. for (i = 0; i < plugins.size(); ++i)
  24365. {
  24366. PluginDescription* const plugin = plugins.getUnchecked(i);
  24367. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24368. plugin->name, true, false);
  24369. }
  24370. }
  24371. };
  24372. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24373. {
  24374. Array <PluginDescription*> sorted;
  24375. {
  24376. PluginSorter sorter;
  24377. sorter.method = sortMethod;
  24378. for (int i = 0; i < types.size(); ++i)
  24379. sorted.addSorted (sorter, types.getUnchecked(i));
  24380. }
  24381. if (sortMethod == sortByCategory
  24382. || sortMethod == sortByManufacturer)
  24383. {
  24384. String lastSubMenuName;
  24385. PopupMenu sub;
  24386. for (int i = 0; i < sorted.size(); ++i)
  24387. {
  24388. const PluginDescription* const pd = sorted.getUnchecked(i);
  24389. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24390. : pd->manufacturerName);
  24391. if (! thisSubMenuName.containsNonWhitespaceChars())
  24392. thisSubMenuName = "Other";
  24393. if (thisSubMenuName != lastSubMenuName)
  24394. {
  24395. if (sub.getNumItems() > 0)
  24396. {
  24397. menu.addSubMenu (lastSubMenuName, sub);
  24398. sub.clear();
  24399. }
  24400. lastSubMenuName = thisSubMenuName;
  24401. }
  24402. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24403. }
  24404. if (sub.getNumItems() > 0)
  24405. menu.addSubMenu (lastSubMenuName, sub);
  24406. }
  24407. else if (sortMethod == sortByFileSystemLocation)
  24408. {
  24409. PluginFilesystemTree root;
  24410. root.buildTree (sorted);
  24411. root.addToMenu (menu, types);
  24412. }
  24413. else
  24414. {
  24415. for (int i = 0; i < sorted.size(); ++i)
  24416. {
  24417. const PluginDescription* const pd = sorted.getUnchecked(i);
  24418. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24419. }
  24420. }
  24421. }
  24422. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24423. {
  24424. const int i = menuResultCode - menuIdBase;
  24425. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24426. }
  24427. END_JUCE_NAMESPACE
  24428. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24429. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24430. BEGIN_JUCE_NAMESPACE
  24431. PluginDescription::PluginDescription()
  24432. : uid (0),
  24433. isInstrument (false),
  24434. numInputChannels (0),
  24435. numOutputChannels (0)
  24436. {
  24437. }
  24438. PluginDescription::~PluginDescription()
  24439. {
  24440. }
  24441. PluginDescription::PluginDescription (const PluginDescription& other)
  24442. : name (other.name),
  24443. descriptiveName (other.descriptiveName),
  24444. pluginFormatName (other.pluginFormatName),
  24445. category (other.category),
  24446. manufacturerName (other.manufacturerName),
  24447. version (other.version),
  24448. fileOrIdentifier (other.fileOrIdentifier),
  24449. lastFileModTime (other.lastFileModTime),
  24450. uid (other.uid),
  24451. isInstrument (other.isInstrument),
  24452. numInputChannels (other.numInputChannels),
  24453. numOutputChannels (other.numOutputChannels)
  24454. {
  24455. }
  24456. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24457. {
  24458. name = other.name;
  24459. descriptiveName = other.descriptiveName;
  24460. pluginFormatName = other.pluginFormatName;
  24461. category = other.category;
  24462. manufacturerName = other.manufacturerName;
  24463. version = other.version;
  24464. fileOrIdentifier = other.fileOrIdentifier;
  24465. uid = other.uid;
  24466. isInstrument = other.isInstrument;
  24467. lastFileModTime = other.lastFileModTime;
  24468. numInputChannels = other.numInputChannels;
  24469. numOutputChannels = other.numOutputChannels;
  24470. return *this;
  24471. }
  24472. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24473. {
  24474. return fileOrIdentifier == other.fileOrIdentifier
  24475. && uid == other.uid;
  24476. }
  24477. const String PluginDescription::createIdentifierString() const
  24478. {
  24479. return pluginFormatName
  24480. + "-" + name
  24481. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24482. + "-" + String::toHexString (uid);
  24483. }
  24484. XmlElement* PluginDescription::createXml() const
  24485. {
  24486. XmlElement* const e = new XmlElement ("PLUGIN");
  24487. e->setAttribute ("name", name);
  24488. if (descriptiveName != name)
  24489. e->setAttribute ("descriptiveName", descriptiveName);
  24490. e->setAttribute ("format", pluginFormatName);
  24491. e->setAttribute ("category", category);
  24492. e->setAttribute ("manufacturer", manufacturerName);
  24493. e->setAttribute ("version", version);
  24494. e->setAttribute ("file", fileOrIdentifier);
  24495. e->setAttribute ("uid", String::toHexString (uid));
  24496. e->setAttribute ("isInstrument", isInstrument);
  24497. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24498. e->setAttribute ("numInputs", numInputChannels);
  24499. e->setAttribute ("numOutputs", numOutputChannels);
  24500. return e;
  24501. }
  24502. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24503. {
  24504. if (xml.hasTagName ("PLUGIN"))
  24505. {
  24506. name = xml.getStringAttribute ("name");
  24507. descriptiveName = xml.getStringAttribute ("name", name);
  24508. pluginFormatName = xml.getStringAttribute ("format");
  24509. category = xml.getStringAttribute ("category");
  24510. manufacturerName = xml.getStringAttribute ("manufacturer");
  24511. version = xml.getStringAttribute ("version");
  24512. fileOrIdentifier = xml.getStringAttribute ("file");
  24513. uid = xml.getStringAttribute ("uid").getHexValue32();
  24514. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24515. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24516. numInputChannels = xml.getIntAttribute ("numInputs");
  24517. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24518. return true;
  24519. }
  24520. return false;
  24521. }
  24522. END_JUCE_NAMESPACE
  24523. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24524. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24525. BEGIN_JUCE_NAMESPACE
  24526. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24527. AudioPluginFormat& formatToLookFor,
  24528. FileSearchPath directoriesToSearch,
  24529. const bool recursive,
  24530. const File& deadMansPedalFile_)
  24531. : list (listToAddTo),
  24532. format (formatToLookFor),
  24533. deadMansPedalFile (deadMansPedalFile_),
  24534. nextIndex (0),
  24535. progress (0)
  24536. {
  24537. directoriesToSearch.removeRedundantPaths();
  24538. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24539. // If any plugins have crashed recently when being loaded, move them to the
  24540. // end of the list to give the others a chance to load correctly..
  24541. const StringArray crashedPlugins (getDeadMansPedalFile());
  24542. for (int i = 0; i < crashedPlugins.size(); ++i)
  24543. {
  24544. const String f = crashedPlugins[i];
  24545. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24546. if (f == filesOrIdentifiersToScan[j])
  24547. filesOrIdentifiersToScan.move (j, -1);
  24548. }
  24549. }
  24550. PluginDirectoryScanner::~PluginDirectoryScanner()
  24551. {
  24552. }
  24553. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24554. {
  24555. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24556. }
  24557. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24558. {
  24559. String file (filesOrIdentifiersToScan [nextIndex]);
  24560. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24561. {
  24562. OwnedArray <PluginDescription> typesFound;
  24563. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24564. StringArray crashedPlugins (getDeadMansPedalFile());
  24565. crashedPlugins.removeString (file);
  24566. crashedPlugins.add (file);
  24567. setDeadMansPedalFile (crashedPlugins);
  24568. list.scanAndAddFile (file,
  24569. dontRescanIfAlreadyInList,
  24570. typesFound,
  24571. format);
  24572. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24573. crashedPlugins.removeString (file);
  24574. setDeadMansPedalFile (crashedPlugins);
  24575. if (typesFound.size() == 0)
  24576. failedFiles.add (file);
  24577. }
  24578. return skipNextFile();
  24579. }
  24580. bool PluginDirectoryScanner::skipNextFile()
  24581. {
  24582. if (nextIndex >= filesOrIdentifiersToScan.size())
  24583. return false;
  24584. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24585. return nextIndex < filesOrIdentifiersToScan.size();
  24586. }
  24587. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24588. {
  24589. StringArray lines;
  24590. if (deadMansPedalFile != File::nonexistent)
  24591. {
  24592. lines.addLines (deadMansPedalFile.loadFileAsString());
  24593. lines.removeEmptyStrings();
  24594. }
  24595. return lines;
  24596. }
  24597. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24598. {
  24599. if (deadMansPedalFile != File::nonexistent)
  24600. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24601. }
  24602. END_JUCE_NAMESPACE
  24603. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24604. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24605. BEGIN_JUCE_NAMESPACE
  24606. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24607. const File& deadMansPedalFile_,
  24608. PropertiesFile* const propertiesToUse_)
  24609. : list (listToEdit),
  24610. deadMansPedalFile (deadMansPedalFile_),
  24611. optionsButton ("Options..."),
  24612. propertiesToUse (propertiesToUse_)
  24613. {
  24614. listBox.setModel (this);
  24615. addAndMakeVisible (&listBox);
  24616. addAndMakeVisible (&optionsButton);
  24617. optionsButton.addListener (this);
  24618. optionsButton.setTriggeredOnMouseDown (true);
  24619. setSize (400, 600);
  24620. list.addChangeListener (this);
  24621. changeListenerCallback (0);
  24622. }
  24623. PluginListComponent::~PluginListComponent()
  24624. {
  24625. list.removeChangeListener (this);
  24626. }
  24627. void PluginListComponent::resized()
  24628. {
  24629. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24630. optionsButton.changeWidthToFitText (24);
  24631. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24632. }
  24633. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24634. {
  24635. listBox.updateContent();
  24636. listBox.repaint();
  24637. }
  24638. int PluginListComponent::getNumRows()
  24639. {
  24640. return list.getNumTypes();
  24641. }
  24642. void PluginListComponent::paintListBoxItem (int row,
  24643. Graphics& g,
  24644. int width, int height,
  24645. bool rowIsSelected)
  24646. {
  24647. if (rowIsSelected)
  24648. g.fillAll (findColour (TextEditor::highlightColourId));
  24649. const PluginDescription* const pd = list.getType (row);
  24650. if (pd != 0)
  24651. {
  24652. GlyphArrangement ga;
  24653. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24654. g.setColour (Colours::black);
  24655. ga.draw (g);
  24656. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24657. String desc;
  24658. desc << pd->pluginFormatName
  24659. << (pd->isInstrument ? " instrument" : " effect")
  24660. << " - "
  24661. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24662. << " / "
  24663. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24664. if (pd->manufacturerName.isNotEmpty())
  24665. desc << " - " << pd->manufacturerName;
  24666. if (pd->version.isNotEmpty())
  24667. desc << " - " << pd->version;
  24668. if (pd->category.isNotEmpty())
  24669. desc << " - category: '" << pd->category << '\'';
  24670. g.setColour (Colours::grey);
  24671. ga.clear();
  24672. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24673. ga.draw (g);
  24674. }
  24675. }
  24676. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24677. {
  24678. list.removeType (lastRowSelected);
  24679. }
  24680. void PluginListComponent::buttonClicked (Button* button)
  24681. {
  24682. if (button == &optionsButton)
  24683. {
  24684. PopupMenu menu;
  24685. menu.addItem (1, TRANS("Clear list"));
  24686. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24687. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24688. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24689. menu.addSeparator();
  24690. menu.addItem (2, TRANS("Sort alphabetically"));
  24691. menu.addItem (3, TRANS("Sort by category"));
  24692. menu.addItem (4, TRANS("Sort by manufacturer"));
  24693. menu.addSeparator();
  24694. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24695. {
  24696. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24697. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24698. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24699. }
  24700. const int r = menu.showAt (&optionsButton);
  24701. if (r == 1)
  24702. {
  24703. list.clear();
  24704. }
  24705. else if (r == 2)
  24706. {
  24707. list.sort (KnownPluginList::sortAlphabetically);
  24708. }
  24709. else if (r == 3)
  24710. {
  24711. list.sort (KnownPluginList::sortByCategory);
  24712. }
  24713. else if (r == 4)
  24714. {
  24715. list.sort (KnownPluginList::sortByManufacturer);
  24716. }
  24717. else if (r == 5)
  24718. {
  24719. const SparseSet <int> selected (listBox.getSelectedRows());
  24720. for (int i = list.getNumTypes(); --i >= 0;)
  24721. if (selected.contains (i))
  24722. list.removeType (i);
  24723. }
  24724. else if (r == 6)
  24725. {
  24726. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24727. if (desc != 0)
  24728. {
  24729. if (File (desc->fileOrIdentifier).existsAsFile())
  24730. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24731. }
  24732. }
  24733. else if (r == 7)
  24734. {
  24735. for (int i = list.getNumTypes(); --i >= 0;)
  24736. {
  24737. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24738. {
  24739. list.removeType (i);
  24740. }
  24741. }
  24742. }
  24743. else if (r != 0)
  24744. {
  24745. typeToScan = r - 10;
  24746. startTimer (1);
  24747. }
  24748. }
  24749. }
  24750. void PluginListComponent::timerCallback()
  24751. {
  24752. stopTimer();
  24753. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24754. }
  24755. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24756. {
  24757. return true;
  24758. }
  24759. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24760. {
  24761. OwnedArray <PluginDescription> typesFound;
  24762. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24763. }
  24764. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24765. {
  24766. if (format == 0)
  24767. return;
  24768. FileSearchPath path (format->getDefaultLocationsToSearch());
  24769. if (propertiesToUse != 0)
  24770. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24771. {
  24772. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24773. FileSearchPathListComponent pathList;
  24774. pathList.setSize (500, 300);
  24775. pathList.setPath (path);
  24776. aw.addCustomComponent (&pathList);
  24777. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24778. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24779. if (aw.runModalLoop() == 0)
  24780. return;
  24781. path = pathList.getPath();
  24782. }
  24783. if (propertiesToUse != 0)
  24784. {
  24785. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24786. propertiesToUse->saveIfNeeded();
  24787. }
  24788. double progress = 0.0;
  24789. AlertWindow aw (TRANS("Scanning for plugins..."),
  24790. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24791. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24792. aw.addProgressBarComponent (progress);
  24793. aw.enterModalState();
  24794. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24795. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24796. for (;;)
  24797. {
  24798. aw.setMessage (TRANS("Testing:\n\n")
  24799. + scanner.getNextPluginFileThatWillBeScanned());
  24800. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24801. if (! scanner.scanNextFile (true))
  24802. break;
  24803. if (! aw.isCurrentlyModal())
  24804. break;
  24805. progress = scanner.getProgress();
  24806. }
  24807. if (scanner.getFailedFiles().size() > 0)
  24808. {
  24809. StringArray shortNames;
  24810. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24811. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24812. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24813. TRANS("Scan complete"),
  24814. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24815. + shortNames.joinIntoString (", "));
  24816. }
  24817. }
  24818. END_JUCE_NAMESPACE
  24819. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24820. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24821. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24822. #include <AudioUnit/AudioUnit.h>
  24823. #include <AudioUnit/AUCocoaUIView.h>
  24824. #include <CoreAudioKit/AUGenericView.h>
  24825. #if JUCE_SUPPORT_CARBON
  24826. #include <AudioToolbox/AudioUnitUtilities.h>
  24827. #include <AudioUnit/AudioUnitCarbonView.h>
  24828. #endif
  24829. BEGIN_JUCE_NAMESPACE
  24830. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24831. #endif
  24832. #if JUCE_MAC
  24833. // Change this to disable logging of various activities
  24834. #ifndef AU_LOGGING
  24835. #define AU_LOGGING 1
  24836. #endif
  24837. #if AU_LOGGING
  24838. #define log(a) Logger::writeToLog(a);
  24839. #else
  24840. #define log(a)
  24841. #endif
  24842. namespace AudioUnitFormatHelpers
  24843. {
  24844. static int insideCallback = 0;
  24845. const String osTypeToString (OSType type)
  24846. {
  24847. char s[4];
  24848. s[0] = (char) (((uint32) type) >> 24);
  24849. s[1] = (char) (((uint32) type) >> 16);
  24850. s[2] = (char) (((uint32) type) >> 8);
  24851. s[3] = (char) ((uint32) type);
  24852. return String (s, 4);
  24853. }
  24854. OSType stringToOSType (const String& s1)
  24855. {
  24856. const String s (s1 + " ");
  24857. return (((OSType) (unsigned char) s[0]) << 24)
  24858. | (((OSType) (unsigned char) s[1]) << 16)
  24859. | (((OSType) (unsigned char) s[2]) << 8)
  24860. | ((OSType) (unsigned char) s[3]);
  24861. }
  24862. static const char* auIdentifierPrefix = "AudioUnit:";
  24863. const String createAUPluginIdentifier (const ComponentDescription& desc)
  24864. {
  24865. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24866. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24867. String s (auIdentifierPrefix);
  24868. if (desc.componentType == kAudioUnitType_MusicDevice)
  24869. s << "Synths/";
  24870. else if (desc.componentType == kAudioUnitType_MusicEffect
  24871. || desc.componentType == kAudioUnitType_Effect)
  24872. s << "Effects/";
  24873. else if (desc.componentType == kAudioUnitType_Generator)
  24874. s << "Generators/";
  24875. else if (desc.componentType == kAudioUnitType_Panner)
  24876. s << "Panners/";
  24877. s << osTypeToString (desc.componentType) << ","
  24878. << osTypeToString (desc.componentSubType) << ","
  24879. << osTypeToString (desc.componentManufacturer);
  24880. return s;
  24881. }
  24882. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24883. {
  24884. Handle componentNameHandle = NewHandle (sizeof (void*));
  24885. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24886. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24887. {
  24888. ComponentDescription desc;
  24889. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24890. {
  24891. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24892. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24893. if (nameString != 0 && nameString[0] != 0)
  24894. {
  24895. const String all ((const char*) nameString + 1, nameString[0]);
  24896. DBG ("name: "+ all);
  24897. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24898. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24899. }
  24900. if (infoString != 0 && infoString[0] != 0)
  24901. {
  24902. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24903. }
  24904. if (name.isEmpty())
  24905. name = "<Unknown>";
  24906. }
  24907. DisposeHandle (componentNameHandle);
  24908. DisposeHandle (componentInfoHandle);
  24909. }
  24910. }
  24911. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24912. String& name, String& version, String& manufacturer)
  24913. {
  24914. zerostruct (desc);
  24915. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24916. {
  24917. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24918. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24919. StringArray tokens;
  24920. tokens.addTokens (s, ",", String::empty);
  24921. tokens.trim();
  24922. tokens.removeEmptyStrings();
  24923. if (tokens.size() == 3)
  24924. {
  24925. desc.componentType = stringToOSType (tokens[0]);
  24926. desc.componentSubType = stringToOSType (tokens[1]);
  24927. desc.componentManufacturer = stringToOSType (tokens[2]);
  24928. ComponentRecord* comp = FindNextComponent (0, &desc);
  24929. if (comp != 0)
  24930. {
  24931. getAUDetails (comp, name, manufacturer);
  24932. return true;
  24933. }
  24934. }
  24935. }
  24936. return false;
  24937. }
  24938. }
  24939. class AudioUnitPluginWindowCarbon;
  24940. class AudioUnitPluginWindowCocoa;
  24941. class AudioUnitPluginInstance : public AudioPluginInstance
  24942. {
  24943. public:
  24944. ~AudioUnitPluginInstance();
  24945. void initialise();
  24946. // AudioPluginInstance methods:
  24947. void fillInPluginDescription (PluginDescription& desc) const
  24948. {
  24949. desc.name = pluginName;
  24950. desc.descriptiveName = pluginName;
  24951. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24952. desc.uid = ((int) componentDesc.componentType)
  24953. ^ ((int) componentDesc.componentSubType)
  24954. ^ ((int) componentDesc.componentManufacturer);
  24955. desc.lastFileModTime = Time();
  24956. desc.pluginFormatName = "AudioUnit";
  24957. desc.category = getCategory();
  24958. desc.manufacturerName = manufacturer;
  24959. desc.version = version;
  24960. desc.numInputChannels = getNumInputChannels();
  24961. desc.numOutputChannels = getNumOutputChannels();
  24962. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24963. }
  24964. void* getPlatformSpecificData() { return audioUnit; }
  24965. const String getName() const { return pluginName; }
  24966. bool acceptsMidi() const { return wantsMidiMessages; }
  24967. bool producesMidi() const { return false; }
  24968. // AudioProcessor methods:
  24969. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24970. void releaseResources();
  24971. void processBlock (AudioSampleBuffer& buffer,
  24972. MidiBuffer& midiMessages);
  24973. bool hasEditor() const;
  24974. AudioProcessorEditor* createEditor();
  24975. const String getInputChannelName (int index) const;
  24976. bool isInputChannelStereoPair (int index) const;
  24977. const String getOutputChannelName (int index) const;
  24978. bool isOutputChannelStereoPair (int index) const;
  24979. int getNumParameters();
  24980. float getParameter (int index);
  24981. void setParameter (int index, float newValue);
  24982. const String getParameterName (int index);
  24983. const String getParameterText (int index);
  24984. bool isParameterAutomatable (int index) const;
  24985. int getNumPrograms();
  24986. int getCurrentProgram();
  24987. void setCurrentProgram (int index);
  24988. const String getProgramName (int index);
  24989. void changeProgramName (int index, const String& newName);
  24990. void getStateInformation (MemoryBlock& destData);
  24991. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24992. void setStateInformation (const void* data, int sizeInBytes);
  24993. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24994. private:
  24995. friend class AudioUnitPluginWindowCarbon;
  24996. friend class AudioUnitPluginWindowCocoa;
  24997. friend class AudioUnitPluginFormat;
  24998. ComponentDescription componentDesc;
  24999. String pluginName, manufacturer, version;
  25000. String fileOrIdentifier;
  25001. CriticalSection lock;
  25002. bool wantsMidiMessages, wasPlaying, prepared;
  25003. HeapBlock <AudioBufferList> outputBufferList;
  25004. AudioTimeStamp timeStamp;
  25005. AudioSampleBuffer* currentBuffer;
  25006. AudioUnit audioUnit;
  25007. Array <int> parameterIds;
  25008. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25009. void setPluginCallbacks();
  25010. void getParameterListFromPlugin();
  25011. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25012. const AudioTimeStamp* inTimeStamp,
  25013. UInt32 inBusNumber,
  25014. UInt32 inNumberFrames,
  25015. AudioBufferList* ioData) const;
  25016. static OSStatus renderGetInputCallback (void* inRefCon,
  25017. AudioUnitRenderActionFlags* ioActionFlags,
  25018. const AudioTimeStamp* inTimeStamp,
  25019. UInt32 inBusNumber,
  25020. UInt32 inNumberFrames,
  25021. AudioBufferList* ioData)
  25022. {
  25023. return ((AudioUnitPluginInstance*) inRefCon)
  25024. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25025. }
  25026. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25027. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25028. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25029. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25030. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25031. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25032. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25033. {
  25034. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25035. }
  25036. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25037. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25038. Float64* outCurrentMeasureDownBeat)
  25039. {
  25040. return ((AudioUnitPluginInstance*) inHostUserData)
  25041. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25042. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25043. }
  25044. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25045. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25046. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25047. {
  25048. return ((AudioUnitPluginInstance*) inHostUserData)
  25049. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25050. outCurrentSampleInTimeLine, outIsCycling,
  25051. outCycleStartBeat, outCycleEndBeat);
  25052. }
  25053. void getNumChannels (int& numIns, int& numOuts)
  25054. {
  25055. numIns = 0;
  25056. numOuts = 0;
  25057. AUChannelInfo supportedChannels [128];
  25058. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25059. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25060. 0, supportedChannels, &supportedChannelsSize) == noErr
  25061. && supportedChannelsSize > 0)
  25062. {
  25063. int explicitNumIns = 0;
  25064. int explicitNumOuts = 0;
  25065. int maximumNumIns = 0;
  25066. int maximumNumOuts = 0;
  25067. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25068. {
  25069. const int inChannels = (int) supportedChannels[i].inChannels;
  25070. const int outChannels = (int) supportedChannels[i].outChannels;
  25071. if (inChannels < 0)
  25072. maximumNumIns = jmin (maximumNumIns, inChannels);
  25073. else
  25074. explicitNumIns = jmax (explicitNumIns, inChannels);
  25075. if (outChannels < 0)
  25076. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25077. else
  25078. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25079. }
  25080. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25081. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25082. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25083. {
  25084. numIns = numOuts = 2;
  25085. }
  25086. else
  25087. {
  25088. numIns = explicitNumIns;
  25089. numOuts = explicitNumOuts;
  25090. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25091. numIns = 2;
  25092. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25093. numOuts = 2;
  25094. }
  25095. }
  25096. else
  25097. {
  25098. // (this really means the plugin will take any number of ins/outs as long
  25099. // as they are the same)
  25100. numIns = numOuts = 2;
  25101. }
  25102. }
  25103. const String getCategory() const;
  25104. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25105. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25106. };
  25107. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25108. : fileOrIdentifier (fileOrIdentifier),
  25109. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25110. currentBuffer (0),
  25111. audioUnit (0)
  25112. {
  25113. using namespace AudioUnitFormatHelpers;
  25114. try
  25115. {
  25116. ++insideCallback;
  25117. log ("Opening AU: " + fileOrIdentifier);
  25118. if (getComponentDescFromFile (fileOrIdentifier))
  25119. {
  25120. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25121. if (comp != 0)
  25122. {
  25123. audioUnit = (AudioUnit) OpenComponent (comp);
  25124. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25125. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25126. }
  25127. }
  25128. --insideCallback;
  25129. }
  25130. catch (...)
  25131. {
  25132. --insideCallback;
  25133. }
  25134. }
  25135. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25136. {
  25137. const ScopedLock sl (lock);
  25138. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25139. if (audioUnit != 0)
  25140. {
  25141. AudioUnitUninitialize (audioUnit);
  25142. CloseComponent (audioUnit);
  25143. audioUnit = 0;
  25144. }
  25145. }
  25146. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25147. {
  25148. zerostruct (componentDesc);
  25149. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25150. return true;
  25151. const File file (fileOrIdentifier);
  25152. if (! file.hasFileExtension (".component"))
  25153. return false;
  25154. const char* const utf8 = fileOrIdentifier.toUTF8();
  25155. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25156. strlen (utf8), file.isDirectory());
  25157. if (url != 0)
  25158. {
  25159. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25160. CFRelease (url);
  25161. if (bundleRef != 0)
  25162. {
  25163. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25164. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25165. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25166. if (pluginName.isEmpty())
  25167. pluginName = file.getFileNameWithoutExtension();
  25168. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25169. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25170. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25171. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25172. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25173. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25174. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25175. UseResFile (resFileId);
  25176. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25177. {
  25178. Handle h = Get1IndResource ('thng', i);
  25179. if (h != 0)
  25180. {
  25181. HLock (h);
  25182. const uint32* const types = (const uint32*) *h;
  25183. if (types[0] == kAudioUnitType_MusicDevice
  25184. || types[0] == kAudioUnitType_MusicEffect
  25185. || types[0] == kAudioUnitType_Effect
  25186. || types[0] == kAudioUnitType_Generator
  25187. || types[0] == kAudioUnitType_Panner)
  25188. {
  25189. componentDesc.componentType = types[0];
  25190. componentDesc.componentSubType = types[1];
  25191. componentDesc.componentManufacturer = types[2];
  25192. break;
  25193. }
  25194. HUnlock (h);
  25195. ReleaseResource (h);
  25196. }
  25197. }
  25198. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25199. CFRelease (bundleRef);
  25200. }
  25201. }
  25202. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25203. }
  25204. void AudioUnitPluginInstance::initialise()
  25205. {
  25206. getParameterListFromPlugin();
  25207. setPluginCallbacks();
  25208. int numIns, numOuts;
  25209. getNumChannels (numIns, numOuts);
  25210. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25211. setLatencySamples (0);
  25212. }
  25213. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25214. {
  25215. parameterIds.clear();
  25216. if (audioUnit != 0)
  25217. {
  25218. UInt32 paramListSize = 0;
  25219. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25220. 0, 0, &paramListSize);
  25221. if (paramListSize > 0)
  25222. {
  25223. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25224. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25225. 0, &parameterIds.getReference(0), &paramListSize);
  25226. }
  25227. }
  25228. }
  25229. void AudioUnitPluginInstance::setPluginCallbacks()
  25230. {
  25231. if (audioUnit != 0)
  25232. {
  25233. {
  25234. AURenderCallbackStruct info;
  25235. zerostruct (info);
  25236. info.inputProcRefCon = this;
  25237. info.inputProc = renderGetInputCallback;
  25238. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25239. 0, &info, sizeof (info));
  25240. }
  25241. {
  25242. HostCallbackInfo info;
  25243. zerostruct (info);
  25244. info.hostUserData = this;
  25245. info.beatAndTempoProc = getBeatAndTempoCallback;
  25246. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25247. info.transportStateProc = getTransportStateCallback;
  25248. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25249. 0, &info, sizeof (info));
  25250. }
  25251. }
  25252. }
  25253. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25254. int samplesPerBlockExpected)
  25255. {
  25256. if (audioUnit != 0)
  25257. {
  25258. releaseResources();
  25259. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25260. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25261. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25262. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25263. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25264. {
  25265. Float64 sr = sampleRate_;
  25266. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25267. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25268. }
  25269. int numIns, numOuts;
  25270. getNumChannels (numIns, numOuts);
  25271. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25272. Float64 latencySecs = 0.0;
  25273. UInt32 latencySize = sizeof (latencySecs);
  25274. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25275. 0, &latencySecs, &latencySize);
  25276. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25277. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25278. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25279. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25280. {
  25281. AudioStreamBasicDescription stream;
  25282. zerostruct (stream);
  25283. stream.mSampleRate = sampleRate_;
  25284. stream.mFormatID = kAudioFormatLinearPCM;
  25285. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25286. stream.mFramesPerPacket = 1;
  25287. stream.mBytesPerPacket = 4;
  25288. stream.mBytesPerFrame = 4;
  25289. stream.mBitsPerChannel = 32;
  25290. stream.mChannelsPerFrame = numIns;
  25291. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25292. 0, &stream, sizeof (stream));
  25293. stream.mChannelsPerFrame = numOuts;
  25294. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25295. 0, &stream, sizeof (stream));
  25296. }
  25297. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25298. outputBufferList->mNumberBuffers = numOuts;
  25299. for (int i = numOuts; --i >= 0;)
  25300. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25301. zerostruct (timeStamp);
  25302. timeStamp.mSampleTime = 0;
  25303. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25304. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25305. currentBuffer = 0;
  25306. wasPlaying = false;
  25307. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25308. }
  25309. }
  25310. void AudioUnitPluginInstance::releaseResources()
  25311. {
  25312. if (prepared)
  25313. {
  25314. AudioUnitUninitialize (audioUnit);
  25315. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25316. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25317. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25318. outputBufferList.free();
  25319. currentBuffer = 0;
  25320. prepared = false;
  25321. }
  25322. }
  25323. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25324. const AudioTimeStamp* inTimeStamp,
  25325. UInt32 inBusNumber,
  25326. UInt32 inNumberFrames,
  25327. AudioBufferList* ioData) const
  25328. {
  25329. if (inBusNumber == 0
  25330. && currentBuffer != 0)
  25331. {
  25332. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25333. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25334. {
  25335. if (i < currentBuffer->getNumChannels())
  25336. {
  25337. memcpy (ioData->mBuffers[i].mData,
  25338. currentBuffer->getSampleData (i, 0),
  25339. sizeof (float) * inNumberFrames);
  25340. }
  25341. else
  25342. {
  25343. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25344. }
  25345. }
  25346. }
  25347. return noErr;
  25348. }
  25349. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25350. MidiBuffer& midiMessages)
  25351. {
  25352. const int numSamples = buffer.getNumSamples();
  25353. if (prepared)
  25354. {
  25355. AudioUnitRenderActionFlags flags = 0;
  25356. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25357. for (int i = getNumOutputChannels(); --i >= 0;)
  25358. {
  25359. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25360. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25361. }
  25362. currentBuffer = &buffer;
  25363. if (wantsMidiMessages)
  25364. {
  25365. const uint8* midiEventData;
  25366. int midiEventSize, midiEventPosition;
  25367. MidiBuffer::Iterator i (midiMessages);
  25368. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25369. {
  25370. if (midiEventSize <= 3)
  25371. MusicDeviceMIDIEvent (audioUnit,
  25372. midiEventData[0], midiEventData[1], midiEventData[2],
  25373. midiEventPosition);
  25374. else
  25375. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25376. }
  25377. midiMessages.clear();
  25378. }
  25379. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25380. 0, numSamples, outputBufferList);
  25381. timeStamp.mSampleTime += numSamples;
  25382. }
  25383. else
  25384. {
  25385. // Plugin not working correctly, so just bypass..
  25386. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25387. buffer.clear (i, 0, buffer.getNumSamples());
  25388. }
  25389. }
  25390. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25391. {
  25392. AudioPlayHead* const ph = getPlayHead();
  25393. AudioPlayHead::CurrentPositionInfo result;
  25394. if (ph != 0 && ph->getCurrentPosition (result))
  25395. {
  25396. if (outCurrentBeat != 0)
  25397. *outCurrentBeat = result.ppqPosition;
  25398. if (outCurrentTempo != 0)
  25399. *outCurrentTempo = result.bpm;
  25400. }
  25401. else
  25402. {
  25403. if (outCurrentBeat != 0)
  25404. *outCurrentBeat = 0;
  25405. if (outCurrentTempo != 0)
  25406. *outCurrentTempo = 120.0;
  25407. }
  25408. return noErr;
  25409. }
  25410. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25411. Float32* outTimeSig_Numerator,
  25412. UInt32* outTimeSig_Denominator,
  25413. Float64* outCurrentMeasureDownBeat) const
  25414. {
  25415. AudioPlayHead* const ph = getPlayHead();
  25416. AudioPlayHead::CurrentPositionInfo result;
  25417. if (ph != 0 && ph->getCurrentPosition (result))
  25418. {
  25419. if (outTimeSig_Numerator != 0)
  25420. *outTimeSig_Numerator = result.timeSigNumerator;
  25421. if (outTimeSig_Denominator != 0)
  25422. *outTimeSig_Denominator = result.timeSigDenominator;
  25423. if (outDeltaSampleOffsetToNextBeat != 0)
  25424. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25425. if (outCurrentMeasureDownBeat != 0)
  25426. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25427. }
  25428. else
  25429. {
  25430. if (outDeltaSampleOffsetToNextBeat != 0)
  25431. *outDeltaSampleOffsetToNextBeat = 0;
  25432. if (outTimeSig_Numerator != 0)
  25433. *outTimeSig_Numerator = 4;
  25434. if (outTimeSig_Denominator != 0)
  25435. *outTimeSig_Denominator = 4;
  25436. if (outCurrentMeasureDownBeat != 0)
  25437. *outCurrentMeasureDownBeat = 0;
  25438. }
  25439. return noErr;
  25440. }
  25441. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25442. Boolean* outTransportStateChanged,
  25443. Float64* outCurrentSampleInTimeLine,
  25444. Boolean* outIsCycling,
  25445. Float64* outCycleStartBeat,
  25446. Float64* outCycleEndBeat)
  25447. {
  25448. AudioPlayHead* const ph = getPlayHead();
  25449. AudioPlayHead::CurrentPositionInfo result;
  25450. if (ph != 0 && ph->getCurrentPosition (result))
  25451. {
  25452. if (outIsPlaying != 0)
  25453. *outIsPlaying = result.isPlaying;
  25454. if (outTransportStateChanged != 0)
  25455. {
  25456. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25457. wasPlaying = result.isPlaying;
  25458. }
  25459. if (outCurrentSampleInTimeLine != 0)
  25460. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25461. if (outIsCycling != 0)
  25462. *outIsCycling = false;
  25463. if (outCycleStartBeat != 0)
  25464. *outCycleStartBeat = 0;
  25465. if (outCycleEndBeat != 0)
  25466. *outCycleEndBeat = 0;
  25467. }
  25468. else
  25469. {
  25470. if (outIsPlaying != 0)
  25471. *outIsPlaying = false;
  25472. if (outTransportStateChanged != 0)
  25473. *outTransportStateChanged = false;
  25474. if (outCurrentSampleInTimeLine != 0)
  25475. *outCurrentSampleInTimeLine = 0;
  25476. if (outIsCycling != 0)
  25477. *outIsCycling = false;
  25478. if (outCycleStartBeat != 0)
  25479. *outCycleStartBeat = 0;
  25480. if (outCycleEndBeat != 0)
  25481. *outCycleEndBeat = 0;
  25482. }
  25483. return noErr;
  25484. }
  25485. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25486. public Timer
  25487. {
  25488. public:
  25489. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25490. : AudioProcessorEditor (&plugin_),
  25491. plugin (plugin_)
  25492. {
  25493. addAndMakeVisible (&wrapper);
  25494. setOpaque (true);
  25495. setVisible (true);
  25496. setSize (100, 100);
  25497. createView (createGenericViewIfNeeded);
  25498. }
  25499. ~AudioUnitPluginWindowCocoa()
  25500. {
  25501. const bool wasValid = isValid();
  25502. wrapper.setView (0);
  25503. if (wasValid)
  25504. plugin.editorBeingDeleted (this);
  25505. }
  25506. bool isValid() const { return wrapper.getView() != 0; }
  25507. void paint (Graphics& g)
  25508. {
  25509. g.fillAll (Colours::white);
  25510. }
  25511. void resized()
  25512. {
  25513. wrapper.setSize (getWidth(), getHeight());
  25514. }
  25515. void timerCallback()
  25516. {
  25517. wrapper.resizeToFitView();
  25518. startTimer (jmin (713, getTimerInterval() + 51));
  25519. }
  25520. void childBoundsChanged (Component* child)
  25521. {
  25522. setSize (wrapper.getWidth(), wrapper.getHeight());
  25523. startTimer (70);
  25524. }
  25525. private:
  25526. AudioUnitPluginInstance& plugin;
  25527. NSViewComponent wrapper;
  25528. bool createView (const bool createGenericViewIfNeeded)
  25529. {
  25530. NSView* pluginView = 0;
  25531. UInt32 dataSize = 0;
  25532. Boolean isWritable = false;
  25533. AudioUnitInitialize (plugin.audioUnit);
  25534. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25535. 0, &dataSize, &isWritable) == noErr
  25536. && dataSize != 0
  25537. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25538. 0, &dataSize, &isWritable) == noErr)
  25539. {
  25540. HeapBlock <AudioUnitCocoaViewInfo> info;
  25541. info.calloc (dataSize, 1);
  25542. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25543. 0, info, &dataSize) == noErr)
  25544. {
  25545. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25546. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25547. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25548. Class viewClass = [viewBundle classNamed: viewClassName];
  25549. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25550. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25551. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25552. {
  25553. id factory = [[[viewClass alloc] init] autorelease];
  25554. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25555. withSize: NSMakeSize (getWidth(), getHeight())];
  25556. }
  25557. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25558. CFRelease (info->mCocoaAUViewClass[i]);
  25559. CFRelease (info->mCocoaAUViewBundleLocation);
  25560. }
  25561. }
  25562. if (createGenericViewIfNeeded && (pluginView == 0))
  25563. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25564. wrapper.setView (pluginView);
  25565. if (pluginView != 0)
  25566. {
  25567. timerCallback();
  25568. startTimer (70);
  25569. }
  25570. return pluginView != 0;
  25571. }
  25572. };
  25573. #if JUCE_SUPPORT_CARBON
  25574. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25575. {
  25576. public:
  25577. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25578. : AudioProcessorEditor (&plugin_),
  25579. plugin (plugin_),
  25580. viewComponent (0)
  25581. {
  25582. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25583. setOpaque (true);
  25584. setVisible (true);
  25585. setSize (400, 300);
  25586. ComponentDescription viewList [16];
  25587. UInt32 viewListSize = sizeof (viewList);
  25588. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25589. 0, &viewList, &viewListSize);
  25590. componentRecord = FindNextComponent (0, &viewList[0]);
  25591. }
  25592. ~AudioUnitPluginWindowCarbon()
  25593. {
  25594. innerWrapper = 0;
  25595. if (isValid())
  25596. plugin.editorBeingDeleted (this);
  25597. }
  25598. bool isValid() const throw() { return componentRecord != 0; }
  25599. void paint (Graphics& g)
  25600. {
  25601. g.fillAll (Colours::black);
  25602. }
  25603. void resized()
  25604. {
  25605. innerWrapper->setSize (getWidth(), getHeight());
  25606. }
  25607. bool keyStateChanged (bool)
  25608. {
  25609. return false;
  25610. }
  25611. bool keyPressed (const KeyPress&)
  25612. {
  25613. return false;
  25614. }
  25615. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25616. AudioUnitCarbonView getViewComponent()
  25617. {
  25618. if (viewComponent == 0 && componentRecord != 0)
  25619. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25620. return viewComponent;
  25621. }
  25622. void closeViewComponent()
  25623. {
  25624. if (viewComponent != 0)
  25625. {
  25626. log ("Closing AU GUI: " + plugin.getName());
  25627. CloseComponent (viewComponent);
  25628. viewComponent = 0;
  25629. }
  25630. }
  25631. private:
  25632. AudioUnitPluginInstance& plugin;
  25633. ComponentRecord* componentRecord;
  25634. AudioUnitCarbonView viewComponent;
  25635. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25636. {
  25637. public:
  25638. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25639. : owner (owner_)
  25640. {
  25641. }
  25642. ~InnerWrapperComponent()
  25643. {
  25644. deleteWindow();
  25645. }
  25646. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25647. {
  25648. log ("Opening AU GUI: " + owner->plugin.getName());
  25649. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25650. if (viewComponent == 0)
  25651. return 0;
  25652. Float32Point pos = { 0, 0 };
  25653. Float32Point size = { 250, 200 };
  25654. HIViewRef pluginView = 0;
  25655. AudioUnitCarbonViewCreate (viewComponent,
  25656. owner->getAudioUnit(),
  25657. windowRef,
  25658. rootView,
  25659. &pos,
  25660. &size,
  25661. (ControlRef*) &pluginView);
  25662. return pluginView;
  25663. }
  25664. void removeView (HIViewRef)
  25665. {
  25666. owner->closeViewComponent();
  25667. }
  25668. private:
  25669. AudioUnitPluginWindowCarbon* const owner;
  25670. };
  25671. friend class InnerWrapperComponent;
  25672. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25673. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25674. };
  25675. #endif
  25676. bool AudioUnitPluginInstance::hasEditor() const
  25677. {
  25678. return true;
  25679. }
  25680. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25681. {
  25682. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25683. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25684. w = 0;
  25685. #if JUCE_SUPPORT_CARBON
  25686. if (w == 0)
  25687. {
  25688. w = new AudioUnitPluginWindowCarbon (*this);
  25689. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25690. w = 0;
  25691. }
  25692. #endif
  25693. if (w == 0)
  25694. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25695. return w.release();
  25696. }
  25697. const String AudioUnitPluginInstance::getCategory() const
  25698. {
  25699. const char* result = 0;
  25700. switch (componentDesc.componentType)
  25701. {
  25702. case kAudioUnitType_Effect:
  25703. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25704. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25705. case kAudioUnitType_Generator: result = "Generator"; break;
  25706. case kAudioUnitType_Panner: result = "Panner"; break;
  25707. default: break;
  25708. }
  25709. return result;
  25710. }
  25711. int AudioUnitPluginInstance::getNumParameters()
  25712. {
  25713. return parameterIds.size();
  25714. }
  25715. float AudioUnitPluginInstance::getParameter (int index)
  25716. {
  25717. const ScopedLock sl (lock);
  25718. Float32 value = 0.0f;
  25719. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25720. {
  25721. AudioUnitGetParameter (audioUnit,
  25722. (UInt32) parameterIds.getUnchecked (index),
  25723. kAudioUnitScope_Global, 0,
  25724. &value);
  25725. }
  25726. return value;
  25727. }
  25728. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25729. {
  25730. const ScopedLock sl (lock);
  25731. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25732. {
  25733. AudioUnitSetParameter (audioUnit,
  25734. (UInt32) parameterIds.getUnchecked (index),
  25735. kAudioUnitScope_Global, 0,
  25736. newValue, 0);
  25737. }
  25738. }
  25739. const String AudioUnitPluginInstance::getParameterName (int index)
  25740. {
  25741. AudioUnitParameterInfo info;
  25742. zerostruct (info);
  25743. UInt32 sz = sizeof (info);
  25744. String name;
  25745. if (AudioUnitGetProperty (audioUnit,
  25746. kAudioUnitProperty_ParameterInfo,
  25747. kAudioUnitScope_Global,
  25748. parameterIds [index], &info, &sz) == noErr)
  25749. {
  25750. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25751. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25752. else
  25753. name = String (info.name, sizeof (info.name));
  25754. }
  25755. return name;
  25756. }
  25757. const String AudioUnitPluginInstance::getParameterText (int index)
  25758. {
  25759. return String (getParameter (index));
  25760. }
  25761. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25762. {
  25763. AudioUnitParameterInfo info;
  25764. UInt32 sz = sizeof (info);
  25765. if (AudioUnitGetProperty (audioUnit,
  25766. kAudioUnitProperty_ParameterInfo,
  25767. kAudioUnitScope_Global,
  25768. parameterIds [index], &info, &sz) == noErr)
  25769. {
  25770. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25771. }
  25772. return true;
  25773. }
  25774. int AudioUnitPluginInstance::getNumPrograms()
  25775. {
  25776. CFArrayRef presets;
  25777. UInt32 sz = sizeof (CFArrayRef);
  25778. int num = 0;
  25779. if (AudioUnitGetProperty (audioUnit,
  25780. kAudioUnitProperty_FactoryPresets,
  25781. kAudioUnitScope_Global,
  25782. 0, &presets, &sz) == noErr)
  25783. {
  25784. num = (int) CFArrayGetCount (presets);
  25785. CFRelease (presets);
  25786. }
  25787. return num;
  25788. }
  25789. int AudioUnitPluginInstance::getCurrentProgram()
  25790. {
  25791. AUPreset current;
  25792. current.presetNumber = 0;
  25793. UInt32 sz = sizeof (AUPreset);
  25794. AudioUnitGetProperty (audioUnit,
  25795. kAudioUnitProperty_FactoryPresets,
  25796. kAudioUnitScope_Global,
  25797. 0, &current, &sz);
  25798. return current.presetNumber;
  25799. }
  25800. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25801. {
  25802. AUPreset current;
  25803. current.presetNumber = newIndex;
  25804. current.presetName = 0;
  25805. AudioUnitSetProperty (audioUnit,
  25806. kAudioUnitProperty_FactoryPresets,
  25807. kAudioUnitScope_Global,
  25808. 0, &current, sizeof (AUPreset));
  25809. }
  25810. const String AudioUnitPluginInstance::getProgramName (int index)
  25811. {
  25812. String s;
  25813. CFArrayRef presets;
  25814. UInt32 sz = sizeof (CFArrayRef);
  25815. if (AudioUnitGetProperty (audioUnit,
  25816. kAudioUnitProperty_FactoryPresets,
  25817. kAudioUnitScope_Global,
  25818. 0, &presets, &sz) == noErr)
  25819. {
  25820. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25821. {
  25822. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25823. if (p != 0 && p->presetNumber == index)
  25824. {
  25825. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25826. break;
  25827. }
  25828. }
  25829. CFRelease (presets);
  25830. }
  25831. return s;
  25832. }
  25833. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25834. {
  25835. jassertfalse; // xxx not implemented!
  25836. }
  25837. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25838. {
  25839. if (isPositiveAndBelow (index, getNumInputChannels()))
  25840. return "Input " + String (index + 1);
  25841. return String::empty;
  25842. }
  25843. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25844. {
  25845. if (! isPositiveAndBelow (index, getNumInputChannels()))
  25846. return false;
  25847. return true;
  25848. }
  25849. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25850. {
  25851. if (isPositiveAndBelow (index, getNumOutputChannels()))
  25852. return "Output " + String (index + 1);
  25853. return String::empty;
  25854. }
  25855. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25856. {
  25857. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  25858. return false;
  25859. return true;
  25860. }
  25861. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25862. {
  25863. getCurrentProgramStateInformation (destData);
  25864. }
  25865. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25866. {
  25867. CFPropertyListRef propertyList = 0;
  25868. UInt32 sz = sizeof (CFPropertyListRef);
  25869. if (AudioUnitGetProperty (audioUnit,
  25870. kAudioUnitProperty_ClassInfo,
  25871. kAudioUnitScope_Global,
  25872. 0, &propertyList, &sz) == noErr)
  25873. {
  25874. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25875. CFWriteStreamOpen (stream);
  25876. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25877. CFWriteStreamClose (stream);
  25878. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25879. destData.setSize (bytesWritten);
  25880. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25881. CFRelease (data);
  25882. CFRelease (stream);
  25883. CFRelease (propertyList);
  25884. }
  25885. }
  25886. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25887. {
  25888. setCurrentProgramStateInformation (data, sizeInBytes);
  25889. }
  25890. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25891. {
  25892. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25893. (const UInt8*) data,
  25894. sizeInBytes,
  25895. kCFAllocatorNull);
  25896. CFReadStreamOpen (stream);
  25897. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25898. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25899. stream,
  25900. 0,
  25901. kCFPropertyListImmutable,
  25902. &format,
  25903. 0);
  25904. CFRelease (stream);
  25905. if (propertyList != 0)
  25906. AudioUnitSetProperty (audioUnit,
  25907. kAudioUnitProperty_ClassInfo,
  25908. kAudioUnitScope_Global,
  25909. 0, &propertyList, sizeof (propertyList));
  25910. }
  25911. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25912. {
  25913. }
  25914. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25915. {
  25916. }
  25917. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25918. const String& fileOrIdentifier)
  25919. {
  25920. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25921. return;
  25922. PluginDescription desc;
  25923. desc.fileOrIdentifier = fileOrIdentifier;
  25924. desc.uid = 0;
  25925. try
  25926. {
  25927. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25928. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25929. if (auInstance != 0)
  25930. {
  25931. auInstance->fillInPluginDescription (desc);
  25932. results.add (new PluginDescription (desc));
  25933. }
  25934. }
  25935. catch (...)
  25936. {
  25937. // crashed while loading...
  25938. }
  25939. }
  25940. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25941. {
  25942. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25943. {
  25944. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25945. if (result->audioUnit != 0)
  25946. {
  25947. result->initialise();
  25948. return result.release();
  25949. }
  25950. }
  25951. return 0;
  25952. }
  25953. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25954. const bool /*recursive*/)
  25955. {
  25956. StringArray result;
  25957. ComponentRecord* comp = 0;
  25958. ComponentDescription desc;
  25959. zerostruct (desc);
  25960. for (;;)
  25961. {
  25962. zerostruct (desc);
  25963. comp = FindNextComponent (comp, &desc);
  25964. if (comp == 0)
  25965. break;
  25966. GetComponentInfo (comp, &desc, 0, 0, 0);
  25967. if (desc.componentType == kAudioUnitType_MusicDevice
  25968. || desc.componentType == kAudioUnitType_MusicEffect
  25969. || desc.componentType == kAudioUnitType_Effect
  25970. || desc.componentType == kAudioUnitType_Generator
  25971. || desc.componentType == kAudioUnitType_Panner)
  25972. {
  25973. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25974. DBG (s);
  25975. result.add (s);
  25976. }
  25977. }
  25978. return result;
  25979. }
  25980. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25981. {
  25982. ComponentDescription desc;
  25983. String name, version, manufacturer;
  25984. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25985. return FindNextComponent (0, &desc) != 0;
  25986. const File f (fileOrIdentifier);
  25987. return f.hasFileExtension (".component")
  25988. && f.isDirectory();
  25989. }
  25990. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25991. {
  25992. ComponentDescription desc;
  25993. String name, version, manufacturer;
  25994. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25995. if (name.isEmpty())
  25996. name = fileOrIdentifier;
  25997. return name;
  25998. }
  25999. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26000. {
  26001. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26002. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26003. else
  26004. return File (desc.fileOrIdentifier).exists();
  26005. }
  26006. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26007. {
  26008. return FileSearchPath ("/(Default AudioUnit locations)");
  26009. }
  26010. #endif
  26011. END_JUCE_NAMESPACE
  26012. #undef log
  26013. #endif
  26014. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26015. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26016. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26017. #define JUCE_MAC_VST_INCLUDED 1
  26018. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26019. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26020. #if JUCE_WINDOWS
  26021. #undef _WIN32_WINNT
  26022. #define _WIN32_WINNT 0x500
  26023. #undef STRICT
  26024. #define STRICT
  26025. #include <windows.h>
  26026. #include <float.h>
  26027. #pragma warning (disable : 4312 4355)
  26028. #ifdef __INTEL_COMPILER
  26029. #pragma warning (disable : 1899)
  26030. #endif
  26031. #elif JUCE_LINUX
  26032. #include <float.h>
  26033. #include <sys/time.h>
  26034. #include <X11/Xlib.h>
  26035. #include <X11/Xutil.h>
  26036. #include <X11/Xatom.h>
  26037. #undef Font
  26038. #undef KeyPress
  26039. #undef Drawable
  26040. #undef Time
  26041. #else
  26042. #include <Cocoa/Cocoa.h>
  26043. #include <Carbon/Carbon.h>
  26044. #endif
  26045. #if ! (JUCE_MAC && JUCE_64BIT)
  26046. BEGIN_JUCE_NAMESPACE
  26047. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26048. #endif
  26049. #undef PRAGMA_ALIGN_SUPPORTED
  26050. #define VST_FORCE_DEPRECATED 0
  26051. #if JUCE_MSVC
  26052. #pragma warning (push)
  26053. #pragma warning (disable: 4996)
  26054. #endif
  26055. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26056. your include path if you want to add VST support.
  26057. If you're not interested in VSTs, you can disable them by changing the
  26058. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26059. */
  26060. #include <pluginterfaces/vst2.x/aeffectx.h>
  26061. #if JUCE_MSVC
  26062. #pragma warning (pop)
  26063. #endif
  26064. #if JUCE_LINUX
  26065. #define Font JUCE_NAMESPACE::Font
  26066. #define KeyPress JUCE_NAMESPACE::KeyPress
  26067. #define Drawable JUCE_NAMESPACE::Drawable
  26068. #define Time JUCE_NAMESPACE::Time
  26069. #endif
  26070. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26071. #ifdef __aeffect__
  26072. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26073. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26074. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26075. events to the list.
  26076. This is used by both the VST hosting code and the plugin wrapper.
  26077. */
  26078. class VSTMidiEventList
  26079. {
  26080. public:
  26081. VSTMidiEventList()
  26082. : numEventsUsed (0), numEventsAllocated (0)
  26083. {
  26084. }
  26085. ~VSTMidiEventList()
  26086. {
  26087. freeEvents();
  26088. }
  26089. void clear()
  26090. {
  26091. numEventsUsed = 0;
  26092. if (events != 0)
  26093. events->numEvents = 0;
  26094. }
  26095. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26096. {
  26097. ensureSize (numEventsUsed + 1);
  26098. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26099. events->numEvents = ++numEventsUsed;
  26100. if (numBytes <= 4)
  26101. {
  26102. if (e->type == kVstSysExType)
  26103. {
  26104. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26105. e->type = kVstMidiType;
  26106. e->byteSize = sizeof (VstMidiEvent);
  26107. e->noteLength = 0;
  26108. e->noteOffset = 0;
  26109. e->detune = 0;
  26110. e->noteOffVelocity = 0;
  26111. }
  26112. e->deltaFrames = frameOffset;
  26113. memcpy (e->midiData, midiData, numBytes);
  26114. }
  26115. else
  26116. {
  26117. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26118. if (se->type == kVstSysExType)
  26119. delete[] se->sysexDump;
  26120. se->sysexDump = new char [numBytes];
  26121. memcpy (se->sysexDump, midiData, numBytes);
  26122. se->type = kVstSysExType;
  26123. se->byteSize = sizeof (VstMidiSysexEvent);
  26124. se->deltaFrames = frameOffset;
  26125. se->flags = 0;
  26126. se->dumpBytes = numBytes;
  26127. se->resvd1 = 0;
  26128. se->resvd2 = 0;
  26129. }
  26130. }
  26131. // Handy method to pull the events out of an event buffer supplied by the host
  26132. // or plugin.
  26133. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26134. {
  26135. for (int i = 0; i < events->numEvents; ++i)
  26136. {
  26137. const VstEvent* const e = events->events[i];
  26138. if (e != 0)
  26139. {
  26140. if (e->type == kVstMidiType)
  26141. {
  26142. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26143. 4, e->deltaFrames);
  26144. }
  26145. else if (e->type == kVstSysExType)
  26146. {
  26147. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26148. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26149. e->deltaFrames);
  26150. }
  26151. }
  26152. }
  26153. }
  26154. void ensureSize (int numEventsNeeded)
  26155. {
  26156. if (numEventsNeeded > numEventsAllocated)
  26157. {
  26158. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26159. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26160. if (events == 0)
  26161. events.calloc (size, 1);
  26162. else
  26163. events.realloc (size, 1);
  26164. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26165. {
  26166. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26167. (int) sizeof (VstMidiSysexEvent)));
  26168. e->type = kVstMidiType;
  26169. e->byteSize = sizeof (VstMidiEvent);
  26170. events->events[i] = (VstEvent*) e;
  26171. }
  26172. numEventsAllocated = numEventsNeeded;
  26173. }
  26174. }
  26175. void freeEvents()
  26176. {
  26177. if (events != 0)
  26178. {
  26179. for (int i = numEventsAllocated; --i >= 0;)
  26180. {
  26181. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26182. if (e->type == kVstSysExType)
  26183. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26184. juce_free (e);
  26185. }
  26186. events.free();
  26187. numEventsUsed = 0;
  26188. numEventsAllocated = 0;
  26189. }
  26190. }
  26191. HeapBlock <VstEvents> events;
  26192. private:
  26193. int numEventsUsed, numEventsAllocated;
  26194. };
  26195. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26196. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26197. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26198. #if ! JUCE_WINDOWS
  26199. static void _fpreset() {}
  26200. static void _clearfp() {}
  26201. #endif
  26202. extern void juce_callAnyTimersSynchronously();
  26203. const int fxbVersionNum = 1;
  26204. struct fxProgram
  26205. {
  26206. long chunkMagic; // 'CcnK'
  26207. long byteSize; // of this chunk, excl. magic + byteSize
  26208. long fxMagic; // 'FxCk'
  26209. long version;
  26210. long fxID; // fx unique id
  26211. long fxVersion;
  26212. long numParams;
  26213. char prgName[28];
  26214. float params[1]; // variable no. of parameters
  26215. };
  26216. struct fxSet
  26217. {
  26218. long chunkMagic; // 'CcnK'
  26219. long byteSize; // of this chunk, excl. magic + byteSize
  26220. long fxMagic; // 'FxBk'
  26221. long version;
  26222. long fxID; // fx unique id
  26223. long fxVersion;
  26224. long numPrograms;
  26225. char future[128];
  26226. fxProgram programs[1]; // variable no. of programs
  26227. };
  26228. struct fxChunkSet
  26229. {
  26230. long chunkMagic; // 'CcnK'
  26231. long byteSize; // of this chunk, excl. magic + byteSize
  26232. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26233. long version;
  26234. long fxID; // fx unique id
  26235. long fxVersion;
  26236. long numPrograms;
  26237. char future[128];
  26238. long chunkSize;
  26239. char chunk[8]; // variable
  26240. };
  26241. struct fxProgramSet
  26242. {
  26243. long chunkMagic; // 'CcnK'
  26244. long byteSize; // of this chunk, excl. magic + byteSize
  26245. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26246. long version;
  26247. long fxID; // fx unique id
  26248. long fxVersion;
  26249. long numPrograms;
  26250. char name[28];
  26251. long chunkSize;
  26252. char chunk[8]; // variable
  26253. };
  26254. namespace
  26255. {
  26256. long vst_swap (const long x) throw()
  26257. {
  26258. #ifdef JUCE_LITTLE_ENDIAN
  26259. return (long) ByteOrder::swap ((uint32) x);
  26260. #else
  26261. return x;
  26262. #endif
  26263. }
  26264. float vst_swapFloat (const float x) throw()
  26265. {
  26266. #ifdef JUCE_LITTLE_ENDIAN
  26267. union { uint32 asInt; float asFloat; } n;
  26268. n.asFloat = x;
  26269. n.asInt = ByteOrder::swap (n.asInt);
  26270. return n.asFloat;
  26271. #else
  26272. return x;
  26273. #endif
  26274. }
  26275. double getVSTHostTimeNanoseconds()
  26276. {
  26277. #if JUCE_WINDOWS
  26278. return timeGetTime() * 1000000.0;
  26279. #elif JUCE_LINUX
  26280. timeval micro;
  26281. gettimeofday (&micro, 0);
  26282. return micro.tv_usec * 1000.0;
  26283. #elif JUCE_MAC
  26284. UnsignedWide micro;
  26285. Microseconds (&micro);
  26286. return micro.lo * 1000.0;
  26287. #endif
  26288. }
  26289. }
  26290. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26291. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26292. static int shellUIDToCreate = 0;
  26293. static int insideVSTCallback = 0;
  26294. class VSTPluginWindow;
  26295. // Change this to disable logging of various VST activities
  26296. #ifndef VST_LOGGING
  26297. #define VST_LOGGING 1
  26298. #endif
  26299. #if VST_LOGGING
  26300. #define log(a) Logger::writeToLog(a);
  26301. #else
  26302. #define log(a)
  26303. #endif
  26304. #if JUCE_MAC && JUCE_PPC
  26305. static void* NewCFMFromMachO (void* const machofp) throw()
  26306. {
  26307. void* result = (void*) new char[8];
  26308. ((void**) result)[0] = machofp;
  26309. ((void**) result)[1] = result;
  26310. return result;
  26311. }
  26312. #endif
  26313. #if JUCE_LINUX
  26314. extern Display* display;
  26315. extern XContext windowHandleXContext;
  26316. typedef void (*EventProcPtr) (XEvent* ev);
  26317. static bool xErrorTriggered;
  26318. namespace
  26319. {
  26320. int temporaryErrorHandler (Display*, XErrorEvent*)
  26321. {
  26322. xErrorTriggered = true;
  26323. return 0;
  26324. }
  26325. int getPropertyFromXWindow (Window handle, Atom atom)
  26326. {
  26327. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26328. xErrorTriggered = false;
  26329. int userSize;
  26330. unsigned long bytes, userCount;
  26331. unsigned char* data;
  26332. Atom userType;
  26333. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26334. &userType, &userSize, &userCount, &bytes, &data);
  26335. XSetErrorHandler (oldErrorHandler);
  26336. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26337. : 0;
  26338. }
  26339. Window getChildWindow (Window windowToCheck)
  26340. {
  26341. Window rootWindow, parentWindow;
  26342. Window* childWindows;
  26343. unsigned int numChildren;
  26344. XQueryTree (display,
  26345. windowToCheck,
  26346. &rootWindow,
  26347. &parentWindow,
  26348. &childWindows,
  26349. &numChildren);
  26350. if (numChildren > 0)
  26351. return childWindows [0];
  26352. return 0;
  26353. }
  26354. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26355. {
  26356. if (e.mods.isLeftButtonDown())
  26357. {
  26358. ev.xbutton.button = Button1;
  26359. ev.xbutton.state |= Button1Mask;
  26360. }
  26361. else if (e.mods.isRightButtonDown())
  26362. {
  26363. ev.xbutton.button = Button3;
  26364. ev.xbutton.state |= Button3Mask;
  26365. }
  26366. else if (e.mods.isMiddleButtonDown())
  26367. {
  26368. ev.xbutton.button = Button2;
  26369. ev.xbutton.state |= Button2Mask;
  26370. }
  26371. }
  26372. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26373. {
  26374. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26375. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26376. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26377. }
  26378. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26379. {
  26380. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26381. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26382. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26383. }
  26384. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26385. {
  26386. if (increment < 0)
  26387. {
  26388. ev.xbutton.button = Button5;
  26389. ev.xbutton.state |= Button5Mask;
  26390. }
  26391. else if (increment > 0)
  26392. {
  26393. ev.xbutton.button = Button4;
  26394. ev.xbutton.state |= Button4Mask;
  26395. }
  26396. }
  26397. }
  26398. #endif
  26399. class ModuleHandle : public ReferenceCountedObject
  26400. {
  26401. public:
  26402. File file;
  26403. MainCall moduleMain;
  26404. String pluginName;
  26405. static Array <ModuleHandle*>& getActiveModules()
  26406. {
  26407. static Array <ModuleHandle*> activeModules;
  26408. return activeModules;
  26409. }
  26410. static ModuleHandle* findOrCreateModule (const File& file)
  26411. {
  26412. for (int i = getActiveModules().size(); --i >= 0;)
  26413. {
  26414. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26415. if (module->file == file)
  26416. return module;
  26417. }
  26418. _fpreset(); // (doesn't do any harm)
  26419. ++insideVSTCallback;
  26420. shellUIDToCreate = 0;
  26421. log ("Attempting to load VST: " + file.getFullPathName());
  26422. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26423. if (! m->open())
  26424. m = 0;
  26425. --insideVSTCallback;
  26426. _fpreset(); // (doesn't do any harm)
  26427. return m.release();
  26428. }
  26429. ModuleHandle (const File& file_)
  26430. : file (file_),
  26431. moduleMain (0),
  26432. #if JUCE_WINDOWS || JUCE_LINUX
  26433. hModule (0)
  26434. #elif JUCE_MAC
  26435. fragId (0),
  26436. resHandle (0),
  26437. bundleRef (0),
  26438. resFileId (0)
  26439. #endif
  26440. {
  26441. getActiveModules().add (this);
  26442. #if JUCE_WINDOWS || JUCE_LINUX
  26443. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26444. #elif JUCE_MAC
  26445. FSRef ref;
  26446. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26447. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26448. #endif
  26449. }
  26450. ~ModuleHandle()
  26451. {
  26452. getActiveModules().removeValue (this);
  26453. close();
  26454. }
  26455. #if JUCE_WINDOWS || JUCE_LINUX
  26456. void* hModule;
  26457. String fullParentDirectoryPathName;
  26458. bool open()
  26459. {
  26460. #if JUCE_WINDOWS
  26461. static bool timePeriodSet = false;
  26462. if (! timePeriodSet)
  26463. {
  26464. timePeriodSet = true;
  26465. timeBeginPeriod (2);
  26466. }
  26467. #endif
  26468. pluginName = file.getFileNameWithoutExtension();
  26469. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26470. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26471. if (moduleMain == 0)
  26472. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26473. return moduleMain != 0;
  26474. }
  26475. void close()
  26476. {
  26477. _fpreset(); // (doesn't do any harm)
  26478. PlatformUtilities::freeDynamicLibrary (hModule);
  26479. }
  26480. void closeEffect (AEffect* eff)
  26481. {
  26482. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26483. }
  26484. #else
  26485. CFragConnectionID fragId;
  26486. Handle resHandle;
  26487. CFBundleRef bundleRef;
  26488. FSSpec parentDirFSSpec;
  26489. short resFileId;
  26490. bool open()
  26491. {
  26492. bool ok = false;
  26493. const String filename (file.getFullPathName());
  26494. if (file.hasFileExtension (".vst"))
  26495. {
  26496. const char* const utf8 = filename.toUTF8();
  26497. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26498. strlen (utf8), file.isDirectory());
  26499. if (url != 0)
  26500. {
  26501. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26502. CFRelease (url);
  26503. if (bundleRef != 0)
  26504. {
  26505. if (CFBundleLoadExecutable (bundleRef))
  26506. {
  26507. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26508. if (moduleMain == 0)
  26509. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26510. if (moduleMain != 0)
  26511. {
  26512. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26513. if (name != 0)
  26514. {
  26515. if (CFGetTypeID (name) == CFStringGetTypeID())
  26516. {
  26517. char buffer[1024];
  26518. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26519. pluginName = buffer;
  26520. }
  26521. }
  26522. if (pluginName.isEmpty())
  26523. pluginName = file.getFileNameWithoutExtension();
  26524. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26525. ok = true;
  26526. }
  26527. }
  26528. if (! ok)
  26529. {
  26530. CFBundleUnloadExecutable (bundleRef);
  26531. CFRelease (bundleRef);
  26532. bundleRef = 0;
  26533. }
  26534. }
  26535. }
  26536. }
  26537. #if JUCE_PPC
  26538. else
  26539. {
  26540. FSRef fn;
  26541. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26542. {
  26543. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26544. if (resFileId != -1)
  26545. {
  26546. const int numEffs = Count1Resources ('aEff');
  26547. for (int i = 0; i < numEffs; ++i)
  26548. {
  26549. resHandle = Get1IndResource ('aEff', i + 1);
  26550. if (resHandle != 0)
  26551. {
  26552. OSType type;
  26553. Str255 name;
  26554. SInt16 id;
  26555. GetResInfo (resHandle, &id, &type, name);
  26556. pluginName = String ((const char*) name + 1, name[0]);
  26557. DetachResource (resHandle);
  26558. HLock (resHandle);
  26559. Ptr ptr;
  26560. Str255 errorText;
  26561. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26562. name, kPrivateCFragCopy,
  26563. &fragId, &ptr, errorText);
  26564. if (err == noErr)
  26565. {
  26566. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26567. ok = true;
  26568. }
  26569. else
  26570. {
  26571. HUnlock (resHandle);
  26572. }
  26573. break;
  26574. }
  26575. }
  26576. if (! ok)
  26577. CloseResFile (resFileId);
  26578. }
  26579. }
  26580. }
  26581. #endif
  26582. return ok;
  26583. }
  26584. void close()
  26585. {
  26586. #if JUCE_PPC
  26587. if (fragId != 0)
  26588. {
  26589. if (moduleMain != 0)
  26590. disposeMachOFromCFM ((void*) moduleMain);
  26591. CloseConnection (&fragId);
  26592. HUnlock (resHandle);
  26593. if (resFileId != 0)
  26594. CloseResFile (resFileId);
  26595. }
  26596. else
  26597. #endif
  26598. if (bundleRef != 0)
  26599. {
  26600. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26601. if (CFGetRetainCount (bundleRef) == 1)
  26602. CFBundleUnloadExecutable (bundleRef);
  26603. if (CFGetRetainCount (bundleRef) > 0)
  26604. CFRelease (bundleRef);
  26605. }
  26606. }
  26607. void closeEffect (AEffect* eff)
  26608. {
  26609. #if JUCE_PPC
  26610. if (fragId != 0)
  26611. {
  26612. Array<void*> thingsToDelete;
  26613. thingsToDelete.add ((void*) eff->dispatcher);
  26614. thingsToDelete.add ((void*) eff->process);
  26615. thingsToDelete.add ((void*) eff->setParameter);
  26616. thingsToDelete.add ((void*) eff->getParameter);
  26617. thingsToDelete.add ((void*) eff->processReplacing);
  26618. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26619. for (int i = thingsToDelete.size(); --i >= 0;)
  26620. disposeMachOFromCFM (thingsToDelete[i]);
  26621. }
  26622. else
  26623. #endif
  26624. {
  26625. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26626. }
  26627. }
  26628. #if JUCE_PPC
  26629. static void* newMachOFromCFM (void* cfmfp)
  26630. {
  26631. if (cfmfp == 0)
  26632. return 0;
  26633. UInt32* const mfp = new UInt32[6];
  26634. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26635. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26636. mfp[2] = 0x800c0000;
  26637. mfp[3] = 0x804c0004;
  26638. mfp[4] = 0x7c0903a6;
  26639. mfp[5] = 0x4e800420;
  26640. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26641. return mfp;
  26642. }
  26643. static void disposeMachOFromCFM (void* ptr)
  26644. {
  26645. delete[] static_cast <UInt32*> (ptr);
  26646. }
  26647. void coerceAEffectFunctionCalls (AEffect* eff)
  26648. {
  26649. if (fragId != 0)
  26650. {
  26651. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26652. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26653. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26654. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26655. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26656. }
  26657. }
  26658. #endif
  26659. #endif
  26660. private:
  26661. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26662. };
  26663. /**
  26664. An instance of a plugin, created by a VSTPluginFormat.
  26665. */
  26666. class VSTPluginInstance : public AudioPluginInstance,
  26667. private Timer,
  26668. private AsyncUpdater
  26669. {
  26670. public:
  26671. ~VSTPluginInstance();
  26672. // AudioPluginInstance methods:
  26673. void fillInPluginDescription (PluginDescription& desc) const
  26674. {
  26675. desc.name = name;
  26676. {
  26677. char buffer [512];
  26678. zerostruct (buffer);
  26679. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26680. desc.descriptiveName = String (buffer).trim();
  26681. if (desc.descriptiveName.isEmpty())
  26682. desc.descriptiveName = name;
  26683. }
  26684. desc.fileOrIdentifier = module->file.getFullPathName();
  26685. desc.uid = getUID();
  26686. desc.lastFileModTime = module->file.getLastModificationTime();
  26687. desc.pluginFormatName = "VST";
  26688. desc.category = getCategory();
  26689. {
  26690. char buffer [kVstMaxVendorStrLen + 8];
  26691. zerostruct (buffer);
  26692. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26693. desc.manufacturerName = buffer;
  26694. }
  26695. desc.version = getVersion();
  26696. desc.numInputChannels = getNumInputChannels();
  26697. desc.numOutputChannels = getNumOutputChannels();
  26698. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26699. }
  26700. void* getPlatformSpecificData() { return effect; }
  26701. const String getName() const { return name; }
  26702. int getUID() const;
  26703. bool acceptsMidi() const { return wantsMidiMessages; }
  26704. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26705. // AudioProcessor methods:
  26706. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26707. void releaseResources();
  26708. void processBlock (AudioSampleBuffer& buffer,
  26709. MidiBuffer& midiMessages);
  26710. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26711. AudioProcessorEditor* createEditor();
  26712. const String getInputChannelName (int index) const;
  26713. bool isInputChannelStereoPair (int index) const;
  26714. const String getOutputChannelName (int index) const;
  26715. bool isOutputChannelStereoPair (int index) const;
  26716. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26717. float getParameter (int index);
  26718. void setParameter (int index, float newValue);
  26719. const String getParameterName (int index);
  26720. const String getParameterText (int index);
  26721. bool isParameterAutomatable (int index) const;
  26722. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26723. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26724. void setCurrentProgram (int index);
  26725. const String getProgramName (int index);
  26726. void changeProgramName (int index, const String& newName);
  26727. void getStateInformation (MemoryBlock& destData);
  26728. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26729. void setStateInformation (const void* data, int sizeInBytes);
  26730. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26731. void timerCallback();
  26732. void handleAsyncUpdate();
  26733. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26734. private:
  26735. friend class VSTPluginWindow;
  26736. friend class VSTPluginFormat;
  26737. AEffect* effect;
  26738. String name;
  26739. CriticalSection lock;
  26740. bool wantsMidiMessages, initialised, isPowerOn;
  26741. mutable StringArray programNames;
  26742. AudioSampleBuffer tempBuffer;
  26743. CriticalSection midiInLock;
  26744. MidiBuffer incomingMidi;
  26745. VSTMidiEventList midiEventsToSend;
  26746. VstTimeInfo vstHostTime;
  26747. ReferenceCountedObjectPtr <ModuleHandle> module;
  26748. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26749. bool restoreProgramSettings (const fxProgram* const prog);
  26750. const String getCurrentProgramName();
  26751. void setParamsInProgramBlock (fxProgram* const prog);
  26752. void updateStoredProgramNames();
  26753. void initialise();
  26754. void handleMidiFromPlugin (const VstEvents* const events);
  26755. void createTempParameterStore (MemoryBlock& dest);
  26756. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26757. const String getParameterLabel (int index) const;
  26758. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26759. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26760. void setChunkData (const char* data, int size, bool isPreset);
  26761. bool loadFromFXBFile (const void* data, int numBytes);
  26762. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26763. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26764. const String getVersion() const;
  26765. const String getCategory() const;
  26766. void setPower (const bool on);
  26767. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26768. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26769. };
  26770. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26771. : effect (0),
  26772. wantsMidiMessages (false),
  26773. initialised (false),
  26774. isPowerOn (false),
  26775. tempBuffer (1, 1),
  26776. module (module_)
  26777. {
  26778. try
  26779. {
  26780. _fpreset();
  26781. ++insideVSTCallback;
  26782. name = module->pluginName;
  26783. log ("Creating VST instance: " + name);
  26784. #if JUCE_MAC
  26785. if (module->resFileId != 0)
  26786. UseResFile (module->resFileId);
  26787. #if JUCE_PPC
  26788. if (module->fragId != 0)
  26789. {
  26790. static void* audioMasterCoerced = 0;
  26791. if (audioMasterCoerced == 0)
  26792. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26793. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26794. }
  26795. else
  26796. #endif
  26797. #endif
  26798. {
  26799. effect = module->moduleMain (&audioMaster);
  26800. }
  26801. --insideVSTCallback;
  26802. if (effect != 0 && effect->magic == kEffectMagic)
  26803. {
  26804. #if JUCE_PPC
  26805. module->coerceAEffectFunctionCalls (effect);
  26806. #endif
  26807. jassert (effect->resvd2 == 0);
  26808. jassert (effect->object != 0);
  26809. _fpreset(); // some dodgy plugs fuck around with this
  26810. }
  26811. else
  26812. {
  26813. effect = 0;
  26814. }
  26815. }
  26816. catch (...)
  26817. {
  26818. --insideVSTCallback;
  26819. }
  26820. }
  26821. VSTPluginInstance::~VSTPluginInstance()
  26822. {
  26823. const ScopedLock sl (lock);
  26824. jassert (insideVSTCallback == 0);
  26825. if (effect != 0 && effect->magic == kEffectMagic)
  26826. {
  26827. try
  26828. {
  26829. #if JUCE_MAC
  26830. if (module->resFileId != 0)
  26831. UseResFile (module->resFileId);
  26832. #endif
  26833. // Must delete any editors before deleting the plugin instance!
  26834. jassert (getActiveEditor() == 0);
  26835. _fpreset(); // some dodgy plugs fuck around with this
  26836. module->closeEffect (effect);
  26837. }
  26838. catch (...)
  26839. {}
  26840. }
  26841. module = 0;
  26842. effect = 0;
  26843. }
  26844. void VSTPluginInstance::initialise()
  26845. {
  26846. if (initialised || effect == 0)
  26847. return;
  26848. log ("Initialising VST: " + module->pluginName);
  26849. initialised = true;
  26850. dispatch (effIdentify, 0, 0, 0, 0);
  26851. if (getSampleRate() > 0)
  26852. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26853. if (getBlockSize() > 0)
  26854. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26855. dispatch (effOpen, 0, 0, 0, 0);
  26856. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26857. getSampleRate(), getBlockSize());
  26858. if (getNumPrograms() > 1)
  26859. setCurrentProgram (0);
  26860. else
  26861. dispatch (effSetProgram, 0, 0, 0, 0);
  26862. int i;
  26863. for (i = effect->numInputs; --i >= 0;)
  26864. dispatch (effConnectInput, i, 1, 0, 0);
  26865. for (i = effect->numOutputs; --i >= 0;)
  26866. dispatch (effConnectOutput, i, 1, 0, 0);
  26867. updateStoredProgramNames();
  26868. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26869. setLatencySamples (effect->initialDelay);
  26870. }
  26871. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26872. int samplesPerBlockExpected)
  26873. {
  26874. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26875. sampleRate_, samplesPerBlockExpected);
  26876. setLatencySamples (effect->initialDelay);
  26877. vstHostTime.tempo = 120.0;
  26878. vstHostTime.timeSigNumerator = 4;
  26879. vstHostTime.timeSigDenominator = 4;
  26880. vstHostTime.sampleRate = sampleRate_;
  26881. vstHostTime.samplePos = 0;
  26882. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26883. initialise();
  26884. if (initialised)
  26885. {
  26886. wantsMidiMessages = wantsMidiMessages
  26887. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26888. if (wantsMidiMessages)
  26889. midiEventsToSend.ensureSize (256);
  26890. else
  26891. midiEventsToSend.freeEvents();
  26892. incomingMidi.clear();
  26893. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26894. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26895. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26896. if (! isPowerOn)
  26897. setPower (true);
  26898. // dodgy hack to force some plugins to initialise the sample rate..
  26899. if ((! hasEditor()) && getNumParameters() > 0)
  26900. {
  26901. const float old = getParameter (0);
  26902. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26903. setParameter (0, old);
  26904. }
  26905. dispatch (effStartProcess, 0, 0, 0, 0);
  26906. }
  26907. }
  26908. void VSTPluginInstance::releaseResources()
  26909. {
  26910. if (initialised)
  26911. {
  26912. dispatch (effStopProcess, 0, 0, 0, 0);
  26913. setPower (false);
  26914. }
  26915. tempBuffer.setSize (1, 1);
  26916. incomingMidi.clear();
  26917. midiEventsToSend.freeEvents();
  26918. }
  26919. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26920. MidiBuffer& midiMessages)
  26921. {
  26922. const int numSamples = buffer.getNumSamples();
  26923. if (initialised)
  26924. {
  26925. AudioPlayHead* playHead = getPlayHead();
  26926. if (playHead != 0)
  26927. {
  26928. AudioPlayHead::CurrentPositionInfo position;
  26929. playHead->getCurrentPosition (position);
  26930. vstHostTime.tempo = position.bpm;
  26931. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26932. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26933. vstHostTime.ppqPos = position.ppqPosition;
  26934. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26935. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26936. if (position.isPlaying)
  26937. vstHostTime.flags |= kVstTransportPlaying;
  26938. else
  26939. vstHostTime.flags &= ~kVstTransportPlaying;
  26940. }
  26941. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  26942. if (wantsMidiMessages)
  26943. {
  26944. midiEventsToSend.clear();
  26945. midiEventsToSend.ensureSize (1);
  26946. MidiBuffer::Iterator iter (midiMessages);
  26947. const uint8* midiData;
  26948. int numBytesOfMidiData, samplePosition;
  26949. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26950. {
  26951. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26952. jlimit (0, numSamples - 1, samplePosition));
  26953. }
  26954. try
  26955. {
  26956. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26957. }
  26958. catch (...)
  26959. {}
  26960. }
  26961. _clearfp();
  26962. if ((effect->flags & effFlagsCanReplacing) != 0)
  26963. {
  26964. try
  26965. {
  26966. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  26967. }
  26968. catch (...)
  26969. {}
  26970. }
  26971. else
  26972. {
  26973. tempBuffer.setSize (effect->numOutputs, numSamples);
  26974. tempBuffer.clear();
  26975. try
  26976. {
  26977. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  26978. }
  26979. catch (...)
  26980. {}
  26981. for (int i = effect->numOutputs; --i >= 0;)
  26982. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  26983. }
  26984. }
  26985. else
  26986. {
  26987. // Not initialised, so just bypass..
  26988. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26989. buffer.clear (i, 0, buffer.getNumSamples());
  26990. }
  26991. {
  26992. // copy any incoming midi..
  26993. const ScopedLock sl (midiInLock);
  26994. midiMessages.swapWith (incomingMidi);
  26995. incomingMidi.clear();
  26996. }
  26997. }
  26998. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26999. {
  27000. if (events != 0)
  27001. {
  27002. const ScopedLock sl (midiInLock);
  27003. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27004. }
  27005. }
  27006. static Array <VSTPluginWindow*> activeVSTWindows;
  27007. class VSTPluginWindow : public AudioProcessorEditor,
  27008. #if ! JUCE_MAC
  27009. public ComponentMovementWatcher,
  27010. #endif
  27011. public Timer
  27012. {
  27013. public:
  27014. VSTPluginWindow (VSTPluginInstance& plugin_)
  27015. : AudioProcessorEditor (&plugin_),
  27016. #if ! JUCE_MAC
  27017. ComponentMovementWatcher (this),
  27018. #endif
  27019. plugin (plugin_),
  27020. isOpen (false),
  27021. recursiveResize (false),
  27022. pluginWantsKeys (false),
  27023. pluginRefusesToResize (false),
  27024. alreadyInside (false)
  27025. {
  27026. #if JUCE_WINDOWS
  27027. sizeCheckCount = 0;
  27028. pluginHWND = 0;
  27029. #elif JUCE_LINUX
  27030. pluginWindow = None;
  27031. pluginProc = None;
  27032. #else
  27033. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27034. #endif
  27035. activeVSTWindows.add (this);
  27036. setSize (1, 1);
  27037. setOpaque (true);
  27038. setVisible (true);
  27039. }
  27040. ~VSTPluginWindow()
  27041. {
  27042. #if JUCE_MAC
  27043. innerWrapper = 0;
  27044. #else
  27045. closePluginWindow();
  27046. #endif
  27047. activeVSTWindows.removeValue (this);
  27048. plugin.editorBeingDeleted (this);
  27049. }
  27050. #if ! JUCE_MAC
  27051. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27052. {
  27053. if (recursiveResize)
  27054. return;
  27055. Component* const topComp = getTopLevelComponent();
  27056. if (topComp->getPeer() != 0)
  27057. {
  27058. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27059. recursiveResize = true;
  27060. #if JUCE_WINDOWS
  27061. if (pluginHWND != 0)
  27062. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27063. #elif JUCE_LINUX
  27064. if (pluginWindow != 0)
  27065. {
  27066. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27067. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27068. XMapRaised (display, pluginWindow);
  27069. }
  27070. #endif
  27071. recursiveResize = false;
  27072. }
  27073. }
  27074. void componentVisibilityChanged()
  27075. {
  27076. if (isShowing())
  27077. openPluginWindow();
  27078. else
  27079. closePluginWindow();
  27080. componentMovedOrResized (true, true);
  27081. }
  27082. void componentPeerChanged()
  27083. {
  27084. closePluginWindow();
  27085. openPluginWindow();
  27086. }
  27087. #endif
  27088. bool keyStateChanged (bool)
  27089. {
  27090. return pluginWantsKeys;
  27091. }
  27092. bool keyPressed (const KeyPress&)
  27093. {
  27094. return pluginWantsKeys;
  27095. }
  27096. #if JUCE_MAC
  27097. void paint (Graphics& g)
  27098. {
  27099. g.fillAll (Colours::black);
  27100. }
  27101. #else
  27102. void paint (Graphics& g)
  27103. {
  27104. if (isOpen)
  27105. {
  27106. ComponentPeer* const peer = getPeer();
  27107. if (peer != 0)
  27108. {
  27109. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27110. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27111. #if JUCE_LINUX
  27112. if (pluginWindow != 0)
  27113. {
  27114. const Rectangle<int> clip (g.getClipBounds());
  27115. XEvent ev;
  27116. zerostruct (ev);
  27117. ev.xexpose.type = Expose;
  27118. ev.xexpose.display = display;
  27119. ev.xexpose.window = pluginWindow;
  27120. ev.xexpose.x = clip.getX();
  27121. ev.xexpose.y = clip.getY();
  27122. ev.xexpose.width = clip.getWidth();
  27123. ev.xexpose.height = clip.getHeight();
  27124. sendEventToChild (&ev);
  27125. }
  27126. #endif
  27127. }
  27128. }
  27129. else
  27130. {
  27131. g.fillAll (Colours::black);
  27132. }
  27133. }
  27134. #endif
  27135. void timerCallback()
  27136. {
  27137. #if JUCE_WINDOWS
  27138. if (--sizeCheckCount <= 0)
  27139. {
  27140. sizeCheckCount = 10;
  27141. checkPluginWindowSize();
  27142. }
  27143. #endif
  27144. try
  27145. {
  27146. static bool reentrant = false;
  27147. if (! reentrant)
  27148. {
  27149. reentrant = true;
  27150. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27151. reentrant = false;
  27152. }
  27153. }
  27154. catch (...)
  27155. {}
  27156. }
  27157. void mouseDown (const MouseEvent& e)
  27158. {
  27159. #if JUCE_LINUX
  27160. if (pluginWindow == 0)
  27161. return;
  27162. toFront (true);
  27163. XEvent ev;
  27164. zerostruct (ev);
  27165. ev.xbutton.display = display;
  27166. ev.xbutton.type = ButtonPress;
  27167. ev.xbutton.window = pluginWindow;
  27168. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27169. ev.xbutton.time = CurrentTime;
  27170. ev.xbutton.x = e.x;
  27171. ev.xbutton.y = e.y;
  27172. ev.xbutton.x_root = e.getScreenX();
  27173. ev.xbutton.y_root = e.getScreenY();
  27174. translateJuceToXButtonModifiers (e, ev);
  27175. sendEventToChild (&ev);
  27176. #elif JUCE_WINDOWS
  27177. (void) e;
  27178. toFront (true);
  27179. #endif
  27180. }
  27181. void broughtToFront()
  27182. {
  27183. activeVSTWindows.removeValue (this);
  27184. activeVSTWindows.add (this);
  27185. #if JUCE_MAC
  27186. dispatch (effEditTop, 0, 0, 0, 0);
  27187. #endif
  27188. }
  27189. private:
  27190. VSTPluginInstance& plugin;
  27191. bool isOpen, recursiveResize;
  27192. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27193. #if JUCE_WINDOWS
  27194. HWND pluginHWND;
  27195. void* originalWndProc;
  27196. int sizeCheckCount;
  27197. #elif JUCE_LINUX
  27198. Window pluginWindow;
  27199. EventProcPtr pluginProc;
  27200. #endif
  27201. #if JUCE_MAC
  27202. void openPluginWindow (WindowRef parentWindow)
  27203. {
  27204. if (isOpen || parentWindow == 0)
  27205. return;
  27206. isOpen = true;
  27207. ERect* rect = 0;
  27208. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27209. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27210. // do this before and after like in the steinberg example
  27211. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27212. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27213. // Install keyboard hooks
  27214. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27215. // double-check it's not too tiny
  27216. int w = 250, h = 150;
  27217. if (rect != 0)
  27218. {
  27219. w = rect->right - rect->left;
  27220. h = rect->bottom - rect->top;
  27221. if (w == 0 || h == 0)
  27222. {
  27223. w = 250;
  27224. h = 150;
  27225. }
  27226. }
  27227. w = jmax (w, 32);
  27228. h = jmax (h, 32);
  27229. setSize (w, h);
  27230. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27231. repaint();
  27232. }
  27233. #else
  27234. void openPluginWindow()
  27235. {
  27236. if (isOpen || getWindowHandle() == 0)
  27237. return;
  27238. log ("Opening VST UI: " + plugin.name);
  27239. isOpen = true;
  27240. ERect* rect = 0;
  27241. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27242. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27243. // do this before and after like in the steinberg example
  27244. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27245. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27246. // Install keyboard hooks
  27247. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27248. #if JUCE_WINDOWS
  27249. originalWndProc = 0;
  27250. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27251. if (pluginHWND == 0)
  27252. {
  27253. isOpen = false;
  27254. setSize (300, 150);
  27255. return;
  27256. }
  27257. #pragma warning (push)
  27258. #pragma warning (disable: 4244)
  27259. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27260. if (! pluginWantsKeys)
  27261. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27262. #pragma warning (pop)
  27263. int w, h;
  27264. RECT r;
  27265. GetWindowRect (pluginHWND, &r);
  27266. w = r.right - r.left;
  27267. h = r.bottom - r.top;
  27268. if (rect != 0)
  27269. {
  27270. const int rw = rect->right - rect->left;
  27271. const int rh = rect->bottom - rect->top;
  27272. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27273. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27274. {
  27275. // very dodgy logic to decide which size is right.
  27276. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27277. {
  27278. SetWindowPos (pluginHWND, 0,
  27279. 0, 0, rw, rh,
  27280. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27281. GetWindowRect (pluginHWND, &r);
  27282. w = r.right - r.left;
  27283. h = r.bottom - r.top;
  27284. pluginRefusesToResize = (w != rw) || (h != rh);
  27285. w = rw;
  27286. h = rh;
  27287. }
  27288. }
  27289. }
  27290. #elif JUCE_LINUX
  27291. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27292. if (pluginWindow != 0)
  27293. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27294. XInternAtom (display, "_XEventProc", False));
  27295. int w = 250, h = 150;
  27296. if (rect != 0)
  27297. {
  27298. w = rect->right - rect->left;
  27299. h = rect->bottom - rect->top;
  27300. if (w == 0 || h == 0)
  27301. {
  27302. w = 250;
  27303. h = 150;
  27304. }
  27305. }
  27306. if (pluginWindow != 0)
  27307. XMapRaised (display, pluginWindow);
  27308. #endif
  27309. // double-check it's not too tiny
  27310. w = jmax (w, 32);
  27311. h = jmax (h, 32);
  27312. setSize (w, h);
  27313. #if JUCE_WINDOWS
  27314. checkPluginWindowSize();
  27315. #endif
  27316. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27317. repaint();
  27318. }
  27319. #endif
  27320. #if ! JUCE_MAC
  27321. void closePluginWindow()
  27322. {
  27323. if (isOpen)
  27324. {
  27325. log ("Closing VST UI: " + plugin.getName());
  27326. isOpen = false;
  27327. dispatch (effEditClose, 0, 0, 0, 0);
  27328. #if JUCE_WINDOWS
  27329. #pragma warning (push)
  27330. #pragma warning (disable: 4244)
  27331. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27332. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27333. #pragma warning (pop)
  27334. stopTimer();
  27335. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27336. DestroyWindow (pluginHWND);
  27337. pluginHWND = 0;
  27338. #elif JUCE_LINUX
  27339. stopTimer();
  27340. pluginWindow = 0;
  27341. pluginProc = 0;
  27342. #endif
  27343. }
  27344. }
  27345. #endif
  27346. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27347. {
  27348. return plugin.dispatch (opcode, index, value, ptr, opt);
  27349. }
  27350. #if JUCE_WINDOWS
  27351. void checkPluginWindowSize()
  27352. {
  27353. RECT r;
  27354. GetWindowRect (pluginHWND, &r);
  27355. const int w = r.right - r.left;
  27356. const int h = r.bottom - r.top;
  27357. if (isShowing() && w > 0 && h > 0
  27358. && (w != getWidth() || h != getHeight())
  27359. && ! pluginRefusesToResize)
  27360. {
  27361. setSize (w, h);
  27362. sizeCheckCount = 0;
  27363. }
  27364. }
  27365. // hooks to get keyboard events from VST windows..
  27366. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27367. {
  27368. for (int i = activeVSTWindows.size(); --i >= 0;)
  27369. {
  27370. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27371. if (w->pluginHWND == hW)
  27372. {
  27373. if (message == WM_CHAR
  27374. || message == WM_KEYDOWN
  27375. || message == WM_SYSKEYDOWN
  27376. || message == WM_KEYUP
  27377. || message == WM_SYSKEYUP
  27378. || message == WM_APPCOMMAND)
  27379. {
  27380. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27381. message, wParam, lParam);
  27382. }
  27383. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27384. (HWND) w->pluginHWND,
  27385. message,
  27386. wParam,
  27387. lParam);
  27388. }
  27389. }
  27390. return DefWindowProc (hW, message, wParam, lParam);
  27391. }
  27392. #endif
  27393. #if JUCE_LINUX
  27394. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27395. void sendEventToChild (XEvent* event)
  27396. {
  27397. if (pluginProc != 0)
  27398. {
  27399. // if the plugin publishes an event procedure, pass the event directly..
  27400. pluginProc (event);
  27401. }
  27402. else if (pluginWindow != 0)
  27403. {
  27404. // if the plugin has a window, then send the event to the window so that
  27405. // its message thread will pick it up..
  27406. XSendEvent (display, pluginWindow, False, 0L, event);
  27407. XFlush (display);
  27408. }
  27409. }
  27410. void mouseEnter (const MouseEvent& e)
  27411. {
  27412. if (pluginWindow != 0)
  27413. {
  27414. XEvent ev;
  27415. zerostruct (ev);
  27416. ev.xcrossing.display = display;
  27417. ev.xcrossing.type = EnterNotify;
  27418. ev.xcrossing.window = pluginWindow;
  27419. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27420. ev.xcrossing.time = CurrentTime;
  27421. ev.xcrossing.x = e.x;
  27422. ev.xcrossing.y = e.y;
  27423. ev.xcrossing.x_root = e.getScreenX();
  27424. ev.xcrossing.y_root = e.getScreenY();
  27425. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27426. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27427. translateJuceToXCrossingModifiers (e, ev);
  27428. sendEventToChild (&ev);
  27429. }
  27430. }
  27431. void mouseExit (const MouseEvent& e)
  27432. {
  27433. if (pluginWindow != 0)
  27434. {
  27435. XEvent ev;
  27436. zerostruct (ev);
  27437. ev.xcrossing.display = display;
  27438. ev.xcrossing.type = LeaveNotify;
  27439. ev.xcrossing.window = pluginWindow;
  27440. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27441. ev.xcrossing.time = CurrentTime;
  27442. ev.xcrossing.x = e.x;
  27443. ev.xcrossing.y = e.y;
  27444. ev.xcrossing.x_root = e.getScreenX();
  27445. ev.xcrossing.y_root = e.getScreenY();
  27446. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27447. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27448. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27449. translateJuceToXCrossingModifiers (e, ev);
  27450. sendEventToChild (&ev);
  27451. }
  27452. }
  27453. void mouseMove (const MouseEvent& e)
  27454. {
  27455. if (pluginWindow != 0)
  27456. {
  27457. XEvent ev;
  27458. zerostruct (ev);
  27459. ev.xmotion.display = display;
  27460. ev.xmotion.type = MotionNotify;
  27461. ev.xmotion.window = pluginWindow;
  27462. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27463. ev.xmotion.time = CurrentTime;
  27464. ev.xmotion.is_hint = NotifyNormal;
  27465. ev.xmotion.x = e.x;
  27466. ev.xmotion.y = e.y;
  27467. ev.xmotion.x_root = e.getScreenX();
  27468. ev.xmotion.y_root = e.getScreenY();
  27469. sendEventToChild (&ev);
  27470. }
  27471. }
  27472. void mouseDrag (const MouseEvent& e)
  27473. {
  27474. if (pluginWindow != 0)
  27475. {
  27476. XEvent ev;
  27477. zerostruct (ev);
  27478. ev.xmotion.display = display;
  27479. ev.xmotion.type = MotionNotify;
  27480. ev.xmotion.window = pluginWindow;
  27481. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27482. ev.xmotion.time = CurrentTime;
  27483. ev.xmotion.x = e.x ;
  27484. ev.xmotion.y = e.y;
  27485. ev.xmotion.x_root = e.getScreenX();
  27486. ev.xmotion.y_root = e.getScreenY();
  27487. ev.xmotion.is_hint = NotifyNormal;
  27488. translateJuceToXMotionModifiers (e, ev);
  27489. sendEventToChild (&ev);
  27490. }
  27491. }
  27492. void mouseUp (const MouseEvent& e)
  27493. {
  27494. if (pluginWindow != 0)
  27495. {
  27496. XEvent ev;
  27497. zerostruct (ev);
  27498. ev.xbutton.display = display;
  27499. ev.xbutton.type = ButtonRelease;
  27500. ev.xbutton.window = pluginWindow;
  27501. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27502. ev.xbutton.time = CurrentTime;
  27503. ev.xbutton.x = e.x;
  27504. ev.xbutton.y = e.y;
  27505. ev.xbutton.x_root = e.getScreenX();
  27506. ev.xbutton.y_root = e.getScreenY();
  27507. translateJuceToXButtonModifiers (e, ev);
  27508. sendEventToChild (&ev);
  27509. }
  27510. }
  27511. void mouseWheelMove (const MouseEvent& e,
  27512. float incrementX,
  27513. float incrementY)
  27514. {
  27515. if (pluginWindow != 0)
  27516. {
  27517. XEvent ev;
  27518. zerostruct (ev);
  27519. ev.xbutton.display = display;
  27520. ev.xbutton.type = ButtonPress;
  27521. ev.xbutton.window = pluginWindow;
  27522. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27523. ev.xbutton.time = CurrentTime;
  27524. ev.xbutton.x = e.x;
  27525. ev.xbutton.y = e.y;
  27526. ev.xbutton.x_root = e.getScreenX();
  27527. ev.xbutton.y_root = e.getScreenY();
  27528. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27529. sendEventToChild (&ev);
  27530. // TODO - put a usleep here ?
  27531. ev.xbutton.type = ButtonRelease;
  27532. sendEventToChild (&ev);
  27533. }
  27534. }
  27535. #endif
  27536. #if JUCE_MAC
  27537. #if ! JUCE_SUPPORT_CARBON
  27538. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27539. #endif
  27540. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27541. {
  27542. public:
  27543. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27544. : owner (owner_),
  27545. alreadyInside (false)
  27546. {
  27547. }
  27548. ~InnerWrapperComponent()
  27549. {
  27550. deleteWindow();
  27551. }
  27552. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27553. {
  27554. owner->openPluginWindow (windowRef);
  27555. return 0;
  27556. }
  27557. void removeView (HIViewRef)
  27558. {
  27559. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27560. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27561. }
  27562. bool getEmbeddedViewSize (int& w, int& h)
  27563. {
  27564. ERect* rect = 0;
  27565. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27566. w = rect->right - rect->left;
  27567. h = rect->bottom - rect->top;
  27568. return true;
  27569. }
  27570. void mouseDown (int x, int y)
  27571. {
  27572. if (! alreadyInside)
  27573. {
  27574. alreadyInside = true;
  27575. getTopLevelComponent()->toFront (true);
  27576. owner->dispatch (effEditMouse, x, y, 0, 0);
  27577. alreadyInside = false;
  27578. }
  27579. else
  27580. {
  27581. PostEvent (::mouseDown, 0);
  27582. }
  27583. }
  27584. void paint()
  27585. {
  27586. ComponentPeer* const peer = getPeer();
  27587. if (peer != 0)
  27588. {
  27589. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27590. ERect r;
  27591. r.left = pos.getX();
  27592. r.right = r.left + getWidth();
  27593. r.top = pos.getY();
  27594. r.bottom = r.top + getHeight();
  27595. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27596. }
  27597. }
  27598. private:
  27599. VSTPluginWindow* const owner;
  27600. bool alreadyInside;
  27601. };
  27602. friend class InnerWrapperComponent;
  27603. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27604. void resized()
  27605. {
  27606. innerWrapper->setSize (getWidth(), getHeight());
  27607. }
  27608. #endif
  27609. private:
  27610. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27611. };
  27612. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27613. {
  27614. if (hasEditor())
  27615. return new VSTPluginWindow (*this);
  27616. return 0;
  27617. }
  27618. void VSTPluginInstance::handleAsyncUpdate()
  27619. {
  27620. // indicates that something about the plugin has changed..
  27621. updateHostDisplay();
  27622. }
  27623. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27624. {
  27625. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27626. {
  27627. changeProgramName (getCurrentProgram(), prog->prgName);
  27628. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27629. setParameter (i, vst_swapFloat (prog->params[i]));
  27630. return true;
  27631. }
  27632. return false;
  27633. }
  27634. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27635. const int dataSize)
  27636. {
  27637. if (dataSize < 28)
  27638. return false;
  27639. const fxSet* const set = (const fxSet*) data;
  27640. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27641. || vst_swap (set->version) > fxbVersionNum)
  27642. return false;
  27643. if (vst_swap (set->fxMagic) == 'FxBk')
  27644. {
  27645. // bank of programs
  27646. if (vst_swap (set->numPrograms) >= 0)
  27647. {
  27648. const int oldProg = getCurrentProgram();
  27649. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27650. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27651. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27652. {
  27653. if (i != oldProg)
  27654. {
  27655. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27656. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27657. return false;
  27658. if (vst_swap (set->numPrograms) > 0)
  27659. setCurrentProgram (i);
  27660. if (! restoreProgramSettings (prog))
  27661. return false;
  27662. }
  27663. }
  27664. if (vst_swap (set->numPrograms) > 0)
  27665. setCurrentProgram (oldProg);
  27666. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27667. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27668. return false;
  27669. if (! restoreProgramSettings (prog))
  27670. return false;
  27671. }
  27672. }
  27673. else if (vst_swap (set->fxMagic) == 'FxCk')
  27674. {
  27675. // single program
  27676. const fxProgram* const prog = (const fxProgram*) data;
  27677. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27678. return false;
  27679. changeProgramName (getCurrentProgram(), prog->prgName);
  27680. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27681. setParameter (i, vst_swapFloat (prog->params[i]));
  27682. }
  27683. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27684. {
  27685. // non-preset chunk
  27686. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27687. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27688. return false;
  27689. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27690. }
  27691. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27692. {
  27693. // preset chunk
  27694. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27695. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27696. return false;
  27697. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27698. changeProgramName (getCurrentProgram(), cset->name);
  27699. }
  27700. else
  27701. {
  27702. return false;
  27703. }
  27704. return true;
  27705. }
  27706. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27707. {
  27708. const int numParams = getNumParameters();
  27709. prog->chunkMagic = vst_swap ('CcnK');
  27710. prog->byteSize = 0;
  27711. prog->fxMagic = vst_swap ('FxCk');
  27712. prog->version = vst_swap (fxbVersionNum);
  27713. prog->fxID = vst_swap (getUID());
  27714. prog->fxVersion = vst_swap (getVersionNumber());
  27715. prog->numParams = vst_swap (numParams);
  27716. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27717. for (int i = 0; i < numParams; ++i)
  27718. prog->params[i] = vst_swapFloat (getParameter (i));
  27719. }
  27720. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27721. {
  27722. const int numPrograms = getNumPrograms();
  27723. const int numParams = getNumParameters();
  27724. if (usesChunks())
  27725. {
  27726. if (isFXB)
  27727. {
  27728. MemoryBlock chunk;
  27729. getChunkData (chunk, false, maxSizeMB);
  27730. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27731. dest.setSize (totalLen, true);
  27732. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27733. set->chunkMagic = vst_swap ('CcnK');
  27734. set->byteSize = 0;
  27735. set->fxMagic = vst_swap ('FBCh');
  27736. set->version = vst_swap (fxbVersionNum);
  27737. set->fxID = vst_swap (getUID());
  27738. set->fxVersion = vst_swap (getVersionNumber());
  27739. set->numPrograms = vst_swap (numPrograms);
  27740. set->chunkSize = vst_swap ((long) chunk.getSize());
  27741. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27742. }
  27743. else
  27744. {
  27745. MemoryBlock chunk;
  27746. getChunkData (chunk, true, maxSizeMB);
  27747. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27748. dest.setSize (totalLen, true);
  27749. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27750. set->chunkMagic = vst_swap ('CcnK');
  27751. set->byteSize = 0;
  27752. set->fxMagic = vst_swap ('FPCh');
  27753. set->version = vst_swap (fxbVersionNum);
  27754. set->fxID = vst_swap (getUID());
  27755. set->fxVersion = vst_swap (getVersionNumber());
  27756. set->numPrograms = vst_swap (numPrograms);
  27757. set->chunkSize = vst_swap ((long) chunk.getSize());
  27758. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27759. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27760. }
  27761. }
  27762. else
  27763. {
  27764. if (isFXB)
  27765. {
  27766. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27767. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27768. dest.setSize (len, true);
  27769. fxSet* const set = (fxSet*) dest.getData();
  27770. set->chunkMagic = vst_swap ('CcnK');
  27771. set->byteSize = 0;
  27772. set->fxMagic = vst_swap ('FxBk');
  27773. set->version = vst_swap (fxbVersionNum);
  27774. set->fxID = vst_swap (getUID());
  27775. set->fxVersion = vst_swap (getVersionNumber());
  27776. set->numPrograms = vst_swap (numPrograms);
  27777. const int oldProgram = getCurrentProgram();
  27778. MemoryBlock oldSettings;
  27779. createTempParameterStore (oldSettings);
  27780. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27781. for (int i = 0; i < numPrograms; ++i)
  27782. {
  27783. if (i != oldProgram)
  27784. {
  27785. setCurrentProgram (i);
  27786. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27787. }
  27788. }
  27789. setCurrentProgram (oldProgram);
  27790. restoreFromTempParameterStore (oldSettings);
  27791. }
  27792. else
  27793. {
  27794. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27795. dest.setSize (totalLen, true);
  27796. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27797. }
  27798. }
  27799. return true;
  27800. }
  27801. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27802. {
  27803. if (usesChunks())
  27804. {
  27805. void* data = 0;
  27806. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27807. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27808. {
  27809. mb.setSize (bytes);
  27810. mb.copyFrom (data, 0, bytes);
  27811. }
  27812. }
  27813. }
  27814. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27815. {
  27816. if (size > 0 && usesChunks())
  27817. {
  27818. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27819. if (! isPreset)
  27820. updateStoredProgramNames();
  27821. }
  27822. }
  27823. void VSTPluginInstance::timerCallback()
  27824. {
  27825. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27826. stopTimer();
  27827. }
  27828. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27829. {
  27830. const ScopedLock sl (lock);
  27831. ++insideVSTCallback;
  27832. int result = 0;
  27833. try
  27834. {
  27835. if (effect != 0)
  27836. {
  27837. #if JUCE_MAC
  27838. if (module->resFileId != 0)
  27839. UseResFile (module->resFileId);
  27840. #endif
  27841. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27842. #if JUCE_MAC
  27843. module->resFileId = CurResFile();
  27844. #endif
  27845. --insideVSTCallback;
  27846. return result;
  27847. }
  27848. }
  27849. catch (...)
  27850. {
  27851. }
  27852. --insideVSTCallback;
  27853. return result;
  27854. }
  27855. namespace
  27856. {
  27857. static const int defaultVSTSampleRateValue = 16384;
  27858. static const int defaultVSTBlockSizeValue = 512;
  27859. // handles non plugin-specific callbacks..
  27860. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27861. {
  27862. (void) index;
  27863. (void) value;
  27864. (void) opt;
  27865. switch (opcode)
  27866. {
  27867. case audioMasterCanDo:
  27868. {
  27869. static const char* canDos[] = { "supplyIdle",
  27870. "sendVstEvents",
  27871. "sendVstMidiEvent",
  27872. "sendVstTimeInfo",
  27873. "receiveVstEvents",
  27874. "receiveVstMidiEvent",
  27875. "supportShell",
  27876. "shellCategory" };
  27877. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27878. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27879. return 1;
  27880. return 0;
  27881. }
  27882. case audioMasterVersion: return 0x2400;
  27883. case audioMasterCurrentId: return shellUIDToCreate;
  27884. case audioMasterGetNumAutomatableParameters: return 0;
  27885. case audioMasterGetAutomationState: return 1;
  27886. case audioMasterGetVendorVersion: return 0x0101;
  27887. case audioMasterGetVendorString:
  27888. case audioMasterGetProductString:
  27889. {
  27890. String hostName ("Juce VST Host");
  27891. if (JUCEApplication::getInstance() != 0)
  27892. hostName = JUCEApplication::getInstance()->getApplicationName();
  27893. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27894. break;
  27895. }
  27896. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  27897. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  27898. case audioMasterSetOutputSampleRate: return 0;
  27899. default:
  27900. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27901. break;
  27902. }
  27903. return 0;
  27904. }
  27905. }
  27906. // handles callbacks for a specific plugin
  27907. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27908. {
  27909. switch (opcode)
  27910. {
  27911. case audioMasterAutomate:
  27912. sendParamChangeMessageToListeners (index, opt);
  27913. break;
  27914. case audioMasterProcessEvents:
  27915. handleMidiFromPlugin ((const VstEvents*) ptr);
  27916. break;
  27917. case audioMasterGetTime:
  27918. #if JUCE_MSVC
  27919. #pragma warning (push)
  27920. #pragma warning (disable: 4311)
  27921. #endif
  27922. return (VstIntPtr) &vstHostTime;
  27923. #if JUCE_MSVC
  27924. #pragma warning (pop)
  27925. #endif
  27926. break;
  27927. case audioMasterIdle:
  27928. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27929. {
  27930. ++insideVSTCallback;
  27931. #if JUCE_MAC
  27932. if (getActiveEditor() != 0)
  27933. dispatch (effEditIdle, 0, 0, 0, 0);
  27934. #endif
  27935. juce_callAnyTimersSynchronously();
  27936. handleUpdateNowIfNeeded();
  27937. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27938. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27939. --insideVSTCallback;
  27940. }
  27941. break;
  27942. case audioMasterUpdateDisplay:
  27943. triggerAsyncUpdate();
  27944. break;
  27945. case audioMasterTempoAt:
  27946. // returns (10000 * bpm)
  27947. break;
  27948. case audioMasterNeedIdle:
  27949. startTimer (50);
  27950. break;
  27951. case audioMasterSizeWindow:
  27952. if (getActiveEditor() != 0)
  27953. getActiveEditor()->setSize (index, value);
  27954. return 1;
  27955. case audioMasterGetSampleRate:
  27956. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27957. case audioMasterGetBlockSize:
  27958. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27959. case audioMasterWantMidi:
  27960. wantsMidiMessages = true;
  27961. break;
  27962. case audioMasterGetDirectory:
  27963. #if JUCE_MAC
  27964. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27965. #else
  27966. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  27967. #endif
  27968. case audioMasterGetAutomationState:
  27969. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27970. break;
  27971. // none of these are handled (yet)..
  27972. case audioMasterBeginEdit:
  27973. case audioMasterEndEdit:
  27974. case audioMasterSetTime:
  27975. case audioMasterPinConnected:
  27976. case audioMasterGetParameterQuantization:
  27977. case audioMasterIOChanged:
  27978. case audioMasterGetInputLatency:
  27979. case audioMasterGetOutputLatency:
  27980. case audioMasterGetPreviousPlug:
  27981. case audioMasterGetNextPlug:
  27982. case audioMasterWillReplaceOrAccumulate:
  27983. case audioMasterGetCurrentProcessLevel:
  27984. case audioMasterOfflineStart:
  27985. case audioMasterOfflineRead:
  27986. case audioMasterOfflineWrite:
  27987. case audioMasterOfflineGetCurrentPass:
  27988. case audioMasterOfflineGetCurrentMetaPass:
  27989. case audioMasterVendorSpecific:
  27990. case audioMasterSetIcon:
  27991. case audioMasterGetLanguage:
  27992. case audioMasterOpenWindow:
  27993. case audioMasterCloseWindow:
  27994. break;
  27995. default:
  27996. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27997. }
  27998. return 0;
  27999. }
  28000. // entry point for all callbacks from the plugin
  28001. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28002. {
  28003. try
  28004. {
  28005. if (effect != 0 && effect->resvd2 != 0)
  28006. {
  28007. return ((VSTPluginInstance*)(effect->resvd2))
  28008. ->handleCallback (opcode, index, value, ptr, opt);
  28009. }
  28010. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28011. }
  28012. catch (...)
  28013. {
  28014. return 0;
  28015. }
  28016. }
  28017. const String VSTPluginInstance::getVersion() const
  28018. {
  28019. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28020. String s;
  28021. if (v == 0 || v == -1)
  28022. v = getVersionNumber();
  28023. if (v != 0)
  28024. {
  28025. int versionBits[4];
  28026. int n = 0;
  28027. while (v != 0)
  28028. {
  28029. versionBits [n++] = (v & 0xff);
  28030. v >>= 8;
  28031. }
  28032. s << 'V';
  28033. while (n > 0)
  28034. {
  28035. s << versionBits [--n];
  28036. if (n > 0)
  28037. s << '.';
  28038. }
  28039. }
  28040. return s;
  28041. }
  28042. int VSTPluginInstance::getUID() const
  28043. {
  28044. int uid = effect != 0 ? effect->uniqueID : 0;
  28045. if (uid == 0)
  28046. uid = module->file.hashCode();
  28047. return uid;
  28048. }
  28049. const String VSTPluginInstance::getCategory() const
  28050. {
  28051. const char* result = 0;
  28052. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28053. {
  28054. case kPlugCategEffect: result = "Effect"; break;
  28055. case kPlugCategSynth: result = "Synth"; break;
  28056. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28057. case kPlugCategMastering: result = "Mastering"; break;
  28058. case kPlugCategSpacializer: result = "Spacial"; break;
  28059. case kPlugCategRoomFx: result = "Reverb"; break;
  28060. case kPlugSurroundFx: result = "Surround"; break;
  28061. case kPlugCategRestoration: result = "Restoration"; break;
  28062. case kPlugCategGenerator: result = "Tone generation"; break;
  28063. default: break;
  28064. }
  28065. return result;
  28066. }
  28067. float VSTPluginInstance::getParameter (int index)
  28068. {
  28069. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28070. {
  28071. try
  28072. {
  28073. const ScopedLock sl (lock);
  28074. return effect->getParameter (effect, index);
  28075. }
  28076. catch (...)
  28077. {
  28078. }
  28079. }
  28080. return 0.0f;
  28081. }
  28082. void VSTPluginInstance::setParameter (int index, float newValue)
  28083. {
  28084. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28085. {
  28086. try
  28087. {
  28088. const ScopedLock sl (lock);
  28089. if (effect->getParameter (effect, index) != newValue)
  28090. effect->setParameter (effect, index, newValue);
  28091. }
  28092. catch (...)
  28093. {
  28094. }
  28095. }
  28096. }
  28097. const String VSTPluginInstance::getParameterName (int index)
  28098. {
  28099. if (effect != 0)
  28100. {
  28101. jassert (index >= 0 && index < effect->numParams);
  28102. char nm [256];
  28103. zerostruct (nm);
  28104. dispatch (effGetParamName, index, 0, nm, 0);
  28105. return String (nm).trim();
  28106. }
  28107. return String::empty;
  28108. }
  28109. const String VSTPluginInstance::getParameterLabel (int index) const
  28110. {
  28111. if (effect != 0)
  28112. {
  28113. jassert (index >= 0 && index < effect->numParams);
  28114. char nm [256];
  28115. zerostruct (nm);
  28116. dispatch (effGetParamLabel, index, 0, nm, 0);
  28117. return String (nm).trim();
  28118. }
  28119. return String::empty;
  28120. }
  28121. const String VSTPluginInstance::getParameterText (int index)
  28122. {
  28123. if (effect != 0)
  28124. {
  28125. jassert (index >= 0 && index < effect->numParams);
  28126. char nm [256];
  28127. zerostruct (nm);
  28128. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28129. return String (nm).trim();
  28130. }
  28131. return String::empty;
  28132. }
  28133. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28134. {
  28135. if (effect != 0)
  28136. {
  28137. jassert (index >= 0 && index < effect->numParams);
  28138. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28139. }
  28140. return false;
  28141. }
  28142. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28143. {
  28144. dest.setSize (64 + 4 * getNumParameters());
  28145. dest.fillWith (0);
  28146. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28147. float* const p = (float*) (((char*) dest.getData()) + 64);
  28148. for (int i = 0; i < getNumParameters(); ++i)
  28149. p[i] = getParameter(i);
  28150. }
  28151. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28152. {
  28153. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28154. float* p = (float*) (((char*) m.getData()) + 64);
  28155. for (int i = 0; i < getNumParameters(); ++i)
  28156. setParameter (i, p[i]);
  28157. }
  28158. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28159. {
  28160. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28161. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28162. }
  28163. const String VSTPluginInstance::getProgramName (int index)
  28164. {
  28165. if (index == getCurrentProgram())
  28166. {
  28167. return getCurrentProgramName();
  28168. }
  28169. else if (effect != 0)
  28170. {
  28171. char nm [256];
  28172. zerostruct (nm);
  28173. if (dispatch (effGetProgramNameIndexed,
  28174. jlimit (0, getNumPrograms(), index),
  28175. -1, nm, 0) != 0)
  28176. {
  28177. return String (nm).trim();
  28178. }
  28179. }
  28180. return programNames [index];
  28181. }
  28182. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28183. {
  28184. if (index == getCurrentProgram())
  28185. {
  28186. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28187. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28188. }
  28189. else
  28190. {
  28191. jassertfalse; // xxx not implemented!
  28192. }
  28193. }
  28194. void VSTPluginInstance::updateStoredProgramNames()
  28195. {
  28196. if (effect != 0 && getNumPrograms() > 0)
  28197. {
  28198. char nm [256];
  28199. zerostruct (nm);
  28200. // only do this if the plugin can't use indexed names..
  28201. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28202. {
  28203. const int oldProgram = getCurrentProgram();
  28204. MemoryBlock oldSettings;
  28205. createTempParameterStore (oldSettings);
  28206. for (int i = 0; i < getNumPrograms(); ++i)
  28207. {
  28208. setCurrentProgram (i);
  28209. getCurrentProgramName(); // (this updates the list)
  28210. }
  28211. setCurrentProgram (oldProgram);
  28212. restoreFromTempParameterStore (oldSettings);
  28213. }
  28214. }
  28215. }
  28216. const String VSTPluginInstance::getCurrentProgramName()
  28217. {
  28218. if (effect != 0)
  28219. {
  28220. char nm [256];
  28221. zerostruct (nm);
  28222. dispatch (effGetProgramName, 0, 0, nm, 0);
  28223. const int index = getCurrentProgram();
  28224. if (programNames[index].isEmpty())
  28225. {
  28226. while (programNames.size() < index)
  28227. programNames.add (String::empty);
  28228. programNames.set (index, String (nm).trim());
  28229. }
  28230. return String (nm).trim();
  28231. }
  28232. return String::empty;
  28233. }
  28234. const String VSTPluginInstance::getInputChannelName (int index) const
  28235. {
  28236. if (index >= 0 && index < getNumInputChannels())
  28237. {
  28238. VstPinProperties pinProps;
  28239. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28240. return String (pinProps.label, sizeof (pinProps.label));
  28241. }
  28242. return String::empty;
  28243. }
  28244. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28245. {
  28246. if (index < 0 || index >= getNumInputChannels())
  28247. return false;
  28248. VstPinProperties pinProps;
  28249. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28250. return (pinProps.flags & kVstPinIsStereo) != 0;
  28251. return true;
  28252. }
  28253. const String VSTPluginInstance::getOutputChannelName (int index) const
  28254. {
  28255. if (index >= 0 && index < getNumOutputChannels())
  28256. {
  28257. VstPinProperties pinProps;
  28258. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28259. return String (pinProps.label, sizeof (pinProps.label));
  28260. }
  28261. return String::empty;
  28262. }
  28263. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28264. {
  28265. if (index < 0 || index >= getNumOutputChannels())
  28266. return false;
  28267. VstPinProperties pinProps;
  28268. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28269. return (pinProps.flags & kVstPinIsStereo) != 0;
  28270. return true;
  28271. }
  28272. void VSTPluginInstance::setPower (const bool on)
  28273. {
  28274. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28275. isPowerOn = on;
  28276. }
  28277. const int defaultMaxSizeMB = 64;
  28278. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28279. {
  28280. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28281. }
  28282. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28283. {
  28284. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28285. }
  28286. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28287. {
  28288. loadFromFXBFile (data, sizeInBytes);
  28289. }
  28290. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28291. {
  28292. loadFromFXBFile (data, sizeInBytes);
  28293. }
  28294. VSTPluginFormat::VSTPluginFormat()
  28295. {
  28296. }
  28297. VSTPluginFormat::~VSTPluginFormat()
  28298. {
  28299. }
  28300. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28301. const String& fileOrIdentifier)
  28302. {
  28303. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28304. return;
  28305. PluginDescription desc;
  28306. desc.fileOrIdentifier = fileOrIdentifier;
  28307. desc.uid = 0;
  28308. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28309. if (instance == 0)
  28310. return;
  28311. try
  28312. {
  28313. #if JUCE_MAC
  28314. if (instance->module->resFileId != 0)
  28315. UseResFile (instance->module->resFileId);
  28316. #endif
  28317. instance->fillInPluginDescription (desc);
  28318. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28319. if (category != kPlugCategShell)
  28320. {
  28321. // Normal plugin...
  28322. results.add (new PluginDescription (desc));
  28323. ++insideVSTCallback;
  28324. instance->dispatch (effOpen, 0, 0, 0, 0);
  28325. --insideVSTCallback;
  28326. }
  28327. else
  28328. {
  28329. // It's a shell plugin, so iterate all the subtypes...
  28330. char shellEffectName [64];
  28331. for (;;)
  28332. {
  28333. zerostruct (shellEffectName);
  28334. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28335. if (uid == 0)
  28336. {
  28337. break;
  28338. }
  28339. else
  28340. {
  28341. desc.uid = uid;
  28342. desc.name = shellEffectName;
  28343. desc.descriptiveName = shellEffectName;
  28344. bool alreadyThere = false;
  28345. for (int i = results.size(); --i >= 0;)
  28346. {
  28347. PluginDescription* const d = results.getUnchecked(i);
  28348. if (d->isDuplicateOf (desc))
  28349. {
  28350. alreadyThere = true;
  28351. break;
  28352. }
  28353. }
  28354. if (! alreadyThere)
  28355. results.add (new PluginDescription (desc));
  28356. }
  28357. }
  28358. }
  28359. }
  28360. catch (...)
  28361. {
  28362. // crashed while loading...
  28363. }
  28364. }
  28365. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28366. {
  28367. ScopedPointer <VSTPluginInstance> result;
  28368. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28369. {
  28370. File file (desc.fileOrIdentifier);
  28371. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28372. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28373. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28374. if (module != 0)
  28375. {
  28376. shellUIDToCreate = desc.uid;
  28377. result = new VSTPluginInstance (module);
  28378. if (result->effect != 0)
  28379. {
  28380. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28381. result->initialise();
  28382. }
  28383. else
  28384. {
  28385. result = 0;
  28386. }
  28387. }
  28388. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28389. }
  28390. return result.release();
  28391. }
  28392. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28393. {
  28394. const File f (fileOrIdentifier);
  28395. #if JUCE_MAC
  28396. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28397. return true;
  28398. #if JUCE_PPC
  28399. FSRef fileRef;
  28400. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28401. {
  28402. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28403. if (resFileId != -1)
  28404. {
  28405. const int numEffects = Count1Resources ('aEff');
  28406. CloseResFile (resFileId);
  28407. if (numEffects > 0)
  28408. return true;
  28409. }
  28410. }
  28411. #endif
  28412. return false;
  28413. #elif JUCE_WINDOWS
  28414. return f.existsAsFile() && f.hasFileExtension (".dll");
  28415. #elif JUCE_LINUX
  28416. return f.existsAsFile() && f.hasFileExtension (".so");
  28417. #endif
  28418. }
  28419. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28420. {
  28421. return fileOrIdentifier;
  28422. }
  28423. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28424. {
  28425. return File (desc.fileOrIdentifier).exists();
  28426. }
  28427. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28428. {
  28429. StringArray results;
  28430. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28431. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28432. return results;
  28433. }
  28434. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28435. {
  28436. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28437. // .component or .vst directories.
  28438. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28439. while (iter.next())
  28440. {
  28441. const File f (iter.getFile());
  28442. bool isPlugin = false;
  28443. if (fileMightContainThisPluginType (f.getFullPathName()))
  28444. {
  28445. isPlugin = true;
  28446. results.add (f.getFullPathName());
  28447. }
  28448. if (recursive && (! isPlugin) && f.isDirectory())
  28449. recursiveFileSearch (results, f, true);
  28450. }
  28451. }
  28452. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28453. {
  28454. #if JUCE_MAC
  28455. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28456. #elif JUCE_WINDOWS
  28457. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28458. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28459. #elif JUCE_LINUX
  28460. return FileSearchPath ("/usr/lib/vst");
  28461. #endif
  28462. }
  28463. END_JUCE_NAMESPACE
  28464. #endif
  28465. #undef log
  28466. #endif
  28467. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28468. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28469. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28470. BEGIN_JUCE_NAMESPACE
  28471. AudioProcessor::AudioProcessor()
  28472. : playHead (0),
  28473. sampleRate (0),
  28474. blockSize (0),
  28475. numInputChannels (0),
  28476. numOutputChannels (0),
  28477. latencySamples (0),
  28478. suspended (false),
  28479. nonRealtime (false)
  28480. {
  28481. }
  28482. AudioProcessor::~AudioProcessor()
  28483. {
  28484. // ooh, nasty - the editor should have been deleted before the filter
  28485. // that it refers to is deleted..
  28486. jassert (activeEditor == 0);
  28487. #if JUCE_DEBUG
  28488. // This will fail if you've called beginParameterChangeGesture() for one
  28489. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28490. jassert (changingParams.countNumberOfSetBits() == 0);
  28491. #endif
  28492. }
  28493. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28494. {
  28495. playHead = newPlayHead;
  28496. }
  28497. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28498. {
  28499. const ScopedLock sl (listenerLock);
  28500. listeners.addIfNotAlreadyThere (newListener);
  28501. }
  28502. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28503. {
  28504. const ScopedLock sl (listenerLock);
  28505. listeners.removeValue (listenerToRemove);
  28506. }
  28507. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28508. const int numOuts,
  28509. const double sampleRate_,
  28510. const int blockSize_) throw()
  28511. {
  28512. numInputChannels = numIns;
  28513. numOutputChannels = numOuts;
  28514. sampleRate = sampleRate_;
  28515. blockSize = blockSize_;
  28516. }
  28517. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28518. {
  28519. nonRealtime = nonRealtime_;
  28520. }
  28521. void AudioProcessor::setLatencySamples (const int newLatency)
  28522. {
  28523. if (latencySamples != newLatency)
  28524. {
  28525. latencySamples = newLatency;
  28526. updateHostDisplay();
  28527. }
  28528. }
  28529. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28530. const float newValue)
  28531. {
  28532. setParameter (parameterIndex, newValue);
  28533. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28534. }
  28535. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28536. {
  28537. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28538. for (int i = listeners.size(); --i >= 0;)
  28539. {
  28540. AudioProcessorListener* l;
  28541. {
  28542. const ScopedLock sl (listenerLock);
  28543. l = listeners [i];
  28544. }
  28545. if (l != 0)
  28546. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28547. }
  28548. }
  28549. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28550. {
  28551. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28552. #if JUCE_DEBUG
  28553. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28554. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28555. jassert (! changingParams [parameterIndex]);
  28556. changingParams.setBit (parameterIndex);
  28557. #endif
  28558. for (int i = listeners.size(); --i >= 0;)
  28559. {
  28560. AudioProcessorListener* l;
  28561. {
  28562. const ScopedLock sl (listenerLock);
  28563. l = listeners [i];
  28564. }
  28565. if (l != 0)
  28566. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28567. }
  28568. }
  28569. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28570. {
  28571. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28572. #if JUCE_DEBUG
  28573. // This means you've called endParameterChangeGesture without having previously called
  28574. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28575. // calls matched correctly.
  28576. jassert (changingParams [parameterIndex]);
  28577. changingParams.clearBit (parameterIndex);
  28578. #endif
  28579. for (int i = listeners.size(); --i >= 0;)
  28580. {
  28581. AudioProcessorListener* l;
  28582. {
  28583. const ScopedLock sl (listenerLock);
  28584. l = listeners [i];
  28585. }
  28586. if (l != 0)
  28587. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28588. }
  28589. }
  28590. void AudioProcessor::updateHostDisplay()
  28591. {
  28592. for (int i = listeners.size(); --i >= 0;)
  28593. {
  28594. AudioProcessorListener* l;
  28595. {
  28596. const ScopedLock sl (listenerLock);
  28597. l = listeners [i];
  28598. }
  28599. if (l != 0)
  28600. l->audioProcessorChanged (this);
  28601. }
  28602. }
  28603. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28604. {
  28605. return true;
  28606. }
  28607. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28608. {
  28609. return false;
  28610. }
  28611. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28612. {
  28613. const ScopedLock sl (callbackLock);
  28614. suspended = shouldBeSuspended;
  28615. }
  28616. void AudioProcessor::reset()
  28617. {
  28618. }
  28619. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28620. {
  28621. const ScopedLock sl (callbackLock);
  28622. if (activeEditor == editor)
  28623. activeEditor = 0;
  28624. }
  28625. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28626. {
  28627. if (activeEditor != 0)
  28628. return activeEditor;
  28629. AudioProcessorEditor* const ed = createEditor();
  28630. // You must make your hasEditor() method return a consistent result!
  28631. jassert (hasEditor() == (ed != 0));
  28632. if (ed != 0)
  28633. {
  28634. // you must give your editor comp a size before returning it..
  28635. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28636. const ScopedLock sl (callbackLock);
  28637. activeEditor = ed;
  28638. }
  28639. return ed;
  28640. }
  28641. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28642. {
  28643. getStateInformation (destData);
  28644. }
  28645. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28646. {
  28647. setStateInformation (data, sizeInBytes);
  28648. }
  28649. // magic number to identify memory blocks that we've stored as XML
  28650. const uint32 magicXmlNumber = 0x21324356;
  28651. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28652. JUCE_NAMESPACE::MemoryBlock& destData)
  28653. {
  28654. const String xmlString (xml.createDocument (String::empty, true, false));
  28655. const int stringLength = xmlString.getNumBytesAsUTF8();
  28656. destData.setSize (stringLength + 10);
  28657. char* const d = static_cast<char*> (destData.getData());
  28658. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28659. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28660. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28661. }
  28662. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28663. const int sizeInBytes)
  28664. {
  28665. if (sizeInBytes > 8
  28666. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28667. {
  28668. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28669. if (stringLength > 0)
  28670. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28671. jmin ((sizeInBytes - 8), stringLength)));
  28672. }
  28673. return 0;
  28674. }
  28675. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28676. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28677. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28678. {
  28679. return timeInSeconds == other.timeInSeconds
  28680. && ppqPosition == other.ppqPosition
  28681. && editOriginTime == other.editOriginTime
  28682. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28683. && frameRate == other.frameRate
  28684. && isPlaying == other.isPlaying
  28685. && isRecording == other.isRecording
  28686. && bpm == other.bpm
  28687. && timeSigNumerator == other.timeSigNumerator
  28688. && timeSigDenominator == other.timeSigDenominator;
  28689. }
  28690. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28691. {
  28692. return ! operator== (other);
  28693. }
  28694. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28695. {
  28696. zerostruct (*this);
  28697. timeSigNumerator = 4;
  28698. timeSigDenominator = 4;
  28699. bpm = 120;
  28700. }
  28701. END_JUCE_NAMESPACE
  28702. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28703. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28704. BEGIN_JUCE_NAMESPACE
  28705. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28706. : owner (owner_)
  28707. {
  28708. // the filter must be valid..
  28709. jassert (owner != 0);
  28710. }
  28711. AudioProcessorEditor::~AudioProcessorEditor()
  28712. {
  28713. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28714. // filter for some reason..
  28715. jassert (owner->getActiveEditor() != this);
  28716. }
  28717. END_JUCE_NAMESPACE
  28718. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28719. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28720. BEGIN_JUCE_NAMESPACE
  28721. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28722. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28723. : id (id_),
  28724. processor (processor_),
  28725. isPrepared (false)
  28726. {
  28727. jassert (processor_ != 0);
  28728. }
  28729. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28730. AudioProcessorGraph* const graph)
  28731. {
  28732. if (! isPrepared)
  28733. {
  28734. isPrepared = true;
  28735. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28736. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28737. if (ioProc != 0)
  28738. ioProc->setParentGraph (graph);
  28739. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28740. processor->getNumOutputChannels(),
  28741. sampleRate, blockSize);
  28742. processor->prepareToPlay (sampleRate, blockSize);
  28743. }
  28744. }
  28745. void AudioProcessorGraph::Node::unprepare()
  28746. {
  28747. if (isPrepared)
  28748. {
  28749. isPrepared = false;
  28750. processor->releaseResources();
  28751. }
  28752. }
  28753. AudioProcessorGraph::AudioProcessorGraph()
  28754. : lastNodeId (0),
  28755. renderingBuffers (1, 1),
  28756. currentAudioOutputBuffer (1, 1)
  28757. {
  28758. }
  28759. AudioProcessorGraph::~AudioProcessorGraph()
  28760. {
  28761. clearRenderingSequence();
  28762. clear();
  28763. }
  28764. const String AudioProcessorGraph::getName() const
  28765. {
  28766. return "Audio Graph";
  28767. }
  28768. void AudioProcessorGraph::clear()
  28769. {
  28770. nodes.clear();
  28771. connections.clear();
  28772. triggerAsyncUpdate();
  28773. }
  28774. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28775. {
  28776. for (int i = nodes.size(); --i >= 0;)
  28777. if (nodes.getUnchecked(i)->id == nodeId)
  28778. return nodes.getUnchecked(i);
  28779. return 0;
  28780. }
  28781. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28782. uint32 nodeId)
  28783. {
  28784. if (newProcessor == 0)
  28785. {
  28786. jassertfalse;
  28787. return 0;
  28788. }
  28789. if (nodeId == 0)
  28790. {
  28791. nodeId = ++lastNodeId;
  28792. }
  28793. else
  28794. {
  28795. // you can't add a node with an id that already exists in the graph..
  28796. jassert (getNodeForId (nodeId) == 0);
  28797. removeNode (nodeId);
  28798. }
  28799. lastNodeId = nodeId;
  28800. Node* const n = new Node (nodeId, newProcessor);
  28801. nodes.add (n);
  28802. triggerAsyncUpdate();
  28803. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28804. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28805. if (ioProc != 0)
  28806. ioProc->setParentGraph (this);
  28807. return n;
  28808. }
  28809. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28810. {
  28811. disconnectNode (nodeId);
  28812. for (int i = nodes.size(); --i >= 0;)
  28813. {
  28814. if (nodes.getUnchecked(i)->id == nodeId)
  28815. {
  28816. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28817. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28818. if (ioProc != 0)
  28819. ioProc->setParentGraph (0);
  28820. nodes.remove (i);
  28821. triggerAsyncUpdate();
  28822. return true;
  28823. }
  28824. }
  28825. return false;
  28826. }
  28827. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28828. const int sourceChannelIndex,
  28829. const uint32 destNodeId,
  28830. const int destChannelIndex) const
  28831. {
  28832. for (int i = connections.size(); --i >= 0;)
  28833. {
  28834. const Connection* const c = connections.getUnchecked(i);
  28835. if (c->sourceNodeId == sourceNodeId
  28836. && c->destNodeId == destNodeId
  28837. && c->sourceChannelIndex == sourceChannelIndex
  28838. && c->destChannelIndex == destChannelIndex)
  28839. {
  28840. return c;
  28841. }
  28842. }
  28843. return 0;
  28844. }
  28845. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28846. const uint32 possibleDestNodeId) const
  28847. {
  28848. for (int i = connections.size(); --i >= 0;)
  28849. {
  28850. const Connection* const c = connections.getUnchecked(i);
  28851. if (c->sourceNodeId == possibleSourceNodeId
  28852. && c->destNodeId == possibleDestNodeId)
  28853. {
  28854. return true;
  28855. }
  28856. }
  28857. return false;
  28858. }
  28859. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28860. const int sourceChannelIndex,
  28861. const uint32 destNodeId,
  28862. const int destChannelIndex) const
  28863. {
  28864. if (sourceChannelIndex < 0
  28865. || destChannelIndex < 0
  28866. || sourceNodeId == destNodeId
  28867. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28868. return false;
  28869. const Node* const source = getNodeForId (sourceNodeId);
  28870. if (source == 0
  28871. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28872. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28873. return false;
  28874. const Node* const dest = getNodeForId (destNodeId);
  28875. if (dest == 0
  28876. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28877. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28878. return false;
  28879. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28880. destNodeId, destChannelIndex) == 0;
  28881. }
  28882. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28883. const int sourceChannelIndex,
  28884. const uint32 destNodeId,
  28885. const int destChannelIndex)
  28886. {
  28887. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28888. return false;
  28889. Connection* const c = new Connection();
  28890. c->sourceNodeId = sourceNodeId;
  28891. c->sourceChannelIndex = sourceChannelIndex;
  28892. c->destNodeId = destNodeId;
  28893. c->destChannelIndex = destChannelIndex;
  28894. connections.add (c);
  28895. triggerAsyncUpdate();
  28896. return true;
  28897. }
  28898. void AudioProcessorGraph::removeConnection (const int index)
  28899. {
  28900. connections.remove (index);
  28901. triggerAsyncUpdate();
  28902. }
  28903. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28904. const uint32 destNodeId, const int destChannelIndex)
  28905. {
  28906. bool doneAnything = false;
  28907. for (int i = connections.size(); --i >= 0;)
  28908. {
  28909. const Connection* const c = connections.getUnchecked(i);
  28910. if (c->sourceNodeId == sourceNodeId
  28911. && c->destNodeId == destNodeId
  28912. && c->sourceChannelIndex == sourceChannelIndex
  28913. && c->destChannelIndex == destChannelIndex)
  28914. {
  28915. removeConnection (i);
  28916. doneAnything = true;
  28917. triggerAsyncUpdate();
  28918. }
  28919. }
  28920. return doneAnything;
  28921. }
  28922. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28923. {
  28924. bool doneAnything = false;
  28925. for (int i = connections.size(); --i >= 0;)
  28926. {
  28927. const Connection* const c = connections.getUnchecked(i);
  28928. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28929. {
  28930. removeConnection (i);
  28931. doneAnything = true;
  28932. triggerAsyncUpdate();
  28933. }
  28934. }
  28935. return doneAnything;
  28936. }
  28937. bool AudioProcessorGraph::removeIllegalConnections()
  28938. {
  28939. bool doneAnything = false;
  28940. for (int i = connections.size(); --i >= 0;)
  28941. {
  28942. const Connection* const c = connections.getUnchecked(i);
  28943. const Node* const source = getNodeForId (c->sourceNodeId);
  28944. const Node* const dest = getNodeForId (c->destNodeId);
  28945. if (source == 0 || dest == 0
  28946. || (c->sourceChannelIndex != midiChannelIndex
  28947. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  28948. || (c->sourceChannelIndex == midiChannelIndex
  28949. && ! source->processor->producesMidi())
  28950. || (c->destChannelIndex != midiChannelIndex
  28951. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  28952. || (c->destChannelIndex == midiChannelIndex
  28953. && ! dest->processor->acceptsMidi()))
  28954. {
  28955. removeConnection (i);
  28956. doneAnything = true;
  28957. triggerAsyncUpdate();
  28958. }
  28959. }
  28960. return doneAnything;
  28961. }
  28962. namespace GraphRenderingOps
  28963. {
  28964. class AudioGraphRenderingOp
  28965. {
  28966. public:
  28967. AudioGraphRenderingOp() {}
  28968. virtual ~AudioGraphRenderingOp() {}
  28969. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28970. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28971. const int numSamples) = 0;
  28972. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  28973. };
  28974. class ClearChannelOp : public AudioGraphRenderingOp
  28975. {
  28976. public:
  28977. ClearChannelOp (const int channelNum_)
  28978. : channelNum (channelNum_)
  28979. {}
  28980. ~ClearChannelOp() {}
  28981. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28982. {
  28983. sharedBufferChans.clear (channelNum, 0, numSamples);
  28984. }
  28985. private:
  28986. const int channelNum;
  28987. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  28988. };
  28989. class CopyChannelOp : public AudioGraphRenderingOp
  28990. {
  28991. public:
  28992. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28993. : srcChannelNum (srcChannelNum_),
  28994. dstChannelNum (dstChannelNum_)
  28995. {}
  28996. ~CopyChannelOp() {}
  28997. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28998. {
  28999. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29000. }
  29001. private:
  29002. const int srcChannelNum, dstChannelNum;
  29003. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29004. };
  29005. class AddChannelOp : public AudioGraphRenderingOp
  29006. {
  29007. public:
  29008. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29009. : srcChannelNum (srcChannelNum_),
  29010. dstChannelNum (dstChannelNum_)
  29011. {}
  29012. ~AddChannelOp() {}
  29013. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29014. {
  29015. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29016. }
  29017. private:
  29018. const int srcChannelNum, dstChannelNum;
  29019. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29020. };
  29021. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29022. {
  29023. public:
  29024. ClearMidiBufferOp (const int bufferNum_)
  29025. : bufferNum (bufferNum_)
  29026. {}
  29027. ~ClearMidiBufferOp() {}
  29028. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29029. {
  29030. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29031. }
  29032. private:
  29033. const int bufferNum;
  29034. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29035. };
  29036. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29037. {
  29038. public:
  29039. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29040. : srcBufferNum (srcBufferNum_),
  29041. dstBufferNum (dstBufferNum_)
  29042. {}
  29043. ~CopyMidiBufferOp() {}
  29044. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29045. {
  29046. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29047. }
  29048. private:
  29049. const int srcBufferNum, dstBufferNum;
  29050. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29051. };
  29052. class AddMidiBufferOp : public AudioGraphRenderingOp
  29053. {
  29054. public:
  29055. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29056. : srcBufferNum (srcBufferNum_),
  29057. dstBufferNum (dstBufferNum_)
  29058. {}
  29059. ~AddMidiBufferOp() {}
  29060. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29061. {
  29062. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29063. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29064. }
  29065. private:
  29066. const int srcBufferNum, dstBufferNum;
  29067. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29068. };
  29069. class ProcessBufferOp : public AudioGraphRenderingOp
  29070. {
  29071. public:
  29072. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29073. const Array <int>& audioChannelsToUse_,
  29074. const int totalChans_,
  29075. const int midiBufferToUse_)
  29076. : node (node_),
  29077. processor (node_->getProcessor()),
  29078. audioChannelsToUse (audioChannelsToUse_),
  29079. totalChans (jmax (1, totalChans_)),
  29080. midiBufferToUse (midiBufferToUse_)
  29081. {
  29082. channels.calloc (totalChans);
  29083. while (audioChannelsToUse.size() < totalChans)
  29084. audioChannelsToUse.add (0);
  29085. }
  29086. ~ProcessBufferOp()
  29087. {
  29088. }
  29089. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29090. {
  29091. for (int i = totalChans; --i >= 0;)
  29092. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29093. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29094. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29095. }
  29096. const AudioProcessorGraph::Node::Ptr node;
  29097. AudioProcessor* const processor;
  29098. private:
  29099. Array <int> audioChannelsToUse;
  29100. HeapBlock <float*> channels;
  29101. int totalChans;
  29102. int midiBufferToUse;
  29103. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29104. };
  29105. /** Used to calculate the correct sequence of rendering ops needed, based on
  29106. the best re-use of shared buffers at each stage.
  29107. */
  29108. class RenderingOpSequenceCalculator
  29109. {
  29110. public:
  29111. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29112. const Array<void*>& orderedNodes_,
  29113. Array<void*>& renderingOps)
  29114. : graph (graph_),
  29115. orderedNodes (orderedNodes_)
  29116. {
  29117. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29118. channels.add (0);
  29119. midiNodeIds.add ((uint32) zeroNodeID);
  29120. for (int i = 0; i < orderedNodes.size(); ++i)
  29121. {
  29122. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29123. renderingOps, i);
  29124. markAnyUnusedBuffersAsFree (i);
  29125. }
  29126. }
  29127. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29128. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29129. private:
  29130. AudioProcessorGraph& graph;
  29131. const Array<void*>& orderedNodes;
  29132. Array <int> channels;
  29133. Array <uint32> nodeIds, midiNodeIds;
  29134. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29135. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29136. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29137. Array<void*>& renderingOps,
  29138. const int ourRenderingIndex)
  29139. {
  29140. const int numIns = node->getProcessor()->getNumInputChannels();
  29141. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29142. const int totalChans = jmax (numIns, numOuts);
  29143. Array <int> audioChannelsToUse;
  29144. int midiBufferToUse = -1;
  29145. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29146. {
  29147. // get a list of all the inputs to this node
  29148. Array <int> sourceNodes, sourceOutputChans;
  29149. for (int i = graph.getNumConnections(); --i >= 0;)
  29150. {
  29151. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29152. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29153. {
  29154. sourceNodes.add (c->sourceNodeId);
  29155. sourceOutputChans.add (c->sourceChannelIndex);
  29156. }
  29157. }
  29158. int bufIndex = -1;
  29159. if (sourceNodes.size() == 0)
  29160. {
  29161. // unconnected input channel
  29162. if (inputChan >= numOuts)
  29163. {
  29164. bufIndex = getReadOnlyEmptyBuffer();
  29165. jassert (bufIndex >= 0);
  29166. }
  29167. else
  29168. {
  29169. bufIndex = getFreeBuffer (false);
  29170. renderingOps.add (new ClearChannelOp (bufIndex));
  29171. }
  29172. }
  29173. else if (sourceNodes.size() == 1)
  29174. {
  29175. // channel with a straightforward single input..
  29176. const int srcNode = sourceNodes.getUnchecked(0);
  29177. const int srcChan = sourceOutputChans.getUnchecked(0);
  29178. bufIndex = getBufferContaining (srcNode, srcChan);
  29179. if (bufIndex < 0)
  29180. {
  29181. // if not found, this is probably a feedback loop
  29182. bufIndex = getReadOnlyEmptyBuffer();
  29183. jassert (bufIndex >= 0);
  29184. }
  29185. if (inputChan < numOuts
  29186. && isBufferNeededLater (ourRenderingIndex,
  29187. inputChan,
  29188. srcNode, srcChan))
  29189. {
  29190. // can't mess up this channel because it's needed later by another node, so we
  29191. // need to use a copy of it..
  29192. const int newFreeBuffer = getFreeBuffer (false);
  29193. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29194. bufIndex = newFreeBuffer;
  29195. }
  29196. }
  29197. else
  29198. {
  29199. // channel with a mix of several inputs..
  29200. // try to find a re-usable channel from our inputs..
  29201. int reusableInputIndex = -1;
  29202. for (int i = 0; i < sourceNodes.size(); ++i)
  29203. {
  29204. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29205. sourceOutputChans.getUnchecked(i));
  29206. if (sourceBufIndex >= 0
  29207. && ! isBufferNeededLater (ourRenderingIndex,
  29208. inputChan,
  29209. sourceNodes.getUnchecked(i),
  29210. sourceOutputChans.getUnchecked(i)))
  29211. {
  29212. // we've found one of our input chans that can be re-used..
  29213. reusableInputIndex = i;
  29214. bufIndex = sourceBufIndex;
  29215. break;
  29216. }
  29217. }
  29218. if (reusableInputIndex < 0)
  29219. {
  29220. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29221. bufIndex = getFreeBuffer (false);
  29222. jassert (bufIndex != 0);
  29223. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29224. sourceOutputChans.getUnchecked (0));
  29225. if (srcIndex < 0)
  29226. {
  29227. // if not found, this is probably a feedback loop
  29228. renderingOps.add (new ClearChannelOp (bufIndex));
  29229. }
  29230. else
  29231. {
  29232. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29233. }
  29234. reusableInputIndex = 0;
  29235. }
  29236. for (int j = 0; j < sourceNodes.size(); ++j)
  29237. {
  29238. if (j != reusableInputIndex)
  29239. {
  29240. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29241. sourceOutputChans.getUnchecked(j));
  29242. if (srcIndex >= 0)
  29243. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29244. }
  29245. }
  29246. }
  29247. jassert (bufIndex >= 0);
  29248. audioChannelsToUse.add (bufIndex);
  29249. if (inputChan < numOuts)
  29250. markBufferAsContaining (bufIndex, node->id, inputChan);
  29251. }
  29252. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29253. {
  29254. const int bufIndex = getFreeBuffer (false);
  29255. jassert (bufIndex != 0);
  29256. audioChannelsToUse.add (bufIndex);
  29257. markBufferAsContaining (bufIndex, node->id, outputChan);
  29258. }
  29259. // Now the same thing for midi..
  29260. Array <int> midiSourceNodes;
  29261. for (int i = graph.getNumConnections(); --i >= 0;)
  29262. {
  29263. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29264. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29265. midiSourceNodes.add (c->sourceNodeId);
  29266. }
  29267. if (midiSourceNodes.size() == 0)
  29268. {
  29269. // No midi inputs..
  29270. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29271. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29272. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29273. }
  29274. else if (midiSourceNodes.size() == 1)
  29275. {
  29276. // One midi input..
  29277. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29278. AudioProcessorGraph::midiChannelIndex);
  29279. if (midiBufferToUse >= 0)
  29280. {
  29281. if (isBufferNeededLater (ourRenderingIndex,
  29282. AudioProcessorGraph::midiChannelIndex,
  29283. midiSourceNodes.getUnchecked(0),
  29284. AudioProcessorGraph::midiChannelIndex))
  29285. {
  29286. // can't mess up this channel because it's needed later by another node, so we
  29287. // need to use a copy of it..
  29288. const int newFreeBuffer = getFreeBuffer (true);
  29289. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29290. midiBufferToUse = newFreeBuffer;
  29291. }
  29292. }
  29293. else
  29294. {
  29295. // probably a feedback loop, so just use an empty one..
  29296. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29297. }
  29298. }
  29299. else
  29300. {
  29301. // More than one midi input being mixed..
  29302. int reusableInputIndex = -1;
  29303. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29304. {
  29305. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29306. AudioProcessorGraph::midiChannelIndex);
  29307. if (sourceBufIndex >= 0
  29308. && ! isBufferNeededLater (ourRenderingIndex,
  29309. AudioProcessorGraph::midiChannelIndex,
  29310. midiSourceNodes.getUnchecked(i),
  29311. AudioProcessorGraph::midiChannelIndex))
  29312. {
  29313. // we've found one of our input buffers that can be re-used..
  29314. reusableInputIndex = i;
  29315. midiBufferToUse = sourceBufIndex;
  29316. break;
  29317. }
  29318. }
  29319. if (reusableInputIndex < 0)
  29320. {
  29321. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29322. midiBufferToUse = getFreeBuffer (true);
  29323. jassert (midiBufferToUse >= 0);
  29324. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29325. AudioProcessorGraph::midiChannelIndex);
  29326. if (srcIndex >= 0)
  29327. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29328. else
  29329. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29330. reusableInputIndex = 0;
  29331. }
  29332. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29333. {
  29334. if (j != reusableInputIndex)
  29335. {
  29336. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29337. AudioProcessorGraph::midiChannelIndex);
  29338. if (srcIndex >= 0)
  29339. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29340. }
  29341. }
  29342. }
  29343. if (node->getProcessor()->producesMidi())
  29344. markBufferAsContaining (midiBufferToUse, node->id,
  29345. AudioProcessorGraph::midiChannelIndex);
  29346. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29347. totalChans, midiBufferToUse));
  29348. }
  29349. int getFreeBuffer (const bool forMidi)
  29350. {
  29351. if (forMidi)
  29352. {
  29353. for (int i = 1; i < midiNodeIds.size(); ++i)
  29354. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29355. return i;
  29356. midiNodeIds.add ((uint32) freeNodeID);
  29357. return midiNodeIds.size() - 1;
  29358. }
  29359. else
  29360. {
  29361. for (int i = 1; i < nodeIds.size(); ++i)
  29362. if (nodeIds.getUnchecked(i) == freeNodeID)
  29363. return i;
  29364. nodeIds.add ((uint32) freeNodeID);
  29365. channels.add (0);
  29366. return nodeIds.size() - 1;
  29367. }
  29368. }
  29369. int getReadOnlyEmptyBuffer() const
  29370. {
  29371. return 0;
  29372. }
  29373. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29374. {
  29375. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29376. {
  29377. for (int i = midiNodeIds.size(); --i >= 0;)
  29378. if (midiNodeIds.getUnchecked(i) == nodeId)
  29379. return i;
  29380. }
  29381. else
  29382. {
  29383. for (int i = nodeIds.size(); --i >= 0;)
  29384. if (nodeIds.getUnchecked(i) == nodeId
  29385. && channels.getUnchecked(i) == outputChannel)
  29386. return i;
  29387. }
  29388. return -1;
  29389. }
  29390. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29391. {
  29392. int i;
  29393. for (i = 0; i < nodeIds.size(); ++i)
  29394. {
  29395. if (isNodeBusy (nodeIds.getUnchecked(i))
  29396. && ! isBufferNeededLater (stepIndex, -1,
  29397. nodeIds.getUnchecked(i),
  29398. channels.getUnchecked(i)))
  29399. {
  29400. nodeIds.set (i, (uint32) freeNodeID);
  29401. }
  29402. }
  29403. for (i = 0; i < midiNodeIds.size(); ++i)
  29404. {
  29405. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29406. && ! isBufferNeededLater (stepIndex, -1,
  29407. midiNodeIds.getUnchecked(i),
  29408. AudioProcessorGraph::midiChannelIndex))
  29409. {
  29410. midiNodeIds.set (i, (uint32) freeNodeID);
  29411. }
  29412. }
  29413. }
  29414. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29415. int inputChannelOfIndexToIgnore,
  29416. const uint32 nodeId,
  29417. const int outputChanIndex) const
  29418. {
  29419. while (stepIndexToSearchFrom < orderedNodes.size())
  29420. {
  29421. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29422. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29423. {
  29424. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29425. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29426. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29427. return true;
  29428. }
  29429. else
  29430. {
  29431. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29432. if (i != inputChannelOfIndexToIgnore
  29433. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29434. node->id, i) != 0)
  29435. return true;
  29436. }
  29437. inputChannelOfIndexToIgnore = -1;
  29438. ++stepIndexToSearchFrom;
  29439. }
  29440. return false;
  29441. }
  29442. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29443. {
  29444. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29445. {
  29446. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29447. midiNodeIds.set (bufferNum, nodeId);
  29448. }
  29449. else
  29450. {
  29451. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29452. nodeIds.set (bufferNum, nodeId);
  29453. channels.set (bufferNum, outputIndex);
  29454. }
  29455. }
  29456. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29457. };
  29458. }
  29459. void AudioProcessorGraph::clearRenderingSequence()
  29460. {
  29461. const ScopedLock sl (renderLock);
  29462. for (int i = renderingOps.size(); --i >= 0;)
  29463. {
  29464. GraphRenderingOps::AudioGraphRenderingOp* const r
  29465. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29466. renderingOps.remove (i);
  29467. delete r;
  29468. }
  29469. }
  29470. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29471. const uint32 possibleDestinationId,
  29472. const int recursionCheck) const
  29473. {
  29474. if (recursionCheck > 0)
  29475. {
  29476. for (int i = connections.size(); --i >= 0;)
  29477. {
  29478. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29479. if (c->destNodeId == possibleDestinationId
  29480. && (c->sourceNodeId == possibleInputId
  29481. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29482. return true;
  29483. }
  29484. }
  29485. return false;
  29486. }
  29487. void AudioProcessorGraph::buildRenderingSequence()
  29488. {
  29489. Array<void*> newRenderingOps;
  29490. int numRenderingBuffersNeeded = 2;
  29491. int numMidiBuffersNeeded = 1;
  29492. {
  29493. MessageManagerLock mml;
  29494. Array<void*> orderedNodes;
  29495. int i;
  29496. for (i = 0; i < nodes.size(); ++i)
  29497. {
  29498. Node* const node = nodes.getUnchecked(i);
  29499. node->prepare (getSampleRate(), getBlockSize(), this);
  29500. int j = 0;
  29501. for (; j < orderedNodes.size(); ++j)
  29502. if (isAnInputTo (node->id,
  29503. ((Node*) orderedNodes.getUnchecked (j))->id,
  29504. nodes.size() + 1))
  29505. break;
  29506. orderedNodes.insert (j, node);
  29507. }
  29508. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29509. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29510. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29511. }
  29512. Array<void*> oldRenderingOps (renderingOps);
  29513. {
  29514. // swap over to the new rendering sequence..
  29515. const ScopedLock sl (renderLock);
  29516. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29517. renderingBuffers.clear();
  29518. for (int i = midiBuffers.size(); --i >= 0;)
  29519. midiBuffers.getUnchecked(i)->clear();
  29520. while (midiBuffers.size() < numMidiBuffersNeeded)
  29521. midiBuffers.add (new MidiBuffer());
  29522. renderingOps = newRenderingOps;
  29523. }
  29524. for (int i = oldRenderingOps.size(); --i >= 0;)
  29525. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29526. }
  29527. void AudioProcessorGraph::handleAsyncUpdate()
  29528. {
  29529. buildRenderingSequence();
  29530. }
  29531. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29532. {
  29533. currentAudioInputBuffer = 0;
  29534. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29535. currentMidiInputBuffer = 0;
  29536. currentMidiOutputBuffer.clear();
  29537. clearRenderingSequence();
  29538. buildRenderingSequence();
  29539. }
  29540. void AudioProcessorGraph::releaseResources()
  29541. {
  29542. for (int i = 0; i < nodes.size(); ++i)
  29543. nodes.getUnchecked(i)->unprepare();
  29544. renderingBuffers.setSize (1, 1);
  29545. midiBuffers.clear();
  29546. currentAudioInputBuffer = 0;
  29547. currentAudioOutputBuffer.setSize (1, 1);
  29548. currentMidiInputBuffer = 0;
  29549. currentMidiOutputBuffer.clear();
  29550. }
  29551. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29552. {
  29553. const int numSamples = buffer.getNumSamples();
  29554. const ScopedLock sl (renderLock);
  29555. currentAudioInputBuffer = &buffer;
  29556. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29557. currentAudioOutputBuffer.clear();
  29558. currentMidiInputBuffer = &midiMessages;
  29559. currentMidiOutputBuffer.clear();
  29560. int i;
  29561. for (i = 0; i < renderingOps.size(); ++i)
  29562. {
  29563. GraphRenderingOps::AudioGraphRenderingOp* const op
  29564. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29565. op->perform (renderingBuffers, midiBuffers, numSamples);
  29566. }
  29567. for (i = 0; i < buffer.getNumChannels(); ++i)
  29568. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29569. midiMessages.clear();
  29570. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29571. }
  29572. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29573. {
  29574. return "Input " + String (channelIndex + 1);
  29575. }
  29576. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29577. {
  29578. return "Output " + String (channelIndex + 1);
  29579. }
  29580. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29581. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29582. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29583. bool AudioProcessorGraph::producesMidi() const { return true; }
  29584. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29585. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29586. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29587. : type (type_),
  29588. graph (0)
  29589. {
  29590. }
  29591. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29592. {
  29593. }
  29594. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29595. {
  29596. switch (type)
  29597. {
  29598. case audioOutputNode: return "Audio Output";
  29599. case audioInputNode: return "Audio Input";
  29600. case midiOutputNode: return "Midi Output";
  29601. case midiInputNode: return "Midi Input";
  29602. default: break;
  29603. }
  29604. return String::empty;
  29605. }
  29606. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29607. {
  29608. d.name = getName();
  29609. d.uid = d.name.hashCode();
  29610. d.category = "I/O devices";
  29611. d.pluginFormatName = "Internal";
  29612. d.manufacturerName = "Raw Material Software";
  29613. d.version = "1.0";
  29614. d.isInstrument = false;
  29615. d.numInputChannels = getNumInputChannels();
  29616. if (type == audioOutputNode && graph != 0)
  29617. d.numInputChannels = graph->getNumInputChannels();
  29618. d.numOutputChannels = getNumOutputChannels();
  29619. if (type == audioInputNode && graph != 0)
  29620. d.numOutputChannels = graph->getNumOutputChannels();
  29621. }
  29622. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29623. {
  29624. jassert (graph != 0);
  29625. }
  29626. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29627. {
  29628. }
  29629. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29630. MidiBuffer& midiMessages)
  29631. {
  29632. jassert (graph != 0);
  29633. switch (type)
  29634. {
  29635. case audioOutputNode:
  29636. {
  29637. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29638. buffer.getNumChannels()); --i >= 0;)
  29639. {
  29640. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29641. }
  29642. break;
  29643. }
  29644. case audioInputNode:
  29645. {
  29646. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29647. buffer.getNumChannels()); --i >= 0;)
  29648. {
  29649. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29650. }
  29651. break;
  29652. }
  29653. case midiOutputNode:
  29654. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29655. break;
  29656. case midiInputNode:
  29657. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29658. break;
  29659. default:
  29660. break;
  29661. }
  29662. }
  29663. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29664. {
  29665. return type == midiOutputNode;
  29666. }
  29667. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29668. {
  29669. return type == midiInputNode;
  29670. }
  29671. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29672. {
  29673. switch (type)
  29674. {
  29675. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29676. case midiOutputNode: return "Midi Output";
  29677. default: break;
  29678. }
  29679. return String::empty;
  29680. }
  29681. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29682. {
  29683. switch (type)
  29684. {
  29685. case audioInputNode: return "Input " + String (channelIndex + 1);
  29686. case midiInputNode: return "Midi Input";
  29687. default: break;
  29688. }
  29689. return String::empty;
  29690. }
  29691. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29692. {
  29693. return type == audioInputNode || type == audioOutputNode;
  29694. }
  29695. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29696. {
  29697. return isInputChannelStereoPair (index);
  29698. }
  29699. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29700. {
  29701. return type == audioInputNode || type == midiInputNode;
  29702. }
  29703. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29704. {
  29705. return type == audioOutputNode || type == midiOutputNode;
  29706. }
  29707. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29708. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29709. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29710. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29711. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29712. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29713. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29714. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29715. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29716. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29717. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29718. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29719. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29720. {
  29721. }
  29722. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29723. {
  29724. }
  29725. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29726. {
  29727. graph = newGraph;
  29728. if (graph != 0)
  29729. {
  29730. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29731. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29732. getSampleRate(),
  29733. getBlockSize());
  29734. updateHostDisplay();
  29735. }
  29736. }
  29737. END_JUCE_NAMESPACE
  29738. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29739. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29740. BEGIN_JUCE_NAMESPACE
  29741. AudioProcessorPlayer::AudioProcessorPlayer()
  29742. : processor (0),
  29743. sampleRate (0),
  29744. blockSize (0),
  29745. isPrepared (false),
  29746. numInputChans (0),
  29747. numOutputChans (0),
  29748. tempBuffer (1, 1)
  29749. {
  29750. }
  29751. AudioProcessorPlayer::~AudioProcessorPlayer()
  29752. {
  29753. setProcessor (0);
  29754. }
  29755. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29756. {
  29757. if (processor != processorToPlay)
  29758. {
  29759. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29760. {
  29761. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29762. sampleRate, blockSize);
  29763. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29764. }
  29765. AudioProcessor* oldOne;
  29766. {
  29767. const ScopedLock sl (lock);
  29768. oldOne = isPrepared ? processor : 0;
  29769. processor = processorToPlay;
  29770. isPrepared = true;
  29771. }
  29772. if (oldOne != 0)
  29773. oldOne->releaseResources();
  29774. }
  29775. }
  29776. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29777. const int numInputChannels,
  29778. float** const outputChannelData,
  29779. const int numOutputChannels,
  29780. const int numSamples)
  29781. {
  29782. // these should have been prepared by audioDeviceAboutToStart()...
  29783. jassert (sampleRate > 0 && blockSize > 0);
  29784. incomingMidi.clear();
  29785. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29786. int i, totalNumChans = 0;
  29787. if (numInputChannels > numOutputChannels)
  29788. {
  29789. // if there aren't enough output channels for the number of
  29790. // inputs, we need to create some temporary extra ones (can't
  29791. // use the input data in case it gets written to)
  29792. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29793. false, false, true);
  29794. for (i = 0; i < numOutputChannels; ++i)
  29795. {
  29796. channels[totalNumChans] = outputChannelData[i];
  29797. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29798. ++totalNumChans;
  29799. }
  29800. for (i = numOutputChannels; i < numInputChannels; ++i)
  29801. {
  29802. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29803. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29804. ++totalNumChans;
  29805. }
  29806. }
  29807. else
  29808. {
  29809. for (i = 0; i < numInputChannels; ++i)
  29810. {
  29811. channels[totalNumChans] = outputChannelData[i];
  29812. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29813. ++totalNumChans;
  29814. }
  29815. for (i = numInputChannels; i < numOutputChannels; ++i)
  29816. {
  29817. channels[totalNumChans] = outputChannelData[i];
  29818. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29819. ++totalNumChans;
  29820. }
  29821. }
  29822. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29823. const ScopedLock sl (lock);
  29824. if (processor != 0)
  29825. {
  29826. const ScopedLock sl2 (processor->getCallbackLock());
  29827. if (processor->isSuspended())
  29828. {
  29829. for (i = 0; i < numOutputChannels; ++i)
  29830. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29831. }
  29832. else
  29833. {
  29834. processor->processBlock (buffer, incomingMidi);
  29835. }
  29836. }
  29837. }
  29838. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29839. {
  29840. const ScopedLock sl (lock);
  29841. sampleRate = device->getCurrentSampleRate();
  29842. blockSize = device->getCurrentBufferSizeSamples();
  29843. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29844. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29845. messageCollector.reset (sampleRate);
  29846. zeromem (channels, sizeof (channels));
  29847. if (processor != 0)
  29848. {
  29849. if (isPrepared)
  29850. processor->releaseResources();
  29851. AudioProcessor* const oldProcessor = processor;
  29852. setProcessor (0);
  29853. setProcessor (oldProcessor);
  29854. }
  29855. }
  29856. void AudioProcessorPlayer::audioDeviceStopped()
  29857. {
  29858. const ScopedLock sl (lock);
  29859. if (processor != 0 && isPrepared)
  29860. processor->releaseResources();
  29861. sampleRate = 0.0;
  29862. blockSize = 0;
  29863. isPrepared = false;
  29864. tempBuffer.setSize (1, 1);
  29865. }
  29866. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29867. {
  29868. messageCollector.addMessageToQueue (message);
  29869. }
  29870. END_JUCE_NAMESPACE
  29871. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29872. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29873. BEGIN_JUCE_NAMESPACE
  29874. class ProcessorParameterPropertyComp : public PropertyComponent,
  29875. public AudioProcessorListener,
  29876. public Timer
  29877. {
  29878. public:
  29879. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  29880. : PropertyComponent (name),
  29881. owner (owner_),
  29882. index (index_),
  29883. paramHasChanged (false),
  29884. slider (owner_, index_)
  29885. {
  29886. startTimer (100);
  29887. addAndMakeVisible (&slider);
  29888. owner_.addListener (this);
  29889. }
  29890. ~ProcessorParameterPropertyComp()
  29891. {
  29892. owner.removeListener (this);
  29893. }
  29894. void refresh()
  29895. {
  29896. paramHasChanged = false;
  29897. slider.setValue (owner.getParameter (index), false);
  29898. }
  29899. void audioProcessorChanged (AudioProcessor*) {}
  29900. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29901. {
  29902. if (parameterIndex == index)
  29903. paramHasChanged = true;
  29904. }
  29905. void timerCallback()
  29906. {
  29907. if (paramHasChanged)
  29908. {
  29909. refresh();
  29910. startTimer (1000 / 50);
  29911. }
  29912. else
  29913. {
  29914. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  29915. }
  29916. }
  29917. private:
  29918. class ParamSlider : public Slider
  29919. {
  29920. public:
  29921. ParamSlider (AudioProcessor& owner_, const int index_)
  29922. : owner (owner_),
  29923. index (index_)
  29924. {
  29925. setRange (0.0, 1.0, 0.0);
  29926. setSliderStyle (Slider::LinearBar);
  29927. setTextBoxIsEditable (false);
  29928. setScrollWheelEnabled (false);
  29929. }
  29930. void valueChanged()
  29931. {
  29932. const float newVal = (float) getValue();
  29933. if (owner.getParameter (index) != newVal)
  29934. owner.setParameter (index, newVal);
  29935. }
  29936. const String getTextFromValue (double /*value*/)
  29937. {
  29938. return owner.getParameterText (index);
  29939. }
  29940. private:
  29941. AudioProcessor& owner;
  29942. const int index;
  29943. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  29944. };
  29945. AudioProcessor& owner;
  29946. const int index;
  29947. bool volatile paramHasChanged;
  29948. ParamSlider slider;
  29949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  29950. };
  29951. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29952. : AudioProcessorEditor (owner_)
  29953. {
  29954. jassert (owner_ != 0);
  29955. setOpaque (true);
  29956. addAndMakeVisible (&panel);
  29957. Array <PropertyComponent*> params;
  29958. const int numParams = owner_->getNumParameters();
  29959. int totalHeight = 0;
  29960. for (int i = 0; i < numParams; ++i)
  29961. {
  29962. String name (owner_->getParameterName (i));
  29963. if (name.trim().isEmpty())
  29964. name = "Unnamed";
  29965. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  29966. params.add (pc);
  29967. totalHeight += pc->getPreferredHeight();
  29968. }
  29969. panel.addProperties (params);
  29970. setSize (400, jlimit (25, 400, totalHeight));
  29971. }
  29972. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29973. {
  29974. }
  29975. void GenericAudioProcessorEditor::paint (Graphics& g)
  29976. {
  29977. g.fillAll (Colours::white);
  29978. }
  29979. void GenericAudioProcessorEditor::resized()
  29980. {
  29981. panel.setBounds (getLocalBounds());
  29982. }
  29983. END_JUCE_NAMESPACE
  29984. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29985. /*** Start of inlined file: juce_Sampler.cpp ***/
  29986. BEGIN_JUCE_NAMESPACE
  29987. SamplerSound::SamplerSound (const String& name_,
  29988. AudioFormatReader& source,
  29989. const BigInteger& midiNotes_,
  29990. const int midiNoteForNormalPitch,
  29991. const double attackTimeSecs,
  29992. const double releaseTimeSecs,
  29993. const double maxSampleLengthSeconds)
  29994. : name (name_),
  29995. midiNotes (midiNotes_),
  29996. midiRootNote (midiNoteForNormalPitch)
  29997. {
  29998. sourceSampleRate = source.sampleRate;
  29999. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30000. {
  30001. length = 0;
  30002. attackSamples = 0;
  30003. releaseSamples = 0;
  30004. }
  30005. else
  30006. {
  30007. length = jmin ((int) source.lengthInSamples,
  30008. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30009. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30010. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30011. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30012. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30013. }
  30014. }
  30015. SamplerSound::~SamplerSound()
  30016. {
  30017. }
  30018. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30019. {
  30020. return midiNotes [midiNoteNumber];
  30021. }
  30022. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30023. {
  30024. return true;
  30025. }
  30026. SamplerVoice::SamplerVoice()
  30027. : pitchRatio (0.0),
  30028. sourceSamplePosition (0.0),
  30029. lgain (0.0f),
  30030. rgain (0.0f),
  30031. isInAttack (false),
  30032. isInRelease (false)
  30033. {
  30034. }
  30035. SamplerVoice::~SamplerVoice()
  30036. {
  30037. }
  30038. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30039. {
  30040. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30041. }
  30042. void SamplerVoice::startNote (const int midiNoteNumber,
  30043. const float velocity,
  30044. SynthesiserSound* s,
  30045. const int /*currentPitchWheelPosition*/)
  30046. {
  30047. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30048. jassert (sound != 0); // this object can only play SamplerSounds!
  30049. if (sound != 0)
  30050. {
  30051. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30052. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30053. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30054. sourceSamplePosition = 0.0;
  30055. lgain = velocity;
  30056. rgain = velocity;
  30057. isInAttack = (sound->attackSamples > 0);
  30058. isInRelease = false;
  30059. if (isInAttack)
  30060. {
  30061. attackReleaseLevel = 0.0f;
  30062. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30063. }
  30064. else
  30065. {
  30066. attackReleaseLevel = 1.0f;
  30067. attackDelta = 0.0f;
  30068. }
  30069. if (sound->releaseSamples > 0)
  30070. {
  30071. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30072. }
  30073. else
  30074. {
  30075. releaseDelta = 0.0f;
  30076. }
  30077. }
  30078. }
  30079. void SamplerVoice::stopNote (const bool allowTailOff)
  30080. {
  30081. if (allowTailOff)
  30082. {
  30083. isInAttack = false;
  30084. isInRelease = true;
  30085. }
  30086. else
  30087. {
  30088. clearCurrentNote();
  30089. }
  30090. }
  30091. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30092. {
  30093. }
  30094. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30095. const int /*newValue*/)
  30096. {
  30097. }
  30098. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30099. {
  30100. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30101. if (playingSound != 0)
  30102. {
  30103. const float* const inL = playingSound->data->getSampleData (0, 0);
  30104. const float* const inR = playingSound->data->getNumChannels() > 1
  30105. ? playingSound->data->getSampleData (1, 0) : 0;
  30106. float* outL = outputBuffer.getSampleData (0, startSample);
  30107. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30108. while (--numSamples >= 0)
  30109. {
  30110. const int pos = (int) sourceSamplePosition;
  30111. const float alpha = (float) (sourceSamplePosition - pos);
  30112. const float invAlpha = 1.0f - alpha;
  30113. // just using a very simple linear interpolation here..
  30114. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30115. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30116. : l;
  30117. l *= lgain;
  30118. r *= rgain;
  30119. if (isInAttack)
  30120. {
  30121. l *= attackReleaseLevel;
  30122. r *= attackReleaseLevel;
  30123. attackReleaseLevel += attackDelta;
  30124. if (attackReleaseLevel >= 1.0f)
  30125. {
  30126. attackReleaseLevel = 1.0f;
  30127. isInAttack = false;
  30128. }
  30129. }
  30130. else if (isInRelease)
  30131. {
  30132. l *= attackReleaseLevel;
  30133. r *= attackReleaseLevel;
  30134. attackReleaseLevel += releaseDelta;
  30135. if (attackReleaseLevel <= 0.0f)
  30136. {
  30137. stopNote (false);
  30138. break;
  30139. }
  30140. }
  30141. if (outR != 0)
  30142. {
  30143. *outL++ += l;
  30144. *outR++ += r;
  30145. }
  30146. else
  30147. {
  30148. *outL++ += (l + r) * 0.5f;
  30149. }
  30150. sourceSamplePosition += pitchRatio;
  30151. if (sourceSamplePosition > playingSound->length)
  30152. {
  30153. stopNote (false);
  30154. break;
  30155. }
  30156. }
  30157. }
  30158. }
  30159. END_JUCE_NAMESPACE
  30160. /*** End of inlined file: juce_Sampler.cpp ***/
  30161. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30162. BEGIN_JUCE_NAMESPACE
  30163. SynthesiserSound::SynthesiserSound()
  30164. {
  30165. }
  30166. SynthesiserSound::~SynthesiserSound()
  30167. {
  30168. }
  30169. SynthesiserVoice::SynthesiserVoice()
  30170. : currentSampleRate (44100.0),
  30171. currentlyPlayingNote (-1),
  30172. noteOnTime (0),
  30173. currentlyPlayingSound (0)
  30174. {
  30175. }
  30176. SynthesiserVoice::~SynthesiserVoice()
  30177. {
  30178. }
  30179. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30180. {
  30181. return currentlyPlayingSound != 0
  30182. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30183. }
  30184. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30185. {
  30186. currentSampleRate = newRate;
  30187. }
  30188. void SynthesiserVoice::clearCurrentNote()
  30189. {
  30190. currentlyPlayingNote = -1;
  30191. currentlyPlayingSound = 0;
  30192. }
  30193. Synthesiser::Synthesiser()
  30194. : sampleRate (0),
  30195. lastNoteOnCounter (0),
  30196. shouldStealNotes (true)
  30197. {
  30198. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30199. lastPitchWheelValues[i] = 0x2000;
  30200. }
  30201. Synthesiser::~Synthesiser()
  30202. {
  30203. }
  30204. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30205. {
  30206. const ScopedLock sl (lock);
  30207. return voices [index];
  30208. }
  30209. void Synthesiser::clearVoices()
  30210. {
  30211. const ScopedLock sl (lock);
  30212. voices.clear();
  30213. }
  30214. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30215. {
  30216. const ScopedLock sl (lock);
  30217. voices.add (newVoice);
  30218. }
  30219. void Synthesiser::removeVoice (const int index)
  30220. {
  30221. const ScopedLock sl (lock);
  30222. voices.remove (index);
  30223. }
  30224. void Synthesiser::clearSounds()
  30225. {
  30226. const ScopedLock sl (lock);
  30227. sounds.clear();
  30228. }
  30229. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30230. {
  30231. const ScopedLock sl (lock);
  30232. sounds.add (newSound);
  30233. }
  30234. void Synthesiser::removeSound (const int index)
  30235. {
  30236. const ScopedLock sl (lock);
  30237. sounds.remove (index);
  30238. }
  30239. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30240. {
  30241. shouldStealNotes = shouldStealNotes_;
  30242. }
  30243. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30244. {
  30245. if (sampleRate != newRate)
  30246. {
  30247. const ScopedLock sl (lock);
  30248. allNotesOff (0, false);
  30249. sampleRate = newRate;
  30250. for (int i = voices.size(); --i >= 0;)
  30251. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30252. }
  30253. }
  30254. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30255. const MidiBuffer& midiData,
  30256. int startSample,
  30257. int numSamples)
  30258. {
  30259. // must set the sample rate before using this!
  30260. jassert (sampleRate != 0);
  30261. const ScopedLock sl (lock);
  30262. MidiBuffer::Iterator midiIterator (midiData);
  30263. midiIterator.setNextSamplePosition (startSample);
  30264. MidiMessage m (0xf4, 0.0);
  30265. while (numSamples > 0)
  30266. {
  30267. int midiEventPos;
  30268. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30269. && midiEventPos < startSample + numSamples;
  30270. const int numThisTime = useEvent ? midiEventPos - startSample
  30271. : numSamples;
  30272. if (numThisTime > 0)
  30273. {
  30274. for (int i = voices.size(); --i >= 0;)
  30275. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30276. }
  30277. if (useEvent)
  30278. {
  30279. if (m.isNoteOn())
  30280. {
  30281. const int channel = m.getChannel();
  30282. noteOn (channel,
  30283. m.getNoteNumber(),
  30284. m.getFloatVelocity());
  30285. }
  30286. else if (m.isNoteOff())
  30287. {
  30288. noteOff (m.getChannel(),
  30289. m.getNoteNumber(),
  30290. true);
  30291. }
  30292. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30293. {
  30294. allNotesOff (m.getChannel(), true);
  30295. }
  30296. else if (m.isPitchWheel())
  30297. {
  30298. const int channel = m.getChannel();
  30299. const int wheelPos = m.getPitchWheelValue();
  30300. lastPitchWheelValues [channel - 1] = wheelPos;
  30301. handlePitchWheel (channel, wheelPos);
  30302. }
  30303. else if (m.isController())
  30304. {
  30305. handleController (m.getChannel(),
  30306. m.getControllerNumber(),
  30307. m.getControllerValue());
  30308. }
  30309. }
  30310. startSample += numThisTime;
  30311. numSamples -= numThisTime;
  30312. }
  30313. }
  30314. void Synthesiser::noteOn (const int midiChannel,
  30315. const int midiNoteNumber,
  30316. const float velocity)
  30317. {
  30318. const ScopedLock sl (lock);
  30319. for (int i = sounds.size(); --i >= 0;)
  30320. {
  30321. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30322. if (sound->appliesToNote (midiNoteNumber)
  30323. && sound->appliesToChannel (midiChannel))
  30324. {
  30325. startVoice (findFreeVoice (sound, shouldStealNotes),
  30326. sound, midiChannel, midiNoteNumber, velocity);
  30327. }
  30328. }
  30329. }
  30330. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30331. SynthesiserSound* const sound,
  30332. const int midiChannel,
  30333. const int midiNoteNumber,
  30334. const float velocity)
  30335. {
  30336. if (voice != 0 && sound != 0)
  30337. {
  30338. if (voice->currentlyPlayingSound != 0)
  30339. voice->stopNote (false);
  30340. voice->startNote (midiNoteNumber,
  30341. velocity,
  30342. sound,
  30343. lastPitchWheelValues [midiChannel - 1]);
  30344. voice->currentlyPlayingNote = midiNoteNumber;
  30345. voice->noteOnTime = ++lastNoteOnCounter;
  30346. voice->currentlyPlayingSound = sound;
  30347. }
  30348. }
  30349. void Synthesiser::noteOff (const int midiChannel,
  30350. const int midiNoteNumber,
  30351. const bool allowTailOff)
  30352. {
  30353. const ScopedLock sl (lock);
  30354. for (int i = voices.size(); --i >= 0;)
  30355. {
  30356. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30357. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30358. {
  30359. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30360. if (sound != 0
  30361. && sound->appliesToNote (midiNoteNumber)
  30362. && sound->appliesToChannel (midiChannel))
  30363. {
  30364. voice->stopNote (allowTailOff);
  30365. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30366. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30367. }
  30368. }
  30369. }
  30370. }
  30371. void Synthesiser::allNotesOff (const int midiChannel,
  30372. const bool allowTailOff)
  30373. {
  30374. const ScopedLock sl (lock);
  30375. for (int i = voices.size(); --i >= 0;)
  30376. {
  30377. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30378. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30379. voice->stopNote (allowTailOff);
  30380. }
  30381. }
  30382. void Synthesiser::handlePitchWheel (const int midiChannel,
  30383. const int wheelValue)
  30384. {
  30385. const ScopedLock sl (lock);
  30386. for (int i = voices.size(); --i >= 0;)
  30387. {
  30388. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30389. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30390. {
  30391. voice->pitchWheelMoved (wheelValue);
  30392. }
  30393. }
  30394. }
  30395. void Synthesiser::handleController (const int midiChannel,
  30396. const int controllerNumber,
  30397. const int controllerValue)
  30398. {
  30399. const ScopedLock sl (lock);
  30400. for (int i = voices.size(); --i >= 0;)
  30401. {
  30402. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30403. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30404. voice->controllerMoved (controllerNumber, controllerValue);
  30405. }
  30406. }
  30407. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30408. const bool stealIfNoneAvailable) const
  30409. {
  30410. const ScopedLock sl (lock);
  30411. for (int i = voices.size(); --i >= 0;)
  30412. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30413. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30414. return voices.getUnchecked (i);
  30415. if (stealIfNoneAvailable)
  30416. {
  30417. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30418. SynthesiserVoice* oldest = 0;
  30419. for (int i = voices.size(); --i >= 0;)
  30420. {
  30421. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30422. if (voice->canPlaySound (soundToPlay)
  30423. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30424. oldest = voice;
  30425. }
  30426. jassert (oldest != 0);
  30427. return oldest;
  30428. }
  30429. return 0;
  30430. }
  30431. END_JUCE_NAMESPACE
  30432. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30433. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30434. BEGIN_JUCE_NAMESPACE
  30435. // special message of our own with a string in it
  30436. class ActionMessage : public Message
  30437. {
  30438. public:
  30439. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30440. : message (messageText)
  30441. {
  30442. pointerParameter = listener_;
  30443. }
  30444. const String message;
  30445. private:
  30446. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30447. };
  30448. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30449. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30450. {
  30451. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30452. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30453. if (owner->actionListeners.contains (target))
  30454. target->actionListenerCallback (am.message);
  30455. }
  30456. ActionBroadcaster::ActionBroadcaster()
  30457. {
  30458. // are you trying to create this object before or after juce has been intialised??
  30459. jassert (MessageManager::instance != 0);
  30460. callback.owner = this;
  30461. }
  30462. ActionBroadcaster::~ActionBroadcaster()
  30463. {
  30464. // all event-based objects must be deleted BEFORE juce is shut down!
  30465. jassert (MessageManager::instance != 0);
  30466. }
  30467. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30468. {
  30469. const ScopedLock sl (actionListenerLock);
  30470. if (listener != 0)
  30471. actionListeners.add (listener);
  30472. }
  30473. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30474. {
  30475. const ScopedLock sl (actionListenerLock);
  30476. actionListeners.removeValue (listener);
  30477. }
  30478. void ActionBroadcaster::removeAllActionListeners()
  30479. {
  30480. const ScopedLock sl (actionListenerLock);
  30481. actionListeners.clear();
  30482. }
  30483. void ActionBroadcaster::sendActionMessage (const String& message) const
  30484. {
  30485. const ScopedLock sl (actionListenerLock);
  30486. for (int i = actionListeners.size(); --i >= 0;)
  30487. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30488. }
  30489. END_JUCE_NAMESPACE
  30490. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30491. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30492. BEGIN_JUCE_NAMESPACE
  30493. class AsyncUpdaterMessage : public CallbackMessage
  30494. {
  30495. public:
  30496. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30497. : owner (owner_)
  30498. {
  30499. }
  30500. void messageCallback()
  30501. {
  30502. if (shouldDeliver.compareAndSetBool (0, 1))
  30503. owner.handleAsyncUpdate();
  30504. }
  30505. Atomic<int> shouldDeliver;
  30506. private:
  30507. AsyncUpdater& owner;
  30508. };
  30509. AsyncUpdater::AsyncUpdater()
  30510. {
  30511. message = new AsyncUpdaterMessage (*this);
  30512. }
  30513. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30514. {
  30515. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30516. }
  30517. AsyncUpdater::~AsyncUpdater()
  30518. {
  30519. // You're deleting this object with a background thread while there's an update
  30520. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30521. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30522. // deleting this object, or find some other way to avoid such a race condition.
  30523. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30524. getDeliveryFlag().set (0);
  30525. }
  30526. void AsyncUpdater::triggerAsyncUpdate()
  30527. {
  30528. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30529. message->post();
  30530. }
  30531. void AsyncUpdater::cancelPendingUpdate() throw()
  30532. {
  30533. getDeliveryFlag().set (0);
  30534. }
  30535. void AsyncUpdater::handleUpdateNowIfNeeded()
  30536. {
  30537. // This can only be called by the event thread.
  30538. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30539. if (getDeliveryFlag().exchange (0) != 0)
  30540. handleAsyncUpdate();
  30541. }
  30542. bool AsyncUpdater::isUpdatePending() const throw()
  30543. {
  30544. return getDeliveryFlag().value != 0;
  30545. }
  30546. END_JUCE_NAMESPACE
  30547. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30548. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30549. BEGIN_JUCE_NAMESPACE
  30550. ChangeBroadcaster::ChangeBroadcaster() throw()
  30551. {
  30552. // are you trying to create this object before or after juce has been intialised??
  30553. jassert (MessageManager::instance != 0);
  30554. callback.owner = this;
  30555. }
  30556. ChangeBroadcaster::~ChangeBroadcaster()
  30557. {
  30558. // all event-based objects must be deleted BEFORE juce is shut down!
  30559. jassert (MessageManager::instance != 0);
  30560. }
  30561. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30562. {
  30563. // Listeners can only be safely added when the event thread is locked
  30564. // You can use a MessageManagerLock if you need to call this from another thread.
  30565. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30566. changeListeners.add (listener);
  30567. }
  30568. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30569. {
  30570. // Listeners can only be safely added when the event thread is locked
  30571. // You can use a MessageManagerLock if you need to call this from another thread.
  30572. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30573. changeListeners.remove (listener);
  30574. }
  30575. void ChangeBroadcaster::removeAllChangeListeners()
  30576. {
  30577. // Listeners can only be safely added when the event thread is locked
  30578. // You can use a MessageManagerLock if you need to call this from another thread.
  30579. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30580. changeListeners.clear();
  30581. }
  30582. void ChangeBroadcaster::sendChangeMessage()
  30583. {
  30584. if (changeListeners.size() > 0)
  30585. callback.triggerAsyncUpdate();
  30586. }
  30587. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30588. {
  30589. // This can only be called by the event thread.
  30590. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30591. callback.cancelPendingUpdate();
  30592. callListeners();
  30593. }
  30594. void ChangeBroadcaster::dispatchPendingMessages()
  30595. {
  30596. callback.handleUpdateNowIfNeeded();
  30597. }
  30598. void ChangeBroadcaster::callListeners()
  30599. {
  30600. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30601. }
  30602. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30603. : owner (0)
  30604. {
  30605. }
  30606. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30607. {
  30608. jassert (owner != 0);
  30609. owner->callListeners();
  30610. }
  30611. END_JUCE_NAMESPACE
  30612. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30613. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30614. BEGIN_JUCE_NAMESPACE
  30615. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30616. const uint32 magicMessageHeaderNumber)
  30617. : Thread ("Juce IPC connection"),
  30618. callbackConnectionState (false),
  30619. useMessageThread (callbacksOnMessageThread),
  30620. magicMessageHeader (magicMessageHeaderNumber),
  30621. pipeReceiveMessageTimeout (-1)
  30622. {
  30623. }
  30624. InterprocessConnection::~InterprocessConnection()
  30625. {
  30626. callbackConnectionState = false;
  30627. disconnect();
  30628. }
  30629. bool InterprocessConnection::connectToSocket (const String& hostName,
  30630. const int portNumber,
  30631. const int timeOutMillisecs)
  30632. {
  30633. disconnect();
  30634. const ScopedLock sl (pipeAndSocketLock);
  30635. socket = new StreamingSocket();
  30636. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30637. {
  30638. connectionMadeInt();
  30639. startThread();
  30640. return true;
  30641. }
  30642. else
  30643. {
  30644. socket = 0;
  30645. return false;
  30646. }
  30647. }
  30648. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30649. const int pipeReceiveMessageTimeoutMs)
  30650. {
  30651. disconnect();
  30652. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30653. if (newPipe->openExisting (pipeName))
  30654. {
  30655. const ScopedLock sl (pipeAndSocketLock);
  30656. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30657. initialiseWithPipe (newPipe.release());
  30658. return true;
  30659. }
  30660. return false;
  30661. }
  30662. bool InterprocessConnection::createPipe (const String& pipeName,
  30663. const int pipeReceiveMessageTimeoutMs)
  30664. {
  30665. disconnect();
  30666. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30667. if (newPipe->createNewPipe (pipeName))
  30668. {
  30669. const ScopedLock sl (pipeAndSocketLock);
  30670. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30671. initialiseWithPipe (newPipe.release());
  30672. return true;
  30673. }
  30674. return false;
  30675. }
  30676. void InterprocessConnection::disconnect()
  30677. {
  30678. if (socket != 0)
  30679. socket->close();
  30680. if (pipe != 0)
  30681. {
  30682. pipe->cancelPendingReads();
  30683. pipe->close();
  30684. }
  30685. stopThread (4000);
  30686. {
  30687. const ScopedLock sl (pipeAndSocketLock);
  30688. socket = 0;
  30689. pipe = 0;
  30690. }
  30691. connectionLostInt();
  30692. }
  30693. bool InterprocessConnection::isConnected() const
  30694. {
  30695. const ScopedLock sl (pipeAndSocketLock);
  30696. return ((socket != 0 && socket->isConnected())
  30697. || (pipe != 0 && pipe->isOpen()))
  30698. && isThreadRunning();
  30699. }
  30700. const String InterprocessConnection::getConnectedHostName() const
  30701. {
  30702. if (pipe != 0)
  30703. {
  30704. return "localhost";
  30705. }
  30706. else if (socket != 0)
  30707. {
  30708. if (! socket->isLocal())
  30709. return socket->getHostName();
  30710. return "localhost";
  30711. }
  30712. return String::empty;
  30713. }
  30714. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30715. {
  30716. uint32 messageHeader[2];
  30717. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30718. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30719. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30720. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30721. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30722. int bytesWritten = 0;
  30723. const ScopedLock sl (pipeAndSocketLock);
  30724. if (socket != 0)
  30725. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30726. else if (pipe != 0)
  30727. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30728. return bytesWritten == (int) messageData.getSize();
  30729. }
  30730. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30731. {
  30732. jassert (socket == 0);
  30733. socket = socket_;
  30734. connectionMadeInt();
  30735. startThread();
  30736. }
  30737. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30738. {
  30739. jassert (pipe == 0);
  30740. pipe = pipe_;
  30741. connectionMadeInt();
  30742. startThread();
  30743. }
  30744. const int messageMagicNumber = 0xb734128b;
  30745. void InterprocessConnection::handleMessage (const Message& message)
  30746. {
  30747. if (message.intParameter1 == messageMagicNumber)
  30748. {
  30749. switch (message.intParameter2)
  30750. {
  30751. case 0:
  30752. {
  30753. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30754. messageReceived (*data);
  30755. break;
  30756. }
  30757. case 1:
  30758. connectionMade();
  30759. break;
  30760. case 2:
  30761. connectionLost();
  30762. break;
  30763. }
  30764. }
  30765. }
  30766. void InterprocessConnection::connectionMadeInt()
  30767. {
  30768. if (! callbackConnectionState)
  30769. {
  30770. callbackConnectionState = true;
  30771. if (useMessageThread)
  30772. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30773. else
  30774. connectionMade();
  30775. }
  30776. }
  30777. void InterprocessConnection::connectionLostInt()
  30778. {
  30779. if (callbackConnectionState)
  30780. {
  30781. callbackConnectionState = false;
  30782. if (useMessageThread)
  30783. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30784. else
  30785. connectionLost();
  30786. }
  30787. }
  30788. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30789. {
  30790. jassert (callbackConnectionState);
  30791. if (useMessageThread)
  30792. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30793. else
  30794. messageReceived (data);
  30795. }
  30796. bool InterprocessConnection::readNextMessageInt()
  30797. {
  30798. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30799. uint32 messageHeader[2];
  30800. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30801. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30802. if (bytes == sizeof (messageHeader)
  30803. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30804. {
  30805. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30806. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30807. {
  30808. MemoryBlock messageData (bytesInMessage, true);
  30809. int bytesRead = 0;
  30810. while (bytesInMessage > 0)
  30811. {
  30812. if (threadShouldExit())
  30813. return false;
  30814. const int numThisTime = jmin (bytesInMessage, 65536);
  30815. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30816. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30817. if (bytesIn <= 0)
  30818. break;
  30819. bytesRead += bytesIn;
  30820. bytesInMessage -= bytesIn;
  30821. }
  30822. if (bytesRead >= 0)
  30823. deliverDataInt (messageData);
  30824. }
  30825. }
  30826. else if (bytes < 0)
  30827. {
  30828. {
  30829. const ScopedLock sl (pipeAndSocketLock);
  30830. socket = 0;
  30831. }
  30832. connectionLostInt();
  30833. return false;
  30834. }
  30835. return true;
  30836. }
  30837. void InterprocessConnection::run()
  30838. {
  30839. while (! threadShouldExit())
  30840. {
  30841. if (socket != 0)
  30842. {
  30843. const int ready = socket->waitUntilReady (true, 0);
  30844. if (ready < 0)
  30845. {
  30846. {
  30847. const ScopedLock sl (pipeAndSocketLock);
  30848. socket = 0;
  30849. }
  30850. connectionLostInt();
  30851. break;
  30852. }
  30853. else if (ready > 0)
  30854. {
  30855. if (! readNextMessageInt())
  30856. break;
  30857. }
  30858. else
  30859. {
  30860. Thread::sleep (2);
  30861. }
  30862. }
  30863. else if (pipe != 0)
  30864. {
  30865. if (! pipe->isOpen())
  30866. {
  30867. {
  30868. const ScopedLock sl (pipeAndSocketLock);
  30869. pipe = 0;
  30870. }
  30871. connectionLostInt();
  30872. break;
  30873. }
  30874. else
  30875. {
  30876. if (! readNextMessageInt())
  30877. break;
  30878. }
  30879. }
  30880. else
  30881. {
  30882. break;
  30883. }
  30884. }
  30885. }
  30886. END_JUCE_NAMESPACE
  30887. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30888. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30889. BEGIN_JUCE_NAMESPACE
  30890. InterprocessConnectionServer::InterprocessConnectionServer()
  30891. : Thread ("Juce IPC server")
  30892. {
  30893. }
  30894. InterprocessConnectionServer::~InterprocessConnectionServer()
  30895. {
  30896. stop();
  30897. }
  30898. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30899. {
  30900. stop();
  30901. socket = new StreamingSocket();
  30902. if (socket->createListener (portNumber))
  30903. {
  30904. startThread();
  30905. return true;
  30906. }
  30907. socket = 0;
  30908. return false;
  30909. }
  30910. void InterprocessConnectionServer::stop()
  30911. {
  30912. signalThreadShouldExit();
  30913. if (socket != 0)
  30914. socket->close();
  30915. stopThread (4000);
  30916. socket = 0;
  30917. }
  30918. void InterprocessConnectionServer::run()
  30919. {
  30920. while ((! threadShouldExit()) && socket != 0)
  30921. {
  30922. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30923. if (clientSocket != 0)
  30924. {
  30925. InterprocessConnection* newConnection = createConnectionObject();
  30926. if (newConnection != 0)
  30927. newConnection->initialiseWithSocket (clientSocket.release());
  30928. }
  30929. }
  30930. }
  30931. END_JUCE_NAMESPACE
  30932. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30933. /*** Start of inlined file: juce_Message.cpp ***/
  30934. BEGIN_JUCE_NAMESPACE
  30935. Message::Message() throw()
  30936. : intParameter1 (0),
  30937. intParameter2 (0),
  30938. intParameter3 (0),
  30939. pointerParameter (0),
  30940. messageRecipient (0)
  30941. {
  30942. }
  30943. Message::Message (const int intParameter1_,
  30944. const int intParameter2_,
  30945. const int intParameter3_,
  30946. void* const pointerParameter_) throw()
  30947. : intParameter1 (intParameter1_),
  30948. intParameter2 (intParameter2_),
  30949. intParameter3 (intParameter3_),
  30950. pointerParameter (pointerParameter_),
  30951. messageRecipient (0)
  30952. {
  30953. }
  30954. Message::~Message()
  30955. {
  30956. }
  30957. END_JUCE_NAMESPACE
  30958. /*** End of inlined file: juce_Message.cpp ***/
  30959. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30960. BEGIN_JUCE_NAMESPACE
  30961. MessageListener::MessageListener() throw()
  30962. {
  30963. // are you trying to create a messagelistener before or after juce has been intialised??
  30964. jassert (MessageManager::instance != 0);
  30965. if (MessageManager::instance != 0)
  30966. MessageManager::instance->messageListeners.add (this);
  30967. }
  30968. MessageListener::~MessageListener()
  30969. {
  30970. if (MessageManager::instance != 0)
  30971. MessageManager::instance->messageListeners.removeValue (this);
  30972. }
  30973. void MessageListener::postMessage (Message* const message) const throw()
  30974. {
  30975. message->messageRecipient = const_cast <MessageListener*> (this);
  30976. if (MessageManager::instance == 0)
  30977. MessageManager::getInstance();
  30978. MessageManager::instance->postMessageToQueue (message);
  30979. }
  30980. bool MessageListener::isValidMessageListener() const throw()
  30981. {
  30982. return (MessageManager::instance != 0)
  30983. && MessageManager::instance->messageListeners.contains (this);
  30984. }
  30985. END_JUCE_NAMESPACE
  30986. /*** End of inlined file: juce_MessageListener.cpp ***/
  30987. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30988. BEGIN_JUCE_NAMESPACE
  30989. // platform-specific functions..
  30990. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30991. bool juce_postMessageToSystemQueue (Message* message);
  30992. MessageManager* MessageManager::instance = 0;
  30993. static const int quitMessageId = 0xfffff321;
  30994. MessageManager::MessageManager() throw()
  30995. : quitMessagePosted (false),
  30996. quitMessageReceived (false),
  30997. threadWithLock (0)
  30998. {
  30999. messageThreadId = Thread::getCurrentThreadId();
  31000. if (JUCEApplication::isStandaloneApp())
  31001. Thread::setCurrentThreadName ("Juce Message Thread");
  31002. }
  31003. MessageManager::~MessageManager() throw()
  31004. {
  31005. broadcaster = 0;
  31006. doPlatformSpecificShutdown();
  31007. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31008. jassert (messageListeners.size() == 0);
  31009. jassert (instance == this);
  31010. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31011. }
  31012. MessageManager* MessageManager::getInstance() throw()
  31013. {
  31014. if (instance == 0)
  31015. {
  31016. instance = new MessageManager();
  31017. doPlatformSpecificInitialisation();
  31018. }
  31019. return instance;
  31020. }
  31021. void MessageManager::postMessageToQueue (Message* const message)
  31022. {
  31023. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31024. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31025. }
  31026. CallbackMessage::CallbackMessage() throw() {}
  31027. CallbackMessage::~CallbackMessage() {}
  31028. void CallbackMessage::post()
  31029. {
  31030. if (MessageManager::instance != 0)
  31031. MessageManager::instance->postMessageToQueue (this);
  31032. }
  31033. // not for public use..
  31034. void MessageManager::deliverMessage (Message* const message)
  31035. {
  31036. JUCE_TRY
  31037. {
  31038. MessageListener* const recipient = message->messageRecipient;
  31039. if (recipient == 0)
  31040. {
  31041. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31042. if (callbackMessage != 0)
  31043. {
  31044. callbackMessage->messageCallback();
  31045. }
  31046. else if (message->intParameter1 == quitMessageId)
  31047. {
  31048. quitMessageReceived = true;
  31049. }
  31050. }
  31051. else if (messageListeners.contains (recipient))
  31052. {
  31053. recipient->handleMessage (*message);
  31054. }
  31055. }
  31056. JUCE_CATCH_EXCEPTION
  31057. }
  31058. #if ! (JUCE_MAC || JUCE_IOS)
  31059. void MessageManager::runDispatchLoop()
  31060. {
  31061. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31062. runDispatchLoopUntil (-1);
  31063. }
  31064. void MessageManager::stopDispatchLoop()
  31065. {
  31066. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31067. quitMessagePosted = true;
  31068. }
  31069. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31070. {
  31071. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31072. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31073. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31074. && ! quitMessageReceived)
  31075. {
  31076. JUCE_TRY
  31077. {
  31078. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31079. {
  31080. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31081. if (msToWait > 0)
  31082. Thread::sleep (jmin (5, msToWait));
  31083. }
  31084. }
  31085. JUCE_CATCH_EXCEPTION
  31086. }
  31087. return ! quitMessageReceived;
  31088. }
  31089. #endif
  31090. void MessageManager::deliverBroadcastMessage (const String& value)
  31091. {
  31092. if (broadcaster != 0)
  31093. broadcaster->sendActionMessage (value);
  31094. }
  31095. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31096. {
  31097. if (broadcaster == 0)
  31098. broadcaster = new ActionBroadcaster();
  31099. broadcaster->addActionListener (listener);
  31100. }
  31101. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31102. {
  31103. if (broadcaster != 0)
  31104. broadcaster->removeActionListener (listener);
  31105. }
  31106. bool MessageManager::isThisTheMessageThread() const throw()
  31107. {
  31108. return Thread::getCurrentThreadId() == messageThreadId;
  31109. }
  31110. void MessageManager::setCurrentThreadAsMessageThread()
  31111. {
  31112. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31113. if (messageThreadId != thisThread)
  31114. {
  31115. messageThreadId = thisThread;
  31116. // This is needed on windows to make sure the message window is created by this thread
  31117. doPlatformSpecificShutdown();
  31118. doPlatformSpecificInitialisation();
  31119. }
  31120. }
  31121. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31122. {
  31123. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31124. return thisThread == messageThreadId || thisThread == threadWithLock;
  31125. }
  31126. /* The only safe way to lock the message thread while another thread does
  31127. some work is by posting a special message, whose purpose is to tie up the event
  31128. loop until the other thread has finished its business.
  31129. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31130. get locked before making an event callback, because if the same OS lock gets indirectly
  31131. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31132. in Cocoa).
  31133. */
  31134. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31135. {
  31136. public:
  31137. BlockingMessage() {}
  31138. void messageCallback()
  31139. {
  31140. lockedEvent.signal();
  31141. releaseEvent.wait();
  31142. }
  31143. WaitableEvent lockedEvent, releaseEvent;
  31144. private:
  31145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31146. };
  31147. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31148. : locked (false)
  31149. {
  31150. init (threadToCheck, 0);
  31151. }
  31152. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31153. : locked (false)
  31154. {
  31155. init (0, jobToCheckForExitSignal);
  31156. }
  31157. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31158. {
  31159. if (MessageManager::instance != 0)
  31160. {
  31161. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31162. {
  31163. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31164. }
  31165. else
  31166. {
  31167. if (threadToCheck == 0 && job == 0)
  31168. {
  31169. MessageManager::instance->lockingLock.enter();
  31170. }
  31171. else
  31172. {
  31173. while (! MessageManager::instance->lockingLock.tryEnter())
  31174. {
  31175. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31176. || (job != 0 && job->shouldExit()))
  31177. return;
  31178. Thread::sleep (1);
  31179. }
  31180. }
  31181. blockingMessage = new BlockingMessage();
  31182. blockingMessage->post();
  31183. while (! blockingMessage->lockedEvent.wait (20))
  31184. {
  31185. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31186. || (job != 0 && job->shouldExit()))
  31187. {
  31188. blockingMessage->releaseEvent.signal();
  31189. blockingMessage = 0;
  31190. MessageManager::instance->lockingLock.exit();
  31191. return;
  31192. }
  31193. }
  31194. jassert (MessageManager::instance->threadWithLock == 0);
  31195. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31196. locked = true;
  31197. }
  31198. }
  31199. }
  31200. MessageManagerLock::~MessageManagerLock() throw()
  31201. {
  31202. if (blockingMessage != 0)
  31203. {
  31204. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31205. blockingMessage->releaseEvent.signal();
  31206. blockingMessage = 0;
  31207. if (MessageManager::instance != 0)
  31208. {
  31209. MessageManager::instance->threadWithLock = 0;
  31210. MessageManager::instance->lockingLock.exit();
  31211. }
  31212. }
  31213. }
  31214. END_JUCE_NAMESPACE
  31215. /*** End of inlined file: juce_MessageManager.cpp ***/
  31216. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31217. BEGIN_JUCE_NAMESPACE
  31218. class MultiTimer::MultiTimerCallback : public Timer
  31219. {
  31220. public:
  31221. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31222. : timerId (timerId_),
  31223. owner (owner_)
  31224. {
  31225. }
  31226. ~MultiTimerCallback()
  31227. {
  31228. }
  31229. void timerCallback()
  31230. {
  31231. owner.timerCallback (timerId);
  31232. }
  31233. const int timerId;
  31234. private:
  31235. MultiTimer& owner;
  31236. };
  31237. MultiTimer::MultiTimer() throw()
  31238. {
  31239. }
  31240. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31241. {
  31242. }
  31243. MultiTimer::~MultiTimer()
  31244. {
  31245. const ScopedLock sl (timerListLock);
  31246. timers.clear();
  31247. }
  31248. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31249. {
  31250. const ScopedLock sl (timerListLock);
  31251. for (int i = timers.size(); --i >= 0;)
  31252. {
  31253. MultiTimerCallback* const t = timers.getUnchecked(i);
  31254. if (t->timerId == timerId)
  31255. {
  31256. t->startTimer (intervalInMilliseconds);
  31257. return;
  31258. }
  31259. }
  31260. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31261. timers.add (newTimer);
  31262. newTimer->startTimer (intervalInMilliseconds);
  31263. }
  31264. void MultiTimer::stopTimer (const int timerId) throw()
  31265. {
  31266. const ScopedLock sl (timerListLock);
  31267. for (int i = timers.size(); --i >= 0;)
  31268. {
  31269. MultiTimerCallback* const t = timers.getUnchecked(i);
  31270. if (t->timerId == timerId)
  31271. t->stopTimer();
  31272. }
  31273. }
  31274. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31275. {
  31276. const ScopedLock sl (timerListLock);
  31277. for (int i = timers.size(); --i >= 0;)
  31278. {
  31279. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31280. if (t->timerId == timerId)
  31281. return t->isTimerRunning();
  31282. }
  31283. return false;
  31284. }
  31285. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31286. {
  31287. const ScopedLock sl (timerListLock);
  31288. for (int i = timers.size(); --i >= 0;)
  31289. {
  31290. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31291. if (t->timerId == timerId)
  31292. return t->getTimerInterval();
  31293. }
  31294. return 0;
  31295. }
  31296. END_JUCE_NAMESPACE
  31297. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31298. /*** Start of inlined file: juce_Timer.cpp ***/
  31299. BEGIN_JUCE_NAMESPACE
  31300. class InternalTimerThread : private Thread,
  31301. private MessageListener,
  31302. private DeletedAtShutdown,
  31303. private AsyncUpdater
  31304. {
  31305. public:
  31306. InternalTimerThread()
  31307. : Thread ("Juce Timer"),
  31308. firstTimer (0),
  31309. callbackNeeded (0)
  31310. {
  31311. triggerAsyncUpdate();
  31312. }
  31313. ~InternalTimerThread() throw()
  31314. {
  31315. stopThread (4000);
  31316. jassert (instance == this || instance == 0);
  31317. if (instance == this)
  31318. instance = 0;
  31319. }
  31320. void run()
  31321. {
  31322. uint32 lastTime = Time::getMillisecondCounter();
  31323. Message::Ptr message (new Message());
  31324. while (! threadShouldExit())
  31325. {
  31326. const uint32 now = Time::getMillisecondCounter();
  31327. if (now <= lastTime)
  31328. {
  31329. wait (2);
  31330. continue;
  31331. }
  31332. const int elapsed = now - lastTime;
  31333. lastTime = now;
  31334. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31335. if (timeUntilFirstTimer <= 0)
  31336. {
  31337. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31338. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31339. but if it fails it means the message-thread changed the value from under us so at least
  31340. some processing is happenening and we can just loop around and try again
  31341. */
  31342. if (callbackNeeded.compareAndSetBool (1, 0))
  31343. {
  31344. postMessage (message);
  31345. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31346. when the app has a modal loop), so this is how long to wait before assuming the
  31347. message has been lost and trying again.
  31348. */
  31349. const uint32 messageDeliveryTimeout = now + 2000;
  31350. while (callbackNeeded.get() != 0)
  31351. {
  31352. wait (4);
  31353. if (threadShouldExit())
  31354. return;
  31355. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31356. break;
  31357. }
  31358. }
  31359. }
  31360. else
  31361. {
  31362. // don't wait for too long because running this loop also helps keep the
  31363. // Time::getApproximateMillisecondTimer value stay up-to-date
  31364. wait (jlimit (1, 50, timeUntilFirstTimer));
  31365. }
  31366. }
  31367. }
  31368. void callTimers()
  31369. {
  31370. const ScopedLock sl (lock);
  31371. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31372. {
  31373. Timer* const t = firstTimer;
  31374. t->countdownMs = t->periodMs;
  31375. removeTimer (t);
  31376. addTimer (t);
  31377. const ScopedUnlock ul (lock);
  31378. JUCE_TRY
  31379. {
  31380. t->timerCallback();
  31381. }
  31382. JUCE_CATCH_EXCEPTION
  31383. }
  31384. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31385. before the boolean is set. This set should never fail since if it was false in the first place,
  31386. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31387. get a message then the value is true and the other thread can only set it to true again and
  31388. we will get another callback to set it to false.
  31389. */
  31390. callbackNeeded.set (0);
  31391. }
  31392. void handleMessage (const Message&)
  31393. {
  31394. callTimers();
  31395. }
  31396. void callTimersSynchronously()
  31397. {
  31398. if (! isThreadRunning())
  31399. {
  31400. // (This is relied on by some plugins in cases where the MM has
  31401. // had to restart and the async callback never started)
  31402. cancelPendingUpdate();
  31403. triggerAsyncUpdate();
  31404. }
  31405. callTimers();
  31406. }
  31407. static void callAnyTimersSynchronously()
  31408. {
  31409. if (InternalTimerThread::instance != 0)
  31410. InternalTimerThread::instance->callTimersSynchronously();
  31411. }
  31412. static inline void add (Timer* const tim) throw()
  31413. {
  31414. if (instance == 0)
  31415. instance = new InternalTimerThread();
  31416. const ScopedLock sl (instance->lock);
  31417. instance->addTimer (tim);
  31418. }
  31419. static inline void remove (Timer* const tim) throw()
  31420. {
  31421. if (instance != 0)
  31422. {
  31423. const ScopedLock sl (instance->lock);
  31424. instance->removeTimer (tim);
  31425. }
  31426. }
  31427. static inline void resetCounter (Timer* const tim,
  31428. const int newCounter) throw()
  31429. {
  31430. if (instance != 0)
  31431. {
  31432. tim->countdownMs = newCounter;
  31433. tim->periodMs = newCounter;
  31434. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31435. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31436. {
  31437. const ScopedLock sl (instance->lock);
  31438. instance->removeTimer (tim);
  31439. instance->addTimer (tim);
  31440. }
  31441. }
  31442. }
  31443. private:
  31444. friend class Timer;
  31445. static InternalTimerThread* instance;
  31446. static CriticalSection lock;
  31447. Timer* volatile firstTimer;
  31448. Atomic <int> callbackNeeded;
  31449. void addTimer (Timer* const t) throw()
  31450. {
  31451. #if JUCE_DEBUG
  31452. Timer* tt = firstTimer;
  31453. while (tt != 0)
  31454. {
  31455. // trying to add a timer that's already here - shouldn't get to this point,
  31456. // so if you get this assertion, let me know!
  31457. jassert (tt != t);
  31458. tt = tt->next;
  31459. }
  31460. jassert (t->previous == 0 && t->next == 0);
  31461. #endif
  31462. Timer* i = firstTimer;
  31463. if (i == 0 || i->countdownMs > t->countdownMs)
  31464. {
  31465. t->next = firstTimer;
  31466. firstTimer = t;
  31467. }
  31468. else
  31469. {
  31470. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31471. i = i->next;
  31472. jassert (i != 0);
  31473. t->next = i->next;
  31474. t->previous = i;
  31475. i->next = t;
  31476. }
  31477. if (t->next != 0)
  31478. t->next->previous = t;
  31479. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31480. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31481. notify();
  31482. }
  31483. void removeTimer (Timer* const t) throw()
  31484. {
  31485. #if JUCE_DEBUG
  31486. Timer* tt = firstTimer;
  31487. bool found = false;
  31488. while (tt != 0)
  31489. {
  31490. if (tt == t)
  31491. {
  31492. found = true;
  31493. break;
  31494. }
  31495. tt = tt->next;
  31496. }
  31497. // trying to remove a timer that's not here - shouldn't get to this point,
  31498. // so if you get this assertion, let me know!
  31499. jassert (found);
  31500. #endif
  31501. if (t->previous != 0)
  31502. {
  31503. jassert (firstTimer != t);
  31504. t->previous->next = t->next;
  31505. }
  31506. else
  31507. {
  31508. jassert (firstTimer == t);
  31509. firstTimer = t->next;
  31510. }
  31511. if (t->next != 0)
  31512. t->next->previous = t->previous;
  31513. t->next = 0;
  31514. t->previous = 0;
  31515. }
  31516. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31517. {
  31518. const ScopedLock sl (lock);
  31519. for (Timer* t = firstTimer; t != 0; t = t->next)
  31520. t->countdownMs -= numMillisecsElapsed;
  31521. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31522. }
  31523. void handleAsyncUpdate()
  31524. {
  31525. startThread (7);
  31526. }
  31527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31528. };
  31529. InternalTimerThread* InternalTimerThread::instance = 0;
  31530. CriticalSection InternalTimerThread::lock;
  31531. void juce_callAnyTimersSynchronously()
  31532. {
  31533. InternalTimerThread::callAnyTimersSynchronously();
  31534. }
  31535. #if JUCE_DEBUG
  31536. static SortedSet <Timer*> activeTimers;
  31537. #endif
  31538. Timer::Timer() throw()
  31539. : countdownMs (0),
  31540. periodMs (0),
  31541. previous (0),
  31542. next (0)
  31543. {
  31544. #if JUCE_DEBUG
  31545. activeTimers.add (this);
  31546. #endif
  31547. }
  31548. Timer::Timer (const Timer&) throw()
  31549. : countdownMs (0),
  31550. periodMs (0),
  31551. previous (0),
  31552. next (0)
  31553. {
  31554. #if JUCE_DEBUG
  31555. activeTimers.add (this);
  31556. #endif
  31557. }
  31558. Timer::~Timer()
  31559. {
  31560. stopTimer();
  31561. #if JUCE_DEBUG
  31562. activeTimers.removeValue (this);
  31563. #endif
  31564. }
  31565. void Timer::startTimer (const int interval) throw()
  31566. {
  31567. const ScopedLock sl (InternalTimerThread::lock);
  31568. #if JUCE_DEBUG
  31569. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31570. jassert (activeTimers.contains (this));
  31571. #endif
  31572. if (periodMs == 0)
  31573. {
  31574. countdownMs = interval;
  31575. periodMs = jmax (1, interval);
  31576. InternalTimerThread::add (this);
  31577. }
  31578. else
  31579. {
  31580. InternalTimerThread::resetCounter (this, interval);
  31581. }
  31582. }
  31583. void Timer::stopTimer() throw()
  31584. {
  31585. const ScopedLock sl (InternalTimerThread::lock);
  31586. #if JUCE_DEBUG
  31587. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31588. jassert (activeTimers.contains (this));
  31589. #endif
  31590. if (periodMs > 0)
  31591. {
  31592. InternalTimerThread::remove (this);
  31593. periodMs = 0;
  31594. }
  31595. }
  31596. END_JUCE_NAMESPACE
  31597. /*** End of inlined file: juce_Timer.cpp ***/
  31598. #endif
  31599. #if JUCE_BUILD_GUI
  31600. /*** Start of inlined file: juce_Component.cpp ***/
  31601. BEGIN_JUCE_NAMESPACE
  31602. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31603. Component* Component::currentlyFocusedComponent = 0;
  31604. class Component::MouseListenerList
  31605. {
  31606. public:
  31607. MouseListenerList()
  31608. : numDeepMouseListeners (0)
  31609. {
  31610. }
  31611. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31612. {
  31613. if (! listeners.contains (newListener))
  31614. {
  31615. if (wantsEventsForAllNestedChildComponents)
  31616. {
  31617. listeners.insert (0, newListener);
  31618. ++numDeepMouseListeners;
  31619. }
  31620. else
  31621. {
  31622. listeners.add (newListener);
  31623. }
  31624. }
  31625. }
  31626. void removeListener (MouseListener* const listenerToRemove)
  31627. {
  31628. const int index = listeners.indexOf (listenerToRemove);
  31629. if (index >= 0)
  31630. {
  31631. if (index < numDeepMouseListeners)
  31632. --numDeepMouseListeners;
  31633. listeners.remove (index);
  31634. }
  31635. }
  31636. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31637. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31638. {
  31639. if (checker.shouldBailOut())
  31640. return;
  31641. {
  31642. MouseListenerList* const list = comp.mouseListeners;
  31643. if (list != 0)
  31644. {
  31645. for (int i = list->listeners.size(); --i >= 0;)
  31646. {
  31647. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31648. if (checker.shouldBailOut())
  31649. return;
  31650. i = jmin (i, list->listeners.size());
  31651. }
  31652. }
  31653. }
  31654. Component* p = comp.parentComponent;
  31655. while (p != 0)
  31656. {
  31657. MouseListenerList* const list = p->mouseListeners;
  31658. if (list != 0 && list->numDeepMouseListeners > 0)
  31659. {
  31660. BailOutChecker2 checker2 (checker, p);
  31661. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31662. {
  31663. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31664. if (checker2.shouldBailOut())
  31665. return;
  31666. i = jmin (i, list->numDeepMouseListeners);
  31667. }
  31668. }
  31669. p = p->parentComponent;
  31670. }
  31671. }
  31672. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31673. const float wheelIncrementX, const float wheelIncrementY)
  31674. {
  31675. {
  31676. MouseListenerList* const list = comp.mouseListeners;
  31677. if (list != 0)
  31678. {
  31679. for (int i = list->listeners.size(); --i >= 0;)
  31680. {
  31681. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31682. if (checker.shouldBailOut())
  31683. return;
  31684. i = jmin (i, list->listeners.size());
  31685. }
  31686. }
  31687. }
  31688. Component* p = comp.parentComponent;
  31689. while (p != 0)
  31690. {
  31691. MouseListenerList* const list = p->mouseListeners;
  31692. if (list != 0 && list->numDeepMouseListeners > 0)
  31693. {
  31694. BailOutChecker2 checker2 (checker, p);
  31695. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31696. {
  31697. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31698. if (checker2.shouldBailOut())
  31699. return;
  31700. i = jmin (i, list->numDeepMouseListeners);
  31701. }
  31702. }
  31703. p = p->parentComponent;
  31704. }
  31705. }
  31706. private:
  31707. Array <MouseListener*> listeners;
  31708. int numDeepMouseListeners;
  31709. class BailOutChecker2
  31710. {
  31711. public:
  31712. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31713. : checker (checker_), safePointer (component)
  31714. {
  31715. }
  31716. bool shouldBailOut() const throw()
  31717. {
  31718. return checker.shouldBailOut() || safePointer == 0;
  31719. }
  31720. private:
  31721. BailOutChecker& checker;
  31722. const WeakReference<Component> safePointer;
  31723. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31724. };
  31725. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31726. };
  31727. class Component::ComponentHelpers
  31728. {
  31729. public:
  31730. static void* runModalLoopCallback (void* userData)
  31731. {
  31732. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31733. }
  31734. static const Identifier getColourPropertyId (const int colourId)
  31735. {
  31736. String s;
  31737. s.preallocateStorage (18);
  31738. s << "jcclr_" << String::toHexString (colourId);
  31739. return s;
  31740. }
  31741. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31742. {
  31743. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31744. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31745. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31746. }
  31747. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31748. {
  31749. if (comp.affineTransform == 0)
  31750. return pointInParentSpace - comp.getPosition();
  31751. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31752. }
  31753. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31754. {
  31755. if (comp.affineTransform == 0)
  31756. return areaInParentSpace - comp.getPosition();
  31757. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31758. }
  31759. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31760. {
  31761. if (comp.affineTransform == 0)
  31762. return pointInLocalSpace + comp.getPosition();
  31763. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31764. }
  31765. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31766. {
  31767. if (comp.affineTransform == 0)
  31768. return areaInLocalSpace + comp.getPosition();
  31769. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31770. }
  31771. template <typename Type>
  31772. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31773. {
  31774. const Component* const directParent = target.getParentComponent();
  31775. jassert (directParent != 0);
  31776. if (directParent == parent)
  31777. return convertFromParentSpace (target, coordInParent);
  31778. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31779. }
  31780. template <typename Type>
  31781. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31782. {
  31783. while (source != 0)
  31784. {
  31785. if (source == target)
  31786. return p;
  31787. if (source->isParentOf (target))
  31788. return convertFromDistantParentSpace (source, *target, p);
  31789. if (source->isOnDesktop())
  31790. {
  31791. p = source->getPeer()->localToGlobal (p);
  31792. source = 0;
  31793. }
  31794. else
  31795. {
  31796. p = convertToParentSpace (*source, p);
  31797. source = source->getParentComponent();
  31798. }
  31799. }
  31800. jassert (source == 0);
  31801. if (target == 0)
  31802. return p;
  31803. const Component* const topLevelComp = target->getTopLevelComponent();
  31804. if (topLevelComp->isOnDesktop())
  31805. p = topLevelComp->getPeer()->globalToLocal (p);
  31806. else
  31807. p = convertFromParentSpace (*topLevelComp, p);
  31808. if (topLevelComp == target)
  31809. return p;
  31810. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31811. }
  31812. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31813. {
  31814. Rectangle<int> r (comp.getLocalBounds());
  31815. Component* const p = comp.getParentComponent();
  31816. if (p != 0)
  31817. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31818. return r;
  31819. }
  31820. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  31821. {
  31822. for (int i = comp.childComponentList.size(); --i >= 0;)
  31823. {
  31824. const Component& child = *comp.childComponentList.getUnchecked(i);
  31825. if (child.isVisible() && ! child.isTransformed())
  31826. {
  31827. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  31828. if (! newClip.isEmpty())
  31829. {
  31830. if (child.isOpaque())
  31831. {
  31832. g.excludeClipRegion (newClip + delta);
  31833. }
  31834. else
  31835. {
  31836. const Point<int> childPos (child.getPosition());
  31837. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  31838. }
  31839. }
  31840. }
  31841. }
  31842. }
  31843. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  31844. const Point<int>& delta,
  31845. const Rectangle<int>& clipRect,
  31846. const Component* const compToAvoid)
  31847. {
  31848. for (int i = comp.childComponentList.size(); --i >= 0;)
  31849. {
  31850. const Component* const c = comp.childComponentList.getUnchecked(i);
  31851. if (c != compToAvoid && c->isVisible())
  31852. {
  31853. if (c->isOpaque())
  31854. {
  31855. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  31856. childBounds.translate (delta.getX(), delta.getY());
  31857. result.subtract (childBounds);
  31858. }
  31859. else
  31860. {
  31861. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  31862. newClip.translate (-c->getX(), -c->getY());
  31863. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  31864. newClip, compToAvoid);
  31865. }
  31866. }
  31867. }
  31868. }
  31869. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  31870. {
  31871. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  31872. : Desktop::getInstance().getMainMonitorArea();
  31873. }
  31874. };
  31875. Component::Component()
  31876. : parentComponent (0),
  31877. lookAndFeel (0),
  31878. effect (0),
  31879. componentFlags (0),
  31880. componentTransparency (0)
  31881. {
  31882. }
  31883. Component::Component (const String& name)
  31884. : componentName (name),
  31885. parentComponent (0),
  31886. lookAndFeel (0),
  31887. effect (0),
  31888. componentFlags (0),
  31889. componentTransparency (0)
  31890. {
  31891. }
  31892. Component::~Component()
  31893. {
  31894. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  31895. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  31896. #endif
  31897. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31898. weakReferenceMaster.clear();
  31899. while (childComponentList.size() > 0)
  31900. removeChildComponent (childComponentList.size() - 1, false, true);
  31901. if (parentComponent != 0)
  31902. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  31903. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31904. giveAwayFocus (currentlyFocusedComponent != this);
  31905. if (flags.hasHeavyweightPeerFlag)
  31906. removeFromDesktop();
  31907. // Something has added some children to this component during its destructor! Not a smart idea!
  31908. jassert (childComponentList.size() == 0);
  31909. }
  31910. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  31911. {
  31912. return weakReferenceMaster (this);
  31913. }
  31914. void Component::setName (const String& name)
  31915. {
  31916. // if component methods are being called from threads other than the message
  31917. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31918. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31919. if (componentName != name)
  31920. {
  31921. componentName = name;
  31922. if (flags.hasHeavyweightPeerFlag)
  31923. {
  31924. ComponentPeer* const peer = getPeer();
  31925. jassert (peer != 0);
  31926. if (peer != 0)
  31927. peer->setTitle (name);
  31928. }
  31929. BailOutChecker checker (this);
  31930. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31931. }
  31932. }
  31933. void Component::setComponentID (const String& newID)
  31934. {
  31935. componentID = newID;
  31936. }
  31937. void Component::setVisible (bool shouldBeVisible)
  31938. {
  31939. if (flags.visibleFlag != shouldBeVisible)
  31940. {
  31941. // if component methods are being called from threads other than the message
  31942. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31943. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31944. WeakReference<Component> safePointer (this);
  31945. flags.visibleFlag = shouldBeVisible;
  31946. internalRepaint (0, 0, getWidth(), getHeight());
  31947. sendFakeMouseMove();
  31948. if (! shouldBeVisible)
  31949. {
  31950. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31951. {
  31952. if (parentComponent != 0)
  31953. parentComponent->grabKeyboardFocus();
  31954. else
  31955. giveAwayFocus (true);
  31956. }
  31957. }
  31958. if (safePointer != 0)
  31959. {
  31960. sendVisibilityChangeMessage();
  31961. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31962. {
  31963. ComponentPeer* const peer = getPeer();
  31964. jassert (peer != 0);
  31965. if (peer != 0)
  31966. {
  31967. peer->setVisible (shouldBeVisible);
  31968. internalHierarchyChanged();
  31969. }
  31970. }
  31971. }
  31972. }
  31973. }
  31974. void Component::visibilityChanged()
  31975. {
  31976. }
  31977. void Component::sendVisibilityChangeMessage()
  31978. {
  31979. BailOutChecker checker (this);
  31980. visibilityChanged();
  31981. if (! checker.shouldBailOut())
  31982. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31983. }
  31984. bool Component::isShowing() const
  31985. {
  31986. if (flags.visibleFlag)
  31987. {
  31988. if (parentComponent != 0)
  31989. {
  31990. return parentComponent->isShowing();
  31991. }
  31992. else
  31993. {
  31994. const ComponentPeer* const peer = getPeer();
  31995. return peer != 0 && ! peer->isMinimised();
  31996. }
  31997. }
  31998. return false;
  31999. }
  32000. void* Component::getWindowHandle() const
  32001. {
  32002. const ComponentPeer* const peer = getPeer();
  32003. if (peer != 0)
  32004. return peer->getNativeHandle();
  32005. return 0;
  32006. }
  32007. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32008. {
  32009. // if component methods are being called from threads other than the message
  32010. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32011. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32012. if (isOpaque())
  32013. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32014. else
  32015. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32016. int currentStyleFlags = 0;
  32017. // don't use getPeer(), so that we only get the peer that's specifically
  32018. // for this comp, and not for one of its parents.
  32019. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32020. if (peer != 0)
  32021. currentStyleFlags = peer->getStyleFlags();
  32022. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32023. {
  32024. WeakReference<Component> safePointer (this);
  32025. #if JUCE_LINUX
  32026. // it's wise to give the component a non-zero size before
  32027. // putting it on the desktop, as X windows get confused by this, and
  32028. // a (1, 1) minimum size is enforced here.
  32029. setSize (jmax (1, getWidth()),
  32030. jmax (1, getHeight()));
  32031. #endif
  32032. const Point<int> topLeft (getScreenPosition());
  32033. bool wasFullscreen = false;
  32034. bool wasMinimised = false;
  32035. ComponentBoundsConstrainer* currentConstainer = 0;
  32036. Rectangle<int> oldNonFullScreenBounds;
  32037. if (peer != 0)
  32038. {
  32039. wasFullscreen = peer->isFullScreen();
  32040. wasMinimised = peer->isMinimised();
  32041. currentConstainer = peer->getConstrainer();
  32042. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32043. removeFromDesktop();
  32044. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32045. }
  32046. if (parentComponent != 0)
  32047. parentComponent->removeChildComponent (this);
  32048. if (safePointer != 0)
  32049. {
  32050. flags.hasHeavyweightPeerFlag = true;
  32051. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32052. Desktop::getInstance().addDesktopComponent (this);
  32053. bounds.setPosition (topLeft);
  32054. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32055. peer->setVisible (isVisible());
  32056. if (wasFullscreen)
  32057. {
  32058. peer->setFullScreen (true);
  32059. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32060. }
  32061. if (wasMinimised)
  32062. peer->setMinimised (true);
  32063. if (isAlwaysOnTop())
  32064. peer->setAlwaysOnTop (true);
  32065. peer->setConstrainer (currentConstainer);
  32066. repaint();
  32067. }
  32068. internalHierarchyChanged();
  32069. }
  32070. }
  32071. void Component::removeFromDesktop()
  32072. {
  32073. // if component methods are being called from threads other than the message
  32074. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32075. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32076. if (flags.hasHeavyweightPeerFlag)
  32077. {
  32078. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32079. flags.hasHeavyweightPeerFlag = false;
  32080. jassert (peer != 0);
  32081. delete peer;
  32082. Desktop::getInstance().removeDesktopComponent (this);
  32083. }
  32084. }
  32085. bool Component::isOnDesktop() const throw()
  32086. {
  32087. return flags.hasHeavyweightPeerFlag;
  32088. }
  32089. void Component::userTriedToCloseWindow()
  32090. {
  32091. /* This means that the user's trying to get rid of your window with the 'close window' system
  32092. menu option (on windows) or possibly the task manager - you should really handle this
  32093. and delete or hide your component in an appropriate way.
  32094. If you want to ignore the event and don't want to trigger this assertion, just override
  32095. this method and do nothing.
  32096. */
  32097. jassertfalse;
  32098. }
  32099. void Component::minimisationStateChanged (bool)
  32100. {
  32101. }
  32102. void Component::setOpaque (const bool shouldBeOpaque)
  32103. {
  32104. if (shouldBeOpaque != flags.opaqueFlag)
  32105. {
  32106. flags.opaqueFlag = shouldBeOpaque;
  32107. if (flags.hasHeavyweightPeerFlag)
  32108. {
  32109. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32110. if (peer != 0)
  32111. {
  32112. // to make it recreate the heavyweight window
  32113. addToDesktop (peer->getStyleFlags());
  32114. }
  32115. }
  32116. repaint();
  32117. }
  32118. }
  32119. bool Component::isOpaque() const throw()
  32120. {
  32121. return flags.opaqueFlag;
  32122. }
  32123. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32124. {
  32125. if (shouldBeBuffered != flags.bufferToImageFlag)
  32126. {
  32127. bufferedImage = Image::null;
  32128. flags.bufferToImageFlag = shouldBeBuffered;
  32129. }
  32130. }
  32131. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32132. {
  32133. if (sourceIndex != destIndex)
  32134. {
  32135. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32136. jassert (c != 0);
  32137. c->repaintParent();
  32138. childComponentList.move (sourceIndex, destIndex);
  32139. sendFakeMouseMove();
  32140. internalChildrenChanged();
  32141. }
  32142. }
  32143. void Component::toFront (const bool setAsForeground)
  32144. {
  32145. // if component methods are being called from threads other than the message
  32146. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32147. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32148. if (flags.hasHeavyweightPeerFlag)
  32149. {
  32150. ComponentPeer* const peer = getPeer();
  32151. if (peer != 0)
  32152. {
  32153. peer->toFront (setAsForeground);
  32154. if (setAsForeground && ! hasKeyboardFocus (true))
  32155. grabKeyboardFocus();
  32156. }
  32157. }
  32158. else if (parentComponent != 0)
  32159. {
  32160. const Array<Component*>& childList = parentComponent->childComponentList;
  32161. if (childList.getLast() != this)
  32162. {
  32163. const int index = childList.indexOf (this);
  32164. if (index >= 0)
  32165. {
  32166. int insertIndex = -1;
  32167. if (! flags.alwaysOnTopFlag)
  32168. {
  32169. insertIndex = childList.size() - 1;
  32170. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32171. --insertIndex;
  32172. }
  32173. parentComponent->moveChildInternal (index, insertIndex);
  32174. }
  32175. }
  32176. if (setAsForeground)
  32177. {
  32178. internalBroughtToFront();
  32179. grabKeyboardFocus();
  32180. }
  32181. }
  32182. }
  32183. void Component::toBehind (Component* const other)
  32184. {
  32185. if (other != 0 && other != this)
  32186. {
  32187. // the two components must belong to the same parent..
  32188. jassert (parentComponent == other->parentComponent);
  32189. if (parentComponent != 0)
  32190. {
  32191. const Array<Component*>& childList = parentComponent->childComponentList;
  32192. const int index = childList.indexOf (this);
  32193. if (index >= 0 && childList [index + 1] != other)
  32194. {
  32195. int otherIndex = childList.indexOf (other);
  32196. if (otherIndex >= 0)
  32197. {
  32198. if (index < otherIndex)
  32199. --otherIndex;
  32200. parentComponent->moveChildInternal (index, otherIndex);
  32201. }
  32202. }
  32203. }
  32204. else if (isOnDesktop())
  32205. {
  32206. jassert (other->isOnDesktop());
  32207. if (other->isOnDesktop())
  32208. {
  32209. ComponentPeer* const us = getPeer();
  32210. ComponentPeer* const them = other->getPeer();
  32211. jassert (us != 0 && them != 0);
  32212. if (us != 0 && them != 0)
  32213. us->toBehind (them);
  32214. }
  32215. }
  32216. }
  32217. }
  32218. void Component::toBack()
  32219. {
  32220. if (isOnDesktop())
  32221. {
  32222. jassertfalse; //xxx need to add this to native window
  32223. }
  32224. else if (parentComponent != 0)
  32225. {
  32226. const Array<Component*>& childList = parentComponent->childComponentList;
  32227. if (childList.getFirst() != this)
  32228. {
  32229. const int index = childList.indexOf (this);
  32230. if (index > 0)
  32231. {
  32232. int insertIndex = 0;
  32233. if (flags.alwaysOnTopFlag)
  32234. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32235. ++insertIndex;
  32236. parentComponent->moveChildInternal (index, insertIndex);
  32237. }
  32238. }
  32239. }
  32240. }
  32241. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32242. {
  32243. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32244. {
  32245. flags.alwaysOnTopFlag = shouldStayOnTop;
  32246. if (isOnDesktop())
  32247. {
  32248. ComponentPeer* const peer = getPeer();
  32249. jassert (peer != 0);
  32250. if (peer != 0)
  32251. {
  32252. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32253. {
  32254. // some kinds of peer can't change their always-on-top status, so
  32255. // for these, we'll need to create a new window
  32256. const int oldFlags = peer->getStyleFlags();
  32257. removeFromDesktop();
  32258. addToDesktop (oldFlags);
  32259. }
  32260. }
  32261. }
  32262. if (shouldStayOnTop)
  32263. toFront (false);
  32264. internalHierarchyChanged();
  32265. }
  32266. }
  32267. bool Component::isAlwaysOnTop() const throw()
  32268. {
  32269. return flags.alwaysOnTopFlag;
  32270. }
  32271. int Component::proportionOfWidth (const float proportion) const throw()
  32272. {
  32273. return roundToInt (proportion * bounds.getWidth());
  32274. }
  32275. int Component::proportionOfHeight (const float proportion) const throw()
  32276. {
  32277. return roundToInt (proportion * bounds.getHeight());
  32278. }
  32279. int Component::getParentWidth() const throw()
  32280. {
  32281. return (parentComponent != 0) ? parentComponent->getWidth()
  32282. : getParentMonitorArea().getWidth();
  32283. }
  32284. int Component::getParentHeight() const throw()
  32285. {
  32286. return (parentComponent != 0) ? parentComponent->getHeight()
  32287. : getParentMonitorArea().getHeight();
  32288. }
  32289. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32290. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32291. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32292. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32293. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32294. {
  32295. return ComponentHelpers::convertCoordinate (this, source, point);
  32296. }
  32297. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32298. {
  32299. return ComponentHelpers::convertCoordinate (this, source, area);
  32300. }
  32301. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32302. {
  32303. return ComponentHelpers::convertCoordinate (0, this, point);
  32304. }
  32305. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32306. {
  32307. return ComponentHelpers::convertCoordinate (0, this, area);
  32308. }
  32309. /* Deprecated methods... */
  32310. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32311. {
  32312. return localPointToGlobal (relativePosition);
  32313. }
  32314. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32315. {
  32316. return getLocalPoint (0, screenPosition);
  32317. }
  32318. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32319. {
  32320. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32321. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32322. }
  32323. void Component::setBounds (const int x, const int y, int w, int h)
  32324. {
  32325. // if component methods are being called from threads other than the message
  32326. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32327. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32328. if (w < 0) w = 0;
  32329. if (h < 0) h = 0;
  32330. const bool wasResized = (getWidth() != w || getHeight() != h);
  32331. const bool wasMoved = (getX() != x || getY() != y);
  32332. #if JUCE_DEBUG
  32333. // It's a very bad idea to try to resize a window during its paint() method!
  32334. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32335. #endif
  32336. if (wasMoved || wasResized)
  32337. {
  32338. const bool showing = isShowing();
  32339. if (showing)
  32340. {
  32341. // send a fake mouse move to trigger enter/exit messages if needed..
  32342. sendFakeMouseMove();
  32343. if (! flags.hasHeavyweightPeerFlag)
  32344. repaintParent();
  32345. }
  32346. bounds.setBounds (x, y, w, h);
  32347. if (showing)
  32348. {
  32349. if (wasResized)
  32350. repaint();
  32351. else if (! flags.hasHeavyweightPeerFlag)
  32352. repaintParent();
  32353. }
  32354. if (flags.hasHeavyweightPeerFlag)
  32355. {
  32356. ComponentPeer* const peer = getPeer();
  32357. if (peer != 0)
  32358. {
  32359. if (wasMoved && wasResized)
  32360. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32361. else if (wasMoved)
  32362. peer->setPosition (getX(), getY());
  32363. else if (wasResized)
  32364. peer->setSize (getWidth(), getHeight());
  32365. }
  32366. }
  32367. sendMovedResizedMessages (wasMoved, wasResized);
  32368. }
  32369. }
  32370. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32371. {
  32372. BailOutChecker checker (this);
  32373. if (wasMoved)
  32374. {
  32375. moved();
  32376. if (checker.shouldBailOut())
  32377. return;
  32378. }
  32379. if (wasResized)
  32380. {
  32381. resized();
  32382. if (checker.shouldBailOut())
  32383. return;
  32384. for (int i = childComponentList.size(); --i >= 0;)
  32385. {
  32386. childComponentList.getUnchecked(i)->parentSizeChanged();
  32387. if (checker.shouldBailOut())
  32388. return;
  32389. i = jmin (i, childComponentList.size());
  32390. }
  32391. }
  32392. if (parentComponent != 0)
  32393. parentComponent->childBoundsChanged (this);
  32394. if (! checker.shouldBailOut())
  32395. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32396. *this, wasMoved, wasResized);
  32397. }
  32398. void Component::setSize (const int w, const int h)
  32399. {
  32400. setBounds (getX(), getY(), w, h);
  32401. }
  32402. void Component::setTopLeftPosition (const int x, const int y)
  32403. {
  32404. setBounds (x, y, getWidth(), getHeight());
  32405. }
  32406. void Component::setTopRightPosition (const int x, const int y)
  32407. {
  32408. setTopLeftPosition (x - getWidth(), y);
  32409. }
  32410. void Component::setBounds (const Rectangle<int>& r)
  32411. {
  32412. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32413. }
  32414. void Component::setBounds (const RelativeRectangle& newBounds)
  32415. {
  32416. newBounds.applyToComponent (*this);
  32417. }
  32418. void Component::setBoundsRelative (const float x, const float y,
  32419. const float w, const float h)
  32420. {
  32421. const int pw = getParentWidth();
  32422. const int ph = getParentHeight();
  32423. setBounds (roundToInt (x * pw),
  32424. roundToInt (y * ph),
  32425. roundToInt (w * pw),
  32426. roundToInt (h * ph));
  32427. }
  32428. void Component::setCentrePosition (const int x, const int y)
  32429. {
  32430. setTopLeftPosition (x - getWidth() / 2,
  32431. y - getHeight() / 2);
  32432. }
  32433. void Component::setCentreRelative (const float x, const float y)
  32434. {
  32435. setCentrePosition (roundToInt (getParentWidth() * x),
  32436. roundToInt (getParentHeight() * y));
  32437. }
  32438. void Component::centreWithSize (const int width, const int height)
  32439. {
  32440. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32441. setBounds (parentArea.getCentreX() - width / 2,
  32442. parentArea.getCentreY() - height / 2,
  32443. width, height);
  32444. }
  32445. void Component::setBoundsInset (const BorderSize<int>& borders)
  32446. {
  32447. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32448. }
  32449. void Component::setBoundsToFit (int x, int y, int width, int height,
  32450. const Justification& justification,
  32451. const bool onlyReduceInSize)
  32452. {
  32453. // it's no good calling this method unless both the component and
  32454. // target rectangle have a finite size.
  32455. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32456. if (getWidth() > 0 && getHeight() > 0
  32457. && width > 0 && height > 0)
  32458. {
  32459. int newW, newH;
  32460. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32461. {
  32462. newW = getWidth();
  32463. newH = getHeight();
  32464. }
  32465. else
  32466. {
  32467. const double imageRatio = getHeight() / (double) getWidth();
  32468. const double targetRatio = height / (double) width;
  32469. if (imageRatio <= targetRatio)
  32470. {
  32471. newW = width;
  32472. newH = jmin (height, roundToInt (newW * imageRatio));
  32473. }
  32474. else
  32475. {
  32476. newH = height;
  32477. newW = jmin (width, roundToInt (newH / imageRatio));
  32478. }
  32479. }
  32480. if (newW > 0 && newH > 0)
  32481. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32482. Rectangle<int> (x, y, width, height)));
  32483. }
  32484. }
  32485. bool Component::isTransformed() const throw()
  32486. {
  32487. return affineTransform != 0;
  32488. }
  32489. void Component::setTransform (const AffineTransform& newTransform)
  32490. {
  32491. // If you pass in a transform with no inverse, the component will have no dimensions,
  32492. // and there will be all sorts of maths errors when converting coordinates.
  32493. jassert (! newTransform.isSingularity());
  32494. if (newTransform.isIdentity())
  32495. {
  32496. if (affineTransform != 0)
  32497. {
  32498. repaint();
  32499. affineTransform = 0;
  32500. repaint();
  32501. sendMovedResizedMessages (false, false);
  32502. }
  32503. }
  32504. else if (affineTransform == 0)
  32505. {
  32506. repaint();
  32507. affineTransform = new AffineTransform (newTransform);
  32508. repaint();
  32509. sendMovedResizedMessages (false, false);
  32510. }
  32511. else if (*affineTransform != newTransform)
  32512. {
  32513. repaint();
  32514. *affineTransform = newTransform;
  32515. repaint();
  32516. sendMovedResizedMessages (false, false);
  32517. }
  32518. }
  32519. const AffineTransform Component::getTransform() const
  32520. {
  32521. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32522. }
  32523. bool Component::hitTest (int x, int y)
  32524. {
  32525. if (! flags.ignoresMouseClicksFlag)
  32526. return true;
  32527. if (flags.allowChildMouseClicksFlag)
  32528. {
  32529. for (int i = getNumChildComponents(); --i >= 0;)
  32530. {
  32531. Component& child = *getChildComponent (i);
  32532. if (child.isVisible()
  32533. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32534. return true;
  32535. }
  32536. }
  32537. return false;
  32538. }
  32539. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32540. const bool allowClicksOnChildComponents) throw()
  32541. {
  32542. flags.ignoresMouseClicksFlag = ! allowClicks;
  32543. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32544. }
  32545. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32546. bool& allowsClicksOnChildComponents) const throw()
  32547. {
  32548. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32549. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32550. }
  32551. bool Component::contains (const Point<int>& point)
  32552. {
  32553. if (ComponentHelpers::hitTest (*this, point))
  32554. {
  32555. if (parentComponent != 0)
  32556. {
  32557. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32558. }
  32559. else if (flags.hasHeavyweightPeerFlag)
  32560. {
  32561. const ComponentPeer* const peer = getPeer();
  32562. if (peer != 0)
  32563. return peer->contains (point, true);
  32564. }
  32565. }
  32566. return false;
  32567. }
  32568. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32569. {
  32570. if (! contains (point))
  32571. return false;
  32572. Component* const top = getTopLevelComponent();
  32573. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32574. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32575. }
  32576. Component* Component::getComponentAt (const Point<int>& position)
  32577. {
  32578. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32579. {
  32580. for (int i = childComponentList.size(); --i >= 0;)
  32581. {
  32582. Component* child = childComponentList.getUnchecked(i);
  32583. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32584. if (child != 0)
  32585. return child;
  32586. }
  32587. return this;
  32588. }
  32589. return 0;
  32590. }
  32591. Component* Component::getComponentAt (const int x, const int y)
  32592. {
  32593. return getComponentAt (Point<int> (x, y));
  32594. }
  32595. void Component::addChildComponent (Component* const child, int zOrder)
  32596. {
  32597. // if component methods are being called from threads other than the message
  32598. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32599. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32600. if (child != 0 && child->parentComponent != this)
  32601. {
  32602. if (child->parentComponent != 0)
  32603. child->parentComponent->removeChildComponent (child);
  32604. else
  32605. child->removeFromDesktop();
  32606. child->parentComponent = this;
  32607. if (child->isVisible())
  32608. child->repaintParent();
  32609. if (! child->isAlwaysOnTop())
  32610. {
  32611. if (zOrder < 0 || zOrder > childComponentList.size())
  32612. zOrder = childComponentList.size();
  32613. while (zOrder > 0)
  32614. {
  32615. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32616. break;
  32617. --zOrder;
  32618. }
  32619. }
  32620. childComponentList.insert (zOrder, child);
  32621. child->internalHierarchyChanged();
  32622. internalChildrenChanged();
  32623. }
  32624. }
  32625. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32626. {
  32627. if (child != 0)
  32628. {
  32629. child->setVisible (true);
  32630. addChildComponent (child, zOrder);
  32631. }
  32632. }
  32633. void Component::removeChildComponent (Component* const child)
  32634. {
  32635. removeChildComponent (childComponentList.indexOf (child), true, true);
  32636. }
  32637. Component* Component::removeChildComponent (const int index)
  32638. {
  32639. return removeChildComponent (index, true, true);
  32640. }
  32641. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32642. {
  32643. // if component methods are being called from threads other than the message
  32644. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32645. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32646. Component* const child = childComponentList [index];
  32647. if (child != 0)
  32648. {
  32649. sendParentEvents = sendParentEvents && child->isShowing();
  32650. if (sendParentEvents)
  32651. {
  32652. sendFakeMouseMove();
  32653. child->repaintParent();
  32654. }
  32655. childComponentList.remove (index);
  32656. child->parentComponent = 0;
  32657. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32658. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32659. {
  32660. if (sendParentEvents)
  32661. {
  32662. const WeakReference<Component> thisPointer (this);
  32663. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32664. if (thisPointer == 0)
  32665. return child;
  32666. grabKeyboardFocus();
  32667. }
  32668. else
  32669. {
  32670. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32671. }
  32672. }
  32673. if (sendChildEvents)
  32674. child->internalHierarchyChanged();
  32675. if (sendParentEvents)
  32676. internalChildrenChanged();
  32677. }
  32678. return child;
  32679. }
  32680. void Component::removeAllChildren()
  32681. {
  32682. while (childComponentList.size() > 0)
  32683. removeChildComponent (childComponentList.size() - 1);
  32684. }
  32685. void Component::deleteAllChildren()
  32686. {
  32687. while (childComponentList.size() > 0)
  32688. delete (removeChildComponent (childComponentList.size() - 1));
  32689. }
  32690. int Component::getNumChildComponents() const throw()
  32691. {
  32692. return childComponentList.size();
  32693. }
  32694. Component* Component::getChildComponent (const int index) const throw()
  32695. {
  32696. return childComponentList [index];
  32697. }
  32698. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32699. {
  32700. return childComponentList.indexOf (const_cast <Component*> (child));
  32701. }
  32702. Component* Component::getTopLevelComponent() const throw()
  32703. {
  32704. const Component* comp = this;
  32705. while (comp->parentComponent != 0)
  32706. comp = comp->parentComponent;
  32707. return const_cast <Component*> (comp);
  32708. }
  32709. bool Component::isParentOf (const Component* possibleChild) const throw()
  32710. {
  32711. while (possibleChild != 0)
  32712. {
  32713. possibleChild = possibleChild->parentComponent;
  32714. if (possibleChild == this)
  32715. return true;
  32716. }
  32717. return false;
  32718. }
  32719. void Component::parentHierarchyChanged()
  32720. {
  32721. }
  32722. void Component::childrenChanged()
  32723. {
  32724. }
  32725. void Component::internalChildrenChanged()
  32726. {
  32727. if (componentListeners.isEmpty())
  32728. {
  32729. childrenChanged();
  32730. }
  32731. else
  32732. {
  32733. BailOutChecker checker (this);
  32734. childrenChanged();
  32735. if (! checker.shouldBailOut())
  32736. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32737. }
  32738. }
  32739. void Component::internalHierarchyChanged()
  32740. {
  32741. BailOutChecker checker (this);
  32742. parentHierarchyChanged();
  32743. if (checker.shouldBailOut())
  32744. return;
  32745. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32746. if (checker.shouldBailOut())
  32747. return;
  32748. for (int i = childComponentList.size(); --i >= 0;)
  32749. {
  32750. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32751. if (checker.shouldBailOut())
  32752. {
  32753. // you really shouldn't delete the parent component during a callback telling you
  32754. // that it's changed..
  32755. jassertfalse;
  32756. return;
  32757. }
  32758. i = jmin (i, childComponentList.size());
  32759. }
  32760. }
  32761. int Component::runModalLoop()
  32762. {
  32763. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32764. {
  32765. // use a callback so this can be called from non-gui threads
  32766. return (int) (pointer_sized_int) MessageManager::getInstance()
  32767. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32768. }
  32769. if (! isCurrentlyModal())
  32770. enterModalState (true);
  32771. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32772. }
  32773. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32774. {
  32775. // if component methods are being called from threads other than the message
  32776. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32777. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32778. // Check for an attempt to make a component modal when it already is!
  32779. // This can cause nasty problems..
  32780. jassert (! flags.currentlyModalFlag);
  32781. if (! isCurrentlyModal())
  32782. {
  32783. ModalComponentManager::getInstance()->startModal (this, callback);
  32784. flags.currentlyModalFlag = true;
  32785. setVisible (true);
  32786. if (shouldTakeKeyboardFocus)
  32787. grabKeyboardFocus();
  32788. }
  32789. }
  32790. void Component::exitModalState (const int returnValue)
  32791. {
  32792. if (flags.currentlyModalFlag)
  32793. {
  32794. if (MessageManager::getInstance()->isThisTheMessageThread())
  32795. {
  32796. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32797. flags.currentlyModalFlag = false;
  32798. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32799. }
  32800. else
  32801. {
  32802. class ExitModalStateMessage : public CallbackMessage
  32803. {
  32804. public:
  32805. ExitModalStateMessage (Component* const target_, const int result_)
  32806. : target (target_), result (result_) {}
  32807. void messageCallback()
  32808. {
  32809. if (target.get() != 0) // (get() required for VS2003 bug)
  32810. target->exitModalState (result);
  32811. }
  32812. private:
  32813. WeakReference<Component> target;
  32814. int result;
  32815. };
  32816. (new ExitModalStateMessage (this, returnValue))->post();
  32817. }
  32818. }
  32819. }
  32820. bool Component::isCurrentlyModal() const throw()
  32821. {
  32822. return flags.currentlyModalFlag
  32823. && getCurrentlyModalComponent() == this;
  32824. }
  32825. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32826. {
  32827. Component* const mc = getCurrentlyModalComponent();
  32828. return mc != 0
  32829. && mc != this
  32830. && (! mc->isParentOf (this))
  32831. && ! mc->canModalEventBeSentToComponent (this);
  32832. }
  32833. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32834. {
  32835. return ModalComponentManager::getInstance()->getNumModalComponents();
  32836. }
  32837. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32838. {
  32839. return ModalComponentManager::getInstance()->getModalComponent (index);
  32840. }
  32841. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32842. {
  32843. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32844. }
  32845. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32846. {
  32847. return flags.bringToFrontOnClickFlag;
  32848. }
  32849. void Component::setMouseCursor (const MouseCursor& newCursor)
  32850. {
  32851. if (cursor != newCursor)
  32852. {
  32853. cursor = newCursor;
  32854. if (flags.visibleFlag)
  32855. updateMouseCursor();
  32856. }
  32857. }
  32858. const MouseCursor Component::getMouseCursor()
  32859. {
  32860. return cursor;
  32861. }
  32862. void Component::updateMouseCursor() const
  32863. {
  32864. sendFakeMouseMove();
  32865. }
  32866. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32867. {
  32868. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32869. }
  32870. void Component::setAlpha (const float newAlpha)
  32871. {
  32872. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  32873. if (componentTransparency != newIntAlpha)
  32874. {
  32875. componentTransparency = newIntAlpha;
  32876. if (flags.hasHeavyweightPeerFlag)
  32877. {
  32878. ComponentPeer* const peer = getPeer();
  32879. if (peer != 0)
  32880. peer->setAlpha (newAlpha);
  32881. }
  32882. else
  32883. {
  32884. repaint();
  32885. }
  32886. }
  32887. }
  32888. float Component::getAlpha() const
  32889. {
  32890. return (255 - componentTransparency) / 255.0f;
  32891. }
  32892. void Component::repaintParent()
  32893. {
  32894. if (flags.visibleFlag)
  32895. internalRepaint (0, 0, getWidth(), getHeight());
  32896. }
  32897. void Component::repaint()
  32898. {
  32899. repaint (0, 0, getWidth(), getHeight());
  32900. }
  32901. void Component::repaint (const int x, const int y,
  32902. const int w, const int h)
  32903. {
  32904. bufferedImage = Image::null;
  32905. if (flags.visibleFlag)
  32906. internalRepaint (x, y, w, h);
  32907. }
  32908. void Component::repaint (const Rectangle<int>& area)
  32909. {
  32910. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32911. }
  32912. void Component::internalRepaint (int x, int y, int w, int h)
  32913. {
  32914. // if component methods are being called from threads other than the message
  32915. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32916. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32917. if (x < 0)
  32918. {
  32919. w += x;
  32920. x = 0;
  32921. }
  32922. if (x + w > getWidth())
  32923. w = getWidth() - x;
  32924. if (w > 0)
  32925. {
  32926. if (y < 0)
  32927. {
  32928. h += y;
  32929. y = 0;
  32930. }
  32931. if (y + h > getHeight())
  32932. h = getHeight() - y;
  32933. if (h > 0)
  32934. {
  32935. if (parentComponent != 0)
  32936. {
  32937. if (parentComponent->flags.visibleFlag)
  32938. {
  32939. if (affineTransform == 0)
  32940. {
  32941. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  32942. }
  32943. else
  32944. {
  32945. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  32946. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32947. }
  32948. }
  32949. }
  32950. else if (flags.hasHeavyweightPeerFlag)
  32951. {
  32952. ComponentPeer* const peer = getPeer();
  32953. if (peer != 0)
  32954. peer->repaint (Rectangle<int> (x, y, w, h));
  32955. }
  32956. }
  32957. }
  32958. }
  32959. void Component::paintComponent (Graphics& g)
  32960. {
  32961. if (flags.bufferToImageFlag)
  32962. {
  32963. if (bufferedImage.isNull())
  32964. {
  32965. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32966. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32967. Graphics imG (bufferedImage);
  32968. paint (imG);
  32969. }
  32970. g.setColour (Colours::black.withAlpha (getAlpha()));
  32971. g.drawImageAt (bufferedImage, 0, 0);
  32972. }
  32973. else
  32974. {
  32975. paint (g);
  32976. }
  32977. }
  32978. void Component::paintWithinParentContext (Graphics& g)
  32979. {
  32980. g.setOrigin (getX(), getY());
  32981. paintEntireComponent (g, false);
  32982. }
  32983. void Component::paintComponentAndChildren (Graphics& g)
  32984. {
  32985. const Rectangle<int> clipBounds (g.getClipBounds());
  32986. if (flags.dontClipGraphicsFlag)
  32987. {
  32988. paintComponent (g);
  32989. }
  32990. else
  32991. {
  32992. g.saveState();
  32993. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  32994. if (! g.isClipEmpty())
  32995. paintComponent (g);
  32996. g.restoreState();
  32997. }
  32998. for (int i = 0; i < childComponentList.size(); ++i)
  32999. {
  33000. Component& child = *childComponentList.getUnchecked (i);
  33001. if (child.isVisible())
  33002. {
  33003. if (child.affineTransform != 0)
  33004. {
  33005. g.saveState();
  33006. g.addTransform (*child.affineTransform);
  33007. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33008. child.paintWithinParentContext (g);
  33009. g.restoreState();
  33010. }
  33011. else if (clipBounds.intersects (child.getBounds()))
  33012. {
  33013. g.saveState();
  33014. if (child.flags.dontClipGraphicsFlag)
  33015. {
  33016. child.paintWithinParentContext (g);
  33017. }
  33018. else if (g.reduceClipRegion (child.getBounds()))
  33019. {
  33020. bool nothingClipped = true;
  33021. for (int j = i + 1; j < childComponentList.size(); ++j)
  33022. {
  33023. const Component& sibling = *childComponentList.getUnchecked (j);
  33024. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33025. {
  33026. nothingClipped = false;
  33027. g.excludeClipRegion (sibling.getBounds());
  33028. }
  33029. }
  33030. if (nothingClipped || ! g.isClipEmpty())
  33031. child.paintWithinParentContext (g);
  33032. }
  33033. g.restoreState();
  33034. }
  33035. }
  33036. }
  33037. g.saveState();
  33038. paintOverChildren (g);
  33039. g.restoreState();
  33040. }
  33041. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33042. {
  33043. jassert (! g.isClipEmpty());
  33044. #if JUCE_DEBUG
  33045. flags.isInsidePaintCall = true;
  33046. #endif
  33047. if (effect != 0)
  33048. {
  33049. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33050. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33051. {
  33052. Graphics g2 (effectImage);
  33053. paintComponentAndChildren (g2);
  33054. }
  33055. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33056. }
  33057. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33058. {
  33059. if (componentTransparency < 255)
  33060. {
  33061. g.beginTransparencyLayer (getAlpha());
  33062. paintComponentAndChildren (g);
  33063. g.endTransparencyLayer();
  33064. }
  33065. }
  33066. else
  33067. {
  33068. paintComponentAndChildren (g);
  33069. }
  33070. #if JUCE_DEBUG
  33071. flags.isInsidePaintCall = false;
  33072. #endif
  33073. }
  33074. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33075. {
  33076. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33077. }
  33078. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33079. const bool clipImageToComponentBounds)
  33080. {
  33081. Rectangle<int> r (areaToGrab);
  33082. if (clipImageToComponentBounds)
  33083. r = r.getIntersection (getLocalBounds());
  33084. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33085. jmax (1, r.getWidth()),
  33086. jmax (1, r.getHeight()),
  33087. true);
  33088. Graphics imageContext (componentImage);
  33089. imageContext.setOrigin (-r.getX(), -r.getY());
  33090. paintEntireComponent (imageContext, true);
  33091. return componentImage;
  33092. }
  33093. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33094. {
  33095. if (effect != newEffect)
  33096. {
  33097. effect = newEffect;
  33098. repaint();
  33099. }
  33100. }
  33101. LookAndFeel& Component::getLookAndFeel() const throw()
  33102. {
  33103. const Component* c = this;
  33104. do
  33105. {
  33106. if (c->lookAndFeel != 0)
  33107. return *(c->lookAndFeel);
  33108. c = c->parentComponent;
  33109. }
  33110. while (c != 0);
  33111. return LookAndFeel::getDefaultLookAndFeel();
  33112. }
  33113. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33114. {
  33115. if (lookAndFeel != newLookAndFeel)
  33116. {
  33117. lookAndFeel = newLookAndFeel;
  33118. sendLookAndFeelChange();
  33119. }
  33120. }
  33121. void Component::lookAndFeelChanged()
  33122. {
  33123. }
  33124. void Component::sendLookAndFeelChange()
  33125. {
  33126. repaint();
  33127. WeakReference<Component> safePointer (this);
  33128. lookAndFeelChanged();
  33129. if (safePointer != 0)
  33130. {
  33131. for (int i = childComponentList.size(); --i >= 0;)
  33132. {
  33133. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33134. if (safePointer == 0)
  33135. return;
  33136. i = jmin (i, childComponentList.size());
  33137. }
  33138. }
  33139. }
  33140. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33141. {
  33142. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33143. if (v != 0)
  33144. return Colour ((int) *v);
  33145. if (inheritFromParent && parentComponent != 0)
  33146. return parentComponent->findColour (colourId, true);
  33147. return getLookAndFeel().findColour (colourId);
  33148. }
  33149. bool Component::isColourSpecified (const int colourId) const
  33150. {
  33151. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33152. }
  33153. void Component::removeColour (const int colourId)
  33154. {
  33155. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33156. colourChanged();
  33157. }
  33158. void Component::setColour (const int colourId, const Colour& colour)
  33159. {
  33160. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33161. colourChanged();
  33162. }
  33163. void Component::copyAllExplicitColoursTo (Component& target) const
  33164. {
  33165. bool changed = false;
  33166. for (int i = properties.size(); --i >= 0;)
  33167. {
  33168. const Identifier name (properties.getName(i));
  33169. if (name.toString().startsWith ("jcclr_"))
  33170. if (target.properties.set (name, properties [name]))
  33171. changed = true;
  33172. }
  33173. if (changed)
  33174. target.colourChanged();
  33175. }
  33176. void Component::colourChanged()
  33177. {
  33178. }
  33179. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33180. {
  33181. return 0;
  33182. }
  33183. Component::Positioner::Positioner (Component& component_) throw()
  33184. : component (component_)
  33185. {
  33186. }
  33187. Component::Positioner* Component::getPositioner() const throw()
  33188. {
  33189. return positioner;
  33190. }
  33191. void Component::setPositioner (Positioner* newPositioner)
  33192. {
  33193. // You can only assign a positioner to the component that it was created for!
  33194. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33195. positioner = newPositioner;
  33196. }
  33197. const Rectangle<int> Component::getLocalBounds() const throw()
  33198. {
  33199. return Rectangle<int> (getWidth(), getHeight());
  33200. }
  33201. const Rectangle<int> Component::getBoundsInParent() const throw()
  33202. {
  33203. return affineTransform == 0 ? bounds
  33204. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33205. }
  33206. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33207. {
  33208. result.clear();
  33209. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33210. if (! unclipped.isEmpty())
  33211. {
  33212. result.add (unclipped);
  33213. if (includeSiblings)
  33214. {
  33215. const Component* const c = getTopLevelComponent();
  33216. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33217. c->getLocalBounds(), this);
  33218. }
  33219. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33220. result.consolidate();
  33221. }
  33222. }
  33223. void Component::mouseEnter (const MouseEvent&)
  33224. {
  33225. // base class does nothing
  33226. }
  33227. void Component::mouseExit (const MouseEvent&)
  33228. {
  33229. // base class does nothing
  33230. }
  33231. void Component::mouseDown (const MouseEvent&)
  33232. {
  33233. // base class does nothing
  33234. }
  33235. void Component::mouseUp (const MouseEvent&)
  33236. {
  33237. // base class does nothing
  33238. }
  33239. void Component::mouseDrag (const MouseEvent&)
  33240. {
  33241. // base class does nothing
  33242. }
  33243. void Component::mouseMove (const MouseEvent&)
  33244. {
  33245. // base class does nothing
  33246. }
  33247. void Component::mouseDoubleClick (const MouseEvent&)
  33248. {
  33249. // base class does nothing
  33250. }
  33251. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33252. {
  33253. // the base class just passes this event up to its parent..
  33254. if (parentComponent != 0)
  33255. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33256. wheelIncrementX, wheelIncrementY);
  33257. }
  33258. void Component::resized()
  33259. {
  33260. // base class does nothing
  33261. }
  33262. void Component::moved()
  33263. {
  33264. // base class does nothing
  33265. }
  33266. void Component::childBoundsChanged (Component*)
  33267. {
  33268. // base class does nothing
  33269. }
  33270. void Component::parentSizeChanged()
  33271. {
  33272. // base class does nothing
  33273. }
  33274. void Component::addComponentListener (ComponentListener* const newListener)
  33275. {
  33276. // if component methods are being called from threads other than the message
  33277. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33278. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33279. componentListeners.add (newListener);
  33280. }
  33281. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33282. {
  33283. componentListeners.remove (listenerToRemove);
  33284. }
  33285. void Component::inputAttemptWhenModal()
  33286. {
  33287. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33288. getLookAndFeel().playAlertSound();
  33289. }
  33290. bool Component::canModalEventBeSentToComponent (const Component*)
  33291. {
  33292. return false;
  33293. }
  33294. void Component::internalModalInputAttempt()
  33295. {
  33296. Component* const current = getCurrentlyModalComponent();
  33297. if (current != 0)
  33298. current->inputAttemptWhenModal();
  33299. }
  33300. void Component::paint (Graphics&)
  33301. {
  33302. // all painting is done in the subclasses
  33303. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33304. }
  33305. void Component::paintOverChildren (Graphics&)
  33306. {
  33307. // all painting is done in the subclasses
  33308. }
  33309. void Component::postCommandMessage (const int commandId)
  33310. {
  33311. class CustomCommandMessage : public CallbackMessage
  33312. {
  33313. public:
  33314. CustomCommandMessage (Component* const target_, const int commandId_)
  33315. : target (target_), commandId (commandId_) {}
  33316. void messageCallback()
  33317. {
  33318. if (target.get() != 0) // (get() required for VS2003 bug)
  33319. target->handleCommandMessage (commandId);
  33320. }
  33321. private:
  33322. WeakReference<Component> target;
  33323. int commandId;
  33324. };
  33325. (new CustomCommandMessage (this, commandId))->post();
  33326. }
  33327. void Component::handleCommandMessage (int)
  33328. {
  33329. // used by subclasses
  33330. }
  33331. void Component::addMouseListener (MouseListener* const newListener,
  33332. const bool wantsEventsForAllNestedChildComponents)
  33333. {
  33334. // if component methods are being called from threads other than the message
  33335. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33336. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33337. // If you register a component as a mouselistener for itself, it'll receive all the events
  33338. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33339. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33340. if (mouseListeners == 0)
  33341. mouseListeners = new MouseListenerList();
  33342. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33343. }
  33344. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33345. {
  33346. // if component methods are being called from threads other than the message
  33347. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33348. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33349. if (mouseListeners != 0)
  33350. mouseListeners->removeListener (listenerToRemove);
  33351. }
  33352. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33353. {
  33354. if (isCurrentlyBlockedByAnotherModalComponent())
  33355. {
  33356. // if something else is modal, always just show a normal mouse cursor
  33357. source.showMouseCursor (MouseCursor::NormalCursor);
  33358. return;
  33359. }
  33360. if (! flags.mouseInsideFlag)
  33361. {
  33362. flags.mouseInsideFlag = true;
  33363. flags.mouseOverFlag = true;
  33364. flags.mouseDownFlag = false;
  33365. BailOutChecker checker (this);
  33366. if (flags.repaintOnMouseActivityFlag)
  33367. repaint();
  33368. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33369. this, this, time, relativePos, time, 0, false);
  33370. mouseEnter (me);
  33371. if (checker.shouldBailOut())
  33372. return;
  33373. Desktop& desktop = Desktop::getInstance();
  33374. desktop.resetTimer();
  33375. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33376. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33377. }
  33378. }
  33379. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33380. {
  33381. BailOutChecker checker (this);
  33382. if (flags.mouseDownFlag)
  33383. {
  33384. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33385. if (checker.shouldBailOut())
  33386. return;
  33387. }
  33388. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33389. {
  33390. flags.mouseInsideFlag = false;
  33391. flags.mouseOverFlag = false;
  33392. flags.mouseDownFlag = false;
  33393. if (flags.repaintOnMouseActivityFlag)
  33394. repaint();
  33395. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33396. this, this, time, relativePos, time, 0, false);
  33397. mouseExit (me);
  33398. if (checker.shouldBailOut())
  33399. return;
  33400. Desktop& desktop = Desktop::getInstance();
  33401. desktop.resetTimer();
  33402. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33403. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33404. }
  33405. }
  33406. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33407. {
  33408. Desktop& desktop = Desktop::getInstance();
  33409. BailOutChecker checker (this);
  33410. if (isCurrentlyBlockedByAnotherModalComponent())
  33411. {
  33412. internalModalInputAttempt();
  33413. if (checker.shouldBailOut())
  33414. return;
  33415. // If processing the input attempt has exited the modal loop, we'll allow the event
  33416. // to be delivered..
  33417. if (isCurrentlyBlockedByAnotherModalComponent())
  33418. {
  33419. // allow blocked mouse-events to go to global listeners..
  33420. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33421. this, this, time, relativePos, time,
  33422. source.getNumberOfMultipleClicks(), false);
  33423. desktop.resetTimer();
  33424. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33425. return;
  33426. }
  33427. }
  33428. {
  33429. Component* c = this;
  33430. while (c != 0)
  33431. {
  33432. if (c->isBroughtToFrontOnMouseClick())
  33433. {
  33434. c->toFront (true);
  33435. if (checker.shouldBailOut())
  33436. return;
  33437. }
  33438. c = c->parentComponent;
  33439. }
  33440. }
  33441. if (! flags.dontFocusOnMouseClickFlag)
  33442. {
  33443. grabFocusInternal (focusChangedByMouseClick);
  33444. if (checker.shouldBailOut())
  33445. return;
  33446. }
  33447. flags.mouseDownFlag = true;
  33448. flags.mouseOverFlag = true;
  33449. if (flags.repaintOnMouseActivityFlag)
  33450. repaint();
  33451. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33452. this, this, time, relativePos, time,
  33453. source.getNumberOfMultipleClicks(), false);
  33454. mouseDown (me);
  33455. if (checker.shouldBailOut())
  33456. return;
  33457. desktop.resetTimer();
  33458. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33459. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33460. }
  33461. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33462. {
  33463. if (flags.mouseDownFlag)
  33464. {
  33465. flags.mouseDownFlag = false;
  33466. BailOutChecker checker (this);
  33467. if (flags.repaintOnMouseActivityFlag)
  33468. repaint();
  33469. const MouseEvent me (source, relativePos,
  33470. oldModifiers, this, this, time,
  33471. getLocalPoint (0, source.getLastMouseDownPosition()),
  33472. source.getLastMouseDownTime(),
  33473. source.getNumberOfMultipleClicks(),
  33474. source.hasMouseMovedSignificantlySincePressed());
  33475. mouseUp (me);
  33476. if (checker.shouldBailOut())
  33477. return;
  33478. Desktop& desktop = Desktop::getInstance();
  33479. desktop.resetTimer();
  33480. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33481. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33482. if (checker.shouldBailOut())
  33483. return;
  33484. // check for double-click
  33485. if (me.getNumberOfClicks() >= 2)
  33486. {
  33487. mouseDoubleClick (me);
  33488. if (checker.shouldBailOut())
  33489. return;
  33490. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33491. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33492. }
  33493. }
  33494. }
  33495. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33496. {
  33497. if (flags.mouseDownFlag)
  33498. {
  33499. flags.mouseOverFlag = reallyContains (relativePos, false);
  33500. BailOutChecker checker (this);
  33501. const MouseEvent me (source, relativePos,
  33502. source.getCurrentModifiers(), this, this, time,
  33503. getLocalPoint (0, source.getLastMouseDownPosition()),
  33504. source.getLastMouseDownTime(),
  33505. source.getNumberOfMultipleClicks(),
  33506. source.hasMouseMovedSignificantlySincePressed());
  33507. mouseDrag (me);
  33508. if (checker.shouldBailOut())
  33509. return;
  33510. Desktop& desktop = Desktop::getInstance();
  33511. desktop.resetTimer();
  33512. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33513. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33514. }
  33515. }
  33516. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33517. {
  33518. Desktop& desktop = Desktop::getInstance();
  33519. BailOutChecker checker (this);
  33520. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33521. this, this, time, relativePos, time, 0, false);
  33522. if (isCurrentlyBlockedByAnotherModalComponent())
  33523. {
  33524. // allow blocked mouse-events to go to global listeners..
  33525. desktop.sendMouseMove();
  33526. }
  33527. else
  33528. {
  33529. flags.mouseOverFlag = true;
  33530. mouseMove (me);
  33531. if (checker.shouldBailOut())
  33532. return;
  33533. desktop.resetTimer();
  33534. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33535. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33536. }
  33537. }
  33538. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33539. const Time& time, const float amountX, const float amountY)
  33540. {
  33541. Desktop& desktop = Desktop::getInstance();
  33542. BailOutChecker checker (this);
  33543. const float wheelIncrementX = amountX / 256.0f;
  33544. const float wheelIncrementY = amountY / 256.0f;
  33545. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33546. this, this, time, relativePos, time, 0, false);
  33547. if (isCurrentlyBlockedByAnotherModalComponent())
  33548. {
  33549. // allow blocked mouse-events to go to global listeners..
  33550. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33551. }
  33552. else
  33553. {
  33554. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33555. if (checker.shouldBailOut())
  33556. return;
  33557. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33558. if (! checker.shouldBailOut())
  33559. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33560. }
  33561. }
  33562. void Component::sendFakeMouseMove() const
  33563. {
  33564. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33565. if (! mainMouse.isDragging())
  33566. mainMouse.triggerFakeMove();
  33567. }
  33568. void Component::beginDragAutoRepeat (const int interval)
  33569. {
  33570. Desktop::getInstance().beginDragAutoRepeat (interval);
  33571. }
  33572. void Component::broughtToFront()
  33573. {
  33574. }
  33575. void Component::internalBroughtToFront()
  33576. {
  33577. if (flags.hasHeavyweightPeerFlag)
  33578. Desktop::getInstance().componentBroughtToFront (this);
  33579. BailOutChecker checker (this);
  33580. broughtToFront();
  33581. if (checker.shouldBailOut())
  33582. return;
  33583. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33584. if (checker.shouldBailOut())
  33585. return;
  33586. // When brought to the front and there's a modal component blocking this one,
  33587. // we need to bring the modal one to the front instead..
  33588. Component* const cm = getCurrentlyModalComponent();
  33589. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33590. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33591. }
  33592. void Component::focusGained (FocusChangeType)
  33593. {
  33594. // base class does nothing
  33595. }
  33596. void Component::internalFocusGain (const FocusChangeType cause)
  33597. {
  33598. internalFocusGain (cause, WeakReference<Component> (this));
  33599. }
  33600. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33601. {
  33602. focusGained (cause);
  33603. if (safePointer != 0)
  33604. internalChildFocusChange (cause, safePointer);
  33605. }
  33606. void Component::focusLost (FocusChangeType)
  33607. {
  33608. // base class does nothing
  33609. }
  33610. void Component::internalFocusLoss (const FocusChangeType cause)
  33611. {
  33612. WeakReference<Component> safePointer (this);
  33613. focusLost (focusChangedDirectly);
  33614. if (safePointer != 0)
  33615. internalChildFocusChange (cause, safePointer);
  33616. }
  33617. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33618. {
  33619. // base class does nothing
  33620. }
  33621. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33622. {
  33623. const bool childIsNowFocused = hasKeyboardFocus (true);
  33624. if (flags.childCompFocusedFlag != childIsNowFocused)
  33625. {
  33626. flags.childCompFocusedFlag = childIsNowFocused;
  33627. focusOfChildComponentChanged (cause);
  33628. if (safePointer == 0)
  33629. return;
  33630. }
  33631. if (parentComponent != 0)
  33632. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33633. }
  33634. bool Component::isEnabled() const throw()
  33635. {
  33636. return (! flags.isDisabledFlag)
  33637. && (parentComponent == 0 || parentComponent->isEnabled());
  33638. }
  33639. void Component::setEnabled (const bool shouldBeEnabled)
  33640. {
  33641. if (flags.isDisabledFlag == shouldBeEnabled)
  33642. {
  33643. flags.isDisabledFlag = ! shouldBeEnabled;
  33644. // if any parent components are disabled, setting our flag won't make a difference,
  33645. // so no need to send a change message
  33646. if (parentComponent == 0 || parentComponent->isEnabled())
  33647. sendEnablementChangeMessage();
  33648. }
  33649. }
  33650. void Component::sendEnablementChangeMessage()
  33651. {
  33652. WeakReference<Component> safePointer (this);
  33653. enablementChanged();
  33654. if (safePointer == 0)
  33655. return;
  33656. for (int i = getNumChildComponents(); --i >= 0;)
  33657. {
  33658. Component* const c = getChildComponent (i);
  33659. if (c != 0)
  33660. {
  33661. c->sendEnablementChangeMessage();
  33662. if (safePointer == 0)
  33663. return;
  33664. }
  33665. }
  33666. }
  33667. void Component::enablementChanged()
  33668. {
  33669. }
  33670. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33671. {
  33672. flags.wantsFocusFlag = wantsFocus;
  33673. }
  33674. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33675. {
  33676. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33677. }
  33678. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33679. {
  33680. return ! flags.dontFocusOnMouseClickFlag;
  33681. }
  33682. bool Component::getWantsKeyboardFocus() const throw()
  33683. {
  33684. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33685. }
  33686. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33687. {
  33688. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33689. }
  33690. bool Component::isFocusContainer() const throw()
  33691. {
  33692. return flags.isFocusContainerFlag;
  33693. }
  33694. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33695. int Component::getExplicitFocusOrder() const
  33696. {
  33697. return properties [juce_explicitFocusOrderId];
  33698. }
  33699. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33700. {
  33701. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33702. }
  33703. KeyboardFocusTraverser* Component::createFocusTraverser()
  33704. {
  33705. if (flags.isFocusContainerFlag || parentComponent == 0)
  33706. return new KeyboardFocusTraverser();
  33707. return parentComponent->createFocusTraverser();
  33708. }
  33709. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33710. {
  33711. // give the focus to this component
  33712. if (currentlyFocusedComponent != this)
  33713. {
  33714. // get the focus onto our desktop window
  33715. ComponentPeer* const peer = getPeer();
  33716. if (peer != 0)
  33717. {
  33718. WeakReference<Component> safePointer (this);
  33719. peer->grabFocus();
  33720. if (peer->isFocused() && currentlyFocusedComponent != this)
  33721. {
  33722. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33723. currentlyFocusedComponent = this;
  33724. Desktop::getInstance().triggerFocusCallback();
  33725. // call this after setting currentlyFocusedComponent so that the one that's
  33726. // losing it has a chance to see where focus is going
  33727. if (componentLosingFocus != 0)
  33728. componentLosingFocus->internalFocusLoss (cause);
  33729. if (currentlyFocusedComponent == this)
  33730. internalFocusGain (cause, safePointer);
  33731. }
  33732. }
  33733. }
  33734. }
  33735. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33736. {
  33737. if (isShowing())
  33738. {
  33739. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33740. {
  33741. takeKeyboardFocus (cause);
  33742. }
  33743. else
  33744. {
  33745. if (isParentOf (currentlyFocusedComponent)
  33746. && currentlyFocusedComponent->isShowing())
  33747. {
  33748. // do nothing if the focused component is actually a child of ours..
  33749. }
  33750. else
  33751. {
  33752. // find the default child component..
  33753. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33754. if (traverser != 0)
  33755. {
  33756. Component* const defaultComp = traverser->getDefaultComponent (this);
  33757. traverser = 0;
  33758. if (defaultComp != 0)
  33759. {
  33760. defaultComp->grabFocusInternal (cause, false);
  33761. return;
  33762. }
  33763. }
  33764. if (canTryParent && parentComponent != 0)
  33765. {
  33766. // if no children want it and we're allowed to try our parent comp,
  33767. // then pass up to parent, which will try our siblings.
  33768. parentComponent->grabFocusInternal (cause, true);
  33769. }
  33770. }
  33771. }
  33772. }
  33773. }
  33774. void Component::grabKeyboardFocus()
  33775. {
  33776. // if component methods are being called from threads other than the message
  33777. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33778. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33779. grabFocusInternal (focusChangedDirectly);
  33780. }
  33781. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33782. {
  33783. // if component methods are being called from threads other than the message
  33784. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33785. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33786. if (parentComponent != 0)
  33787. {
  33788. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33789. if (traverser != 0)
  33790. {
  33791. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33792. : traverser->getPreviousComponent (this);
  33793. traverser = 0;
  33794. if (nextComp != 0)
  33795. {
  33796. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33797. {
  33798. WeakReference<Component> nextCompPointer (nextComp);
  33799. internalModalInputAttempt();
  33800. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33801. return;
  33802. }
  33803. nextComp->grabFocusInternal (focusChangedByTabKey);
  33804. return;
  33805. }
  33806. }
  33807. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  33808. }
  33809. }
  33810. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33811. {
  33812. return (currentlyFocusedComponent == this)
  33813. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33814. }
  33815. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33816. {
  33817. return currentlyFocusedComponent;
  33818. }
  33819. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  33820. {
  33821. Component* const componentLosingFocus = currentlyFocusedComponent;
  33822. currentlyFocusedComponent = 0;
  33823. if (sendFocusLossEvent && componentLosingFocus != 0)
  33824. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33825. Desktop::getInstance().triggerFocusCallback();
  33826. }
  33827. bool Component::isMouseOver (const bool includeChildren) const
  33828. {
  33829. if (flags.mouseOverFlag)
  33830. return true;
  33831. if (includeChildren)
  33832. {
  33833. Desktop& desktop = Desktop::getInstance();
  33834. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33835. {
  33836. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  33837. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  33838. return true;
  33839. }
  33840. }
  33841. return false;
  33842. }
  33843. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  33844. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  33845. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33846. {
  33847. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33848. }
  33849. const Point<int> Component::getMouseXYRelative() const
  33850. {
  33851. return getLocalPoint (0, Desktop::getMousePosition());
  33852. }
  33853. const Rectangle<int> Component::getParentMonitorArea() const
  33854. {
  33855. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  33856. }
  33857. void Component::addKeyListener (KeyListener* const newListener)
  33858. {
  33859. if (keyListeners == 0)
  33860. keyListeners = new Array <KeyListener*>();
  33861. keyListeners->addIfNotAlreadyThere (newListener);
  33862. }
  33863. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33864. {
  33865. if (keyListeners != 0)
  33866. keyListeners->removeValue (listenerToRemove);
  33867. }
  33868. bool Component::keyPressed (const KeyPress&)
  33869. {
  33870. return false;
  33871. }
  33872. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33873. {
  33874. return false;
  33875. }
  33876. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33877. {
  33878. if (parentComponent != 0)
  33879. parentComponent->modifierKeysChanged (modifiers);
  33880. }
  33881. void Component::internalModifierKeysChanged()
  33882. {
  33883. sendFakeMouseMove();
  33884. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33885. }
  33886. ComponentPeer* Component::getPeer() const
  33887. {
  33888. if (flags.hasHeavyweightPeerFlag)
  33889. return ComponentPeer::getPeerFor (this);
  33890. else if (parentComponent == 0)
  33891. return 0;
  33892. return parentComponent->getPeer();
  33893. }
  33894. Component::BailOutChecker::BailOutChecker (Component* const component)
  33895. : safePointer (component)
  33896. {
  33897. jassert (component != 0);
  33898. }
  33899. bool Component::BailOutChecker::shouldBailOut() const throw()
  33900. {
  33901. return safePointer == 0;
  33902. }
  33903. END_JUCE_NAMESPACE
  33904. /*** End of inlined file: juce_Component.cpp ***/
  33905. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33906. BEGIN_JUCE_NAMESPACE
  33907. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33908. void ComponentListener::componentBroughtToFront (Component&) {}
  33909. void ComponentListener::componentVisibilityChanged (Component&) {}
  33910. void ComponentListener::componentChildrenChanged (Component&) {}
  33911. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33912. void ComponentListener::componentNameChanged (Component&) {}
  33913. void ComponentListener::componentBeingDeleted (Component&) {}
  33914. END_JUCE_NAMESPACE
  33915. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33916. /*** Start of inlined file: juce_Desktop.cpp ***/
  33917. BEGIN_JUCE_NAMESPACE
  33918. Desktop::Desktop()
  33919. : mouseClickCounter (0),
  33920. kioskModeComponent (0),
  33921. allowedOrientations (allOrientations)
  33922. {
  33923. createMouseInputSources();
  33924. refreshMonitorSizes();
  33925. }
  33926. Desktop::~Desktop()
  33927. {
  33928. jassert (instance == this);
  33929. instance = 0;
  33930. // doh! If you don't delete all your windows before exiting, you're going to
  33931. // be leaking memory!
  33932. jassert (desktopComponents.size() == 0);
  33933. }
  33934. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33935. {
  33936. if (instance == 0)
  33937. instance = new Desktop();
  33938. return *instance;
  33939. }
  33940. Desktop* Desktop::instance = 0;
  33941. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33942. const bool clipToWorkArea);
  33943. void Desktop::refreshMonitorSizes()
  33944. {
  33945. Array <Rectangle<int> > oldClipped, oldUnclipped;
  33946. oldClipped.swapWithArray (monitorCoordsClipped);
  33947. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  33948. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33949. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33950. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33951. if (oldClipped != monitorCoordsClipped
  33952. || oldUnclipped != monitorCoordsUnclipped)
  33953. {
  33954. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33955. {
  33956. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33957. if (p != 0)
  33958. p->handleScreenSizeChange();
  33959. }
  33960. }
  33961. }
  33962. int Desktop::getNumDisplayMonitors() const throw()
  33963. {
  33964. return monitorCoordsClipped.size();
  33965. }
  33966. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33967. {
  33968. return clippedToWorkArea ? monitorCoordsClipped [index]
  33969. : monitorCoordsUnclipped [index];
  33970. }
  33971. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33972. {
  33973. RectangleList rl;
  33974. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33975. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33976. return rl;
  33977. }
  33978. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33979. {
  33980. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33981. }
  33982. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33983. {
  33984. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33985. double bestDistance = 1.0e10;
  33986. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33987. {
  33988. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33989. if (rect.contains (position))
  33990. return rect;
  33991. const double distance = rect.getCentre().getDistanceFrom (position);
  33992. if (distance < bestDistance)
  33993. {
  33994. bestDistance = distance;
  33995. best = rect;
  33996. }
  33997. }
  33998. return best;
  33999. }
  34000. int Desktop::getNumComponents() const throw()
  34001. {
  34002. return desktopComponents.size();
  34003. }
  34004. Component* Desktop::getComponent (const int index) const throw()
  34005. {
  34006. return desktopComponents [index];
  34007. }
  34008. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34009. {
  34010. for (int i = desktopComponents.size(); --i >= 0;)
  34011. {
  34012. Component* const c = desktopComponents.getUnchecked(i);
  34013. if (c->isVisible())
  34014. {
  34015. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34016. if (c->contains (relative))
  34017. return c->getComponentAt (relative);
  34018. }
  34019. }
  34020. return 0;
  34021. }
  34022. void Desktop::addDesktopComponent (Component* const c)
  34023. {
  34024. jassert (c != 0);
  34025. jassert (! desktopComponents.contains (c));
  34026. desktopComponents.addIfNotAlreadyThere (c);
  34027. }
  34028. void Desktop::removeDesktopComponent (Component* const c)
  34029. {
  34030. desktopComponents.removeValue (c);
  34031. }
  34032. void Desktop::componentBroughtToFront (Component* const c)
  34033. {
  34034. const int index = desktopComponents.indexOf (c);
  34035. jassert (index >= 0);
  34036. if (index >= 0)
  34037. {
  34038. int newIndex = -1;
  34039. if (! c->isAlwaysOnTop())
  34040. {
  34041. newIndex = desktopComponents.size();
  34042. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34043. --newIndex;
  34044. --newIndex;
  34045. }
  34046. desktopComponents.move (index, newIndex);
  34047. }
  34048. }
  34049. const Point<int> Desktop::getMousePosition()
  34050. {
  34051. return getInstance().getMainMouseSource().getScreenPosition();
  34052. }
  34053. const Point<int> Desktop::getLastMouseDownPosition()
  34054. {
  34055. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34056. }
  34057. int Desktop::getMouseButtonClickCounter()
  34058. {
  34059. return getInstance().mouseClickCounter;
  34060. }
  34061. void Desktop::incrementMouseClickCounter() throw()
  34062. {
  34063. ++mouseClickCounter;
  34064. }
  34065. int Desktop::getNumDraggingMouseSources() const throw()
  34066. {
  34067. int num = 0;
  34068. for (int i = mouseSources.size(); --i >= 0;)
  34069. if (mouseSources.getUnchecked(i)->isDragging())
  34070. ++num;
  34071. return num;
  34072. }
  34073. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34074. {
  34075. int num = 0;
  34076. for (int i = mouseSources.size(); --i >= 0;)
  34077. {
  34078. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34079. if (mi->isDragging())
  34080. {
  34081. if (index == num)
  34082. return mi;
  34083. ++num;
  34084. }
  34085. }
  34086. return 0;
  34087. }
  34088. class MouseDragAutoRepeater : public Timer
  34089. {
  34090. public:
  34091. MouseDragAutoRepeater() {}
  34092. void timerCallback()
  34093. {
  34094. Desktop& desktop = Desktop::getInstance();
  34095. int numMiceDown = 0;
  34096. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34097. {
  34098. MouseInputSource* const source = desktop.getMouseSource(i);
  34099. if (source->isDragging())
  34100. {
  34101. source->triggerFakeMove();
  34102. ++numMiceDown;
  34103. }
  34104. }
  34105. if (numMiceDown == 0)
  34106. desktop.beginDragAutoRepeat (0);
  34107. }
  34108. private:
  34109. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34110. };
  34111. void Desktop::beginDragAutoRepeat (const int interval)
  34112. {
  34113. if (interval > 0)
  34114. {
  34115. if (dragRepeater == 0)
  34116. dragRepeater = new MouseDragAutoRepeater();
  34117. if (dragRepeater->getTimerInterval() != interval)
  34118. dragRepeater->startTimer (interval);
  34119. }
  34120. else
  34121. {
  34122. dragRepeater = 0;
  34123. }
  34124. }
  34125. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34126. {
  34127. focusListeners.add (listener);
  34128. }
  34129. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34130. {
  34131. focusListeners.remove (listener);
  34132. }
  34133. void Desktop::triggerFocusCallback()
  34134. {
  34135. triggerAsyncUpdate();
  34136. }
  34137. void Desktop::handleAsyncUpdate()
  34138. {
  34139. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34140. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34141. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34142. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34143. }
  34144. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34145. {
  34146. mouseListeners.add (listener);
  34147. resetTimer();
  34148. }
  34149. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34150. {
  34151. mouseListeners.remove (listener);
  34152. resetTimer();
  34153. }
  34154. void Desktop::timerCallback()
  34155. {
  34156. if (lastFakeMouseMove != getMousePosition())
  34157. sendMouseMove();
  34158. }
  34159. void Desktop::sendMouseMove()
  34160. {
  34161. if (! mouseListeners.isEmpty())
  34162. {
  34163. startTimer (20);
  34164. lastFakeMouseMove = getMousePosition();
  34165. Component* const target = findComponentAt (lastFakeMouseMove);
  34166. if (target != 0)
  34167. {
  34168. Component::BailOutChecker checker (target);
  34169. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34170. const Time now (Time::getCurrentTime());
  34171. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34172. target, target, now, pos, now, 0, false);
  34173. if (me.mods.isAnyMouseButtonDown())
  34174. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34175. else
  34176. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34177. }
  34178. }
  34179. }
  34180. void Desktop::resetTimer()
  34181. {
  34182. if (mouseListeners.size() == 0)
  34183. stopTimer();
  34184. else
  34185. startTimer (100);
  34186. lastFakeMouseMove = getMousePosition();
  34187. }
  34188. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34189. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34190. {
  34191. if (kioskModeComponent != componentToUse)
  34192. {
  34193. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34194. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34195. if (kioskModeComponent != 0)
  34196. {
  34197. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34198. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34199. }
  34200. kioskModeComponent = componentToUse;
  34201. if (kioskModeComponent != 0)
  34202. {
  34203. // Only components that are already on the desktop can be put into kiosk mode!
  34204. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34205. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34206. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34207. }
  34208. }
  34209. }
  34210. void Desktop::setOrientationsEnabled (const int newOrientations)
  34211. {
  34212. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34213. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34214. allowedOrientations = newOrientations;
  34215. }
  34216. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34217. {
  34218. // Make sure you only pass one valid flag in here...
  34219. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34220. return (allowedOrientations & orientation) != 0;
  34221. }
  34222. END_JUCE_NAMESPACE
  34223. /*** End of inlined file: juce_Desktop.cpp ***/
  34224. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34225. BEGIN_JUCE_NAMESPACE
  34226. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34227. {
  34228. public:
  34229. ModalItem (Component* const comp, Callback* const callback)
  34230. : ComponentMovementWatcher (comp),
  34231. component (comp), returnValue (0), isActive (true)
  34232. {
  34233. jassert (comp != 0);
  34234. if (callback != 0)
  34235. callbacks.add (callback);
  34236. }
  34237. void componentMovedOrResized (bool, bool) {}
  34238. void componentPeerChanged()
  34239. {
  34240. if (! component->isShowing())
  34241. cancel();
  34242. }
  34243. void componentVisibilityChanged()
  34244. {
  34245. if (! component->isShowing())
  34246. cancel();
  34247. }
  34248. void componentBeingDeleted (Component& comp)
  34249. {
  34250. ComponentMovementWatcher::componentBeingDeleted (comp);
  34251. if (component == &comp || comp.isParentOf (component))
  34252. cancel();
  34253. }
  34254. void cancel()
  34255. {
  34256. if (isActive)
  34257. {
  34258. isActive = false;
  34259. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34260. }
  34261. }
  34262. Component* component;
  34263. OwnedArray<Callback> callbacks;
  34264. int returnValue;
  34265. bool isActive;
  34266. private:
  34267. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34268. };
  34269. ModalComponentManager::ModalComponentManager()
  34270. {
  34271. }
  34272. ModalComponentManager::~ModalComponentManager()
  34273. {
  34274. clearSingletonInstance();
  34275. }
  34276. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34277. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34278. {
  34279. if (component != 0)
  34280. stack.add (new ModalItem (component, callback));
  34281. }
  34282. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34283. {
  34284. if (callback != 0)
  34285. {
  34286. ScopedPointer<Callback> callbackDeleter (callback);
  34287. for (int i = stack.size(); --i >= 0;)
  34288. {
  34289. ModalItem* const item = stack.getUnchecked(i);
  34290. if (item->component == component)
  34291. {
  34292. item->callbacks.add (callback);
  34293. callbackDeleter.release();
  34294. break;
  34295. }
  34296. }
  34297. }
  34298. }
  34299. void ModalComponentManager::endModal (Component* component)
  34300. {
  34301. for (int i = stack.size(); --i >= 0;)
  34302. {
  34303. ModalItem* const item = stack.getUnchecked(i);
  34304. if (item->component == component)
  34305. item->cancel();
  34306. }
  34307. }
  34308. void ModalComponentManager::endModal (Component* component, int returnValue)
  34309. {
  34310. for (int i = stack.size(); --i >= 0;)
  34311. {
  34312. ModalItem* const item = stack.getUnchecked(i);
  34313. if (item->component == component)
  34314. {
  34315. item->returnValue = returnValue;
  34316. item->cancel();
  34317. }
  34318. }
  34319. }
  34320. int ModalComponentManager::getNumModalComponents() const
  34321. {
  34322. int n = 0;
  34323. for (int i = 0; i < stack.size(); ++i)
  34324. if (stack.getUnchecked(i)->isActive)
  34325. ++n;
  34326. return n;
  34327. }
  34328. Component* ModalComponentManager::getModalComponent (const int index) const
  34329. {
  34330. int n = 0;
  34331. for (int i = stack.size(); --i >= 0;)
  34332. {
  34333. const ModalItem* const item = stack.getUnchecked(i);
  34334. if (item->isActive)
  34335. if (n++ == index)
  34336. return item->component;
  34337. }
  34338. return 0;
  34339. }
  34340. bool ModalComponentManager::isModal (Component* const comp) const
  34341. {
  34342. for (int i = stack.size(); --i >= 0;)
  34343. {
  34344. const ModalItem* const item = stack.getUnchecked(i);
  34345. if (item->isActive && item->component == comp)
  34346. return true;
  34347. }
  34348. return false;
  34349. }
  34350. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34351. {
  34352. return comp == getModalComponent (0);
  34353. }
  34354. void ModalComponentManager::handleAsyncUpdate()
  34355. {
  34356. for (int i = stack.size(); --i >= 0;)
  34357. {
  34358. const ModalItem* const item = stack.getUnchecked(i);
  34359. if (! item->isActive)
  34360. {
  34361. for (int j = item->callbacks.size(); --j >= 0;)
  34362. {
  34363. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34364. if (! stack.contains (item))
  34365. break;
  34366. }
  34367. stack.removeObject (item);
  34368. }
  34369. }
  34370. }
  34371. void ModalComponentManager::bringModalComponentsToFront()
  34372. {
  34373. ComponentPeer* lastOne = 0;
  34374. for (int i = 0; i < getNumModalComponents(); ++i)
  34375. {
  34376. Component* const c = getModalComponent (i);
  34377. if (c == 0)
  34378. break;
  34379. ComponentPeer* peer = c->getPeer();
  34380. if (peer != 0 && peer != lastOne)
  34381. {
  34382. if (lastOne == 0)
  34383. {
  34384. peer->toFront (true);
  34385. peer->grabFocus();
  34386. }
  34387. else
  34388. peer->toBehind (lastOne);
  34389. lastOne = peer;
  34390. }
  34391. }
  34392. }
  34393. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34394. {
  34395. public:
  34396. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34397. ~ReturnValueRetriever() {}
  34398. void modalStateFinished (int returnValue)
  34399. {
  34400. finished = true;
  34401. value = returnValue;
  34402. }
  34403. private:
  34404. int& value;
  34405. bool& finished;
  34406. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34407. };
  34408. int ModalComponentManager::runEventLoopForCurrentComponent()
  34409. {
  34410. // This can only be run from the message thread!
  34411. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34412. Component* currentlyModal = getModalComponent (0);
  34413. if (currentlyModal == 0)
  34414. return 0;
  34415. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34416. int returnValue = 0;
  34417. bool finished = false;
  34418. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34419. JUCE_TRY
  34420. {
  34421. while (! finished)
  34422. {
  34423. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34424. break;
  34425. }
  34426. }
  34427. JUCE_CATCH_EXCEPTION
  34428. if (prevFocused != 0)
  34429. prevFocused->grabKeyboardFocus();
  34430. return returnValue;
  34431. }
  34432. END_JUCE_NAMESPACE
  34433. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34434. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34435. BEGIN_JUCE_NAMESPACE
  34436. ArrowButton::ArrowButton (const String& name,
  34437. float arrowDirectionInRadians,
  34438. const Colour& arrowColour)
  34439. : Button (name),
  34440. colour (arrowColour)
  34441. {
  34442. path.lineTo (0.0f, 1.0f);
  34443. path.lineTo (1.0f, 0.5f);
  34444. path.closeSubPath();
  34445. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34446. 0.5f, 0.5f));
  34447. setComponentEffect (&shadow);
  34448. buttonStateChanged();
  34449. }
  34450. ArrowButton::~ArrowButton()
  34451. {
  34452. }
  34453. void ArrowButton::paintButton (Graphics& g,
  34454. bool /*isMouseOverButton*/,
  34455. bool /*isButtonDown*/)
  34456. {
  34457. g.setColour (colour);
  34458. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34459. (float) offset,
  34460. (float) (getWidth() - 3),
  34461. (float) (getHeight() - 3),
  34462. false));
  34463. }
  34464. void ArrowButton::buttonStateChanged()
  34465. {
  34466. offset = (isDown()) ? 1 : 0;
  34467. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34468. 0.3f, -1, 0);
  34469. }
  34470. END_JUCE_NAMESPACE
  34471. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34472. /*** Start of inlined file: juce_Button.cpp ***/
  34473. BEGIN_JUCE_NAMESPACE
  34474. class Button::RepeatTimer : public Timer
  34475. {
  34476. public:
  34477. RepeatTimer (Button& owner_) : owner (owner_) {}
  34478. void timerCallback() { owner.repeatTimerCallback(); }
  34479. private:
  34480. Button& owner;
  34481. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34482. };
  34483. Button::Button (const String& name)
  34484. : Component (name),
  34485. text (name),
  34486. buttonPressTime (0),
  34487. lastRepeatTime (0),
  34488. commandManagerToUse (0),
  34489. autoRepeatDelay (-1),
  34490. autoRepeatSpeed (0),
  34491. autoRepeatMinimumDelay (-1),
  34492. radioGroupId (0),
  34493. commandID (0),
  34494. connectedEdgeFlags (0),
  34495. buttonState (buttonNormal),
  34496. lastToggleState (false),
  34497. clickTogglesState (false),
  34498. needsToRelease (false),
  34499. needsRepainting (false),
  34500. isKeyDown (false),
  34501. triggerOnMouseDown (false),
  34502. generateTooltip (false)
  34503. {
  34504. setWantsKeyboardFocus (true);
  34505. isOn.addListener (this);
  34506. }
  34507. Button::~Button()
  34508. {
  34509. isOn.removeListener (this);
  34510. if (commandManagerToUse != 0)
  34511. commandManagerToUse->removeListener (this);
  34512. repeatTimer = 0;
  34513. clearShortcuts();
  34514. }
  34515. void Button::setButtonText (const String& newText)
  34516. {
  34517. if (text != newText)
  34518. {
  34519. text = newText;
  34520. repaint();
  34521. }
  34522. }
  34523. void Button::setTooltip (const String& newTooltip)
  34524. {
  34525. SettableTooltipClient::setTooltip (newTooltip);
  34526. generateTooltip = false;
  34527. }
  34528. const String Button::getTooltip()
  34529. {
  34530. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34531. {
  34532. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34533. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34534. for (int i = 0; i < keyPresses.size(); ++i)
  34535. {
  34536. const String key (keyPresses.getReference(i).getTextDescription());
  34537. tt << " [";
  34538. if (key.length() == 1)
  34539. tt << TRANS("shortcut") << ": '" << key << "']";
  34540. else
  34541. tt << key << ']';
  34542. }
  34543. return tt;
  34544. }
  34545. return SettableTooltipClient::getTooltip();
  34546. }
  34547. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34548. {
  34549. if (connectedEdgeFlags != connectedEdgeFlags_)
  34550. {
  34551. connectedEdgeFlags = connectedEdgeFlags_;
  34552. repaint();
  34553. }
  34554. }
  34555. void Button::setToggleState (const bool shouldBeOn,
  34556. const bool sendChangeNotification)
  34557. {
  34558. if (shouldBeOn != lastToggleState)
  34559. {
  34560. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34561. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34562. lastToggleState = shouldBeOn;
  34563. repaint();
  34564. WeakReference<Component> deletionWatcher (this);
  34565. if (sendChangeNotification)
  34566. {
  34567. sendClickMessage (ModifierKeys());
  34568. if (deletionWatcher == 0)
  34569. return;
  34570. }
  34571. if (lastToggleState)
  34572. {
  34573. turnOffOtherButtonsInGroup (sendChangeNotification);
  34574. if (deletionWatcher == 0)
  34575. return;
  34576. }
  34577. sendStateMessage();
  34578. }
  34579. }
  34580. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34581. {
  34582. clickTogglesState = shouldToggle;
  34583. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34584. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34585. // it is that this button represents, and the button will update its state to reflect this
  34586. // in the applicationCommandListChanged() method.
  34587. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34588. }
  34589. bool Button::getClickingTogglesState() const throw()
  34590. {
  34591. return clickTogglesState;
  34592. }
  34593. void Button::valueChanged (Value& value)
  34594. {
  34595. if (value.refersToSameSourceAs (isOn))
  34596. setToggleState (isOn.getValue(), true);
  34597. }
  34598. void Button::setRadioGroupId (const int newGroupId)
  34599. {
  34600. if (radioGroupId != newGroupId)
  34601. {
  34602. radioGroupId = newGroupId;
  34603. if (lastToggleState)
  34604. turnOffOtherButtonsInGroup (true);
  34605. }
  34606. }
  34607. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34608. {
  34609. Component* const p = getParentComponent();
  34610. if (p != 0 && radioGroupId != 0)
  34611. {
  34612. WeakReference<Component> deletionWatcher (this);
  34613. for (int i = p->getNumChildComponents(); --i >= 0;)
  34614. {
  34615. Component* const c = p->getChildComponent (i);
  34616. if (c != this)
  34617. {
  34618. Button* const b = dynamic_cast <Button*> (c);
  34619. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34620. {
  34621. b->setToggleState (false, sendChangeNotification);
  34622. if (deletionWatcher == 0)
  34623. return;
  34624. }
  34625. }
  34626. }
  34627. }
  34628. }
  34629. void Button::enablementChanged()
  34630. {
  34631. updateState();
  34632. repaint();
  34633. }
  34634. Button::ButtonState Button::updateState()
  34635. {
  34636. return updateState (isMouseOver (true), isMouseButtonDown());
  34637. }
  34638. Button::ButtonState Button::updateState (const bool over, const bool down)
  34639. {
  34640. ButtonState newState = buttonNormal;
  34641. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34642. {
  34643. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34644. newState = buttonDown;
  34645. else if (over)
  34646. newState = buttonOver;
  34647. }
  34648. setState (newState);
  34649. return newState;
  34650. }
  34651. void Button::setState (const ButtonState newState)
  34652. {
  34653. if (buttonState != newState)
  34654. {
  34655. buttonState = newState;
  34656. repaint();
  34657. if (buttonState == buttonDown)
  34658. {
  34659. buttonPressTime = Time::getApproximateMillisecondCounter();
  34660. lastRepeatTime = 0;
  34661. }
  34662. sendStateMessage();
  34663. }
  34664. }
  34665. bool Button::isDown() const throw()
  34666. {
  34667. return buttonState == buttonDown;
  34668. }
  34669. bool Button::isOver() const throw()
  34670. {
  34671. return buttonState != buttonNormal;
  34672. }
  34673. void Button::buttonStateChanged()
  34674. {
  34675. }
  34676. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34677. {
  34678. const uint32 now = Time::getApproximateMillisecondCounter();
  34679. return now > buttonPressTime ? now - buttonPressTime : 0;
  34680. }
  34681. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34682. {
  34683. triggerOnMouseDown = isTriggeredOnMouseDown;
  34684. }
  34685. void Button::clicked()
  34686. {
  34687. }
  34688. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34689. {
  34690. clicked();
  34691. }
  34692. static const int clickMessageId = 0x2f3f4f99;
  34693. void Button::triggerClick()
  34694. {
  34695. postCommandMessage (clickMessageId);
  34696. }
  34697. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34698. {
  34699. if (clickTogglesState)
  34700. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34701. sendClickMessage (modifiers);
  34702. }
  34703. void Button::flashButtonState()
  34704. {
  34705. if (isEnabled())
  34706. {
  34707. needsToRelease = true;
  34708. setState (buttonDown);
  34709. getRepeatTimer().startTimer (100);
  34710. }
  34711. }
  34712. void Button::handleCommandMessage (int commandId)
  34713. {
  34714. if (commandId == clickMessageId)
  34715. {
  34716. if (isEnabled())
  34717. {
  34718. flashButtonState();
  34719. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34720. }
  34721. }
  34722. else
  34723. {
  34724. Component::handleCommandMessage (commandId);
  34725. }
  34726. }
  34727. void Button::addListener (ButtonListener* const newListener)
  34728. {
  34729. buttonListeners.add (newListener);
  34730. }
  34731. void Button::removeListener (ButtonListener* const listener)
  34732. {
  34733. buttonListeners.remove (listener);
  34734. }
  34735. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34736. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34737. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34738. {
  34739. Component::BailOutChecker checker (this);
  34740. if (commandManagerToUse != 0 && commandID != 0)
  34741. {
  34742. ApplicationCommandTarget::InvocationInfo info (commandID);
  34743. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34744. info.originatingComponent = this;
  34745. commandManagerToUse->invoke (info, true);
  34746. }
  34747. clicked (modifiers);
  34748. if (! checker.shouldBailOut())
  34749. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34750. }
  34751. void Button::sendStateMessage()
  34752. {
  34753. Component::BailOutChecker checker (this);
  34754. buttonStateChanged();
  34755. if (! checker.shouldBailOut())
  34756. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34757. }
  34758. void Button::paint (Graphics& g)
  34759. {
  34760. if (needsToRelease && isEnabled())
  34761. {
  34762. needsToRelease = false;
  34763. needsRepainting = true;
  34764. }
  34765. paintButton (g, isOver(), isDown());
  34766. }
  34767. void Button::mouseEnter (const MouseEvent&)
  34768. {
  34769. updateState (true, false);
  34770. }
  34771. void Button::mouseExit (const MouseEvent&)
  34772. {
  34773. updateState (false, false);
  34774. }
  34775. void Button::mouseDown (const MouseEvent& e)
  34776. {
  34777. updateState (true, true);
  34778. if (isDown())
  34779. {
  34780. if (autoRepeatDelay >= 0)
  34781. getRepeatTimer().startTimer (autoRepeatDelay);
  34782. if (triggerOnMouseDown)
  34783. internalClickCallback (e.mods);
  34784. }
  34785. }
  34786. void Button::mouseUp (const MouseEvent& e)
  34787. {
  34788. const bool wasDown = isDown();
  34789. updateState (isMouseOver(), false);
  34790. if (wasDown && isOver() && ! triggerOnMouseDown)
  34791. internalClickCallback (e.mods);
  34792. }
  34793. void Button::mouseDrag (const MouseEvent&)
  34794. {
  34795. const ButtonState oldState = buttonState;
  34796. updateState (isMouseOver(), true);
  34797. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34798. getRepeatTimer().startTimer (autoRepeatSpeed);
  34799. }
  34800. void Button::focusGained (FocusChangeType)
  34801. {
  34802. updateState();
  34803. repaint();
  34804. }
  34805. void Button::focusLost (FocusChangeType)
  34806. {
  34807. updateState();
  34808. repaint();
  34809. }
  34810. void Button::visibilityChanged()
  34811. {
  34812. needsToRelease = false;
  34813. updateState();
  34814. }
  34815. void Button::parentHierarchyChanged()
  34816. {
  34817. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34818. if (newKeySource != keySource.get())
  34819. {
  34820. if (keySource != 0)
  34821. keySource->removeKeyListener (this);
  34822. keySource = newKeySource;
  34823. if (keySource != 0)
  34824. keySource->addKeyListener (this);
  34825. }
  34826. }
  34827. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34828. const int commandID_,
  34829. const bool generateTooltip_)
  34830. {
  34831. commandID = commandID_;
  34832. generateTooltip = generateTooltip_;
  34833. if (commandManagerToUse != commandManagerToUse_)
  34834. {
  34835. if (commandManagerToUse != 0)
  34836. commandManagerToUse->removeListener (this);
  34837. commandManagerToUse = commandManagerToUse_;
  34838. if (commandManagerToUse != 0)
  34839. commandManagerToUse->addListener (this);
  34840. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34841. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34842. // it is that this button represents, and the button will update its state to reflect this
  34843. // in the applicationCommandListChanged() method.
  34844. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34845. }
  34846. if (commandManagerToUse != 0)
  34847. applicationCommandListChanged();
  34848. else
  34849. setEnabled (true);
  34850. }
  34851. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34852. {
  34853. if (info.commandID == commandID
  34854. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34855. {
  34856. flashButtonState();
  34857. }
  34858. }
  34859. void Button::applicationCommandListChanged()
  34860. {
  34861. if (commandManagerToUse != 0)
  34862. {
  34863. ApplicationCommandInfo info (0);
  34864. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34865. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34866. if (target != 0)
  34867. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34868. }
  34869. }
  34870. void Button::addShortcut (const KeyPress& key)
  34871. {
  34872. if (key.isValid())
  34873. {
  34874. jassert (! isRegisteredForShortcut (key)); // already registered!
  34875. shortcuts.add (key);
  34876. parentHierarchyChanged();
  34877. }
  34878. }
  34879. void Button::clearShortcuts()
  34880. {
  34881. shortcuts.clear();
  34882. parentHierarchyChanged();
  34883. }
  34884. bool Button::isShortcutPressed() const
  34885. {
  34886. if (! isCurrentlyBlockedByAnotherModalComponent())
  34887. {
  34888. for (int i = shortcuts.size(); --i >= 0;)
  34889. if (shortcuts.getReference(i).isCurrentlyDown())
  34890. return true;
  34891. }
  34892. return false;
  34893. }
  34894. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34895. {
  34896. for (int i = shortcuts.size(); --i >= 0;)
  34897. if (key == shortcuts.getReference(i))
  34898. return true;
  34899. return false;
  34900. }
  34901. bool Button::keyStateChanged (const bool, Component*)
  34902. {
  34903. if (! isEnabled())
  34904. return false;
  34905. const bool wasDown = isKeyDown;
  34906. isKeyDown = isShortcutPressed();
  34907. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34908. getRepeatTimer().startTimer (autoRepeatDelay);
  34909. updateState();
  34910. if (isEnabled() && wasDown && ! isKeyDown)
  34911. {
  34912. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34913. // (return immediately - this button may now have been deleted)
  34914. return true;
  34915. }
  34916. return wasDown || isKeyDown;
  34917. }
  34918. bool Button::keyPressed (const KeyPress&, Component*)
  34919. {
  34920. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34921. return isShortcutPressed();
  34922. }
  34923. bool Button::keyPressed (const KeyPress& key)
  34924. {
  34925. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34926. {
  34927. triggerClick();
  34928. return true;
  34929. }
  34930. return false;
  34931. }
  34932. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34933. const int repeatMillisecs,
  34934. const int minimumDelayInMillisecs) throw()
  34935. {
  34936. autoRepeatDelay = initialDelayMillisecs;
  34937. autoRepeatSpeed = repeatMillisecs;
  34938. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34939. }
  34940. void Button::repeatTimerCallback()
  34941. {
  34942. if (needsRepainting)
  34943. {
  34944. getRepeatTimer().stopTimer();
  34945. updateState();
  34946. needsRepainting = false;
  34947. }
  34948. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  34949. {
  34950. int repeatSpeed = autoRepeatSpeed;
  34951. if (autoRepeatMinimumDelay >= 0)
  34952. {
  34953. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34954. timeHeldDown *= timeHeldDown;
  34955. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34956. }
  34957. repeatSpeed = jmax (1, repeatSpeed);
  34958. const uint32 now = Time::getMillisecondCounter();
  34959. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  34960. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  34961. repeatSpeed = jmax (1, repeatSpeed / 2);
  34962. lastRepeatTime = now;
  34963. getRepeatTimer().startTimer (repeatSpeed);
  34964. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34965. }
  34966. else if (! needsToRelease)
  34967. {
  34968. getRepeatTimer().stopTimer();
  34969. }
  34970. }
  34971. Button::RepeatTimer& Button::getRepeatTimer()
  34972. {
  34973. if (repeatTimer == 0)
  34974. repeatTimer = new RepeatTimer (*this);
  34975. return *repeatTimer;
  34976. }
  34977. END_JUCE_NAMESPACE
  34978. /*** End of inlined file: juce_Button.cpp ***/
  34979. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34980. BEGIN_JUCE_NAMESPACE
  34981. DrawableButton::DrawableButton (const String& name,
  34982. const DrawableButton::ButtonStyle buttonStyle)
  34983. : Button (name),
  34984. style (buttonStyle),
  34985. currentImage (0),
  34986. edgeIndent (3)
  34987. {
  34988. if (buttonStyle == ImageOnButtonBackground)
  34989. {
  34990. backgroundOff = Colour (0xffbbbbff);
  34991. backgroundOn = Colour (0xff3333ff);
  34992. }
  34993. else
  34994. {
  34995. backgroundOff = Colours::transparentBlack;
  34996. backgroundOn = Colour (0xaabbbbff);
  34997. }
  34998. }
  34999. DrawableButton::~DrawableButton()
  35000. {
  35001. }
  35002. void DrawableButton::setImages (const Drawable* normal,
  35003. const Drawable* over,
  35004. const Drawable* down,
  35005. const Drawable* disabled,
  35006. const Drawable* normalOn,
  35007. const Drawable* overOn,
  35008. const Drawable* downOn,
  35009. const Drawable* disabledOn)
  35010. {
  35011. jassert (normal != 0); // you really need to give it at least a normal image..
  35012. if (normal != 0) normalImage = normal->createCopy();
  35013. if (over != 0) overImage = over->createCopy();
  35014. if (down != 0) downImage = down->createCopy();
  35015. if (disabled != 0) disabledImage = disabled->createCopy();
  35016. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35017. if (overOn != 0) overImageOn = overOn->createCopy();
  35018. if (downOn != 0) downImageOn = downOn->createCopy();
  35019. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35020. buttonStateChanged();
  35021. }
  35022. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35023. {
  35024. if (style != newStyle)
  35025. {
  35026. style = newStyle;
  35027. buttonStateChanged();
  35028. }
  35029. }
  35030. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35031. const Colour& toggledOnColour)
  35032. {
  35033. if (backgroundOff != toggledOffColour
  35034. || backgroundOn != toggledOnColour)
  35035. {
  35036. backgroundOff = toggledOffColour;
  35037. backgroundOn = toggledOnColour;
  35038. repaint();
  35039. }
  35040. }
  35041. const Colour& DrawableButton::getBackgroundColour() const throw()
  35042. {
  35043. return getToggleState() ? backgroundOn
  35044. : backgroundOff;
  35045. }
  35046. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35047. {
  35048. edgeIndent = numPixelsIndent;
  35049. repaint();
  35050. resized();
  35051. }
  35052. void DrawableButton::resized()
  35053. {
  35054. Button::resized();
  35055. if (currentImage != 0)
  35056. {
  35057. if (style == ImageRaw)
  35058. {
  35059. currentImage->setOriginWithOriginalSize (Point<float>());
  35060. }
  35061. else
  35062. {
  35063. Rectangle<int> imageSpace;
  35064. if (style == ImageOnButtonBackground)
  35065. {
  35066. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35067. }
  35068. else
  35069. {
  35070. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35071. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35072. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35073. imageSpace.setBounds (indentX, indentY,
  35074. getWidth() - indentX * 2,
  35075. getHeight() - indentY * 2 - textH);
  35076. }
  35077. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35078. }
  35079. }
  35080. }
  35081. void DrawableButton::buttonStateChanged()
  35082. {
  35083. repaint();
  35084. Drawable* imageToDraw = 0;
  35085. float opacity = 1.0f;
  35086. if (isEnabled())
  35087. {
  35088. imageToDraw = getCurrentImage();
  35089. }
  35090. else
  35091. {
  35092. imageToDraw = getToggleState() ? disabledImageOn
  35093. : disabledImage;
  35094. if (imageToDraw == 0)
  35095. {
  35096. opacity = 0.4f;
  35097. imageToDraw = getNormalImage();
  35098. }
  35099. }
  35100. if (imageToDraw != currentImage)
  35101. {
  35102. removeChildComponent (currentImage);
  35103. currentImage = imageToDraw;
  35104. if (currentImage != 0)
  35105. {
  35106. addAndMakeVisible (currentImage);
  35107. DrawableButton::resized();
  35108. }
  35109. }
  35110. if (currentImage != 0)
  35111. currentImage->setAlpha (opacity);
  35112. }
  35113. void DrawableButton::paintButton (Graphics& g,
  35114. bool isMouseOverButton,
  35115. bool isButtonDown)
  35116. {
  35117. if (style == ImageOnButtonBackground)
  35118. {
  35119. getLookAndFeel().drawButtonBackground (g, *this,
  35120. getBackgroundColour(),
  35121. isMouseOverButton,
  35122. isButtonDown);
  35123. }
  35124. else
  35125. {
  35126. g.fillAll (getBackgroundColour());
  35127. const int textH = (style == ImageAboveTextLabel)
  35128. ? jmin (16, proportionOfHeight (0.25f))
  35129. : 0;
  35130. if (textH > 0)
  35131. {
  35132. g.setFont ((float) textH);
  35133. g.setColour (findColour (DrawableButton::textColourId)
  35134. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35135. g.drawFittedText (getButtonText(),
  35136. 2, getHeight() - textH - 1,
  35137. getWidth() - 4, textH,
  35138. Justification::centred, 1);
  35139. }
  35140. }
  35141. }
  35142. Drawable* DrawableButton::getCurrentImage() const throw()
  35143. {
  35144. if (isDown())
  35145. return getDownImage();
  35146. if (isOver())
  35147. return getOverImage();
  35148. return getNormalImage();
  35149. }
  35150. Drawable* DrawableButton::getNormalImage() const throw()
  35151. {
  35152. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35153. : normalImage;
  35154. }
  35155. Drawable* DrawableButton::getOverImage() const throw()
  35156. {
  35157. Drawable* d = normalImage;
  35158. if (getToggleState())
  35159. {
  35160. if (overImageOn != 0)
  35161. d = overImageOn;
  35162. else if (normalImageOn != 0)
  35163. d = normalImageOn;
  35164. else if (overImage != 0)
  35165. d = overImage;
  35166. }
  35167. else
  35168. {
  35169. if (overImage != 0)
  35170. d = overImage;
  35171. }
  35172. return d;
  35173. }
  35174. Drawable* DrawableButton::getDownImage() const throw()
  35175. {
  35176. Drawable* d = normalImage;
  35177. if (getToggleState())
  35178. {
  35179. if (downImageOn != 0)
  35180. d = downImageOn;
  35181. else if (overImageOn != 0)
  35182. d = overImageOn;
  35183. else if (normalImageOn != 0)
  35184. d = normalImageOn;
  35185. else if (downImage != 0)
  35186. d = downImage;
  35187. else
  35188. d = getOverImage();
  35189. }
  35190. else
  35191. {
  35192. if (downImage != 0)
  35193. d = downImage;
  35194. else
  35195. d = getOverImage();
  35196. }
  35197. return d;
  35198. }
  35199. END_JUCE_NAMESPACE
  35200. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35201. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35202. BEGIN_JUCE_NAMESPACE
  35203. HyperlinkButton::HyperlinkButton (const String& linkText,
  35204. const URL& linkURL)
  35205. : Button (linkText),
  35206. url (linkURL),
  35207. font (14.0f, Font::underlined),
  35208. resizeFont (true),
  35209. justification (Justification::centred)
  35210. {
  35211. setMouseCursor (MouseCursor::PointingHandCursor);
  35212. setTooltip (linkURL.toString (false));
  35213. }
  35214. HyperlinkButton::~HyperlinkButton()
  35215. {
  35216. }
  35217. void HyperlinkButton::setFont (const Font& newFont,
  35218. const bool resizeToMatchComponentHeight,
  35219. const Justification& justificationType)
  35220. {
  35221. font = newFont;
  35222. resizeFont = resizeToMatchComponentHeight;
  35223. justification = justificationType;
  35224. repaint();
  35225. }
  35226. void HyperlinkButton::setURL (const URL& newURL) throw()
  35227. {
  35228. url = newURL;
  35229. setTooltip (newURL.toString (false));
  35230. }
  35231. const Font HyperlinkButton::getFontToUse() const
  35232. {
  35233. Font f (font);
  35234. if (resizeFont)
  35235. f.setHeight (getHeight() * 0.7f);
  35236. return f;
  35237. }
  35238. void HyperlinkButton::changeWidthToFitText()
  35239. {
  35240. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35241. }
  35242. void HyperlinkButton::colourChanged()
  35243. {
  35244. repaint();
  35245. }
  35246. void HyperlinkButton::clicked()
  35247. {
  35248. if (url.isWellFormed())
  35249. url.launchInDefaultBrowser();
  35250. }
  35251. void HyperlinkButton::paintButton (Graphics& g,
  35252. bool isMouseOverButton,
  35253. bool isButtonDown)
  35254. {
  35255. const Colour textColour (findColour (textColourId));
  35256. if (isEnabled())
  35257. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35258. : textColour);
  35259. else
  35260. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35261. g.setFont (getFontToUse());
  35262. g.drawText (getButtonText(),
  35263. 2, 0, getWidth() - 2, getHeight(),
  35264. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35265. true);
  35266. }
  35267. END_JUCE_NAMESPACE
  35268. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35269. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35270. BEGIN_JUCE_NAMESPACE
  35271. ImageButton::ImageButton (const String& text_)
  35272. : Button (text_),
  35273. scaleImageToFit (true),
  35274. preserveProportions (true),
  35275. alphaThreshold (0),
  35276. imageX (0),
  35277. imageY (0),
  35278. imageW (0),
  35279. imageH (0),
  35280. normalImage (0),
  35281. overImage (0),
  35282. downImage (0)
  35283. {
  35284. }
  35285. ImageButton::~ImageButton()
  35286. {
  35287. }
  35288. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35289. const bool rescaleImagesWhenButtonSizeChanges,
  35290. const bool preserveImageProportions,
  35291. const Image& normalImage_,
  35292. const float imageOpacityWhenNormal,
  35293. const Colour& overlayColourWhenNormal,
  35294. const Image& overImage_,
  35295. const float imageOpacityWhenOver,
  35296. const Colour& overlayColourWhenOver,
  35297. const Image& downImage_,
  35298. const float imageOpacityWhenDown,
  35299. const Colour& overlayColourWhenDown,
  35300. const float hitTestAlphaThreshold)
  35301. {
  35302. normalImage = normalImage_;
  35303. overImage = overImage_;
  35304. downImage = downImage_;
  35305. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35306. {
  35307. imageW = normalImage.getWidth();
  35308. imageH = normalImage.getHeight();
  35309. setSize (imageW, imageH);
  35310. }
  35311. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35312. preserveProportions = preserveImageProportions;
  35313. normalOpacity = imageOpacityWhenNormal;
  35314. normalOverlay = overlayColourWhenNormal;
  35315. overOpacity = imageOpacityWhenOver;
  35316. overOverlay = overlayColourWhenOver;
  35317. downOpacity = imageOpacityWhenDown;
  35318. downOverlay = overlayColourWhenDown;
  35319. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35320. repaint();
  35321. }
  35322. const Image ImageButton::getCurrentImage() const
  35323. {
  35324. if (isDown() || getToggleState())
  35325. return getDownImage();
  35326. if (isOver())
  35327. return getOverImage();
  35328. return getNormalImage();
  35329. }
  35330. const Image ImageButton::getNormalImage() const
  35331. {
  35332. return normalImage;
  35333. }
  35334. const Image ImageButton::getOverImage() const
  35335. {
  35336. return overImage.isValid() ? overImage
  35337. : normalImage;
  35338. }
  35339. const Image ImageButton::getDownImage() const
  35340. {
  35341. return downImage.isValid() ? downImage
  35342. : getOverImage();
  35343. }
  35344. void ImageButton::paintButton (Graphics& g,
  35345. bool isMouseOverButton,
  35346. bool isButtonDown)
  35347. {
  35348. if (! isEnabled())
  35349. {
  35350. isMouseOverButton = false;
  35351. isButtonDown = false;
  35352. }
  35353. Image im (getCurrentImage());
  35354. if (im.isValid())
  35355. {
  35356. const int iw = im.getWidth();
  35357. const int ih = im.getHeight();
  35358. imageW = getWidth();
  35359. imageH = getHeight();
  35360. imageX = (imageW - iw) >> 1;
  35361. imageY = (imageH - ih) >> 1;
  35362. if (scaleImageToFit)
  35363. {
  35364. if (preserveProportions)
  35365. {
  35366. int newW, newH;
  35367. const float imRatio = ih / (float)iw;
  35368. const float destRatio = imageH / (float)imageW;
  35369. if (imRatio > destRatio)
  35370. {
  35371. newW = roundToInt (imageH / imRatio);
  35372. newH = imageH;
  35373. }
  35374. else
  35375. {
  35376. newW = imageW;
  35377. newH = roundToInt (imageW * imRatio);
  35378. }
  35379. imageX = (imageW - newW) / 2;
  35380. imageY = (imageH - newH) / 2;
  35381. imageW = newW;
  35382. imageH = newH;
  35383. }
  35384. else
  35385. {
  35386. imageX = 0;
  35387. imageY = 0;
  35388. }
  35389. }
  35390. if (! scaleImageToFit)
  35391. {
  35392. imageW = iw;
  35393. imageH = ih;
  35394. }
  35395. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35396. isButtonDown ? downOverlay
  35397. : (isMouseOverButton ? overOverlay
  35398. : normalOverlay),
  35399. isButtonDown ? downOpacity
  35400. : (isMouseOverButton ? overOpacity
  35401. : normalOpacity),
  35402. *this);
  35403. }
  35404. }
  35405. bool ImageButton::hitTest (int x, int y)
  35406. {
  35407. if (alphaThreshold == 0)
  35408. return true;
  35409. Image im (getCurrentImage());
  35410. return im.isNull() || (imageW > 0 && imageH > 0
  35411. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35412. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35413. }
  35414. END_JUCE_NAMESPACE
  35415. /*** End of inlined file: juce_ImageButton.cpp ***/
  35416. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35417. BEGIN_JUCE_NAMESPACE
  35418. ShapeButton::ShapeButton (const String& text_,
  35419. const Colour& normalColour_,
  35420. const Colour& overColour_,
  35421. const Colour& downColour_)
  35422. : Button (text_),
  35423. normalColour (normalColour_),
  35424. overColour (overColour_),
  35425. downColour (downColour_),
  35426. maintainShapeProportions (false),
  35427. outlineWidth (0.0f)
  35428. {
  35429. }
  35430. ShapeButton::~ShapeButton()
  35431. {
  35432. }
  35433. void ShapeButton::setColours (const Colour& newNormalColour,
  35434. const Colour& newOverColour,
  35435. const Colour& newDownColour)
  35436. {
  35437. normalColour = newNormalColour;
  35438. overColour = newOverColour;
  35439. downColour = newDownColour;
  35440. }
  35441. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35442. const float newOutlineWidth)
  35443. {
  35444. outlineColour = newOutlineColour;
  35445. outlineWidth = newOutlineWidth;
  35446. }
  35447. void ShapeButton::setShape (const Path& newShape,
  35448. const bool resizeNowToFitThisShape,
  35449. const bool maintainShapeProportions_,
  35450. const bool hasShadow)
  35451. {
  35452. shape = newShape;
  35453. maintainShapeProportions = maintainShapeProportions_;
  35454. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35455. setComponentEffect ((hasShadow) ? &shadow : 0);
  35456. if (resizeNowToFitThisShape)
  35457. {
  35458. Rectangle<float> bounds (shape.getBounds());
  35459. if (hasShadow)
  35460. bounds.expand (4.0f, 4.0f);
  35461. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35462. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35463. 1 + (int) (bounds.getHeight() + outlineWidth));
  35464. }
  35465. }
  35466. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35467. {
  35468. if (! isEnabled())
  35469. {
  35470. isMouseOverButton = false;
  35471. isButtonDown = false;
  35472. }
  35473. g.setColour ((isButtonDown) ? downColour
  35474. : (isMouseOverButton) ? overColour
  35475. : normalColour);
  35476. int w = getWidth();
  35477. int h = getHeight();
  35478. if (getComponentEffect() != 0)
  35479. {
  35480. w -= 4;
  35481. h -= 4;
  35482. }
  35483. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35484. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35485. w - offset - outlineWidth,
  35486. h - offset - outlineWidth,
  35487. maintainShapeProportions));
  35488. g.fillPath (shape, trans);
  35489. if (outlineWidth > 0.0f)
  35490. {
  35491. g.setColour (outlineColour);
  35492. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35493. }
  35494. }
  35495. END_JUCE_NAMESPACE
  35496. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35497. /*** Start of inlined file: juce_TextButton.cpp ***/
  35498. BEGIN_JUCE_NAMESPACE
  35499. TextButton::TextButton (const String& name,
  35500. const String& toolTip)
  35501. : Button (name)
  35502. {
  35503. setTooltip (toolTip);
  35504. }
  35505. TextButton::~TextButton()
  35506. {
  35507. }
  35508. void TextButton::paintButton (Graphics& g,
  35509. bool isMouseOverButton,
  35510. bool isButtonDown)
  35511. {
  35512. getLookAndFeel().drawButtonBackground (g, *this,
  35513. findColour (getToggleState() ? buttonOnColourId
  35514. : buttonColourId),
  35515. isMouseOverButton,
  35516. isButtonDown);
  35517. getLookAndFeel().drawButtonText (g, *this,
  35518. isMouseOverButton,
  35519. isButtonDown);
  35520. }
  35521. void TextButton::colourChanged()
  35522. {
  35523. repaint();
  35524. }
  35525. const Font TextButton::getFont()
  35526. {
  35527. return Font (jmin (15.0f, getHeight() * 0.6f));
  35528. }
  35529. void TextButton::changeWidthToFitText (const int newHeight)
  35530. {
  35531. if (newHeight >= 0)
  35532. setSize (jmax (1, getWidth()), newHeight);
  35533. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35534. getHeight());
  35535. }
  35536. END_JUCE_NAMESPACE
  35537. /*** End of inlined file: juce_TextButton.cpp ***/
  35538. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35539. BEGIN_JUCE_NAMESPACE
  35540. ToggleButton::ToggleButton (const String& buttonText)
  35541. : Button (buttonText)
  35542. {
  35543. setClickingTogglesState (true);
  35544. }
  35545. ToggleButton::~ToggleButton()
  35546. {
  35547. }
  35548. void ToggleButton::paintButton (Graphics& g,
  35549. bool isMouseOverButton,
  35550. bool isButtonDown)
  35551. {
  35552. getLookAndFeel().drawToggleButton (g, *this,
  35553. isMouseOverButton,
  35554. isButtonDown);
  35555. }
  35556. void ToggleButton::changeWidthToFitText()
  35557. {
  35558. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35559. }
  35560. void ToggleButton::colourChanged()
  35561. {
  35562. repaint();
  35563. }
  35564. END_JUCE_NAMESPACE
  35565. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35566. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35567. BEGIN_JUCE_NAMESPACE
  35568. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35569. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35570. : ToolbarItemComponent (itemId_, buttonText, true),
  35571. normalImage (normalImage_),
  35572. toggledOnImage (toggledOnImage_),
  35573. currentImage (0)
  35574. {
  35575. jassert (normalImage_ != 0);
  35576. }
  35577. ToolbarButton::~ToolbarButton()
  35578. {
  35579. }
  35580. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35581. {
  35582. preferredSize = minSize = maxSize = toolbarDepth;
  35583. return true;
  35584. }
  35585. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35586. {
  35587. }
  35588. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35589. {
  35590. buttonStateChanged();
  35591. }
  35592. void ToolbarButton::updateDrawable()
  35593. {
  35594. if (currentImage != 0)
  35595. {
  35596. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35597. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35598. }
  35599. }
  35600. void ToolbarButton::resized()
  35601. {
  35602. ToolbarItemComponent::resized();
  35603. updateDrawable();
  35604. }
  35605. void ToolbarButton::enablementChanged()
  35606. {
  35607. ToolbarItemComponent::enablementChanged();
  35608. updateDrawable();
  35609. }
  35610. void ToolbarButton::buttonStateChanged()
  35611. {
  35612. Drawable* d = normalImage;
  35613. if (getToggleState() && toggledOnImage != 0)
  35614. d = toggledOnImage;
  35615. if (d != currentImage)
  35616. {
  35617. removeChildComponent (currentImage);
  35618. currentImage = d;
  35619. if (d != 0)
  35620. {
  35621. enablementChanged();
  35622. addAndMakeVisible (d);
  35623. updateDrawable();
  35624. }
  35625. }
  35626. }
  35627. END_JUCE_NAMESPACE
  35628. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35629. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35630. BEGIN_JUCE_NAMESPACE
  35631. class CodeDocumentLine
  35632. {
  35633. public:
  35634. CodeDocumentLine (const juce_wchar* const line_,
  35635. const int lineLength_,
  35636. const int numNewLineChars,
  35637. const int lineStartInFile_)
  35638. : line (line_, lineLength_),
  35639. lineStartInFile (lineStartInFile_),
  35640. lineLength (lineLength_),
  35641. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35642. {
  35643. }
  35644. ~CodeDocumentLine()
  35645. {
  35646. }
  35647. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35648. {
  35649. const juce_wchar* const t = text;
  35650. int pos = 0;
  35651. while (t [pos] != 0)
  35652. {
  35653. const int startOfLine = pos;
  35654. int numNewLineChars = 0;
  35655. while (t[pos] != 0)
  35656. {
  35657. if (t[pos] == '\r')
  35658. {
  35659. ++numNewLineChars;
  35660. ++pos;
  35661. if (t[pos] == '\n')
  35662. {
  35663. ++numNewLineChars;
  35664. ++pos;
  35665. }
  35666. break;
  35667. }
  35668. if (t[pos] == '\n')
  35669. {
  35670. ++numNewLineChars;
  35671. ++pos;
  35672. break;
  35673. }
  35674. ++pos;
  35675. }
  35676. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35677. numNewLineChars, startOfLine));
  35678. }
  35679. jassert (pos == text.length());
  35680. }
  35681. bool endsWithLineBreak() const throw()
  35682. {
  35683. return lineLengthWithoutNewLines != lineLength;
  35684. }
  35685. void updateLength() throw()
  35686. {
  35687. lineLengthWithoutNewLines = lineLength = line.length();
  35688. while (lineLengthWithoutNewLines > 0
  35689. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35690. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35691. {
  35692. --lineLengthWithoutNewLines;
  35693. }
  35694. }
  35695. String line;
  35696. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35697. };
  35698. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35699. : document (document_),
  35700. currentLine (document_->lines[0]),
  35701. line (0),
  35702. position (0)
  35703. {
  35704. }
  35705. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35706. : document (other.document),
  35707. currentLine (other.currentLine),
  35708. line (other.line),
  35709. position (other.position)
  35710. {
  35711. }
  35712. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35713. {
  35714. document = other.document;
  35715. currentLine = other.currentLine;
  35716. line = other.line;
  35717. position = other.position;
  35718. return *this;
  35719. }
  35720. CodeDocument::Iterator::~Iterator() throw()
  35721. {
  35722. }
  35723. juce_wchar CodeDocument::Iterator::nextChar()
  35724. {
  35725. if (currentLine == 0)
  35726. return 0;
  35727. jassert (currentLine == document->lines.getUnchecked (line));
  35728. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35729. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35730. {
  35731. ++line;
  35732. currentLine = document->lines [line];
  35733. }
  35734. return result;
  35735. }
  35736. void CodeDocument::Iterator::skip()
  35737. {
  35738. if (currentLine != 0)
  35739. {
  35740. jassert (currentLine == document->lines.getUnchecked (line));
  35741. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35742. {
  35743. ++line;
  35744. currentLine = document->lines [line];
  35745. }
  35746. }
  35747. }
  35748. void CodeDocument::Iterator::skipToEndOfLine()
  35749. {
  35750. if (currentLine != 0)
  35751. {
  35752. jassert (currentLine == document->lines.getUnchecked (line));
  35753. ++line;
  35754. currentLine = document->lines [line];
  35755. if (currentLine != 0)
  35756. position = currentLine->lineStartInFile;
  35757. else
  35758. position = document->getNumCharacters();
  35759. }
  35760. }
  35761. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35762. {
  35763. if (currentLine == 0)
  35764. return 0;
  35765. jassert (currentLine == document->lines.getUnchecked (line));
  35766. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35767. }
  35768. void CodeDocument::Iterator::skipWhitespace()
  35769. {
  35770. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35771. skip();
  35772. }
  35773. bool CodeDocument::Iterator::isEOF() const throw()
  35774. {
  35775. return currentLine == 0;
  35776. }
  35777. CodeDocument::Position::Position() throw()
  35778. : owner (0), characterPos (0), line (0),
  35779. indexInLine (0), positionMaintained (false)
  35780. {
  35781. }
  35782. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35783. const int line_, const int indexInLine_) throw()
  35784. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35785. characterPos (0), line (line_),
  35786. indexInLine (indexInLine_), positionMaintained (false)
  35787. {
  35788. setLineAndIndex (line_, indexInLine_);
  35789. }
  35790. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35791. const int characterPos_) throw()
  35792. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35793. positionMaintained (false)
  35794. {
  35795. setPosition (characterPos_);
  35796. }
  35797. CodeDocument::Position::Position (const Position& other) throw()
  35798. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35799. indexInLine (other.indexInLine), positionMaintained (false)
  35800. {
  35801. jassert (*this == other);
  35802. }
  35803. CodeDocument::Position::~Position()
  35804. {
  35805. setPositionMaintained (false);
  35806. }
  35807. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  35808. {
  35809. if (this != &other)
  35810. {
  35811. const bool wasPositionMaintained = positionMaintained;
  35812. if (owner != other.owner)
  35813. setPositionMaintained (false);
  35814. owner = other.owner;
  35815. line = other.line;
  35816. indexInLine = other.indexInLine;
  35817. characterPos = other.characterPos;
  35818. setPositionMaintained (wasPositionMaintained);
  35819. jassert (*this == other);
  35820. }
  35821. return *this;
  35822. }
  35823. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35824. {
  35825. jassert ((characterPos == other.characterPos)
  35826. == (line == other.line && indexInLine == other.indexInLine));
  35827. return characterPos == other.characterPos
  35828. && line == other.line
  35829. && indexInLine == other.indexInLine
  35830. && owner == other.owner;
  35831. }
  35832. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35833. {
  35834. return ! operator== (other);
  35835. }
  35836. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  35837. {
  35838. jassert (owner != 0);
  35839. if (owner->lines.size() == 0)
  35840. {
  35841. line = 0;
  35842. indexInLine = 0;
  35843. characterPos = 0;
  35844. }
  35845. else
  35846. {
  35847. if (newLineNum >= owner->lines.size())
  35848. {
  35849. line = owner->lines.size() - 1;
  35850. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35851. jassert (l != 0);
  35852. indexInLine = l->lineLengthWithoutNewLines;
  35853. characterPos = l->lineStartInFile + indexInLine;
  35854. }
  35855. else
  35856. {
  35857. line = jmax (0, newLineNum);
  35858. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35859. jassert (l != 0);
  35860. if (l->lineLengthWithoutNewLines > 0)
  35861. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35862. else
  35863. indexInLine = 0;
  35864. characterPos = l->lineStartInFile + indexInLine;
  35865. }
  35866. }
  35867. }
  35868. void CodeDocument::Position::setPosition (const int newPosition)
  35869. {
  35870. jassert (owner != 0);
  35871. line = 0;
  35872. indexInLine = 0;
  35873. characterPos = 0;
  35874. if (newPosition > 0)
  35875. {
  35876. int lineStart = 0;
  35877. int lineEnd = owner->lines.size();
  35878. for (;;)
  35879. {
  35880. if (lineEnd - lineStart < 4)
  35881. {
  35882. for (int i = lineStart; i < lineEnd; ++i)
  35883. {
  35884. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35885. int index = newPosition - l->lineStartInFile;
  35886. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35887. {
  35888. line = i;
  35889. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35890. characterPos = l->lineStartInFile + indexInLine;
  35891. }
  35892. }
  35893. break;
  35894. }
  35895. else
  35896. {
  35897. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35898. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35899. if (newPosition >= mid->lineStartInFile)
  35900. lineStart = midIndex;
  35901. else
  35902. lineEnd = midIndex;
  35903. }
  35904. }
  35905. }
  35906. }
  35907. void CodeDocument::Position::moveBy (int characterDelta)
  35908. {
  35909. jassert (owner != 0);
  35910. if (characterDelta == 1)
  35911. {
  35912. setPosition (getPosition());
  35913. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35914. if (line < owner->lines.size())
  35915. {
  35916. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35917. if (indexInLine + characterDelta < l->lineLength
  35918. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35919. ++characterDelta;
  35920. }
  35921. }
  35922. setPosition (characterPos + characterDelta);
  35923. }
  35924. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  35925. {
  35926. CodeDocument::Position p (*this);
  35927. p.moveBy (characterDelta);
  35928. return p;
  35929. }
  35930. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  35931. {
  35932. CodeDocument::Position p (*this);
  35933. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35934. return p;
  35935. }
  35936. const juce_wchar CodeDocument::Position::getCharacter() const
  35937. {
  35938. const CodeDocumentLine* const l = owner->lines [line];
  35939. return l == 0 ? 0 : l->line [getIndexInLine()];
  35940. }
  35941. const String CodeDocument::Position::getLineText() const
  35942. {
  35943. const CodeDocumentLine* const l = owner->lines [line];
  35944. return l == 0 ? String::empty : l->line;
  35945. }
  35946. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  35947. {
  35948. if (isMaintained != positionMaintained)
  35949. {
  35950. positionMaintained = isMaintained;
  35951. if (owner != 0)
  35952. {
  35953. if (isMaintained)
  35954. {
  35955. jassert (! owner->positionsToMaintain.contains (this));
  35956. owner->positionsToMaintain.add (this);
  35957. }
  35958. else
  35959. {
  35960. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35961. jassert (owner->positionsToMaintain.contains (this));
  35962. owner->positionsToMaintain.removeValue (this);
  35963. }
  35964. }
  35965. }
  35966. }
  35967. CodeDocument::CodeDocument()
  35968. : undoManager (std::numeric_limits<int>::max(), 10000),
  35969. currentActionIndex (0),
  35970. indexOfSavedState (-1),
  35971. maximumLineLength (-1),
  35972. newLineChars ("\r\n")
  35973. {
  35974. }
  35975. CodeDocument::~CodeDocument()
  35976. {
  35977. }
  35978. const String CodeDocument::getAllContent() const
  35979. {
  35980. return getTextBetween (Position (this, 0),
  35981. Position (this, lines.size(), 0));
  35982. }
  35983. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  35984. {
  35985. if (end.getPosition() <= start.getPosition())
  35986. return String::empty;
  35987. const int startLine = start.getLineNumber();
  35988. const int endLine = end.getLineNumber();
  35989. if (startLine == endLine)
  35990. {
  35991. CodeDocumentLine* const line = lines [startLine];
  35992. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35993. }
  35994. String result;
  35995. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35996. String::Concatenator concatenator (result);
  35997. const int maxLine = jmin (lines.size() - 1, endLine);
  35998. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35999. {
  36000. const CodeDocumentLine* line = lines.getUnchecked(i);
  36001. int len = line->lineLength;
  36002. if (i == startLine)
  36003. {
  36004. const int index = start.getIndexInLine();
  36005. concatenator.append (line->line.substring (index, len));
  36006. }
  36007. else if (i == endLine)
  36008. {
  36009. len = end.getIndexInLine();
  36010. concatenator.append (line->line.substring (0, len));
  36011. }
  36012. else
  36013. {
  36014. concatenator.append (line->line);
  36015. }
  36016. }
  36017. return result;
  36018. }
  36019. int CodeDocument::getNumCharacters() const throw()
  36020. {
  36021. const CodeDocumentLine* const lastLine = lines.getLast();
  36022. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36023. }
  36024. const String CodeDocument::getLine (const int lineIndex) const throw()
  36025. {
  36026. const CodeDocumentLine* const line = lines [lineIndex];
  36027. return (line == 0) ? String::empty : line->line;
  36028. }
  36029. int CodeDocument::getMaximumLineLength() throw()
  36030. {
  36031. if (maximumLineLength < 0)
  36032. {
  36033. maximumLineLength = 0;
  36034. for (int i = lines.size(); --i >= 0;)
  36035. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36036. }
  36037. return maximumLineLength;
  36038. }
  36039. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36040. {
  36041. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36042. }
  36043. void CodeDocument::insertText (const Position& position, const String& text)
  36044. {
  36045. insert (text, position.getPosition(), true);
  36046. }
  36047. void CodeDocument::replaceAllContent (const String& newContent)
  36048. {
  36049. remove (0, getNumCharacters(), true);
  36050. insert (newContent, 0, true);
  36051. }
  36052. bool CodeDocument::loadFromStream (InputStream& stream)
  36053. {
  36054. replaceAllContent (stream.readEntireStreamAsString());
  36055. setSavePoint();
  36056. clearUndoHistory();
  36057. return true;
  36058. }
  36059. bool CodeDocument::writeToStream (OutputStream& stream)
  36060. {
  36061. for (int i = 0; i < lines.size(); ++i)
  36062. {
  36063. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36064. const char* utf8 = temp.toUTF8();
  36065. if (! stream.write (utf8, (int) strlen (utf8)))
  36066. return false;
  36067. }
  36068. return true;
  36069. }
  36070. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36071. {
  36072. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36073. newLineChars = newLineChars_;
  36074. }
  36075. void CodeDocument::newTransaction()
  36076. {
  36077. undoManager.beginNewTransaction (String::empty);
  36078. }
  36079. void CodeDocument::undo()
  36080. {
  36081. newTransaction();
  36082. undoManager.undo();
  36083. }
  36084. void CodeDocument::redo()
  36085. {
  36086. undoManager.redo();
  36087. }
  36088. void CodeDocument::clearUndoHistory()
  36089. {
  36090. undoManager.clearUndoHistory();
  36091. }
  36092. void CodeDocument::setSavePoint() throw()
  36093. {
  36094. indexOfSavedState = currentActionIndex;
  36095. }
  36096. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36097. {
  36098. return currentActionIndex != indexOfSavedState;
  36099. }
  36100. namespace CodeDocumentHelpers
  36101. {
  36102. int getCharacterType (const juce_wchar character) throw()
  36103. {
  36104. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36105. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36106. }
  36107. }
  36108. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36109. {
  36110. Position p (position);
  36111. const int maxDistance = 256;
  36112. int i = 0;
  36113. while (i < maxDistance
  36114. && CharacterFunctions::isWhitespace (p.getCharacter())
  36115. && (i == 0 || (p.getCharacter() != '\n'
  36116. && p.getCharacter() != '\r')))
  36117. {
  36118. ++i;
  36119. p.moveBy (1);
  36120. }
  36121. if (i == 0)
  36122. {
  36123. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36124. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36125. {
  36126. ++i;
  36127. p.moveBy (1);
  36128. }
  36129. while (i < maxDistance
  36130. && CharacterFunctions::isWhitespace (p.getCharacter())
  36131. && (i == 0 || (p.getCharacter() != '\n'
  36132. && p.getCharacter() != '\r')))
  36133. {
  36134. ++i;
  36135. p.moveBy (1);
  36136. }
  36137. }
  36138. return p;
  36139. }
  36140. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36141. {
  36142. Position p (position);
  36143. const int maxDistance = 256;
  36144. int i = 0;
  36145. bool stoppedAtLineStart = false;
  36146. while (i < maxDistance)
  36147. {
  36148. const juce_wchar c = p.movedBy (-1).getCharacter();
  36149. if (c == '\r' || c == '\n')
  36150. {
  36151. stoppedAtLineStart = true;
  36152. if (i > 0)
  36153. break;
  36154. }
  36155. if (! CharacterFunctions::isWhitespace (c))
  36156. break;
  36157. p.moveBy (-1);
  36158. ++i;
  36159. }
  36160. if (i < maxDistance && ! stoppedAtLineStart)
  36161. {
  36162. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36163. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36164. {
  36165. p.moveBy (-1);
  36166. ++i;
  36167. }
  36168. }
  36169. return p;
  36170. }
  36171. void CodeDocument::checkLastLineStatus()
  36172. {
  36173. while (lines.size() > 0
  36174. && lines.getLast()->lineLength == 0
  36175. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36176. {
  36177. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36178. lines.removeLast();
  36179. }
  36180. const CodeDocumentLine* const lastLine = lines.getLast();
  36181. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36182. {
  36183. // check that there's an empty line at the end if the preceding one ends in a newline..
  36184. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36185. }
  36186. }
  36187. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36188. {
  36189. listeners.add (listener);
  36190. }
  36191. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36192. {
  36193. listeners.remove (listener);
  36194. }
  36195. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36196. {
  36197. Position startPos (this, startLine, 0);
  36198. Position endPos (this, endLine, 0);
  36199. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36200. }
  36201. class CodeDocumentInsertAction : public UndoableAction
  36202. {
  36203. public:
  36204. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36205. : owner (owner_),
  36206. text (text_),
  36207. insertPos (insertPos_)
  36208. {
  36209. }
  36210. bool perform()
  36211. {
  36212. owner.currentActionIndex++;
  36213. owner.insert (text, insertPos, false);
  36214. return true;
  36215. }
  36216. bool undo()
  36217. {
  36218. owner.currentActionIndex--;
  36219. owner.remove (insertPos, insertPos + text.length(), false);
  36220. return true;
  36221. }
  36222. int getSizeInUnits() { return text.length() + 32; }
  36223. private:
  36224. CodeDocument& owner;
  36225. const String text;
  36226. int insertPos;
  36227. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36228. };
  36229. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36230. {
  36231. if (text.isEmpty())
  36232. return;
  36233. if (undoable)
  36234. {
  36235. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36236. }
  36237. else
  36238. {
  36239. Position pos (this, insertPos);
  36240. const int firstAffectedLine = pos.getLineNumber();
  36241. int lastAffectedLine = firstAffectedLine + 1;
  36242. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36243. String textInsideOriginalLine (text);
  36244. if (firstLine != 0)
  36245. {
  36246. const int index = pos.getIndexInLine();
  36247. textInsideOriginalLine = firstLine->line.substring (0, index)
  36248. + textInsideOriginalLine
  36249. + firstLine->line.substring (index);
  36250. }
  36251. maximumLineLength = -1;
  36252. Array <CodeDocumentLine*> newLines;
  36253. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36254. jassert (newLines.size() > 0);
  36255. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36256. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36257. lines.set (firstAffectedLine, newFirstLine);
  36258. if (newLines.size() > 1)
  36259. {
  36260. for (int i = 1; i < newLines.size(); ++i)
  36261. {
  36262. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36263. lines.insert (firstAffectedLine + i, l);
  36264. }
  36265. lastAffectedLine = lines.size();
  36266. }
  36267. int i, lineStart = newFirstLine->lineStartInFile;
  36268. for (i = firstAffectedLine; i < lines.size(); ++i)
  36269. {
  36270. CodeDocumentLine* const l = lines.getUnchecked (i);
  36271. l->lineStartInFile = lineStart;
  36272. lineStart += l->lineLength;
  36273. }
  36274. checkLastLineStatus();
  36275. const int newTextLength = text.length();
  36276. for (i = 0; i < positionsToMaintain.size(); ++i)
  36277. {
  36278. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36279. if (p->getPosition() >= insertPos)
  36280. p->setPosition (p->getPosition() + newTextLength);
  36281. }
  36282. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36283. }
  36284. }
  36285. class CodeDocumentDeleteAction : public UndoableAction
  36286. {
  36287. public:
  36288. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36289. : owner (owner_),
  36290. startPos (startPos_),
  36291. endPos (endPos_)
  36292. {
  36293. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36294. CodeDocument::Position (&owner, endPos));
  36295. }
  36296. bool perform()
  36297. {
  36298. owner.currentActionIndex++;
  36299. owner.remove (startPos, endPos, false);
  36300. return true;
  36301. }
  36302. bool undo()
  36303. {
  36304. owner.currentActionIndex--;
  36305. owner.insert (removedText, startPos, false);
  36306. return true;
  36307. }
  36308. int getSizeInUnits() { return removedText.length() + 32; }
  36309. private:
  36310. CodeDocument& owner;
  36311. int startPos, endPos;
  36312. String removedText;
  36313. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36314. };
  36315. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36316. {
  36317. if (endPos <= startPos)
  36318. return;
  36319. if (undoable)
  36320. {
  36321. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36322. }
  36323. else
  36324. {
  36325. Position startPosition (this, startPos);
  36326. Position endPosition (this, endPos);
  36327. maximumLineLength = -1;
  36328. const int firstAffectedLine = startPosition.getLineNumber();
  36329. const int endLine = endPosition.getLineNumber();
  36330. int lastAffectedLine = firstAffectedLine + 1;
  36331. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36332. if (firstAffectedLine == endLine)
  36333. {
  36334. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36335. + firstLine->line.substring (endPosition.getIndexInLine());
  36336. firstLine->updateLength();
  36337. }
  36338. else
  36339. {
  36340. lastAffectedLine = lines.size();
  36341. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36342. jassert (lastLine != 0);
  36343. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36344. + lastLine->line.substring (endPosition.getIndexInLine());
  36345. firstLine->updateLength();
  36346. int numLinesToRemove = endLine - firstAffectedLine;
  36347. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36348. }
  36349. int i;
  36350. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36351. {
  36352. CodeDocumentLine* const l = lines.getUnchecked (i);
  36353. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36354. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36355. }
  36356. checkLastLineStatus();
  36357. const int totalChars = getNumCharacters();
  36358. for (i = 0; i < positionsToMaintain.size(); ++i)
  36359. {
  36360. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36361. if (p->getPosition() > startPosition.getPosition())
  36362. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36363. if (p->getPosition() > totalChars)
  36364. p->setPosition (totalChars);
  36365. }
  36366. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36367. }
  36368. }
  36369. END_JUCE_NAMESPACE
  36370. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36371. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36372. BEGIN_JUCE_NAMESPACE
  36373. class CodeEditorComponent::CaretComponent : public Component,
  36374. public Timer
  36375. {
  36376. public:
  36377. CaretComponent (CodeEditorComponent& owner_)
  36378. : owner (owner_)
  36379. {
  36380. setAlwaysOnTop (true);
  36381. setInterceptsMouseClicks (false, false);
  36382. }
  36383. void paint (Graphics& g)
  36384. {
  36385. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36386. }
  36387. void timerCallback()
  36388. {
  36389. setVisible (shouldBeShown() && ! isVisible());
  36390. }
  36391. void updatePosition()
  36392. {
  36393. startTimer (400);
  36394. setVisible (shouldBeShown());
  36395. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36396. }
  36397. private:
  36398. CodeEditorComponent& owner;
  36399. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36400. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36401. };
  36402. class CodeEditorComponent::CodeEditorLine
  36403. {
  36404. public:
  36405. CodeEditorLine() throw()
  36406. : highlightColumnStart (0), highlightColumnEnd (0)
  36407. {
  36408. }
  36409. bool update (CodeDocument& document, int lineNum,
  36410. CodeDocument::Iterator& source,
  36411. CodeTokeniser* analyser, const int spacesPerTab,
  36412. const CodeDocument::Position& selectionStart,
  36413. const CodeDocument::Position& selectionEnd)
  36414. {
  36415. Array <SyntaxToken> newTokens;
  36416. newTokens.ensureStorageAllocated (8);
  36417. if (analyser == 0)
  36418. {
  36419. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36420. }
  36421. else if (lineNum < document.getNumLines())
  36422. {
  36423. const CodeDocument::Position pos (&document, lineNum, 0);
  36424. createTokens (pos.getPosition(), pos.getLineText(),
  36425. source, analyser, newTokens);
  36426. }
  36427. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36428. int newHighlightStart = 0;
  36429. int newHighlightEnd = 0;
  36430. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36431. {
  36432. const String line (document.getLine (lineNum));
  36433. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36434. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36435. line, spacesPerTab);
  36436. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36437. line, spacesPerTab);
  36438. }
  36439. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36440. {
  36441. highlightColumnStart = newHighlightStart;
  36442. highlightColumnEnd = newHighlightEnd;
  36443. }
  36444. else
  36445. {
  36446. if (tokens.size() == newTokens.size())
  36447. {
  36448. bool allTheSame = true;
  36449. for (int i = newTokens.size(); --i >= 0;)
  36450. {
  36451. if (tokens.getReference(i) != newTokens.getReference(i))
  36452. {
  36453. allTheSame = false;
  36454. break;
  36455. }
  36456. }
  36457. if (allTheSame)
  36458. return false;
  36459. }
  36460. }
  36461. tokens.swapWithArray (newTokens);
  36462. return true;
  36463. }
  36464. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36465. float x, const int y, const int baselineOffset, const int lineHeight,
  36466. const Colour& highlightColour) const
  36467. {
  36468. if (highlightColumnStart < highlightColumnEnd)
  36469. {
  36470. g.setColour (highlightColour);
  36471. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36472. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36473. }
  36474. int lastType = std::numeric_limits<int>::min();
  36475. for (int i = 0; i < tokens.size(); ++i)
  36476. {
  36477. SyntaxToken& token = tokens.getReference(i);
  36478. if (lastType != token.tokenType)
  36479. {
  36480. lastType = token.tokenType;
  36481. g.setColour (owner.getColourForTokenType (lastType));
  36482. }
  36483. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36484. if (i < tokens.size() - 1)
  36485. {
  36486. if (token.width < 0)
  36487. token.width = font.getStringWidthFloat (token.text);
  36488. x += token.width;
  36489. }
  36490. }
  36491. }
  36492. private:
  36493. struct SyntaxToken
  36494. {
  36495. SyntaxToken (const String& text_, const int type) throw()
  36496. : text (text_), tokenType (type), width (-1.0f)
  36497. {
  36498. }
  36499. bool operator!= (const SyntaxToken& other) const throw()
  36500. {
  36501. return text != other.text || tokenType != other.tokenType;
  36502. }
  36503. String text;
  36504. int tokenType;
  36505. float width;
  36506. };
  36507. Array <SyntaxToken> tokens;
  36508. int highlightColumnStart, highlightColumnEnd;
  36509. static void createTokens (int startPosition, const String& lineText,
  36510. CodeDocument::Iterator& source,
  36511. CodeTokeniser* analyser,
  36512. Array <SyntaxToken>& newTokens)
  36513. {
  36514. CodeDocument::Iterator lastIterator (source);
  36515. const int lineLength = lineText.length();
  36516. for (;;)
  36517. {
  36518. int tokenType = analyser->readNextToken (source);
  36519. int tokenStart = lastIterator.getPosition();
  36520. int tokenEnd = source.getPosition();
  36521. if (tokenEnd <= tokenStart)
  36522. break;
  36523. tokenEnd -= startPosition;
  36524. if (tokenEnd > 0)
  36525. {
  36526. tokenStart -= startPosition;
  36527. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36528. tokenType));
  36529. if (tokenEnd >= lineLength)
  36530. break;
  36531. }
  36532. lastIterator = source;
  36533. }
  36534. source = lastIterator;
  36535. }
  36536. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36537. {
  36538. int x = 0;
  36539. for (int i = 0; i < tokens.size(); ++i)
  36540. {
  36541. SyntaxToken& t = tokens.getReference(i);
  36542. for (;;)
  36543. {
  36544. int tabPos = t.text.indexOfChar ('\t');
  36545. if (tabPos < 0)
  36546. break;
  36547. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36548. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36549. }
  36550. x += t.text.length();
  36551. }
  36552. }
  36553. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36554. {
  36555. jassert (index <= line.length());
  36556. int col = 0;
  36557. for (int i = 0; i < index; ++i)
  36558. {
  36559. if (line[i] != '\t')
  36560. ++col;
  36561. else
  36562. col += spacesPerTab - (col % spacesPerTab);
  36563. }
  36564. return col;
  36565. }
  36566. };
  36567. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36568. CodeTokeniser* const codeTokeniser_)
  36569. : document (document_),
  36570. firstLineOnScreen (0),
  36571. gutter (5),
  36572. spacesPerTab (4),
  36573. lineHeight (0),
  36574. linesOnScreen (0),
  36575. columnsOnScreen (0),
  36576. scrollbarThickness (16),
  36577. columnToTryToMaintain (-1),
  36578. useSpacesForTabs (false),
  36579. xOffset (0),
  36580. verticalScrollBar (true),
  36581. horizontalScrollBar (false),
  36582. codeTokeniser (codeTokeniser_)
  36583. {
  36584. caretPos = CodeDocument::Position (&document_, 0, 0);
  36585. caretPos.setPositionMaintained (true);
  36586. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36587. selectionStart.setPositionMaintained (true);
  36588. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36589. selectionEnd.setPositionMaintained (true);
  36590. setOpaque (true);
  36591. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36592. setWantsKeyboardFocus (true);
  36593. addAndMakeVisible (&verticalScrollBar);
  36594. verticalScrollBar.setSingleStepSize (1.0);
  36595. addAndMakeVisible (&horizontalScrollBar);
  36596. horizontalScrollBar.setSingleStepSize (1.0);
  36597. addAndMakeVisible (caret = new CaretComponent (*this));
  36598. Font f (12.0f);
  36599. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36600. setFont (f);
  36601. resetToDefaultColours();
  36602. verticalScrollBar.addListener (this);
  36603. horizontalScrollBar.addListener (this);
  36604. document.addListener (this);
  36605. }
  36606. CodeEditorComponent::~CodeEditorComponent()
  36607. {
  36608. document.removeListener (this);
  36609. }
  36610. void CodeEditorComponent::loadContent (const String& newContent)
  36611. {
  36612. clearCachedIterators (0);
  36613. document.replaceAllContent (newContent);
  36614. document.clearUndoHistory();
  36615. document.setSavePoint();
  36616. caretPos.setPosition (0);
  36617. selectionStart.setPosition (0);
  36618. selectionEnd.setPosition (0);
  36619. scrollToLine (0);
  36620. }
  36621. bool CodeEditorComponent::isTextInputActive() const
  36622. {
  36623. return true;
  36624. }
  36625. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36626. const CodeDocument::Position& affectedTextEnd)
  36627. {
  36628. clearCachedIterators (affectedTextStart.getLineNumber());
  36629. triggerAsyncUpdate();
  36630. caret->updatePosition();
  36631. columnToTryToMaintain = -1;
  36632. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36633. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36634. deselectAll();
  36635. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36636. || caretPos.getPosition() < affectedTextStart.getPosition())
  36637. moveCaretTo (affectedTextStart, false);
  36638. updateScrollBars();
  36639. }
  36640. void CodeEditorComponent::resized()
  36641. {
  36642. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36643. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36644. lines.clear();
  36645. rebuildLineTokens();
  36646. caret->updatePosition();
  36647. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36648. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36649. updateScrollBars();
  36650. }
  36651. void CodeEditorComponent::paint (Graphics& g)
  36652. {
  36653. handleUpdateNowIfNeeded();
  36654. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36655. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36656. g.setFont (font);
  36657. const int baselineOffset = (int) font.getAscent();
  36658. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36659. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36660. const Rectangle<int> clip (g.getClipBounds());
  36661. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36662. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36663. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36664. {
  36665. lines.getUnchecked(j)->draw (*this, g, font,
  36666. (float) (gutter - xOffset * charWidth),
  36667. lineHeight * j, baselineOffset, lineHeight,
  36668. highlightColour);
  36669. }
  36670. }
  36671. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36672. {
  36673. if (scrollbarThickness != thickness)
  36674. {
  36675. scrollbarThickness = thickness;
  36676. resized();
  36677. }
  36678. }
  36679. void CodeEditorComponent::handleAsyncUpdate()
  36680. {
  36681. rebuildLineTokens();
  36682. }
  36683. void CodeEditorComponent::rebuildLineTokens()
  36684. {
  36685. cancelPendingUpdate();
  36686. const int numNeeded = linesOnScreen + 1;
  36687. int minLineToRepaint = numNeeded;
  36688. int maxLineToRepaint = 0;
  36689. if (numNeeded != lines.size())
  36690. {
  36691. lines.clear();
  36692. for (int i = numNeeded; --i >= 0;)
  36693. lines.add (new CodeEditorLine());
  36694. minLineToRepaint = 0;
  36695. maxLineToRepaint = numNeeded;
  36696. }
  36697. jassert (numNeeded == lines.size());
  36698. CodeDocument::Iterator source (&document);
  36699. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36700. for (int i = 0; i < numNeeded; ++i)
  36701. {
  36702. CodeEditorLine* const line = lines.getUnchecked(i);
  36703. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36704. selectionStart, selectionEnd))
  36705. {
  36706. minLineToRepaint = jmin (minLineToRepaint, i);
  36707. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36708. }
  36709. }
  36710. if (minLineToRepaint <= maxLineToRepaint)
  36711. {
  36712. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36713. verticalScrollBar.getX() - gutter,
  36714. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36715. }
  36716. }
  36717. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36718. {
  36719. caretPos = newPos;
  36720. columnToTryToMaintain = -1;
  36721. if (highlighting)
  36722. {
  36723. if (dragType == notDragging)
  36724. {
  36725. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36726. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36727. dragType = draggingSelectionStart;
  36728. else
  36729. dragType = draggingSelectionEnd;
  36730. }
  36731. if (dragType == draggingSelectionStart)
  36732. {
  36733. selectionStart = caretPos;
  36734. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36735. {
  36736. const CodeDocument::Position temp (selectionStart);
  36737. selectionStart = selectionEnd;
  36738. selectionEnd = temp;
  36739. dragType = draggingSelectionEnd;
  36740. }
  36741. }
  36742. else
  36743. {
  36744. selectionEnd = caretPos;
  36745. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36746. {
  36747. const CodeDocument::Position temp (selectionStart);
  36748. selectionStart = selectionEnd;
  36749. selectionEnd = temp;
  36750. dragType = draggingSelectionStart;
  36751. }
  36752. }
  36753. triggerAsyncUpdate();
  36754. }
  36755. else
  36756. {
  36757. deselectAll();
  36758. }
  36759. caret->updatePosition();
  36760. scrollToKeepCaretOnScreen();
  36761. updateScrollBars();
  36762. }
  36763. void CodeEditorComponent::deselectAll()
  36764. {
  36765. if (selectionStart != selectionEnd)
  36766. triggerAsyncUpdate();
  36767. selectionStart = caretPos;
  36768. selectionEnd = caretPos;
  36769. }
  36770. void CodeEditorComponent::updateScrollBars()
  36771. {
  36772. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36773. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36774. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36775. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36776. }
  36777. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36778. {
  36779. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36780. newFirstLineOnScreen);
  36781. if (newFirstLineOnScreen != firstLineOnScreen)
  36782. {
  36783. firstLineOnScreen = newFirstLineOnScreen;
  36784. caret->updatePosition();
  36785. updateCachedIterators (firstLineOnScreen);
  36786. triggerAsyncUpdate();
  36787. }
  36788. }
  36789. void CodeEditorComponent::scrollToColumnInternal (double column)
  36790. {
  36791. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36792. if (xOffset != newOffset)
  36793. {
  36794. xOffset = newOffset;
  36795. caret->updatePosition();
  36796. repaint();
  36797. }
  36798. }
  36799. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36800. {
  36801. scrollToLineInternal (newFirstLineOnScreen);
  36802. updateScrollBars();
  36803. }
  36804. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36805. {
  36806. scrollToColumnInternal (newFirstColumnOnScreen);
  36807. updateScrollBars();
  36808. }
  36809. void CodeEditorComponent::scrollBy (int deltaLines)
  36810. {
  36811. scrollToLine (firstLineOnScreen + deltaLines);
  36812. }
  36813. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36814. {
  36815. if (caretPos.getLineNumber() < firstLineOnScreen)
  36816. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36817. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36818. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36819. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36820. if (column >= xOffset + columnsOnScreen - 1)
  36821. scrollToColumn (column + 1 - columnsOnScreen);
  36822. else if (column < xOffset)
  36823. scrollToColumn (column);
  36824. }
  36825. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  36826. {
  36827. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36828. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36829. roundToInt (charWidth),
  36830. lineHeight);
  36831. }
  36832. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36833. {
  36834. const int line = y / lineHeight + firstLineOnScreen;
  36835. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36836. const int index = columnToIndex (line, column);
  36837. return CodeDocument::Position (&document, line, index);
  36838. }
  36839. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36840. {
  36841. document.deleteSection (selectionStart, selectionEnd);
  36842. if (newText.isNotEmpty())
  36843. document.insertText (caretPos, newText);
  36844. scrollToKeepCaretOnScreen();
  36845. }
  36846. void CodeEditorComponent::insertTabAtCaret()
  36847. {
  36848. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36849. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36850. {
  36851. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36852. }
  36853. if (useSpacesForTabs)
  36854. {
  36855. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36856. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36857. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36858. }
  36859. else
  36860. {
  36861. insertTextAtCaret ("\t");
  36862. }
  36863. }
  36864. void CodeEditorComponent::cut()
  36865. {
  36866. insertTextAtCaret (String::empty);
  36867. }
  36868. void CodeEditorComponent::copy()
  36869. {
  36870. newTransaction();
  36871. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36872. if (selection.isNotEmpty())
  36873. SystemClipboard::copyTextToClipboard (selection);
  36874. }
  36875. void CodeEditorComponent::copyThenCut()
  36876. {
  36877. copy();
  36878. cut();
  36879. newTransaction();
  36880. }
  36881. void CodeEditorComponent::paste()
  36882. {
  36883. newTransaction();
  36884. const String clip (SystemClipboard::getTextFromClipboard());
  36885. if (clip.isNotEmpty())
  36886. insertTextAtCaret (clip);
  36887. newTransaction();
  36888. }
  36889. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36890. {
  36891. newTransaction();
  36892. if (moveInWholeWordSteps)
  36893. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36894. else
  36895. moveCaretTo (caretPos.movedBy (-1), selecting);
  36896. }
  36897. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36898. {
  36899. newTransaction();
  36900. if (moveInWholeWordSteps)
  36901. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36902. else
  36903. moveCaretTo (caretPos.movedBy (1), selecting);
  36904. }
  36905. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36906. {
  36907. CodeDocument::Position pos (caretPos);
  36908. const int newLineNum = pos.getLineNumber() + delta;
  36909. if (columnToTryToMaintain < 0)
  36910. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36911. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36912. const int colToMaintain = columnToTryToMaintain;
  36913. moveCaretTo (pos, selecting);
  36914. columnToTryToMaintain = colToMaintain;
  36915. }
  36916. void CodeEditorComponent::cursorDown (const bool selecting)
  36917. {
  36918. newTransaction();
  36919. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36920. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36921. else
  36922. moveLineDelta (1, selecting);
  36923. }
  36924. void CodeEditorComponent::cursorUp (const bool selecting)
  36925. {
  36926. newTransaction();
  36927. if (caretPos.getLineNumber() == 0)
  36928. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36929. else
  36930. moveLineDelta (-1, selecting);
  36931. }
  36932. void CodeEditorComponent::pageDown (const bool selecting)
  36933. {
  36934. newTransaction();
  36935. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36936. moveLineDelta (linesOnScreen, selecting);
  36937. }
  36938. void CodeEditorComponent::pageUp (const bool selecting)
  36939. {
  36940. newTransaction();
  36941. scrollBy (-linesOnScreen);
  36942. moveLineDelta (-linesOnScreen, selecting);
  36943. }
  36944. void CodeEditorComponent::scrollUp()
  36945. {
  36946. newTransaction();
  36947. scrollBy (1);
  36948. if (caretPos.getLineNumber() < firstLineOnScreen)
  36949. moveLineDelta (1, false);
  36950. }
  36951. void CodeEditorComponent::scrollDown()
  36952. {
  36953. newTransaction();
  36954. scrollBy (-1);
  36955. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36956. moveLineDelta (-1, false);
  36957. }
  36958. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36959. {
  36960. newTransaction();
  36961. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36962. }
  36963. namespace CodeEditorHelpers
  36964. {
  36965. int findFirstNonWhitespaceChar (const String& line) throw()
  36966. {
  36967. const int len = line.length();
  36968. for (int i = 0; i < len; ++i)
  36969. if (! CharacterFunctions::isWhitespace (line [i]))
  36970. return i;
  36971. return 0;
  36972. }
  36973. }
  36974. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36975. {
  36976. newTransaction();
  36977. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  36978. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36979. index = 0;
  36980. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36981. }
  36982. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36983. {
  36984. newTransaction();
  36985. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36986. }
  36987. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36988. {
  36989. newTransaction();
  36990. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36991. }
  36992. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36993. {
  36994. if (moveInWholeWordSteps)
  36995. {
  36996. cut(); // in case something is already highlighted
  36997. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36998. }
  36999. else
  37000. {
  37001. if (selectionStart == selectionEnd)
  37002. selectionStart.moveBy (-1);
  37003. }
  37004. cut();
  37005. }
  37006. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37007. {
  37008. if (moveInWholeWordSteps)
  37009. {
  37010. cut(); // in case something is already highlighted
  37011. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37012. }
  37013. else
  37014. {
  37015. if (selectionStart == selectionEnd)
  37016. selectionEnd.moveBy (1);
  37017. else
  37018. newTransaction();
  37019. }
  37020. cut();
  37021. }
  37022. void CodeEditorComponent::selectAll()
  37023. {
  37024. newTransaction();
  37025. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37026. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37027. }
  37028. void CodeEditorComponent::undo()
  37029. {
  37030. document.undo();
  37031. scrollToKeepCaretOnScreen();
  37032. }
  37033. void CodeEditorComponent::redo()
  37034. {
  37035. document.redo();
  37036. scrollToKeepCaretOnScreen();
  37037. }
  37038. void CodeEditorComponent::newTransaction()
  37039. {
  37040. document.newTransaction();
  37041. startTimer (600);
  37042. }
  37043. void CodeEditorComponent::timerCallback()
  37044. {
  37045. newTransaction();
  37046. }
  37047. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37048. {
  37049. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37050. }
  37051. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37052. {
  37053. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37054. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37055. }
  37056. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37057. {
  37058. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37059. CodeDocument::Position (&document, range.getEnd()));
  37060. }
  37061. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37062. {
  37063. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37064. const bool shiftDown = key.getModifiers().isShiftDown();
  37065. if (key.isKeyCode (KeyPress::leftKey))
  37066. {
  37067. cursorLeft (moveInWholeWordSteps, shiftDown);
  37068. }
  37069. else if (key.isKeyCode (KeyPress::rightKey))
  37070. {
  37071. cursorRight (moveInWholeWordSteps, shiftDown);
  37072. }
  37073. else if (key.isKeyCode (KeyPress::upKey))
  37074. {
  37075. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37076. scrollDown();
  37077. #if JUCE_MAC
  37078. else if (key.getModifiers().isCommandDown())
  37079. goToStartOfDocument (shiftDown);
  37080. #endif
  37081. else
  37082. cursorUp (shiftDown);
  37083. }
  37084. else if (key.isKeyCode (KeyPress::downKey))
  37085. {
  37086. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37087. scrollUp();
  37088. #if JUCE_MAC
  37089. else if (key.getModifiers().isCommandDown())
  37090. goToEndOfDocument (shiftDown);
  37091. #endif
  37092. else
  37093. cursorDown (shiftDown);
  37094. }
  37095. else if (key.isKeyCode (KeyPress::pageDownKey))
  37096. {
  37097. pageDown (shiftDown);
  37098. }
  37099. else if (key.isKeyCode (KeyPress::pageUpKey))
  37100. {
  37101. pageUp (shiftDown);
  37102. }
  37103. else if (key.isKeyCode (KeyPress::homeKey))
  37104. {
  37105. if (moveInWholeWordSteps)
  37106. goToStartOfDocument (shiftDown);
  37107. else
  37108. goToStartOfLine (shiftDown);
  37109. }
  37110. else if (key.isKeyCode (KeyPress::endKey))
  37111. {
  37112. if (moveInWholeWordSteps)
  37113. goToEndOfDocument (shiftDown);
  37114. else
  37115. goToEndOfLine (shiftDown);
  37116. }
  37117. else if (key.isKeyCode (KeyPress::backspaceKey))
  37118. {
  37119. backspace (moveInWholeWordSteps);
  37120. }
  37121. else if (key.isKeyCode (KeyPress::deleteKey))
  37122. {
  37123. deleteForward (moveInWholeWordSteps);
  37124. }
  37125. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37126. {
  37127. copy();
  37128. }
  37129. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37130. {
  37131. copyThenCut();
  37132. }
  37133. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37134. {
  37135. paste();
  37136. }
  37137. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37138. {
  37139. undo();
  37140. }
  37141. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37142. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37143. {
  37144. redo();
  37145. }
  37146. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37147. {
  37148. selectAll();
  37149. }
  37150. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37151. {
  37152. insertTabAtCaret();
  37153. }
  37154. else if (key == KeyPress::returnKey)
  37155. {
  37156. newTransaction();
  37157. insertTextAtCaret (document.getNewLineCharacters());
  37158. }
  37159. else if (key.isKeyCode (KeyPress::escapeKey))
  37160. {
  37161. newTransaction();
  37162. }
  37163. else if (key.getTextCharacter() >= ' ')
  37164. {
  37165. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37166. }
  37167. else
  37168. {
  37169. return false;
  37170. }
  37171. return true;
  37172. }
  37173. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37174. {
  37175. newTransaction();
  37176. dragType = notDragging;
  37177. if (! e.mods.isPopupMenu())
  37178. {
  37179. beginDragAutoRepeat (100);
  37180. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37181. }
  37182. else
  37183. {
  37184. /*PopupMenu m;
  37185. addPopupMenuItems (m, &e);
  37186. const int result = m.show();
  37187. if (result != 0)
  37188. performPopupMenuAction (result);
  37189. */
  37190. }
  37191. }
  37192. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37193. {
  37194. if (! e.mods.isPopupMenu())
  37195. moveCaretTo (getPositionAt (e.x, e.y), true);
  37196. }
  37197. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37198. {
  37199. newTransaction();
  37200. beginDragAutoRepeat (0);
  37201. dragType = notDragging;
  37202. }
  37203. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37204. {
  37205. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37206. CodeDocument::Position tokenEnd (tokenStart);
  37207. if (e.getNumberOfClicks() > 2)
  37208. {
  37209. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37210. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37211. }
  37212. else
  37213. {
  37214. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37215. tokenEnd.moveBy (1);
  37216. tokenStart = tokenEnd;
  37217. while (tokenStart.getIndexInLine() > 0
  37218. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37219. tokenStart.moveBy (-1);
  37220. }
  37221. moveCaretTo (tokenEnd, false);
  37222. moveCaretTo (tokenStart, true);
  37223. }
  37224. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37225. {
  37226. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37227. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37228. {
  37229. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37230. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37231. }
  37232. else
  37233. {
  37234. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37235. }
  37236. }
  37237. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37238. {
  37239. if (scrollBarThatHasMoved == &verticalScrollBar)
  37240. scrollToLineInternal ((int) newRangeStart);
  37241. else
  37242. scrollToColumnInternal (newRangeStart);
  37243. }
  37244. void CodeEditorComponent::focusGained (FocusChangeType)
  37245. {
  37246. caret->updatePosition();
  37247. }
  37248. void CodeEditorComponent::focusLost (FocusChangeType)
  37249. {
  37250. caret->updatePosition();
  37251. }
  37252. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37253. {
  37254. useSpacesForTabs = insertSpaces;
  37255. if (spacesPerTab != numSpaces)
  37256. {
  37257. spacesPerTab = numSpaces;
  37258. triggerAsyncUpdate();
  37259. }
  37260. }
  37261. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37262. {
  37263. const String line (document.getLine (lineNum));
  37264. jassert (index <= line.length());
  37265. int col = 0;
  37266. for (int i = 0; i < index; ++i)
  37267. {
  37268. if (line[i] != '\t')
  37269. ++col;
  37270. else
  37271. col += getTabSize() - (col % getTabSize());
  37272. }
  37273. return col;
  37274. }
  37275. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37276. {
  37277. const String line (document.getLine (lineNum));
  37278. const int lineLength = line.length();
  37279. int i, col = 0;
  37280. for (i = 0; i < lineLength; ++i)
  37281. {
  37282. if (line[i] != '\t')
  37283. ++col;
  37284. else
  37285. col += getTabSize() - (col % getTabSize());
  37286. if (col > column)
  37287. break;
  37288. }
  37289. return i;
  37290. }
  37291. void CodeEditorComponent::setFont (const Font& newFont)
  37292. {
  37293. font = newFont;
  37294. charWidth = font.getStringWidthFloat ("0");
  37295. lineHeight = roundToInt (font.getHeight());
  37296. resized();
  37297. }
  37298. void CodeEditorComponent::resetToDefaultColours()
  37299. {
  37300. coloursForTokenCategories.clear();
  37301. if (codeTokeniser != 0)
  37302. {
  37303. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37304. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37305. }
  37306. }
  37307. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37308. {
  37309. jassert (tokenType < 256);
  37310. while (coloursForTokenCategories.size() < tokenType)
  37311. coloursForTokenCategories.add (Colours::black);
  37312. coloursForTokenCategories.set (tokenType, colour);
  37313. repaint();
  37314. }
  37315. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37316. {
  37317. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37318. return findColour (CodeEditorComponent::defaultTextColourId);
  37319. return coloursForTokenCategories.getReference (tokenType);
  37320. }
  37321. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37322. {
  37323. int i;
  37324. for (i = cachedIterators.size(); --i >= 0;)
  37325. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37326. break;
  37327. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37328. }
  37329. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37330. {
  37331. const int maxNumCachedPositions = 5000;
  37332. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37333. if (cachedIterators.size() == 0)
  37334. cachedIterators.add (new CodeDocument::Iterator (&document));
  37335. if (codeTokeniser == 0)
  37336. return;
  37337. for (;;)
  37338. {
  37339. CodeDocument::Iterator* last = cachedIterators.getLast();
  37340. if (last->getLine() >= maxLineNum)
  37341. break;
  37342. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37343. cachedIterators.add (t);
  37344. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37345. for (;;)
  37346. {
  37347. codeTokeniser->readNextToken (*t);
  37348. if (t->getLine() >= targetLine)
  37349. break;
  37350. if (t->isEOF())
  37351. return;
  37352. }
  37353. }
  37354. }
  37355. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37356. {
  37357. if (codeTokeniser == 0)
  37358. return;
  37359. for (int i = cachedIterators.size(); --i >= 0;)
  37360. {
  37361. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37362. if (t->getPosition() <= position)
  37363. {
  37364. source = *t;
  37365. break;
  37366. }
  37367. }
  37368. while (source.getPosition() < position)
  37369. {
  37370. const CodeDocument::Iterator original (source);
  37371. codeTokeniser->readNextToken (source);
  37372. if (source.getPosition() > position || source.isEOF())
  37373. {
  37374. source = original;
  37375. break;
  37376. }
  37377. }
  37378. }
  37379. END_JUCE_NAMESPACE
  37380. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37381. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37382. BEGIN_JUCE_NAMESPACE
  37383. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37384. {
  37385. }
  37386. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37387. {
  37388. }
  37389. namespace CppTokeniser
  37390. {
  37391. bool isIdentifierStart (const juce_wchar c) throw()
  37392. {
  37393. return CharacterFunctions::isLetter (c)
  37394. || c == '_' || c == '@';
  37395. }
  37396. bool isIdentifierBody (const juce_wchar c) throw()
  37397. {
  37398. return CharacterFunctions::isLetterOrDigit (c)
  37399. || c == '_' || c == '@';
  37400. }
  37401. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37402. {
  37403. static const char* const keywords2Char[] =
  37404. { "if", "do", "or", "id", 0 };
  37405. static const char* const keywords3Char[] =
  37406. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37407. static const char* const keywords4Char[] =
  37408. { "bool", "void", "this", "true", "long", "else", "char",
  37409. "enum", "case", "goto", "auto", 0 };
  37410. static const char* const keywords5Char[] =
  37411. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37412. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37413. static const char* const keywords6Char[] =
  37414. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37415. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37416. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37417. static const char* const keywordsOther[] =
  37418. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37419. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37420. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37421. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37422. "@private", "@property", "@protected", "@class", 0 };
  37423. const char* const* k;
  37424. switch (tokenLength)
  37425. {
  37426. case 2: k = keywords2Char; break;
  37427. case 3: k = keywords3Char; break;
  37428. case 4: k = keywords4Char; break;
  37429. case 5: k = keywords5Char; break;
  37430. case 6: k = keywords6Char; break;
  37431. default:
  37432. if (tokenLength < 2 || tokenLength > 16)
  37433. return false;
  37434. k = keywordsOther;
  37435. break;
  37436. }
  37437. int i = 0;
  37438. while (k[i] != 0)
  37439. {
  37440. if (k[i][0] == (char) token[0] && CharPointer_UTF8 (k[i]).compare (CharPointer_UTF32 (token)) == 0)
  37441. return true;
  37442. ++i;
  37443. }
  37444. return false;
  37445. }
  37446. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37447. {
  37448. int tokenLength = 0;
  37449. juce_wchar possibleIdentifier [19];
  37450. while (isIdentifierBody (source.peekNextChar()))
  37451. {
  37452. const juce_wchar c = source.nextChar();
  37453. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37454. possibleIdentifier [tokenLength] = c;
  37455. ++tokenLength;
  37456. }
  37457. if (tokenLength > 1 && tokenLength <= 16)
  37458. {
  37459. possibleIdentifier [tokenLength] = 0;
  37460. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37461. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37462. }
  37463. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37464. }
  37465. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37466. {
  37467. const juce_wchar c = source.peekNextChar();
  37468. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37469. source.skip();
  37470. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37471. return false;
  37472. return true;
  37473. }
  37474. bool isHexDigit (const juce_wchar c) throw()
  37475. {
  37476. return (c >= '0' && c <= '9')
  37477. || (c >= 'a' && c <= 'f')
  37478. || (c >= 'A' && c <= 'F');
  37479. }
  37480. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37481. {
  37482. if (source.nextChar() != '0')
  37483. return false;
  37484. juce_wchar c = source.nextChar();
  37485. if (c != 'x' && c != 'X')
  37486. return false;
  37487. int numDigits = 0;
  37488. while (isHexDigit (source.peekNextChar()))
  37489. {
  37490. ++numDigits;
  37491. source.skip();
  37492. }
  37493. if (numDigits == 0)
  37494. return false;
  37495. return skipNumberSuffix (source);
  37496. }
  37497. bool isOctalDigit (const juce_wchar c) throw()
  37498. {
  37499. return c >= '0' && c <= '7';
  37500. }
  37501. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37502. {
  37503. if (source.nextChar() != '0')
  37504. return false;
  37505. if (! isOctalDigit (source.nextChar()))
  37506. return false;
  37507. while (isOctalDigit (source.peekNextChar()))
  37508. source.skip();
  37509. return skipNumberSuffix (source);
  37510. }
  37511. bool isDecimalDigit (const juce_wchar c) throw()
  37512. {
  37513. return c >= '0' && c <= '9';
  37514. }
  37515. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37516. {
  37517. int numChars = 0;
  37518. while (isDecimalDigit (source.peekNextChar()))
  37519. {
  37520. ++numChars;
  37521. source.skip();
  37522. }
  37523. if (numChars == 0)
  37524. return false;
  37525. return skipNumberSuffix (source);
  37526. }
  37527. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37528. {
  37529. int numDigits = 0;
  37530. while (isDecimalDigit (source.peekNextChar()))
  37531. {
  37532. source.skip();
  37533. ++numDigits;
  37534. }
  37535. const bool hasPoint = (source.peekNextChar() == '.');
  37536. if (hasPoint)
  37537. {
  37538. source.skip();
  37539. while (isDecimalDigit (source.peekNextChar()))
  37540. {
  37541. source.skip();
  37542. ++numDigits;
  37543. }
  37544. }
  37545. if (numDigits == 0)
  37546. return false;
  37547. juce_wchar c = source.peekNextChar();
  37548. const bool hasExponent = (c == 'e' || c == 'E');
  37549. if (hasExponent)
  37550. {
  37551. source.skip();
  37552. c = source.peekNextChar();
  37553. if (c == '+' || c == '-')
  37554. source.skip();
  37555. int numExpDigits = 0;
  37556. while (isDecimalDigit (source.peekNextChar()))
  37557. {
  37558. source.skip();
  37559. ++numExpDigits;
  37560. }
  37561. if (numExpDigits == 0)
  37562. return false;
  37563. }
  37564. c = source.peekNextChar();
  37565. if (c == 'f' || c == 'F')
  37566. source.skip();
  37567. else if (! (hasExponent || hasPoint))
  37568. return false;
  37569. return true;
  37570. }
  37571. int parseNumber (CodeDocument::Iterator& source)
  37572. {
  37573. const CodeDocument::Iterator original (source);
  37574. if (parseFloatLiteral (source))
  37575. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37576. source = original;
  37577. if (parseHexLiteral (source))
  37578. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37579. source = original;
  37580. if (parseOctalLiteral (source))
  37581. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37582. source = original;
  37583. if (parseDecimalLiteral (source))
  37584. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37585. source = original;
  37586. source.skip();
  37587. return CPlusPlusCodeTokeniser::tokenType_error;
  37588. }
  37589. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37590. {
  37591. const juce_wchar quote = source.nextChar();
  37592. for (;;)
  37593. {
  37594. const juce_wchar c = source.nextChar();
  37595. if (c == quote || c == 0)
  37596. break;
  37597. if (c == '\\')
  37598. source.skip();
  37599. }
  37600. }
  37601. void skipComment (CodeDocument::Iterator& source) throw()
  37602. {
  37603. bool lastWasStar = false;
  37604. for (;;)
  37605. {
  37606. const juce_wchar c = source.nextChar();
  37607. if (c == 0 || (c == '/' && lastWasStar))
  37608. break;
  37609. lastWasStar = (c == '*');
  37610. }
  37611. }
  37612. }
  37613. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37614. {
  37615. int result = tokenType_error;
  37616. source.skipWhitespace();
  37617. juce_wchar firstChar = source.peekNextChar();
  37618. switch (firstChar)
  37619. {
  37620. case 0:
  37621. source.skip();
  37622. break;
  37623. case '0':
  37624. case '1':
  37625. case '2':
  37626. case '3':
  37627. case '4':
  37628. case '5':
  37629. case '6':
  37630. case '7':
  37631. case '8':
  37632. case '9':
  37633. result = CppTokeniser::parseNumber (source);
  37634. break;
  37635. case '.':
  37636. result = CppTokeniser::parseNumber (source);
  37637. if (result == tokenType_error)
  37638. result = tokenType_punctuation;
  37639. break;
  37640. case ',':
  37641. case ';':
  37642. case ':':
  37643. source.skip();
  37644. result = tokenType_punctuation;
  37645. break;
  37646. case '(':
  37647. case ')':
  37648. case '{':
  37649. case '}':
  37650. case '[':
  37651. case ']':
  37652. source.skip();
  37653. result = tokenType_bracket;
  37654. break;
  37655. case '"':
  37656. case '\'':
  37657. CppTokeniser::skipQuotedString (source);
  37658. result = tokenType_stringLiteral;
  37659. break;
  37660. case '+':
  37661. result = tokenType_operator;
  37662. source.skip();
  37663. if (source.peekNextChar() == '+')
  37664. source.skip();
  37665. else if (source.peekNextChar() == '=')
  37666. source.skip();
  37667. break;
  37668. case '-':
  37669. source.skip();
  37670. result = CppTokeniser::parseNumber (source);
  37671. if (result == tokenType_error)
  37672. {
  37673. result = tokenType_operator;
  37674. if (source.peekNextChar() == '-')
  37675. source.skip();
  37676. else if (source.peekNextChar() == '=')
  37677. source.skip();
  37678. }
  37679. break;
  37680. case '*':
  37681. case '%':
  37682. case '=':
  37683. case '!':
  37684. result = tokenType_operator;
  37685. source.skip();
  37686. if (source.peekNextChar() == '=')
  37687. source.skip();
  37688. break;
  37689. case '/':
  37690. result = tokenType_operator;
  37691. source.skip();
  37692. if (source.peekNextChar() == '=')
  37693. {
  37694. source.skip();
  37695. }
  37696. else if (source.peekNextChar() == '/')
  37697. {
  37698. result = tokenType_comment;
  37699. source.skipToEndOfLine();
  37700. }
  37701. else if (source.peekNextChar() == '*')
  37702. {
  37703. source.skip();
  37704. result = tokenType_comment;
  37705. CppTokeniser::skipComment (source);
  37706. }
  37707. break;
  37708. case '?':
  37709. case '~':
  37710. source.skip();
  37711. result = tokenType_operator;
  37712. break;
  37713. case '<':
  37714. source.skip();
  37715. result = tokenType_operator;
  37716. if (source.peekNextChar() == '=')
  37717. {
  37718. source.skip();
  37719. }
  37720. else if (source.peekNextChar() == '<')
  37721. {
  37722. source.skip();
  37723. if (source.peekNextChar() == '=')
  37724. source.skip();
  37725. }
  37726. break;
  37727. case '>':
  37728. source.skip();
  37729. result = tokenType_operator;
  37730. if (source.peekNextChar() == '=')
  37731. {
  37732. source.skip();
  37733. }
  37734. else if (source.peekNextChar() == '<')
  37735. {
  37736. source.skip();
  37737. if (source.peekNextChar() == '=')
  37738. source.skip();
  37739. }
  37740. break;
  37741. case '|':
  37742. source.skip();
  37743. result = tokenType_operator;
  37744. if (source.peekNextChar() == '=')
  37745. {
  37746. source.skip();
  37747. }
  37748. else if (source.peekNextChar() == '|')
  37749. {
  37750. source.skip();
  37751. if (source.peekNextChar() == '=')
  37752. source.skip();
  37753. }
  37754. break;
  37755. case '&':
  37756. source.skip();
  37757. result = tokenType_operator;
  37758. if (source.peekNextChar() == '=')
  37759. {
  37760. source.skip();
  37761. }
  37762. else if (source.peekNextChar() == '&')
  37763. {
  37764. source.skip();
  37765. if (source.peekNextChar() == '=')
  37766. source.skip();
  37767. }
  37768. break;
  37769. case '^':
  37770. source.skip();
  37771. result = tokenType_operator;
  37772. if (source.peekNextChar() == '=')
  37773. {
  37774. source.skip();
  37775. }
  37776. else if (source.peekNextChar() == '^')
  37777. {
  37778. source.skip();
  37779. if (source.peekNextChar() == '=')
  37780. source.skip();
  37781. }
  37782. break;
  37783. case '#':
  37784. result = tokenType_preprocessor;
  37785. source.skipToEndOfLine();
  37786. break;
  37787. default:
  37788. if (CppTokeniser::isIdentifierStart (firstChar))
  37789. result = CppTokeniser::parseIdentifier (source);
  37790. else
  37791. source.skip();
  37792. break;
  37793. }
  37794. return result;
  37795. }
  37796. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37797. {
  37798. const char* const types[] =
  37799. {
  37800. "Error",
  37801. "Comment",
  37802. "C++ keyword",
  37803. "Identifier",
  37804. "Integer literal",
  37805. "Float literal",
  37806. "String literal",
  37807. "Operator",
  37808. "Bracket",
  37809. "Punctuation",
  37810. "Preprocessor line",
  37811. 0
  37812. };
  37813. return StringArray (types);
  37814. }
  37815. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37816. {
  37817. const uint32 colours[] =
  37818. {
  37819. 0xffcc0000, // error
  37820. 0xff00aa00, // comment
  37821. 0xff0000cc, // keyword
  37822. 0xff000000, // identifier
  37823. 0xff880000, // int literal
  37824. 0xff885500, // float literal
  37825. 0xff990099, // string literal
  37826. 0xff225500, // operator
  37827. 0xff000055, // bracket
  37828. 0xff004400, // punctuation
  37829. 0xff660000 // preprocessor
  37830. };
  37831. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37832. return Colour (colours [tokenType]);
  37833. return Colours::black;
  37834. }
  37835. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37836. {
  37837. return CppTokeniser::isReservedKeyword (token, token.length());
  37838. }
  37839. END_JUCE_NAMESPACE
  37840. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37841. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37842. BEGIN_JUCE_NAMESPACE
  37843. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  37844. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  37845. {
  37846. }
  37847. bool ComboBox::ItemInfo::isSeparator() const throw()
  37848. {
  37849. return name.isEmpty();
  37850. }
  37851. bool ComboBox::ItemInfo::isRealItem() const throw()
  37852. {
  37853. return ! (isHeading || name.isEmpty());
  37854. }
  37855. ComboBox::ComboBox (const String& name)
  37856. : Component (name),
  37857. lastCurrentId (0),
  37858. isButtonDown (false),
  37859. separatorPending (false),
  37860. menuActive (false),
  37861. noChoicesMessage (TRANS("(no choices)"))
  37862. {
  37863. setRepaintsOnMouseActivity (true);
  37864. lookAndFeelChanged();
  37865. currentId.addListener (this);
  37866. }
  37867. ComboBox::~ComboBox()
  37868. {
  37869. currentId.removeListener (this);
  37870. if (menuActive)
  37871. PopupMenu::dismissAllActiveMenus();
  37872. label = 0;
  37873. }
  37874. void ComboBox::setEditableText (const bool isEditable)
  37875. {
  37876. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37877. {
  37878. label->setEditable (isEditable, isEditable, false);
  37879. setWantsKeyboardFocus (! isEditable);
  37880. resized();
  37881. }
  37882. }
  37883. bool ComboBox::isTextEditable() const throw()
  37884. {
  37885. return label->isEditable();
  37886. }
  37887. void ComboBox::setJustificationType (const Justification& justification)
  37888. {
  37889. label->setJustificationType (justification);
  37890. }
  37891. const Justification ComboBox::getJustificationType() const throw()
  37892. {
  37893. return label->getJustificationType();
  37894. }
  37895. void ComboBox::setTooltip (const String& newTooltip)
  37896. {
  37897. SettableTooltipClient::setTooltip (newTooltip);
  37898. label->setTooltip (newTooltip);
  37899. }
  37900. void ComboBox::addItem (const String& newItemText, const int newItemId)
  37901. {
  37902. // you can't add empty strings to the list..
  37903. jassert (newItemText.isNotEmpty());
  37904. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37905. jassert (newItemId != 0);
  37906. // you shouldn't use duplicate item IDs!
  37907. jassert (getItemForId (newItemId) == 0);
  37908. if (newItemText.isNotEmpty() && newItemId != 0)
  37909. {
  37910. if (separatorPending)
  37911. {
  37912. separatorPending = false;
  37913. items.add (new ItemInfo (String::empty, 0, false, false));
  37914. }
  37915. items.add (new ItemInfo (newItemText, newItemId, true, false));
  37916. }
  37917. }
  37918. void ComboBox::addSeparator()
  37919. {
  37920. separatorPending = (items.size() > 0);
  37921. }
  37922. void ComboBox::addSectionHeading (const String& headingName)
  37923. {
  37924. // you can't add empty strings to the list..
  37925. jassert (headingName.isNotEmpty());
  37926. if (headingName.isNotEmpty())
  37927. {
  37928. if (separatorPending)
  37929. {
  37930. separatorPending = false;
  37931. items.add (new ItemInfo (String::empty, 0, false, false));
  37932. }
  37933. items.add (new ItemInfo (headingName, 0, true, true));
  37934. }
  37935. }
  37936. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  37937. {
  37938. ItemInfo* const item = getItemForId (itemId);
  37939. if (item != 0)
  37940. item->isEnabled = shouldBeEnabled;
  37941. }
  37942. bool ComboBox::isItemEnabled (int itemId) const throw()
  37943. {
  37944. const ItemInfo* const item = getItemForId (itemId);
  37945. return item != 0 && item->isEnabled;
  37946. }
  37947. void ComboBox::changeItemText (const int itemId, const String& newText)
  37948. {
  37949. ItemInfo* const item = getItemForId (itemId);
  37950. jassert (item != 0);
  37951. if (item != 0)
  37952. item->name = newText;
  37953. }
  37954. void ComboBox::clear (const bool dontSendChangeMessage)
  37955. {
  37956. items.clear();
  37957. separatorPending = false;
  37958. if (! label->isEditable())
  37959. setSelectedItemIndex (-1, dontSendChangeMessage);
  37960. }
  37961. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37962. {
  37963. if (itemId != 0)
  37964. {
  37965. for (int i = items.size(); --i >= 0;)
  37966. if (items.getUnchecked(i)->itemId == itemId)
  37967. return items.getUnchecked(i);
  37968. }
  37969. return 0;
  37970. }
  37971. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37972. {
  37973. for (int n = 0, i = 0; i < items.size(); ++i)
  37974. {
  37975. ItemInfo* const item = items.getUnchecked(i);
  37976. if (item->isRealItem())
  37977. if (n++ == index)
  37978. return item;
  37979. }
  37980. return 0;
  37981. }
  37982. int ComboBox::getNumItems() const throw()
  37983. {
  37984. int n = 0;
  37985. for (int i = items.size(); --i >= 0;)
  37986. if (items.getUnchecked(i)->isRealItem())
  37987. ++n;
  37988. return n;
  37989. }
  37990. const String ComboBox::getItemText (const int index) const
  37991. {
  37992. const ItemInfo* const item = getItemForIndex (index);
  37993. return item != 0 ? item->name : String::empty;
  37994. }
  37995. int ComboBox::getItemId (const int index) const throw()
  37996. {
  37997. const ItemInfo* const item = getItemForIndex (index);
  37998. return item != 0 ? item->itemId : 0;
  37999. }
  38000. int ComboBox::indexOfItemId (const int itemId) const throw()
  38001. {
  38002. for (int n = 0, i = 0; i < items.size(); ++i)
  38003. {
  38004. const ItemInfo* const item = items.getUnchecked(i);
  38005. if (item->isRealItem())
  38006. {
  38007. if (item->itemId == itemId)
  38008. return n;
  38009. ++n;
  38010. }
  38011. }
  38012. return -1;
  38013. }
  38014. int ComboBox::getSelectedItemIndex() const
  38015. {
  38016. int index = indexOfItemId (currentId.getValue());
  38017. if (getText() != getItemText (index))
  38018. index = -1;
  38019. return index;
  38020. }
  38021. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38022. {
  38023. setSelectedId (getItemId (index), dontSendChangeMessage);
  38024. }
  38025. int ComboBox::getSelectedId() const throw()
  38026. {
  38027. const ItemInfo* const item = getItemForId (currentId.getValue());
  38028. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38029. }
  38030. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38031. {
  38032. const ItemInfo* const item = getItemForId (newItemId);
  38033. const String newItemText (item != 0 ? item->name : String::empty);
  38034. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38035. {
  38036. if (! dontSendChangeMessage)
  38037. triggerAsyncUpdate();
  38038. label->setText (newItemText, false);
  38039. lastCurrentId = newItemId;
  38040. currentId = newItemId;
  38041. repaint(); // for the benefit of the 'none selected' text
  38042. }
  38043. }
  38044. bool ComboBox::selectIfEnabled (const int index)
  38045. {
  38046. const ItemInfo* const item = getItemForIndex (index);
  38047. if (item != 0 && item->isEnabled)
  38048. {
  38049. setSelectedItemIndex (index);
  38050. return true;
  38051. }
  38052. return false;
  38053. }
  38054. void ComboBox::valueChanged (Value&)
  38055. {
  38056. if (lastCurrentId != (int) currentId.getValue())
  38057. setSelectedId (currentId.getValue(), false);
  38058. }
  38059. const String ComboBox::getText() const
  38060. {
  38061. return label->getText();
  38062. }
  38063. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38064. {
  38065. for (int i = items.size(); --i >= 0;)
  38066. {
  38067. const ItemInfo* const item = items.getUnchecked(i);
  38068. if (item->isRealItem()
  38069. && item->name == newText)
  38070. {
  38071. setSelectedId (item->itemId, dontSendChangeMessage);
  38072. return;
  38073. }
  38074. }
  38075. lastCurrentId = 0;
  38076. currentId = 0;
  38077. if (label->getText() != newText)
  38078. {
  38079. label->setText (newText, false);
  38080. if (! dontSendChangeMessage)
  38081. triggerAsyncUpdate();
  38082. }
  38083. repaint();
  38084. }
  38085. void ComboBox::showEditor()
  38086. {
  38087. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38088. label->showEditor();
  38089. }
  38090. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38091. {
  38092. if (textWhenNothingSelected != newMessage)
  38093. {
  38094. textWhenNothingSelected = newMessage;
  38095. repaint();
  38096. }
  38097. }
  38098. const String ComboBox::getTextWhenNothingSelected() const
  38099. {
  38100. return textWhenNothingSelected;
  38101. }
  38102. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38103. {
  38104. noChoicesMessage = newMessage;
  38105. }
  38106. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38107. {
  38108. return noChoicesMessage;
  38109. }
  38110. void ComboBox::paint (Graphics& g)
  38111. {
  38112. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38113. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38114. *this);
  38115. if (textWhenNothingSelected.isNotEmpty()
  38116. && label->getText().isEmpty()
  38117. && ! label->isBeingEdited())
  38118. {
  38119. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38120. g.setFont (label->getFont());
  38121. g.drawFittedText (textWhenNothingSelected,
  38122. label->getX() + 2, label->getY() + 1,
  38123. label->getWidth() - 4, label->getHeight() - 2,
  38124. label->getJustificationType(),
  38125. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38126. }
  38127. }
  38128. void ComboBox::resized()
  38129. {
  38130. if (getHeight() > 0 && getWidth() > 0)
  38131. getLookAndFeel().positionComboBoxText (*this, *label);
  38132. }
  38133. void ComboBox::enablementChanged()
  38134. {
  38135. repaint();
  38136. }
  38137. void ComboBox::lookAndFeelChanged()
  38138. {
  38139. repaint();
  38140. {
  38141. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38142. jassert (newLabel != 0);
  38143. if (label != 0)
  38144. {
  38145. newLabel->setEditable (label->isEditable());
  38146. newLabel->setJustificationType (label->getJustificationType());
  38147. newLabel->setTooltip (label->getTooltip());
  38148. newLabel->setText (label->getText(), false);
  38149. }
  38150. label = newLabel;
  38151. }
  38152. addAndMakeVisible (label);
  38153. label->addListener (this);
  38154. label->addMouseListener (this, false);
  38155. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38156. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38157. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38158. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38159. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38160. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38161. resized();
  38162. }
  38163. void ComboBox::colourChanged()
  38164. {
  38165. lookAndFeelChanged();
  38166. }
  38167. bool ComboBox::keyPressed (const KeyPress& key)
  38168. {
  38169. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38170. {
  38171. int index = getSelectedItemIndex() - 1;
  38172. while (index >= 0 && ! selectIfEnabled (index))
  38173. --index;
  38174. return true;
  38175. }
  38176. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38177. {
  38178. int index = getSelectedItemIndex() + 1;
  38179. while (index < getNumItems() && ! selectIfEnabled (index))
  38180. ++index;
  38181. return true;
  38182. }
  38183. else if (key.isKeyCode (KeyPress::returnKey))
  38184. {
  38185. showPopup();
  38186. return true;
  38187. }
  38188. return false;
  38189. }
  38190. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38191. {
  38192. // only forward key events that aren't used by this component
  38193. return isKeyDown
  38194. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38195. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38196. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38197. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38198. }
  38199. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38200. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38201. void ComboBox::labelTextChanged (Label*)
  38202. {
  38203. triggerAsyncUpdate();
  38204. }
  38205. class ComboBox::Callback : public ModalComponentManager::Callback
  38206. {
  38207. public:
  38208. Callback (ComboBox* const box_)
  38209. : box (box_)
  38210. {
  38211. }
  38212. void modalStateFinished (int returnValue)
  38213. {
  38214. if (box != 0)
  38215. {
  38216. box->menuActive = false;
  38217. if (returnValue != 0)
  38218. box->setSelectedId (returnValue);
  38219. }
  38220. }
  38221. private:
  38222. Component::SafePointer<ComboBox> box;
  38223. JUCE_DECLARE_NON_COPYABLE (Callback);
  38224. };
  38225. void ComboBox::showPopup()
  38226. {
  38227. if (! menuActive)
  38228. {
  38229. const int selectedId = getSelectedId();
  38230. PopupMenu menu;
  38231. menu.setLookAndFeel (&getLookAndFeel());
  38232. for (int i = 0; i < items.size(); ++i)
  38233. {
  38234. const ItemInfo* const item = items.getUnchecked(i);
  38235. if (item->isSeparator())
  38236. menu.addSeparator();
  38237. else if (item->isHeading)
  38238. menu.addSectionHeader (item->name);
  38239. else
  38240. menu.addItem (item->itemId, item->name,
  38241. item->isEnabled, item->itemId == selectedId);
  38242. }
  38243. if (items.size() == 0)
  38244. menu.addItem (1, noChoicesMessage, false);
  38245. menuActive = true;
  38246. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38247. new Callback (this));
  38248. }
  38249. }
  38250. void ComboBox::mouseDown (const MouseEvent& e)
  38251. {
  38252. beginDragAutoRepeat (300);
  38253. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38254. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38255. showPopup();
  38256. }
  38257. void ComboBox::mouseDrag (const MouseEvent& e)
  38258. {
  38259. beginDragAutoRepeat (50);
  38260. if (isButtonDown && ! e.mouseWasClicked())
  38261. showPopup();
  38262. }
  38263. void ComboBox::mouseUp (const MouseEvent& e2)
  38264. {
  38265. if (isButtonDown)
  38266. {
  38267. isButtonDown = false;
  38268. repaint();
  38269. const MouseEvent e (e2.getEventRelativeTo (this));
  38270. if (reallyContains (e.getPosition(), true)
  38271. && (e2.eventComponent == this || ! label->isEditable()))
  38272. {
  38273. showPopup();
  38274. }
  38275. }
  38276. }
  38277. void ComboBox::addListener (ComboBoxListener* const listener)
  38278. {
  38279. listeners.add (listener);
  38280. }
  38281. void ComboBox::removeListener (ComboBoxListener* const listener)
  38282. {
  38283. listeners.remove (listener);
  38284. }
  38285. void ComboBox::handleAsyncUpdate()
  38286. {
  38287. Component::BailOutChecker checker (this);
  38288. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38289. }
  38290. END_JUCE_NAMESPACE
  38291. /*** End of inlined file: juce_ComboBox.cpp ***/
  38292. /*** Start of inlined file: juce_Label.cpp ***/
  38293. BEGIN_JUCE_NAMESPACE
  38294. Label::Label (const String& componentName,
  38295. const String& labelText)
  38296. : Component (componentName),
  38297. textValue (labelText),
  38298. lastTextValue (labelText),
  38299. font (15.0f),
  38300. justification (Justification::centredLeft),
  38301. ownerComponent (0),
  38302. horizontalBorderSize (5),
  38303. verticalBorderSize (1),
  38304. minimumHorizontalScale (0.7f),
  38305. editSingleClick (false),
  38306. editDoubleClick (false),
  38307. lossOfFocusDiscardsChanges (false)
  38308. {
  38309. setColour (TextEditor::textColourId, Colours::black);
  38310. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38311. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38312. textValue.addListener (this);
  38313. }
  38314. Label::~Label()
  38315. {
  38316. textValue.removeListener (this);
  38317. if (ownerComponent != 0)
  38318. ownerComponent->removeComponentListener (this);
  38319. editor = 0;
  38320. }
  38321. void Label::setText (const String& newText,
  38322. const bool broadcastChangeMessage)
  38323. {
  38324. hideEditor (true);
  38325. if (lastTextValue != newText)
  38326. {
  38327. lastTextValue = newText;
  38328. textValue = newText;
  38329. repaint();
  38330. textWasChanged();
  38331. if (ownerComponent != 0)
  38332. componentMovedOrResized (*ownerComponent, true, true);
  38333. if (broadcastChangeMessage)
  38334. callChangeListeners();
  38335. }
  38336. }
  38337. const String Label::getText (const bool returnActiveEditorContents) const
  38338. {
  38339. return (returnActiveEditorContents && isBeingEdited())
  38340. ? editor->getText()
  38341. : textValue.toString();
  38342. }
  38343. void Label::valueChanged (Value&)
  38344. {
  38345. if (lastTextValue != textValue.toString())
  38346. setText (textValue.toString(), true);
  38347. }
  38348. void Label::setFont (const Font& newFont)
  38349. {
  38350. if (font != newFont)
  38351. {
  38352. font = newFont;
  38353. repaint();
  38354. }
  38355. }
  38356. const Font& Label::getFont() const throw()
  38357. {
  38358. return font;
  38359. }
  38360. void Label::setEditable (const bool editOnSingleClick,
  38361. const bool editOnDoubleClick,
  38362. const bool lossOfFocusDiscardsChanges_)
  38363. {
  38364. editSingleClick = editOnSingleClick;
  38365. editDoubleClick = editOnDoubleClick;
  38366. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38367. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38368. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38369. }
  38370. void Label::setJustificationType (const Justification& newJustification)
  38371. {
  38372. if (justification != newJustification)
  38373. {
  38374. justification = newJustification;
  38375. repaint();
  38376. }
  38377. }
  38378. void Label::setBorderSize (int h, int v)
  38379. {
  38380. if (horizontalBorderSize != h || verticalBorderSize != v)
  38381. {
  38382. horizontalBorderSize = h;
  38383. verticalBorderSize = v;
  38384. repaint();
  38385. }
  38386. }
  38387. Component* Label::getAttachedComponent() const
  38388. {
  38389. return static_cast<Component*> (ownerComponent);
  38390. }
  38391. void Label::attachToComponent (Component* owner,
  38392. const bool onLeft)
  38393. {
  38394. if (ownerComponent != 0)
  38395. ownerComponent->removeComponentListener (this);
  38396. ownerComponent = owner;
  38397. leftOfOwnerComp = onLeft;
  38398. if (ownerComponent != 0)
  38399. {
  38400. setVisible (owner->isVisible());
  38401. ownerComponent->addComponentListener (this);
  38402. componentParentHierarchyChanged (*ownerComponent);
  38403. componentMovedOrResized (*ownerComponent, true, true);
  38404. }
  38405. }
  38406. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38407. {
  38408. if (leftOfOwnerComp)
  38409. {
  38410. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38411. component.getHeight());
  38412. setTopRightPosition (component.getX(), component.getY());
  38413. }
  38414. else
  38415. {
  38416. setSize (component.getWidth(),
  38417. 8 + roundToInt (getFont().getHeight()));
  38418. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38419. }
  38420. }
  38421. void Label::componentParentHierarchyChanged (Component& component)
  38422. {
  38423. if (component.getParentComponent() != 0)
  38424. component.getParentComponent()->addChildComponent (this);
  38425. }
  38426. void Label::componentVisibilityChanged (Component& component)
  38427. {
  38428. setVisible (component.isVisible());
  38429. }
  38430. void Label::textWasEdited()
  38431. {
  38432. }
  38433. void Label::textWasChanged()
  38434. {
  38435. }
  38436. void Label::showEditor()
  38437. {
  38438. if (editor == 0)
  38439. {
  38440. addAndMakeVisible (editor = createEditorComponent());
  38441. editor->setText (getText(), false);
  38442. editor->addListener (this);
  38443. editor->grabKeyboardFocus();
  38444. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38445. editor->addListener (this);
  38446. resized();
  38447. repaint();
  38448. editorShown (editor);
  38449. enterModalState (false);
  38450. editor->grabKeyboardFocus();
  38451. }
  38452. }
  38453. void Label::editorShown (TextEditor*)
  38454. {
  38455. }
  38456. void Label::editorAboutToBeHidden (TextEditor*)
  38457. {
  38458. }
  38459. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38460. {
  38461. const String newText (ed.getText());
  38462. if (textValue.toString() != newText)
  38463. {
  38464. lastTextValue = newText;
  38465. textValue = newText;
  38466. repaint();
  38467. textWasChanged();
  38468. if (ownerComponent != 0)
  38469. componentMovedOrResized (*ownerComponent, true, true);
  38470. return true;
  38471. }
  38472. return false;
  38473. }
  38474. void Label::hideEditor (const bool discardCurrentEditorContents)
  38475. {
  38476. if (editor != 0)
  38477. {
  38478. WeakReference<Component> deletionChecker (this);
  38479. ScopedPointer<TextEditor> outgoingEditor (editor);
  38480. editorAboutToBeHidden (outgoingEditor);
  38481. const bool changed = (! discardCurrentEditorContents)
  38482. && updateFromTextEditorContents (*outgoingEditor);
  38483. outgoingEditor = 0;
  38484. repaint();
  38485. if (changed)
  38486. textWasEdited();
  38487. if (deletionChecker != 0)
  38488. exitModalState (0);
  38489. if (changed && deletionChecker != 0)
  38490. callChangeListeners();
  38491. }
  38492. }
  38493. void Label::inputAttemptWhenModal()
  38494. {
  38495. if (editor != 0)
  38496. {
  38497. if (lossOfFocusDiscardsChanges)
  38498. textEditorEscapeKeyPressed (*editor);
  38499. else
  38500. textEditorReturnKeyPressed (*editor);
  38501. }
  38502. }
  38503. bool Label::isBeingEdited() const throw()
  38504. {
  38505. return editor != 0;
  38506. }
  38507. TextEditor* Label::createEditorComponent()
  38508. {
  38509. TextEditor* const ed = new TextEditor (getName());
  38510. ed->setFont (font);
  38511. // copy these colours from our own settings..
  38512. const int cols[] = { TextEditor::backgroundColourId,
  38513. TextEditor::textColourId,
  38514. TextEditor::highlightColourId,
  38515. TextEditor::highlightedTextColourId,
  38516. TextEditor::caretColourId,
  38517. TextEditor::outlineColourId,
  38518. TextEditor::focusedOutlineColourId,
  38519. TextEditor::shadowColourId };
  38520. for (int i = 0; i < numElementsInArray (cols); ++i)
  38521. ed->setColour (cols[i], findColour (cols[i]));
  38522. return ed;
  38523. }
  38524. void Label::paint (Graphics& g)
  38525. {
  38526. getLookAndFeel().drawLabel (g, *this);
  38527. }
  38528. void Label::mouseUp (const MouseEvent& e)
  38529. {
  38530. if (editSingleClick
  38531. && e.mouseWasClicked()
  38532. && contains (e.getPosition())
  38533. && ! e.mods.isPopupMenu())
  38534. {
  38535. showEditor();
  38536. }
  38537. }
  38538. void Label::mouseDoubleClick (const MouseEvent& e)
  38539. {
  38540. if (editDoubleClick && ! e.mods.isPopupMenu())
  38541. showEditor();
  38542. }
  38543. void Label::resized()
  38544. {
  38545. if (editor != 0)
  38546. editor->setBoundsInset (BorderSize<int> (0));
  38547. }
  38548. void Label::focusGained (FocusChangeType cause)
  38549. {
  38550. if (editSingleClick && cause == focusChangedByTabKey)
  38551. showEditor();
  38552. }
  38553. void Label::enablementChanged()
  38554. {
  38555. repaint();
  38556. }
  38557. void Label::colourChanged()
  38558. {
  38559. repaint();
  38560. }
  38561. void Label::setMinimumHorizontalScale (const float newScale)
  38562. {
  38563. if (minimumHorizontalScale != newScale)
  38564. {
  38565. minimumHorizontalScale = newScale;
  38566. repaint();
  38567. }
  38568. }
  38569. // We'll use a custom focus traverser here to make sure focus goes from the
  38570. // text editor to another component rather than back to the label itself.
  38571. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38572. {
  38573. public:
  38574. LabelKeyboardFocusTraverser() {}
  38575. Component* getNextComponent (Component* current)
  38576. {
  38577. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38578. ? current->getParentComponent() : current);
  38579. }
  38580. Component* getPreviousComponent (Component* current)
  38581. {
  38582. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38583. ? current->getParentComponent() : current);
  38584. }
  38585. };
  38586. KeyboardFocusTraverser* Label::createFocusTraverser()
  38587. {
  38588. return new LabelKeyboardFocusTraverser();
  38589. }
  38590. void Label::addListener (LabelListener* const listener)
  38591. {
  38592. listeners.add (listener);
  38593. }
  38594. void Label::removeListener (LabelListener* const listener)
  38595. {
  38596. listeners.remove (listener);
  38597. }
  38598. void Label::callChangeListeners()
  38599. {
  38600. Component::BailOutChecker checker (this);
  38601. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38602. }
  38603. void Label::textEditorTextChanged (TextEditor& ed)
  38604. {
  38605. if (editor != 0)
  38606. {
  38607. jassert (&ed == editor);
  38608. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38609. {
  38610. if (lossOfFocusDiscardsChanges)
  38611. textEditorEscapeKeyPressed (ed);
  38612. else
  38613. textEditorReturnKeyPressed (ed);
  38614. }
  38615. }
  38616. }
  38617. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38618. {
  38619. if (editor != 0)
  38620. {
  38621. jassert (&ed == editor);
  38622. const bool changed = updateFromTextEditorContents (ed);
  38623. hideEditor (true);
  38624. if (changed)
  38625. {
  38626. WeakReference<Component> deletionChecker (this);
  38627. textWasEdited();
  38628. if (deletionChecker != 0)
  38629. callChangeListeners();
  38630. }
  38631. }
  38632. }
  38633. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38634. {
  38635. if (editor != 0)
  38636. {
  38637. jassert (&ed == editor);
  38638. (void) ed;
  38639. editor->setText (textValue.toString(), false);
  38640. hideEditor (true);
  38641. }
  38642. }
  38643. void Label::textEditorFocusLost (TextEditor& ed)
  38644. {
  38645. textEditorTextChanged (ed);
  38646. }
  38647. END_JUCE_NAMESPACE
  38648. /*** End of inlined file: juce_Label.cpp ***/
  38649. /*** Start of inlined file: juce_ListBox.cpp ***/
  38650. BEGIN_JUCE_NAMESPACE
  38651. class ListBoxRowComponent : public Component,
  38652. public TooltipClient
  38653. {
  38654. public:
  38655. ListBoxRowComponent (ListBox& owner_)
  38656. : owner (owner_), row (-1),
  38657. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38658. {
  38659. }
  38660. void paint (Graphics& g)
  38661. {
  38662. if (owner.getModel() != 0)
  38663. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38664. }
  38665. void update (const int row_, const bool selected_)
  38666. {
  38667. if (row != row_ || selected != selected_)
  38668. {
  38669. repaint();
  38670. row = row_;
  38671. selected = selected_;
  38672. }
  38673. if (owner.getModel() != 0)
  38674. {
  38675. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38676. if (customComponent != 0)
  38677. {
  38678. addAndMakeVisible (customComponent);
  38679. customComponent->setBounds (getLocalBounds());
  38680. }
  38681. }
  38682. }
  38683. void mouseDown (const MouseEvent& e)
  38684. {
  38685. isDragging = false;
  38686. selectRowOnMouseUp = false;
  38687. if (isEnabled())
  38688. {
  38689. if (! selected)
  38690. {
  38691. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38692. if (owner.getModel() != 0)
  38693. owner.getModel()->listBoxItemClicked (row, e);
  38694. }
  38695. else
  38696. {
  38697. selectRowOnMouseUp = true;
  38698. }
  38699. }
  38700. }
  38701. void mouseUp (const MouseEvent& e)
  38702. {
  38703. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38704. {
  38705. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38706. if (owner.getModel() != 0)
  38707. owner.getModel()->listBoxItemClicked (row, e);
  38708. }
  38709. }
  38710. void mouseDoubleClick (const MouseEvent& e)
  38711. {
  38712. if (owner.getModel() != 0 && isEnabled())
  38713. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38714. }
  38715. void mouseDrag (const MouseEvent& e)
  38716. {
  38717. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38718. {
  38719. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38720. if (selectedRows.size() > 0)
  38721. {
  38722. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38723. if (dragDescription.isNotEmpty())
  38724. {
  38725. isDragging = true;
  38726. owner.startDragAndDrop (e, dragDescription);
  38727. }
  38728. }
  38729. }
  38730. }
  38731. void resized()
  38732. {
  38733. if (customComponent != 0)
  38734. customComponent->setBounds (getLocalBounds());
  38735. }
  38736. const String getTooltip()
  38737. {
  38738. if (owner.getModel() != 0)
  38739. return owner.getModel()->getTooltipForRow (row);
  38740. return String::empty;
  38741. }
  38742. ScopedPointer<Component> customComponent;
  38743. private:
  38744. ListBox& owner;
  38745. int row;
  38746. bool selected, isDragging, selectRowOnMouseUp;
  38747. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38748. };
  38749. class ListViewport : public Viewport
  38750. {
  38751. public:
  38752. ListViewport (ListBox& owner_)
  38753. : owner (owner_)
  38754. {
  38755. setWantsKeyboardFocus (false);
  38756. Component* const content = new Component();
  38757. setViewedComponent (content);
  38758. content->addMouseListener (this, false);
  38759. content->setWantsKeyboardFocus (false);
  38760. }
  38761. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38762. {
  38763. return rows [row % jmax (1, rows.size())];
  38764. }
  38765. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38766. {
  38767. return (row >= firstIndex && row < firstIndex + rows.size())
  38768. ? getComponentForRow (row) : 0;
  38769. }
  38770. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38771. {
  38772. const int index = getIndexOfChildComponent (rowComponent);
  38773. const int num = rows.size();
  38774. for (int i = num; --i >= 0;)
  38775. if (((firstIndex + i) % jmax (1, num)) == index)
  38776. return firstIndex + i;
  38777. return -1;
  38778. }
  38779. void visibleAreaChanged (const Rectangle<int>&)
  38780. {
  38781. updateVisibleArea (true);
  38782. if (owner.getModel() != 0)
  38783. owner.getModel()->listWasScrolled();
  38784. }
  38785. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38786. {
  38787. hasUpdated = false;
  38788. const int newX = getViewedComponent()->getX();
  38789. int newY = getViewedComponent()->getY();
  38790. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38791. const int newH = owner.totalItems * owner.getRowHeight();
  38792. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38793. newY = getMaximumVisibleHeight() - newH;
  38794. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38795. if (makeSureItUpdatesContent && ! hasUpdated)
  38796. updateContents();
  38797. }
  38798. void updateContents()
  38799. {
  38800. hasUpdated = true;
  38801. const int rowHeight = owner.getRowHeight();
  38802. if (rowHeight > 0)
  38803. {
  38804. const int y = getViewPositionY();
  38805. const int w = getViewedComponent()->getWidth();
  38806. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38807. rows.removeRange (numNeeded, rows.size());
  38808. while (numNeeded > rows.size())
  38809. {
  38810. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  38811. rows.add (newRow);
  38812. getViewedComponent()->addAndMakeVisible (newRow);
  38813. }
  38814. firstIndex = y / rowHeight;
  38815. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38816. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38817. for (int i = 0; i < numNeeded; ++i)
  38818. {
  38819. const int row = i + firstIndex;
  38820. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38821. if (rowComp != 0)
  38822. {
  38823. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38824. rowComp->update (row, owner.isRowSelected (row));
  38825. }
  38826. }
  38827. }
  38828. if (owner.headerComponent != 0)
  38829. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38830. owner.outlineThickness,
  38831. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38832. getViewedComponent()->getWidth()),
  38833. owner.headerComponent->getHeight());
  38834. }
  38835. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  38836. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  38837. {
  38838. hasUpdated = false;
  38839. if (row < firstWholeIndex && ! dontScroll)
  38840. {
  38841. setViewPosition (getViewPositionX(), row * rowHeight);
  38842. }
  38843. else if (row >= lastWholeIndex && ! dontScroll)
  38844. {
  38845. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  38846. if (row >= lastRowSelected + rowsOnScreen
  38847. && rowsOnScreen < totalItems - 1
  38848. && ! isMouseClick)
  38849. {
  38850. setViewPosition (getViewPositionX(),
  38851. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  38852. }
  38853. else
  38854. {
  38855. setViewPosition (getViewPositionX(),
  38856. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38857. }
  38858. }
  38859. if (! hasUpdated)
  38860. updateContents();
  38861. }
  38862. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  38863. {
  38864. if (row < firstWholeIndex)
  38865. {
  38866. setViewPosition (getViewPositionX(), row * rowHeight);
  38867. }
  38868. else if (row >= lastWholeIndex)
  38869. {
  38870. setViewPosition (getViewPositionX(),
  38871. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38872. }
  38873. }
  38874. void paint (Graphics& g)
  38875. {
  38876. if (isOpaque())
  38877. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38878. }
  38879. bool keyPressed (const KeyPress& key)
  38880. {
  38881. if (key.isKeyCode (KeyPress::upKey)
  38882. || key.isKeyCode (KeyPress::downKey)
  38883. || key.isKeyCode (KeyPress::pageUpKey)
  38884. || key.isKeyCode (KeyPress::pageDownKey)
  38885. || key.isKeyCode (KeyPress::homeKey)
  38886. || key.isKeyCode (KeyPress::endKey))
  38887. {
  38888. // we want to avoid these keypresses going to the viewport, and instead allow
  38889. // them to pass up to our listbox..
  38890. return false;
  38891. }
  38892. return Viewport::keyPressed (key);
  38893. }
  38894. private:
  38895. ListBox& owner;
  38896. OwnedArray<ListBoxRowComponent> rows;
  38897. int firstIndex, firstWholeIndex, lastWholeIndex;
  38898. bool hasUpdated;
  38899. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  38900. };
  38901. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38902. : Component (name),
  38903. model (model_),
  38904. totalItems (0),
  38905. rowHeight (22),
  38906. minimumRowWidth (0),
  38907. outlineThickness (0),
  38908. lastRowSelected (-1),
  38909. mouseMoveSelects (false),
  38910. multipleSelection (false),
  38911. hasDoneInitialUpdate (false)
  38912. {
  38913. addAndMakeVisible (viewport = new ListViewport (*this));
  38914. setWantsKeyboardFocus (true);
  38915. colourChanged();
  38916. }
  38917. ListBox::~ListBox()
  38918. {
  38919. headerComponent = 0;
  38920. viewport = 0;
  38921. }
  38922. void ListBox::setModel (ListBoxModel* const newModel)
  38923. {
  38924. if (model != newModel)
  38925. {
  38926. model = newModel;
  38927. repaint();
  38928. updateContent();
  38929. }
  38930. }
  38931. void ListBox::setMultipleSelectionEnabled (bool b)
  38932. {
  38933. multipleSelection = b;
  38934. }
  38935. void ListBox::setMouseMoveSelectsRows (bool b)
  38936. {
  38937. mouseMoveSelects = b;
  38938. if (b)
  38939. addMouseListener (this, true);
  38940. }
  38941. void ListBox::paint (Graphics& g)
  38942. {
  38943. if (! hasDoneInitialUpdate)
  38944. updateContent();
  38945. g.fillAll (findColour (backgroundColourId));
  38946. }
  38947. void ListBox::paintOverChildren (Graphics& g)
  38948. {
  38949. if (outlineThickness > 0)
  38950. {
  38951. g.setColour (findColour (outlineColourId));
  38952. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38953. }
  38954. }
  38955. void ListBox::resized()
  38956. {
  38957. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38958. outlineThickness, outlineThickness, outlineThickness));
  38959. viewport->setSingleStepSizes (20, getRowHeight());
  38960. viewport->updateVisibleArea (false);
  38961. }
  38962. void ListBox::visibilityChanged()
  38963. {
  38964. viewport->updateVisibleArea (true);
  38965. }
  38966. Viewport* ListBox::getViewport() const throw()
  38967. {
  38968. return viewport;
  38969. }
  38970. void ListBox::updateContent()
  38971. {
  38972. hasDoneInitialUpdate = true;
  38973. totalItems = (model != 0) ? model->getNumRows() : 0;
  38974. bool selectionChanged = false;
  38975. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  38976. {
  38977. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38978. lastRowSelected = getSelectedRow (0);
  38979. selectionChanged = true;
  38980. }
  38981. viewport->updateVisibleArea (isVisible());
  38982. viewport->resized();
  38983. if (selectionChanged && model != 0)
  38984. model->selectedRowsChanged (lastRowSelected);
  38985. }
  38986. void ListBox::selectRow (const int row,
  38987. bool dontScroll,
  38988. bool deselectOthersFirst)
  38989. {
  38990. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38991. }
  38992. void ListBox::selectRowInternal (const int row,
  38993. bool dontScroll,
  38994. bool deselectOthersFirst,
  38995. bool isMouseClick)
  38996. {
  38997. if (! multipleSelection)
  38998. deselectOthersFirst = true;
  38999. if ((! isRowSelected (row))
  39000. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39001. {
  39002. if (isPositiveAndBelow (row, totalItems))
  39003. {
  39004. if (deselectOthersFirst)
  39005. selected.clear();
  39006. selected.addRange (Range<int> (row, row + 1));
  39007. if (getHeight() == 0 || getWidth() == 0)
  39008. dontScroll = true;
  39009. viewport->selectRow (row, getRowHeight(), dontScroll,
  39010. lastRowSelected, totalItems, isMouseClick);
  39011. lastRowSelected = row;
  39012. model->selectedRowsChanged (row);
  39013. }
  39014. else
  39015. {
  39016. if (deselectOthersFirst)
  39017. deselectAllRows();
  39018. }
  39019. }
  39020. }
  39021. void ListBox::deselectRow (const int row)
  39022. {
  39023. if (selected.contains (row))
  39024. {
  39025. selected.removeRange (Range <int> (row, row + 1));
  39026. if (row == lastRowSelected)
  39027. lastRowSelected = getSelectedRow (0);
  39028. viewport->updateContents();
  39029. model->selectedRowsChanged (lastRowSelected);
  39030. }
  39031. }
  39032. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39033. const bool sendNotificationEventToModel)
  39034. {
  39035. selected = setOfRowsToBeSelected;
  39036. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39037. if (! isRowSelected (lastRowSelected))
  39038. lastRowSelected = getSelectedRow (0);
  39039. viewport->updateContents();
  39040. if ((model != 0) && sendNotificationEventToModel)
  39041. model->selectedRowsChanged (lastRowSelected);
  39042. }
  39043. const SparseSet<int> ListBox::getSelectedRows() const
  39044. {
  39045. return selected;
  39046. }
  39047. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39048. {
  39049. if (multipleSelection && (firstRow != lastRow))
  39050. {
  39051. const int numRows = totalItems - 1;
  39052. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39053. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39054. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39055. jmax (firstRow, lastRow) + 1));
  39056. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39057. }
  39058. selectRowInternal (lastRow, false, false, true);
  39059. }
  39060. void ListBox::flipRowSelection (const int row)
  39061. {
  39062. if (isRowSelected (row))
  39063. deselectRow (row);
  39064. else
  39065. selectRowInternal (row, false, false, true);
  39066. }
  39067. void ListBox::deselectAllRows()
  39068. {
  39069. if (! selected.isEmpty())
  39070. {
  39071. selected.clear();
  39072. lastRowSelected = -1;
  39073. viewport->updateContents();
  39074. if (model != 0)
  39075. model->selectedRowsChanged (lastRowSelected);
  39076. }
  39077. }
  39078. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39079. const ModifierKeys& mods,
  39080. const bool isMouseUpEvent)
  39081. {
  39082. if (multipleSelection && mods.isCommandDown())
  39083. {
  39084. flipRowSelection (row);
  39085. }
  39086. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39087. {
  39088. selectRangeOfRows (lastRowSelected, row);
  39089. }
  39090. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39091. {
  39092. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39093. }
  39094. }
  39095. int ListBox::getNumSelectedRows() const
  39096. {
  39097. return selected.size();
  39098. }
  39099. int ListBox::getSelectedRow (const int index) const
  39100. {
  39101. return (isPositiveAndBelow (index, selected.size()))
  39102. ? selected [index] : -1;
  39103. }
  39104. bool ListBox::isRowSelected (const int row) const
  39105. {
  39106. return selected.contains (row);
  39107. }
  39108. int ListBox::getLastRowSelected() const
  39109. {
  39110. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39111. }
  39112. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39113. {
  39114. if (isPositiveAndBelow (x, getWidth()))
  39115. {
  39116. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39117. if (isPositiveAndBelow (row, totalItems))
  39118. return row;
  39119. }
  39120. return -1;
  39121. }
  39122. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39123. {
  39124. if (isPositiveAndBelow (x, getWidth()))
  39125. {
  39126. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39127. return jlimit (0, totalItems, row);
  39128. }
  39129. return -1;
  39130. }
  39131. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39132. {
  39133. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39134. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39135. }
  39136. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39137. {
  39138. return viewport->getRowNumberOfComponent (rowComponent);
  39139. }
  39140. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39141. const bool relativeToComponentTopLeft) const throw()
  39142. {
  39143. int y = viewport->getY() + rowHeight * rowNumber;
  39144. if (relativeToComponentTopLeft)
  39145. y -= viewport->getViewPositionY();
  39146. return Rectangle<int> (viewport->getX(), y,
  39147. viewport->getViewedComponent()->getWidth(), rowHeight);
  39148. }
  39149. void ListBox::setVerticalPosition (const double proportion)
  39150. {
  39151. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39152. viewport->setViewPosition (viewport->getViewPositionX(),
  39153. jmax (0, roundToInt (proportion * offscreen)));
  39154. }
  39155. double ListBox::getVerticalPosition() const
  39156. {
  39157. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39158. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39159. : 0;
  39160. }
  39161. int ListBox::getVisibleRowWidth() const throw()
  39162. {
  39163. return viewport->getViewWidth();
  39164. }
  39165. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39166. {
  39167. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39168. }
  39169. bool ListBox::keyPressed (const KeyPress& key)
  39170. {
  39171. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39172. const bool multiple = multipleSelection
  39173. && (lastRowSelected >= 0)
  39174. && (key.getModifiers().isShiftDown()
  39175. || key.getModifiers().isCtrlDown()
  39176. || key.getModifiers().isCommandDown());
  39177. if (key.isKeyCode (KeyPress::upKey))
  39178. {
  39179. if (multiple)
  39180. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39181. else
  39182. selectRow (jmax (0, lastRowSelected - 1));
  39183. }
  39184. else if (key.isKeyCode (KeyPress::returnKey)
  39185. && isRowSelected (lastRowSelected))
  39186. {
  39187. if (model != 0)
  39188. model->returnKeyPressed (lastRowSelected);
  39189. }
  39190. else if (key.isKeyCode (KeyPress::pageUpKey))
  39191. {
  39192. if (multiple)
  39193. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39194. else
  39195. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39196. }
  39197. else if (key.isKeyCode (KeyPress::pageDownKey))
  39198. {
  39199. if (multiple)
  39200. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39201. else
  39202. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39203. }
  39204. else if (key.isKeyCode (KeyPress::homeKey))
  39205. {
  39206. if (multiple && key.getModifiers().isShiftDown())
  39207. selectRangeOfRows (lastRowSelected, 0);
  39208. else
  39209. selectRow (0);
  39210. }
  39211. else if (key.isKeyCode (KeyPress::endKey))
  39212. {
  39213. if (multiple && key.getModifiers().isShiftDown())
  39214. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39215. else
  39216. selectRow (totalItems - 1);
  39217. }
  39218. else if (key.isKeyCode (KeyPress::downKey))
  39219. {
  39220. if (multiple)
  39221. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39222. else
  39223. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39224. }
  39225. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39226. && isRowSelected (lastRowSelected))
  39227. {
  39228. if (model != 0)
  39229. model->deleteKeyPressed (lastRowSelected);
  39230. }
  39231. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39232. {
  39233. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39234. }
  39235. else
  39236. {
  39237. return false;
  39238. }
  39239. return true;
  39240. }
  39241. bool ListBox::keyStateChanged (const bool isKeyDown)
  39242. {
  39243. return isKeyDown
  39244. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39245. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39246. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39247. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39248. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39249. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39250. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39251. }
  39252. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39253. {
  39254. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39255. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39256. }
  39257. void ListBox::mouseMove (const MouseEvent& e)
  39258. {
  39259. if (mouseMoveSelects)
  39260. {
  39261. const MouseEvent e2 (e.getEventRelativeTo (this));
  39262. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39263. }
  39264. }
  39265. void ListBox::mouseExit (const MouseEvent& e)
  39266. {
  39267. mouseMove (e);
  39268. }
  39269. void ListBox::mouseUp (const MouseEvent& e)
  39270. {
  39271. if (e.mouseWasClicked() && model != 0)
  39272. model->backgroundClicked();
  39273. }
  39274. void ListBox::setRowHeight (const int newHeight)
  39275. {
  39276. rowHeight = jmax (1, newHeight);
  39277. viewport->setSingleStepSizes (20, rowHeight);
  39278. updateContent();
  39279. }
  39280. int ListBox::getNumRowsOnScreen() const throw()
  39281. {
  39282. return viewport->getMaximumVisibleHeight() / rowHeight;
  39283. }
  39284. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39285. {
  39286. minimumRowWidth = newMinimumWidth;
  39287. updateContent();
  39288. }
  39289. int ListBox::getVisibleContentWidth() const throw()
  39290. {
  39291. return viewport->getMaximumVisibleWidth();
  39292. }
  39293. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39294. {
  39295. return viewport->getVerticalScrollBar();
  39296. }
  39297. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39298. {
  39299. return viewport->getHorizontalScrollBar();
  39300. }
  39301. void ListBox::colourChanged()
  39302. {
  39303. setOpaque (findColour (backgroundColourId).isOpaque());
  39304. viewport->setOpaque (isOpaque());
  39305. repaint();
  39306. }
  39307. void ListBox::setOutlineThickness (const int outlineThickness_)
  39308. {
  39309. outlineThickness = outlineThickness_;
  39310. resized();
  39311. }
  39312. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39313. {
  39314. if (headerComponent != newHeaderComponent)
  39315. {
  39316. headerComponent = newHeaderComponent;
  39317. addAndMakeVisible (newHeaderComponent);
  39318. ListBox::resized();
  39319. }
  39320. }
  39321. void ListBox::repaintRow (const int rowNumber) throw()
  39322. {
  39323. repaint (getRowPosition (rowNumber, true));
  39324. }
  39325. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39326. {
  39327. Rectangle<int> imageArea;
  39328. const int firstRow = getRowContainingPosition (0, 0);
  39329. int i;
  39330. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39331. {
  39332. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39333. if (rowComp != 0 && isRowSelected (firstRow + i))
  39334. {
  39335. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39336. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39337. imageArea = imageArea.getUnion (rowRect);
  39338. }
  39339. }
  39340. imageArea = imageArea.getIntersection (getLocalBounds());
  39341. imageX = imageArea.getX();
  39342. imageY = imageArea.getY();
  39343. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39344. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39345. {
  39346. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39347. if (rowComp != 0 && isRowSelected (firstRow + i))
  39348. {
  39349. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39350. Graphics g (snapshot);
  39351. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39352. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39353. {
  39354. g.beginTransparencyLayer (0.6f);
  39355. rowComp->paintEntireComponent (g, false);
  39356. g.endTransparencyLayer();
  39357. }
  39358. }
  39359. }
  39360. return snapshot;
  39361. }
  39362. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39363. {
  39364. DragAndDropContainer* const dragContainer
  39365. = DragAndDropContainer::findParentDragContainerFor (this);
  39366. if (dragContainer != 0)
  39367. {
  39368. int x, y;
  39369. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39370. MouseEvent e2 (e.getEventRelativeTo (this));
  39371. const Point<int> p (x - e2.x, y - e2.y);
  39372. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39373. }
  39374. else
  39375. {
  39376. // to be able to do a drag-and-drop operation, the listbox needs to
  39377. // be inside a component which is also a DragAndDropContainer.
  39378. jassertfalse;
  39379. }
  39380. }
  39381. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39382. {
  39383. (void) existingComponentToUpdate;
  39384. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39385. return 0;
  39386. }
  39387. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39388. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39389. void ListBoxModel::backgroundClicked() {}
  39390. void ListBoxModel::selectedRowsChanged (int) {}
  39391. void ListBoxModel::deleteKeyPressed (int) {}
  39392. void ListBoxModel::returnKeyPressed (int) {}
  39393. void ListBoxModel::listWasScrolled() {}
  39394. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39395. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39396. END_JUCE_NAMESPACE
  39397. /*** End of inlined file: juce_ListBox.cpp ***/
  39398. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39399. BEGIN_JUCE_NAMESPACE
  39400. ProgressBar::ProgressBar (double& progress_)
  39401. : progress (progress_),
  39402. displayPercentage (true),
  39403. lastCallbackTime (0)
  39404. {
  39405. currentValue = jlimit (0.0, 1.0, progress);
  39406. }
  39407. ProgressBar::~ProgressBar()
  39408. {
  39409. }
  39410. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39411. {
  39412. displayPercentage = shouldDisplayPercentage;
  39413. repaint();
  39414. }
  39415. void ProgressBar::setTextToDisplay (const String& text)
  39416. {
  39417. displayPercentage = false;
  39418. displayedMessage = text;
  39419. }
  39420. void ProgressBar::lookAndFeelChanged()
  39421. {
  39422. setOpaque (findColour (backgroundColourId).isOpaque());
  39423. }
  39424. void ProgressBar::colourChanged()
  39425. {
  39426. lookAndFeelChanged();
  39427. }
  39428. void ProgressBar::paint (Graphics& g)
  39429. {
  39430. String text;
  39431. if (displayPercentage)
  39432. {
  39433. if (currentValue >= 0 && currentValue <= 1.0)
  39434. text << roundToInt (currentValue * 100.0) << '%';
  39435. }
  39436. else
  39437. {
  39438. text = displayedMessage;
  39439. }
  39440. getLookAndFeel().drawProgressBar (g, *this,
  39441. getWidth(), getHeight(),
  39442. currentValue, text);
  39443. }
  39444. void ProgressBar::visibilityChanged()
  39445. {
  39446. if (isVisible())
  39447. startTimer (30);
  39448. else
  39449. stopTimer();
  39450. }
  39451. void ProgressBar::timerCallback()
  39452. {
  39453. double newProgress = progress;
  39454. const uint32 now = Time::getMillisecondCounter();
  39455. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39456. lastCallbackTime = now;
  39457. if (currentValue != newProgress
  39458. || newProgress < 0 || newProgress >= 1.0
  39459. || currentMessage != displayedMessage)
  39460. {
  39461. if (currentValue < newProgress
  39462. && newProgress >= 0 && newProgress < 1.0
  39463. && currentValue >= 0 && currentValue < 1.0)
  39464. {
  39465. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39466. newProgress);
  39467. }
  39468. currentValue = newProgress;
  39469. currentMessage = displayedMessage;
  39470. repaint();
  39471. }
  39472. }
  39473. END_JUCE_NAMESPACE
  39474. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39475. /*** Start of inlined file: juce_Slider.cpp ***/
  39476. BEGIN_JUCE_NAMESPACE
  39477. class SliderPopupDisplayComponent : public BubbleComponent
  39478. {
  39479. public:
  39480. SliderPopupDisplayComponent (Slider* const owner_)
  39481. : owner (owner_),
  39482. font (15.0f, Font::bold)
  39483. {
  39484. setAlwaysOnTop (true);
  39485. }
  39486. ~SliderPopupDisplayComponent()
  39487. {
  39488. }
  39489. void paintContent (Graphics& g, int w, int h)
  39490. {
  39491. g.setFont (font);
  39492. g.setColour (Colours::black);
  39493. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39494. }
  39495. void getContentSize (int& w, int& h)
  39496. {
  39497. w = font.getStringWidth (text) + 18;
  39498. h = (int) (font.getHeight() * 1.6f);
  39499. }
  39500. void updatePosition (const String& newText)
  39501. {
  39502. if (text != newText)
  39503. {
  39504. text = newText;
  39505. repaint();
  39506. }
  39507. BubbleComponent::setPosition (owner);
  39508. }
  39509. private:
  39510. Slider* owner;
  39511. Font font;
  39512. String text;
  39513. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39514. };
  39515. Slider::Slider (const String& name)
  39516. : Component (name),
  39517. lastCurrentValue (0),
  39518. lastValueMin (0),
  39519. lastValueMax (0),
  39520. minimum (0),
  39521. maximum (10),
  39522. interval (0),
  39523. skewFactor (1.0),
  39524. velocityModeSensitivity (1.0),
  39525. velocityModeOffset (0.0),
  39526. velocityModeThreshold (1),
  39527. rotaryStart (float_Pi * 1.2f),
  39528. rotaryEnd (float_Pi * 2.8f),
  39529. numDecimalPlaces (7),
  39530. sliderRegionStart (0),
  39531. sliderRegionSize (1),
  39532. sliderBeingDragged (-1),
  39533. pixelsForFullDragExtent (250),
  39534. style (LinearHorizontal),
  39535. textBoxPos (TextBoxLeft),
  39536. textBoxWidth (80),
  39537. textBoxHeight (20),
  39538. incDecButtonMode (incDecButtonsNotDraggable),
  39539. editableText (true),
  39540. doubleClickToValue (false),
  39541. isVelocityBased (false),
  39542. userKeyOverridesVelocity (true),
  39543. rotaryStop (true),
  39544. incDecButtonsSideBySide (false),
  39545. sendChangeOnlyOnRelease (false),
  39546. popupDisplayEnabled (false),
  39547. menuEnabled (false),
  39548. menuShown (false),
  39549. scrollWheelEnabled (true),
  39550. snapsToMousePos (true),
  39551. popupDisplay (0),
  39552. parentForPopupDisplay (0)
  39553. {
  39554. setWantsKeyboardFocus (false);
  39555. setRepaintsOnMouseActivity (true);
  39556. lookAndFeelChanged();
  39557. updateText();
  39558. currentValue.addListener (this);
  39559. valueMin.addListener (this);
  39560. valueMax.addListener (this);
  39561. }
  39562. Slider::~Slider()
  39563. {
  39564. currentValue.removeListener (this);
  39565. valueMin.removeListener (this);
  39566. valueMax.removeListener (this);
  39567. popupDisplay = 0;
  39568. }
  39569. void Slider::handleAsyncUpdate()
  39570. {
  39571. cancelPendingUpdate();
  39572. Component::BailOutChecker checker (this);
  39573. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39574. }
  39575. void Slider::sendDragStart()
  39576. {
  39577. startedDragging();
  39578. Component::BailOutChecker checker (this);
  39579. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39580. }
  39581. void Slider::sendDragEnd()
  39582. {
  39583. stoppedDragging();
  39584. sliderBeingDragged = -1;
  39585. Component::BailOutChecker checker (this);
  39586. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39587. }
  39588. void Slider::addListener (SliderListener* const listener)
  39589. {
  39590. listeners.add (listener);
  39591. }
  39592. void Slider::removeListener (SliderListener* const listener)
  39593. {
  39594. listeners.remove (listener);
  39595. }
  39596. void Slider::setSliderStyle (const SliderStyle newStyle)
  39597. {
  39598. if (style != newStyle)
  39599. {
  39600. style = newStyle;
  39601. repaint();
  39602. lookAndFeelChanged();
  39603. }
  39604. }
  39605. void Slider::setRotaryParameters (const float startAngleRadians,
  39606. const float endAngleRadians,
  39607. const bool stopAtEnd)
  39608. {
  39609. // make sure the values are sensible..
  39610. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39611. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39612. jassert (rotaryStart < rotaryEnd);
  39613. rotaryStart = startAngleRadians;
  39614. rotaryEnd = endAngleRadians;
  39615. rotaryStop = stopAtEnd;
  39616. }
  39617. void Slider::setVelocityBasedMode (const bool velBased)
  39618. {
  39619. isVelocityBased = velBased;
  39620. }
  39621. void Slider::setVelocityModeParameters (const double sensitivity,
  39622. const int threshold,
  39623. const double offset,
  39624. const bool userCanPressKeyToSwapMode)
  39625. {
  39626. jassert (threshold >= 0);
  39627. jassert (sensitivity > 0);
  39628. jassert (offset >= 0);
  39629. velocityModeSensitivity = sensitivity;
  39630. velocityModeOffset = offset;
  39631. velocityModeThreshold = threshold;
  39632. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39633. }
  39634. void Slider::setSkewFactor (const double factor)
  39635. {
  39636. skewFactor = factor;
  39637. }
  39638. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39639. {
  39640. if (maximum > minimum)
  39641. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39642. / (maximum - minimum));
  39643. }
  39644. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39645. {
  39646. jassert (distanceForFullScaleDrag > 0);
  39647. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39648. }
  39649. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39650. {
  39651. if (incDecButtonMode != mode)
  39652. {
  39653. incDecButtonMode = mode;
  39654. lookAndFeelChanged();
  39655. }
  39656. }
  39657. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39658. const bool isReadOnly,
  39659. const int textEntryBoxWidth,
  39660. const int textEntryBoxHeight)
  39661. {
  39662. if (textBoxPos != newPosition
  39663. || editableText != (! isReadOnly)
  39664. || textBoxWidth != textEntryBoxWidth
  39665. || textBoxHeight != textEntryBoxHeight)
  39666. {
  39667. textBoxPos = newPosition;
  39668. editableText = ! isReadOnly;
  39669. textBoxWidth = textEntryBoxWidth;
  39670. textBoxHeight = textEntryBoxHeight;
  39671. repaint();
  39672. lookAndFeelChanged();
  39673. }
  39674. }
  39675. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39676. {
  39677. editableText = shouldBeEditable;
  39678. if (valueBox != 0)
  39679. valueBox->setEditable (shouldBeEditable && isEnabled());
  39680. }
  39681. void Slider::showTextBox()
  39682. {
  39683. jassert (editableText); // this should probably be avoided in read-only sliders.
  39684. if (valueBox != 0)
  39685. valueBox->showEditor();
  39686. }
  39687. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39688. {
  39689. if (valueBox != 0)
  39690. {
  39691. valueBox->hideEditor (discardCurrentEditorContents);
  39692. if (discardCurrentEditorContents)
  39693. updateText();
  39694. }
  39695. }
  39696. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39697. {
  39698. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39699. }
  39700. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39701. {
  39702. snapsToMousePos = shouldSnapToMouse;
  39703. }
  39704. void Slider::setPopupDisplayEnabled (const bool enabled,
  39705. Component* const parentComponentToUse)
  39706. {
  39707. popupDisplayEnabled = enabled;
  39708. parentForPopupDisplay = parentComponentToUse;
  39709. }
  39710. void Slider::colourChanged()
  39711. {
  39712. lookAndFeelChanged();
  39713. }
  39714. void Slider::lookAndFeelChanged()
  39715. {
  39716. LookAndFeel& lf = getLookAndFeel();
  39717. if (textBoxPos != NoTextBox)
  39718. {
  39719. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39720. : getTextFromValue (currentValue.getValue()));
  39721. valueBox = 0;
  39722. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39723. valueBox->setWantsKeyboardFocus (false);
  39724. valueBox->setText (previousTextBoxContent, false);
  39725. valueBox->setEditable (editableText && isEnabled());
  39726. valueBox->addListener (this);
  39727. if (style == LinearBar)
  39728. valueBox->addMouseListener (this, false);
  39729. valueBox->setTooltip (getTooltip());
  39730. }
  39731. else
  39732. {
  39733. valueBox = 0;
  39734. }
  39735. if (style == IncDecButtons)
  39736. {
  39737. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39738. incButton->addListener (this);
  39739. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39740. decButton->addListener (this);
  39741. if (incDecButtonMode != incDecButtonsNotDraggable)
  39742. {
  39743. incButton->addMouseListener (this, false);
  39744. decButton->addMouseListener (this, false);
  39745. }
  39746. else
  39747. {
  39748. incButton->setRepeatSpeed (300, 100, 20);
  39749. incButton->addMouseListener (decButton, false);
  39750. decButton->setRepeatSpeed (300, 100, 20);
  39751. decButton->addMouseListener (incButton, false);
  39752. }
  39753. incButton->setTooltip (getTooltip());
  39754. decButton->setTooltip (getTooltip());
  39755. }
  39756. else
  39757. {
  39758. incButton = 0;
  39759. decButton = 0;
  39760. }
  39761. setComponentEffect (lf.getSliderEffect());
  39762. resized();
  39763. repaint();
  39764. }
  39765. void Slider::setRange (const double newMin,
  39766. const double newMax,
  39767. const double newInt)
  39768. {
  39769. if (minimum != newMin
  39770. || maximum != newMax
  39771. || interval != newInt)
  39772. {
  39773. minimum = newMin;
  39774. maximum = newMax;
  39775. interval = newInt;
  39776. // figure out the number of DPs needed to display all values at this
  39777. // interval setting.
  39778. numDecimalPlaces = 7;
  39779. if (newInt != 0)
  39780. {
  39781. int v = abs ((int) (newInt * 10000000));
  39782. while ((v % 10) == 0)
  39783. {
  39784. --numDecimalPlaces;
  39785. v /= 10;
  39786. }
  39787. }
  39788. // keep the current values inside the new range..
  39789. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39790. {
  39791. setValue (getValue(), false, false);
  39792. }
  39793. else
  39794. {
  39795. setMinValue (getMinValue(), false, false);
  39796. setMaxValue (getMaxValue(), false, false);
  39797. }
  39798. updateText();
  39799. }
  39800. }
  39801. void Slider::triggerChangeMessage (const bool synchronous)
  39802. {
  39803. if (synchronous)
  39804. handleAsyncUpdate();
  39805. else
  39806. triggerAsyncUpdate();
  39807. valueChanged();
  39808. }
  39809. void Slider::valueChanged (Value& value)
  39810. {
  39811. if (value.refersToSameSourceAs (currentValue))
  39812. {
  39813. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39814. setValue (currentValue.getValue(), false, false);
  39815. }
  39816. else if (value.refersToSameSourceAs (valueMin))
  39817. setMinValue (valueMin.getValue(), false, false, true);
  39818. else if (value.refersToSameSourceAs (valueMax))
  39819. setMaxValue (valueMax.getValue(), false, false, true);
  39820. }
  39821. double Slider::getValue() const
  39822. {
  39823. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39824. // methods to get the two values.
  39825. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39826. return currentValue.getValue();
  39827. }
  39828. void Slider::setValue (double newValue,
  39829. const bool sendUpdateMessage,
  39830. const bool sendMessageSynchronously)
  39831. {
  39832. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39833. // methods to set the two values.
  39834. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39835. newValue = constrainedValue (newValue);
  39836. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39837. {
  39838. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39839. newValue = jlimit ((double) valueMin.getValue(),
  39840. (double) valueMax.getValue(),
  39841. newValue);
  39842. }
  39843. if (newValue != lastCurrentValue)
  39844. {
  39845. if (valueBox != 0)
  39846. valueBox->hideEditor (true);
  39847. lastCurrentValue = newValue;
  39848. currentValue = newValue;
  39849. updateText();
  39850. repaint();
  39851. if (popupDisplay != 0)
  39852. {
  39853. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39854. ->updatePosition (getTextFromValue (newValue));
  39855. popupDisplay->repaint();
  39856. }
  39857. if (sendUpdateMessage)
  39858. triggerChangeMessage (sendMessageSynchronously);
  39859. }
  39860. }
  39861. double Slider::getMinValue() const
  39862. {
  39863. // The minimum value only applies to sliders that are in two- or three-value mode.
  39864. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39865. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39866. return valueMin.getValue();
  39867. }
  39868. double Slider::getMaxValue() const
  39869. {
  39870. // The maximum value only applies to sliders that are in two- or three-value mode.
  39871. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39872. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39873. return valueMax.getValue();
  39874. }
  39875. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39876. {
  39877. // The minimum value only applies to sliders that are in two- or three-value mode.
  39878. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39879. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39880. newValue = constrainedValue (newValue);
  39881. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39882. {
  39883. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39884. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39885. newValue = jmin ((double) valueMax.getValue(), newValue);
  39886. }
  39887. else
  39888. {
  39889. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39890. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39891. newValue = jmin (lastCurrentValue, newValue);
  39892. }
  39893. if (lastValueMin != newValue)
  39894. {
  39895. lastValueMin = newValue;
  39896. valueMin = newValue;
  39897. repaint();
  39898. if (popupDisplay != 0)
  39899. {
  39900. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39901. ->updatePosition (getTextFromValue (newValue));
  39902. popupDisplay->repaint();
  39903. }
  39904. if (sendUpdateMessage)
  39905. triggerChangeMessage (sendMessageSynchronously);
  39906. }
  39907. }
  39908. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39909. {
  39910. // The maximum value only applies to sliders that are in two- or three-value mode.
  39911. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39912. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39913. newValue = constrainedValue (newValue);
  39914. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39915. {
  39916. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39917. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39918. newValue = jmax ((double) valueMin.getValue(), newValue);
  39919. }
  39920. else
  39921. {
  39922. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39923. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39924. newValue = jmax (lastCurrentValue, newValue);
  39925. }
  39926. if (lastValueMax != newValue)
  39927. {
  39928. lastValueMax = newValue;
  39929. valueMax = newValue;
  39930. repaint();
  39931. if (popupDisplay != 0)
  39932. {
  39933. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39934. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39935. popupDisplay->repaint();
  39936. }
  39937. if (sendUpdateMessage)
  39938. triggerChangeMessage (sendMessageSynchronously);
  39939. }
  39940. }
  39941. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39942. const double valueToSetOnDoubleClick)
  39943. {
  39944. doubleClickToValue = isDoubleClickEnabled;
  39945. doubleClickReturnValue = valueToSetOnDoubleClick;
  39946. }
  39947. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39948. {
  39949. isEnabled_ = doubleClickToValue;
  39950. return doubleClickReturnValue;
  39951. }
  39952. void Slider::updateText()
  39953. {
  39954. if (valueBox != 0)
  39955. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39956. }
  39957. void Slider::setTextValueSuffix (const String& suffix)
  39958. {
  39959. if (textSuffix != suffix)
  39960. {
  39961. textSuffix = suffix;
  39962. updateText();
  39963. }
  39964. }
  39965. const String Slider::getTextValueSuffix() const
  39966. {
  39967. return textSuffix;
  39968. }
  39969. const String Slider::getTextFromValue (double v)
  39970. {
  39971. if (getNumDecimalPlacesToDisplay() > 0)
  39972. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39973. else
  39974. return String (roundToInt (v)) + getTextValueSuffix();
  39975. }
  39976. double Slider::getValueFromText (const String& text)
  39977. {
  39978. String t (text.trimStart());
  39979. if (t.endsWith (textSuffix))
  39980. t = t.substring (0, t.length() - textSuffix.length());
  39981. while (t.startsWithChar ('+'))
  39982. t = t.substring (1).trimStart();
  39983. return t.initialSectionContainingOnly ("0123456789.,-")
  39984. .getDoubleValue();
  39985. }
  39986. double Slider::proportionOfLengthToValue (double proportion)
  39987. {
  39988. if (skewFactor != 1.0 && proportion > 0.0)
  39989. proportion = exp (log (proportion) / skewFactor);
  39990. return minimum + (maximum - minimum) * proportion;
  39991. }
  39992. double Slider::valueToProportionOfLength (double value)
  39993. {
  39994. const double n = (value - minimum) / (maximum - minimum);
  39995. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39996. }
  39997. double Slider::snapValue (double attemptedValue, const bool)
  39998. {
  39999. return attemptedValue;
  40000. }
  40001. void Slider::startedDragging()
  40002. {
  40003. }
  40004. void Slider::stoppedDragging()
  40005. {
  40006. }
  40007. void Slider::valueChanged()
  40008. {
  40009. }
  40010. void Slider::enablementChanged()
  40011. {
  40012. repaint();
  40013. }
  40014. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40015. {
  40016. menuEnabled = menuEnabled_;
  40017. }
  40018. void Slider::setScrollWheelEnabled (const bool enabled)
  40019. {
  40020. scrollWheelEnabled = enabled;
  40021. }
  40022. void Slider::labelTextChanged (Label* label)
  40023. {
  40024. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40025. if (newValue != (double) currentValue.getValue())
  40026. {
  40027. sendDragStart();
  40028. setValue (newValue, true, true);
  40029. sendDragEnd();
  40030. }
  40031. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40032. }
  40033. void Slider::buttonClicked (Button* button)
  40034. {
  40035. if (style == IncDecButtons)
  40036. {
  40037. sendDragStart();
  40038. if (button == incButton)
  40039. setValue (snapValue (getValue() + interval, false), true, true);
  40040. else if (button == decButton)
  40041. setValue (snapValue (getValue() - interval, false), true, true);
  40042. sendDragEnd();
  40043. }
  40044. }
  40045. double Slider::constrainedValue (double value) const
  40046. {
  40047. if (interval > 0)
  40048. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40049. if (value <= minimum || maximum <= minimum)
  40050. value = minimum;
  40051. else if (value >= maximum)
  40052. value = maximum;
  40053. return value;
  40054. }
  40055. float Slider::getLinearSliderPos (const double value)
  40056. {
  40057. double sliderPosProportional;
  40058. if (maximum > minimum)
  40059. {
  40060. if (value < minimum)
  40061. {
  40062. sliderPosProportional = 0.0;
  40063. }
  40064. else if (value > maximum)
  40065. {
  40066. sliderPosProportional = 1.0;
  40067. }
  40068. else
  40069. {
  40070. sliderPosProportional = valueToProportionOfLength (value);
  40071. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40072. }
  40073. }
  40074. else
  40075. {
  40076. sliderPosProportional = 0.5;
  40077. }
  40078. if (isVertical() || style == IncDecButtons)
  40079. sliderPosProportional = 1.0 - sliderPosProportional;
  40080. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40081. }
  40082. bool Slider::isHorizontal() const
  40083. {
  40084. return style == LinearHorizontal
  40085. || style == LinearBar
  40086. || style == TwoValueHorizontal
  40087. || style == ThreeValueHorizontal;
  40088. }
  40089. bool Slider::isVertical() const
  40090. {
  40091. return style == LinearVertical
  40092. || style == TwoValueVertical
  40093. || style == ThreeValueVertical;
  40094. }
  40095. bool Slider::incDecDragDirectionIsHorizontal() const
  40096. {
  40097. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40098. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40099. }
  40100. float Slider::getPositionOfValue (const double value)
  40101. {
  40102. if (isHorizontal() || isVertical())
  40103. {
  40104. return getLinearSliderPos (value);
  40105. }
  40106. else
  40107. {
  40108. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40109. return 0.0f;
  40110. }
  40111. }
  40112. void Slider::paint (Graphics& g)
  40113. {
  40114. if (style != IncDecButtons)
  40115. {
  40116. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40117. {
  40118. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40119. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40120. getLookAndFeel().drawRotarySlider (g,
  40121. sliderRect.getX(),
  40122. sliderRect.getY(),
  40123. sliderRect.getWidth(),
  40124. sliderRect.getHeight(),
  40125. sliderPos,
  40126. rotaryStart, rotaryEnd,
  40127. *this);
  40128. }
  40129. else
  40130. {
  40131. getLookAndFeel().drawLinearSlider (g,
  40132. sliderRect.getX(),
  40133. sliderRect.getY(),
  40134. sliderRect.getWidth(),
  40135. sliderRect.getHeight(),
  40136. getLinearSliderPos (lastCurrentValue),
  40137. getLinearSliderPos (lastValueMin),
  40138. getLinearSliderPos (lastValueMax),
  40139. style,
  40140. *this);
  40141. }
  40142. if (style == LinearBar && valueBox == 0)
  40143. {
  40144. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40145. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40146. }
  40147. }
  40148. }
  40149. void Slider::resized()
  40150. {
  40151. int minXSpace = 0;
  40152. int minYSpace = 0;
  40153. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40154. minXSpace = 30;
  40155. else
  40156. minYSpace = 15;
  40157. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40158. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40159. if (style == LinearBar)
  40160. {
  40161. if (valueBox != 0)
  40162. valueBox->setBounds (getLocalBounds());
  40163. }
  40164. else
  40165. {
  40166. if (textBoxPos == NoTextBox)
  40167. {
  40168. sliderRect = getLocalBounds();
  40169. }
  40170. else if (textBoxPos == TextBoxLeft)
  40171. {
  40172. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40173. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40174. }
  40175. else if (textBoxPos == TextBoxRight)
  40176. {
  40177. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40178. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40179. }
  40180. else if (textBoxPos == TextBoxAbove)
  40181. {
  40182. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40183. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40184. }
  40185. else if (textBoxPos == TextBoxBelow)
  40186. {
  40187. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40188. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40189. }
  40190. }
  40191. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40192. if (style == LinearBar)
  40193. {
  40194. const int barIndent = 1;
  40195. sliderRegionStart = barIndent;
  40196. sliderRegionSize = getWidth() - barIndent * 2;
  40197. sliderRect.setBounds (sliderRegionStart, barIndent,
  40198. sliderRegionSize, getHeight() - barIndent * 2);
  40199. }
  40200. else if (isHorizontal())
  40201. {
  40202. sliderRegionStart = sliderRect.getX() + indent;
  40203. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40204. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40205. sliderRegionSize, sliderRect.getHeight());
  40206. }
  40207. else if (isVertical())
  40208. {
  40209. sliderRegionStart = sliderRect.getY() + indent;
  40210. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40211. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40212. sliderRect.getWidth(), sliderRegionSize);
  40213. }
  40214. else
  40215. {
  40216. sliderRegionStart = 0;
  40217. sliderRegionSize = 100;
  40218. }
  40219. if (style == IncDecButtons)
  40220. {
  40221. Rectangle<int> buttonRect (sliderRect);
  40222. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40223. buttonRect.expand (-2, 0);
  40224. else
  40225. buttonRect.expand (0, -2);
  40226. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40227. if (incDecButtonsSideBySide)
  40228. {
  40229. decButton->setBounds (buttonRect.getX(),
  40230. buttonRect.getY(),
  40231. buttonRect.getWidth() / 2,
  40232. buttonRect.getHeight());
  40233. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40234. incButton->setBounds (buttonRect.getCentreX(),
  40235. buttonRect.getY(),
  40236. buttonRect.getWidth() / 2,
  40237. buttonRect.getHeight());
  40238. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40239. }
  40240. else
  40241. {
  40242. incButton->setBounds (buttonRect.getX(),
  40243. buttonRect.getY(),
  40244. buttonRect.getWidth(),
  40245. buttonRect.getHeight() / 2);
  40246. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40247. decButton->setBounds (buttonRect.getX(),
  40248. buttonRect.getCentreY(),
  40249. buttonRect.getWidth(),
  40250. buttonRect.getHeight() / 2);
  40251. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40252. }
  40253. }
  40254. }
  40255. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40256. {
  40257. repaint();
  40258. }
  40259. void Slider::mouseDown (const MouseEvent& e)
  40260. {
  40261. mouseWasHidden = false;
  40262. incDecDragged = false;
  40263. mouseXWhenLastDragged = e.x;
  40264. mouseYWhenLastDragged = e.y;
  40265. mouseDragStartX = e.getMouseDownX();
  40266. mouseDragStartY = e.getMouseDownY();
  40267. if (isEnabled())
  40268. {
  40269. if (e.mods.isPopupMenu() && menuEnabled)
  40270. {
  40271. menuShown = true;
  40272. PopupMenu m;
  40273. m.setLookAndFeel (&getLookAndFeel());
  40274. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40275. m.addSeparator();
  40276. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40277. {
  40278. PopupMenu rotaryMenu;
  40279. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40280. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40281. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40282. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40283. }
  40284. const int r = m.show();
  40285. if (r == 1)
  40286. {
  40287. setVelocityBasedMode (! isVelocityBased);
  40288. }
  40289. else if (r == 2)
  40290. {
  40291. setSliderStyle (Rotary);
  40292. }
  40293. else if (r == 3)
  40294. {
  40295. setSliderStyle (RotaryHorizontalDrag);
  40296. }
  40297. else if (r == 4)
  40298. {
  40299. setSliderStyle (RotaryVerticalDrag);
  40300. }
  40301. }
  40302. else if (maximum > minimum)
  40303. {
  40304. menuShown = false;
  40305. if (valueBox != 0)
  40306. valueBox->hideEditor (true);
  40307. sliderBeingDragged = 0;
  40308. if (style == TwoValueHorizontal
  40309. || style == TwoValueVertical
  40310. || style == ThreeValueHorizontal
  40311. || style == ThreeValueVertical)
  40312. {
  40313. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40314. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40315. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40316. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40317. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40318. {
  40319. if (maxPosDistance <= minPosDistance)
  40320. sliderBeingDragged = 2;
  40321. else
  40322. sliderBeingDragged = 1;
  40323. }
  40324. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40325. {
  40326. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40327. sliderBeingDragged = 1;
  40328. else if (normalPosDistance >= maxPosDistance)
  40329. sliderBeingDragged = 2;
  40330. }
  40331. }
  40332. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40333. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40334. * valueToProportionOfLength (currentValue.getValue());
  40335. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40336. : ((sliderBeingDragged == 1) ? valueMin
  40337. : currentValue)).getValue();
  40338. valueOnMouseDown = valueWhenLastDragged;
  40339. if (popupDisplayEnabled)
  40340. {
  40341. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40342. popupDisplay = popup;
  40343. if (parentForPopupDisplay != 0)
  40344. {
  40345. parentForPopupDisplay->addChildComponent (popup);
  40346. }
  40347. else
  40348. {
  40349. popup->addToDesktop (0);
  40350. }
  40351. popup->setVisible (true);
  40352. }
  40353. sendDragStart();
  40354. mouseDrag (e);
  40355. }
  40356. }
  40357. }
  40358. void Slider::mouseUp (const MouseEvent&)
  40359. {
  40360. if (isEnabled()
  40361. && (! menuShown)
  40362. && (maximum > minimum)
  40363. && (style != IncDecButtons || incDecDragged))
  40364. {
  40365. restoreMouseIfHidden();
  40366. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40367. triggerChangeMessage (false);
  40368. sendDragEnd();
  40369. popupDisplay = 0;
  40370. if (style == IncDecButtons)
  40371. {
  40372. incButton->setState (Button::buttonNormal);
  40373. decButton->setState (Button::buttonNormal);
  40374. }
  40375. }
  40376. }
  40377. void Slider::restoreMouseIfHidden()
  40378. {
  40379. if (mouseWasHidden)
  40380. {
  40381. mouseWasHidden = false;
  40382. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40383. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40384. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40385. : ((sliderBeingDragged == 1) ? getMinValue()
  40386. : (double) currentValue.getValue());
  40387. Point<int> mousePos;
  40388. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40389. {
  40390. mousePos = Desktop::getLastMouseDownPosition();
  40391. if (style == RotaryHorizontalDrag)
  40392. {
  40393. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40394. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40395. }
  40396. else
  40397. {
  40398. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40399. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40400. }
  40401. }
  40402. else
  40403. {
  40404. const int pixelPos = (int) getLinearSliderPos (pos);
  40405. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40406. isVertical() ? pixelPos : (getHeight() / 2)));
  40407. }
  40408. Desktop::setMousePosition (mousePos);
  40409. }
  40410. }
  40411. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40412. {
  40413. if (isEnabled()
  40414. && style != IncDecButtons
  40415. && style != Rotary
  40416. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40417. {
  40418. restoreMouseIfHidden();
  40419. }
  40420. }
  40421. namespace SliderHelpers
  40422. {
  40423. double smallestAngleBetween (double a1, double a2) throw()
  40424. {
  40425. return jmin (std::abs (a1 - a2),
  40426. std::abs (a1 + double_Pi * 2.0 - a2),
  40427. std::abs (a2 + double_Pi * 2.0 - a1));
  40428. }
  40429. }
  40430. void Slider::mouseDrag (const MouseEvent& e)
  40431. {
  40432. if (isEnabled()
  40433. && (! menuShown)
  40434. && (maximum > minimum))
  40435. {
  40436. if (style == Rotary)
  40437. {
  40438. int dx = e.x - sliderRect.getCentreX();
  40439. int dy = e.y - sliderRect.getCentreY();
  40440. if (dx * dx + dy * dy > 25)
  40441. {
  40442. double angle = std::atan2 ((double) dx, (double) -dy);
  40443. while (angle < 0.0)
  40444. angle += double_Pi * 2.0;
  40445. if (rotaryStop && ! e.mouseWasClicked())
  40446. {
  40447. if (std::abs (angle - lastAngle) > double_Pi)
  40448. {
  40449. if (angle >= lastAngle)
  40450. angle -= double_Pi * 2.0;
  40451. else
  40452. angle += double_Pi * 2.0;
  40453. }
  40454. if (angle >= lastAngle)
  40455. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40456. else
  40457. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40458. }
  40459. else
  40460. {
  40461. while (angle < rotaryStart)
  40462. angle += double_Pi * 2.0;
  40463. if (angle > rotaryEnd)
  40464. {
  40465. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40466. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40467. angle = rotaryStart;
  40468. else
  40469. angle = rotaryEnd;
  40470. }
  40471. }
  40472. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40473. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40474. lastAngle = angle;
  40475. }
  40476. }
  40477. else
  40478. {
  40479. if (style == LinearBar && e.mouseWasClicked()
  40480. && valueBox != 0 && valueBox->isEditable())
  40481. return;
  40482. if (style == IncDecButtons && ! incDecDragged)
  40483. {
  40484. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40485. return;
  40486. incDecDragged = true;
  40487. mouseDragStartX = e.x;
  40488. mouseDragStartY = e.y;
  40489. }
  40490. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40491. : false))
  40492. || ((maximum - minimum) / sliderRegionSize < interval))
  40493. {
  40494. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40495. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40496. if (style == RotaryHorizontalDrag
  40497. || style == RotaryVerticalDrag
  40498. || style == IncDecButtons
  40499. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40500. && ! snapsToMousePos))
  40501. {
  40502. const int mouseDiff = (style == RotaryHorizontalDrag
  40503. || style == LinearHorizontal
  40504. || style == LinearBar
  40505. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40506. ? e.x - mouseDragStartX
  40507. : mouseDragStartY - e.y;
  40508. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40509. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40510. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40511. if (style == IncDecButtons)
  40512. {
  40513. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40514. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40515. }
  40516. }
  40517. else
  40518. {
  40519. if (isVertical())
  40520. scaledMousePos = 1.0 - scaledMousePos;
  40521. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40522. }
  40523. }
  40524. else
  40525. {
  40526. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40527. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40528. ? e.x - mouseXWhenLastDragged
  40529. : e.y - mouseYWhenLastDragged;
  40530. const double maxSpeed = jmax (200, sliderRegionSize);
  40531. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40532. if (speed != 0)
  40533. {
  40534. speed = 0.2 * velocityModeSensitivity
  40535. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40536. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40537. / maxSpeed))));
  40538. if (mouseDiff < 0)
  40539. speed = -speed;
  40540. if (isVertical() || style == RotaryVerticalDrag
  40541. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40542. speed = -speed;
  40543. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40544. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40545. e.source.enableUnboundedMouseMovement (true, false);
  40546. mouseWasHidden = true;
  40547. }
  40548. }
  40549. }
  40550. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40551. if (sliderBeingDragged == 0)
  40552. {
  40553. setValue (snapValue (valueWhenLastDragged, true),
  40554. ! sendChangeOnlyOnRelease, true);
  40555. }
  40556. else if (sliderBeingDragged == 1)
  40557. {
  40558. setMinValue (snapValue (valueWhenLastDragged, true),
  40559. ! sendChangeOnlyOnRelease, false, true);
  40560. if (e.mods.isShiftDown())
  40561. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40562. else
  40563. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40564. }
  40565. else
  40566. {
  40567. jassert (sliderBeingDragged == 2);
  40568. setMaxValue (snapValue (valueWhenLastDragged, true),
  40569. ! sendChangeOnlyOnRelease, false, true);
  40570. if (e.mods.isShiftDown())
  40571. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40572. else
  40573. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40574. }
  40575. mouseXWhenLastDragged = e.x;
  40576. mouseYWhenLastDragged = e.y;
  40577. }
  40578. }
  40579. void Slider::mouseDoubleClick (const MouseEvent&)
  40580. {
  40581. if (doubleClickToValue
  40582. && isEnabled()
  40583. && style != IncDecButtons
  40584. && minimum <= doubleClickReturnValue
  40585. && maximum >= doubleClickReturnValue)
  40586. {
  40587. sendDragStart();
  40588. setValue (doubleClickReturnValue, true, true);
  40589. sendDragEnd();
  40590. }
  40591. }
  40592. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40593. {
  40594. if (scrollWheelEnabled && isEnabled()
  40595. && style != TwoValueHorizontal
  40596. && style != TwoValueVertical)
  40597. {
  40598. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40599. {
  40600. if (valueBox != 0)
  40601. valueBox->hideEditor (false);
  40602. const double value = (double) currentValue.getValue();
  40603. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40604. const double currentPos = valueToProportionOfLength (value);
  40605. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40606. double delta = (newValue != value)
  40607. ? jmax (std::abs (newValue - value), interval) : 0;
  40608. if (value > newValue)
  40609. delta = -delta;
  40610. sendDragStart();
  40611. setValue (snapValue (value + delta, false), true, true);
  40612. sendDragEnd();
  40613. }
  40614. }
  40615. else
  40616. {
  40617. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40618. }
  40619. }
  40620. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40621. {
  40622. }
  40623. void SliderListener::sliderDragEnded (Slider*)
  40624. {
  40625. }
  40626. END_JUCE_NAMESPACE
  40627. /*** End of inlined file: juce_Slider.cpp ***/
  40628. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40629. BEGIN_JUCE_NAMESPACE
  40630. class DragOverlayComp : public Component
  40631. {
  40632. public:
  40633. DragOverlayComp (const Image& image_)
  40634. : image (image_)
  40635. {
  40636. image.duplicateIfShared();
  40637. image.multiplyAllAlphas (0.8f);
  40638. setAlwaysOnTop (true);
  40639. }
  40640. void paint (Graphics& g)
  40641. {
  40642. g.drawImageAt (image, 0, 0);
  40643. }
  40644. private:
  40645. Image image;
  40646. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40647. };
  40648. TableHeaderComponent::TableHeaderComponent()
  40649. : columnsChanged (false),
  40650. columnsResized (false),
  40651. sortChanged (false),
  40652. menuActive (true),
  40653. stretchToFit (false),
  40654. columnIdBeingResized (0),
  40655. columnIdBeingDragged (0),
  40656. columnIdUnderMouse (0),
  40657. lastDeliberateWidth (0)
  40658. {
  40659. }
  40660. TableHeaderComponent::~TableHeaderComponent()
  40661. {
  40662. dragOverlayComp = 0;
  40663. }
  40664. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40665. {
  40666. menuActive = hasMenu;
  40667. }
  40668. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40669. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40670. {
  40671. if (onlyCountVisibleColumns)
  40672. {
  40673. int num = 0;
  40674. for (int i = columns.size(); --i >= 0;)
  40675. if (columns.getUnchecked(i)->isVisible())
  40676. ++num;
  40677. return num;
  40678. }
  40679. else
  40680. {
  40681. return columns.size();
  40682. }
  40683. }
  40684. const String TableHeaderComponent::getColumnName (const int columnId) const
  40685. {
  40686. const ColumnInfo* const ci = getInfoForId (columnId);
  40687. return ci != 0 ? ci->name : String::empty;
  40688. }
  40689. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40690. {
  40691. ColumnInfo* const ci = getInfoForId (columnId);
  40692. if (ci != 0 && ci->name != newName)
  40693. {
  40694. ci->name = newName;
  40695. sendColumnsChanged();
  40696. }
  40697. }
  40698. void TableHeaderComponent::addColumn (const String& columnName,
  40699. const int columnId,
  40700. const int width,
  40701. const int minimumWidth,
  40702. const int maximumWidth,
  40703. const int propertyFlags,
  40704. const int insertIndex)
  40705. {
  40706. // can't have a duplicate or null ID!
  40707. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40708. jassert (width > 0);
  40709. ColumnInfo* const ci = new ColumnInfo();
  40710. ci->name = columnName;
  40711. ci->id = columnId;
  40712. ci->width = width;
  40713. ci->lastDeliberateWidth = width;
  40714. ci->minimumWidth = minimumWidth;
  40715. ci->maximumWidth = maximumWidth;
  40716. if (ci->maximumWidth < 0)
  40717. ci->maximumWidth = std::numeric_limits<int>::max();
  40718. jassert (ci->maximumWidth >= ci->minimumWidth);
  40719. ci->propertyFlags = propertyFlags;
  40720. columns.insert (insertIndex, ci);
  40721. sendColumnsChanged();
  40722. }
  40723. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40724. {
  40725. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40726. if (index >= 0)
  40727. {
  40728. columns.remove (index);
  40729. sortChanged = true;
  40730. sendColumnsChanged();
  40731. }
  40732. }
  40733. void TableHeaderComponent::removeAllColumns()
  40734. {
  40735. if (columns.size() > 0)
  40736. {
  40737. columns.clear();
  40738. sendColumnsChanged();
  40739. }
  40740. }
  40741. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40742. {
  40743. const int currentIndex = getIndexOfColumnId (columnId, false);
  40744. newIndex = visibleIndexToTotalIndex (newIndex);
  40745. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40746. {
  40747. columns.move (currentIndex, newIndex);
  40748. sendColumnsChanged();
  40749. }
  40750. }
  40751. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40752. {
  40753. const ColumnInfo* const ci = getInfoForId (columnId);
  40754. return ci != 0 ? ci->width : 0;
  40755. }
  40756. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40757. {
  40758. ColumnInfo* const ci = getInfoForId (columnId);
  40759. if (ci != 0 && ci->width != newWidth)
  40760. {
  40761. const int numColumns = getNumColumns (true);
  40762. ci->lastDeliberateWidth = ci->width
  40763. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40764. if (stretchToFit)
  40765. {
  40766. const int index = getIndexOfColumnId (columnId, true) + 1;
  40767. if (isPositiveAndBelow (index, numColumns))
  40768. {
  40769. const int x = getColumnPosition (index).getX();
  40770. if (lastDeliberateWidth == 0)
  40771. lastDeliberateWidth = getTotalWidth();
  40772. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40773. }
  40774. }
  40775. repaint();
  40776. columnsResized = true;
  40777. triggerAsyncUpdate();
  40778. }
  40779. }
  40780. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40781. {
  40782. int n = 0;
  40783. for (int i = 0; i < columns.size(); ++i)
  40784. {
  40785. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40786. {
  40787. if (columns.getUnchecked(i)->id == columnId)
  40788. return n;
  40789. ++n;
  40790. }
  40791. }
  40792. return -1;
  40793. }
  40794. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40795. {
  40796. if (onlyCountVisibleColumns)
  40797. index = visibleIndexToTotalIndex (index);
  40798. const ColumnInfo* const ci = columns [index];
  40799. return (ci != 0) ? ci->id : 0;
  40800. }
  40801. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40802. {
  40803. int x = 0, width = 0, n = 0;
  40804. for (int i = 0; i < columns.size(); ++i)
  40805. {
  40806. x += width;
  40807. if (columns.getUnchecked(i)->isVisible())
  40808. {
  40809. width = columns.getUnchecked(i)->width;
  40810. if (n++ == index)
  40811. break;
  40812. }
  40813. else
  40814. {
  40815. width = 0;
  40816. }
  40817. }
  40818. return Rectangle<int> (x, 0, width, getHeight());
  40819. }
  40820. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40821. {
  40822. if (xToFind >= 0)
  40823. {
  40824. int x = 0;
  40825. for (int i = 0; i < columns.size(); ++i)
  40826. {
  40827. const ColumnInfo* const ci = columns.getUnchecked(i);
  40828. if (ci->isVisible())
  40829. {
  40830. x += ci->width;
  40831. if (xToFind < x)
  40832. return ci->id;
  40833. }
  40834. }
  40835. }
  40836. return 0;
  40837. }
  40838. int TableHeaderComponent::getTotalWidth() const
  40839. {
  40840. int w = 0;
  40841. for (int i = columns.size(); --i >= 0;)
  40842. if (columns.getUnchecked(i)->isVisible())
  40843. w += columns.getUnchecked(i)->width;
  40844. return w;
  40845. }
  40846. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40847. {
  40848. stretchToFit = shouldStretchToFit;
  40849. lastDeliberateWidth = getTotalWidth();
  40850. resized();
  40851. }
  40852. bool TableHeaderComponent::isStretchToFitActive() const
  40853. {
  40854. return stretchToFit;
  40855. }
  40856. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40857. {
  40858. if (stretchToFit && getWidth() > 0
  40859. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40860. {
  40861. lastDeliberateWidth = targetTotalWidth;
  40862. resizeColumnsToFit (0, targetTotalWidth);
  40863. }
  40864. }
  40865. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40866. {
  40867. targetTotalWidth = jmax (targetTotalWidth, 0);
  40868. StretchableObjectResizer sor;
  40869. int i;
  40870. for (i = firstColumnIndex; i < columns.size(); ++i)
  40871. {
  40872. ColumnInfo* const ci = columns.getUnchecked(i);
  40873. if (ci->isVisible())
  40874. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40875. }
  40876. sor.resizeToFit (targetTotalWidth);
  40877. int visIndex = 0;
  40878. for (i = firstColumnIndex; i < columns.size(); ++i)
  40879. {
  40880. ColumnInfo* const ci = columns.getUnchecked(i);
  40881. if (ci->isVisible())
  40882. {
  40883. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40884. (int) std::floor (sor.getItemSize (visIndex++)));
  40885. if (newWidth != ci->width)
  40886. {
  40887. ci->width = newWidth;
  40888. repaint();
  40889. columnsResized = true;
  40890. triggerAsyncUpdate();
  40891. }
  40892. }
  40893. }
  40894. }
  40895. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40896. {
  40897. ColumnInfo* const ci = getInfoForId (columnId);
  40898. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40899. {
  40900. if (shouldBeVisible)
  40901. ci->propertyFlags |= visible;
  40902. else
  40903. ci->propertyFlags &= ~visible;
  40904. sendColumnsChanged();
  40905. resized();
  40906. }
  40907. }
  40908. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40909. {
  40910. const ColumnInfo* const ci = getInfoForId (columnId);
  40911. return ci != 0 && ci->isVisible();
  40912. }
  40913. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40914. {
  40915. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40916. {
  40917. for (int i = columns.size(); --i >= 0;)
  40918. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40919. ColumnInfo* const ci = getInfoForId (columnId);
  40920. if (ci != 0)
  40921. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40922. reSortTable();
  40923. }
  40924. }
  40925. int TableHeaderComponent::getSortColumnId() const
  40926. {
  40927. for (int i = columns.size(); --i >= 0;)
  40928. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40929. return columns.getUnchecked(i)->id;
  40930. return 0;
  40931. }
  40932. bool TableHeaderComponent::isSortedForwards() const
  40933. {
  40934. for (int i = columns.size(); --i >= 0;)
  40935. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40936. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40937. return true;
  40938. }
  40939. void TableHeaderComponent::reSortTable()
  40940. {
  40941. sortChanged = true;
  40942. repaint();
  40943. triggerAsyncUpdate();
  40944. }
  40945. const String TableHeaderComponent::toString() const
  40946. {
  40947. String s;
  40948. XmlElement doc ("TABLELAYOUT");
  40949. doc.setAttribute ("sortedCol", getSortColumnId());
  40950. doc.setAttribute ("sortForwards", isSortedForwards());
  40951. for (int i = 0; i < columns.size(); ++i)
  40952. {
  40953. const ColumnInfo* const ci = columns.getUnchecked (i);
  40954. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40955. e->setAttribute ("id", ci->id);
  40956. e->setAttribute ("visible", ci->isVisible());
  40957. e->setAttribute ("width", ci->width);
  40958. }
  40959. return doc.createDocument (String::empty, true, false);
  40960. }
  40961. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40962. {
  40963. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  40964. int index = 0;
  40965. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40966. {
  40967. forEachXmlChildElement (*storedXml, col)
  40968. {
  40969. const int tabId = col->getIntAttribute ("id");
  40970. ColumnInfo* const ci = getInfoForId (tabId);
  40971. if (ci != 0)
  40972. {
  40973. columns.move (columns.indexOf (ci), index);
  40974. ci->width = col->getIntAttribute ("width");
  40975. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40976. }
  40977. ++index;
  40978. }
  40979. columnsResized = true;
  40980. sendColumnsChanged();
  40981. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40982. storedXml->getBoolAttribute ("sortForwards", true));
  40983. }
  40984. }
  40985. void TableHeaderComponent::addListener (Listener* const newListener)
  40986. {
  40987. listeners.addIfNotAlreadyThere (newListener);
  40988. }
  40989. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  40990. {
  40991. listeners.removeValue (listenerToRemove);
  40992. }
  40993. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40994. {
  40995. const ColumnInfo* const ci = getInfoForId (columnId);
  40996. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40997. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40998. }
  40999. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41000. {
  41001. for (int i = 0; i < columns.size(); ++i)
  41002. {
  41003. const ColumnInfo* const ci = columns.getUnchecked(i);
  41004. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41005. menu.addItem (ci->id, ci->name,
  41006. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41007. isColumnVisible (ci->id));
  41008. }
  41009. }
  41010. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41011. {
  41012. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41013. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41014. }
  41015. void TableHeaderComponent::paint (Graphics& g)
  41016. {
  41017. LookAndFeel& lf = getLookAndFeel();
  41018. lf.drawTableHeaderBackground (g, *this);
  41019. const Rectangle<int> clip (g.getClipBounds());
  41020. int x = 0;
  41021. for (int i = 0; i < columns.size(); ++i)
  41022. {
  41023. const ColumnInfo* const ci = columns.getUnchecked(i);
  41024. if (ci->isVisible())
  41025. {
  41026. if (x + ci->width > clip.getX()
  41027. && (ci->id != columnIdBeingDragged
  41028. || dragOverlayComp == 0
  41029. || ! dragOverlayComp->isVisible()))
  41030. {
  41031. Graphics::ScopedSaveState ss (g);
  41032. g.setOrigin (x, 0);
  41033. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41034. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41035. ci->id == columnIdUnderMouse,
  41036. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41037. ci->propertyFlags);
  41038. }
  41039. x += ci->width;
  41040. if (x >= clip.getRight())
  41041. break;
  41042. }
  41043. }
  41044. }
  41045. void TableHeaderComponent::resized()
  41046. {
  41047. }
  41048. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41049. {
  41050. updateColumnUnderMouse (e.x, e.y);
  41051. }
  41052. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41053. {
  41054. updateColumnUnderMouse (e.x, e.y);
  41055. }
  41056. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41057. {
  41058. updateColumnUnderMouse (e.x, e.y);
  41059. }
  41060. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41061. {
  41062. repaint();
  41063. columnIdBeingResized = 0;
  41064. columnIdBeingDragged = 0;
  41065. if (columnIdUnderMouse != 0)
  41066. {
  41067. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41068. if (e.mods.isPopupMenu())
  41069. columnClicked (columnIdUnderMouse, e.mods);
  41070. }
  41071. if (menuActive && e.mods.isPopupMenu())
  41072. showColumnChooserMenu (columnIdUnderMouse);
  41073. }
  41074. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41075. {
  41076. if (columnIdBeingResized == 0
  41077. && columnIdBeingDragged == 0
  41078. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41079. {
  41080. dragOverlayComp = 0;
  41081. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41082. if (columnIdBeingResized != 0)
  41083. {
  41084. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41085. initialColumnWidth = ci->width;
  41086. }
  41087. else
  41088. {
  41089. beginDrag (e);
  41090. }
  41091. }
  41092. if (columnIdBeingResized != 0)
  41093. {
  41094. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41095. if (ci != 0)
  41096. {
  41097. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41098. initialColumnWidth + e.getDistanceFromDragStartX());
  41099. if (stretchToFit)
  41100. {
  41101. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41102. int minWidthOnRight = 0;
  41103. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41104. if (columns.getUnchecked (i)->isVisible())
  41105. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41106. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41107. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41108. }
  41109. setColumnWidth (columnIdBeingResized, w);
  41110. }
  41111. }
  41112. else if (columnIdBeingDragged != 0)
  41113. {
  41114. if (e.y >= -50 && e.y < getHeight() + 50)
  41115. {
  41116. if (dragOverlayComp != 0)
  41117. {
  41118. dragOverlayComp->setVisible (true);
  41119. dragOverlayComp->setBounds (jlimit (0,
  41120. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41121. e.x - draggingColumnOffset),
  41122. 0,
  41123. dragOverlayComp->getWidth(),
  41124. getHeight());
  41125. for (int i = columns.size(); --i >= 0;)
  41126. {
  41127. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41128. int newIndex = currentIndex;
  41129. if (newIndex > 0)
  41130. {
  41131. // if the previous column isn't draggable, we can't move our column
  41132. // past it, because that'd change the undraggable column's position..
  41133. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41134. if ((previous->propertyFlags & draggable) != 0)
  41135. {
  41136. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41137. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41138. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41139. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41140. {
  41141. --newIndex;
  41142. }
  41143. }
  41144. }
  41145. if (newIndex < columns.size() - 1)
  41146. {
  41147. // if the next column isn't draggable, we can't move our column
  41148. // past it, because that'd change the undraggable column's position..
  41149. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41150. if ((nextCol->propertyFlags & draggable) != 0)
  41151. {
  41152. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41153. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41154. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41155. > abs (dragOverlayComp->getRight() - rightOfNext))
  41156. {
  41157. ++newIndex;
  41158. }
  41159. }
  41160. }
  41161. if (newIndex != currentIndex)
  41162. moveColumn (columnIdBeingDragged, newIndex);
  41163. else
  41164. break;
  41165. }
  41166. }
  41167. }
  41168. else
  41169. {
  41170. endDrag (draggingColumnOriginalIndex);
  41171. }
  41172. }
  41173. }
  41174. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41175. {
  41176. if (columnIdBeingDragged == 0)
  41177. {
  41178. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41179. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41180. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41181. {
  41182. columnIdBeingDragged = 0;
  41183. }
  41184. else
  41185. {
  41186. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41187. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41188. const int temp = columnIdBeingDragged;
  41189. columnIdBeingDragged = 0;
  41190. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41191. columnIdBeingDragged = temp;
  41192. dragOverlayComp->setBounds (columnRect);
  41193. for (int i = listeners.size(); --i >= 0;)
  41194. {
  41195. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41196. i = jmin (i, listeners.size() - 1);
  41197. }
  41198. }
  41199. }
  41200. }
  41201. void TableHeaderComponent::endDrag (const int finalIndex)
  41202. {
  41203. if (columnIdBeingDragged != 0)
  41204. {
  41205. moveColumn (columnIdBeingDragged, finalIndex);
  41206. columnIdBeingDragged = 0;
  41207. repaint();
  41208. for (int i = listeners.size(); --i >= 0;)
  41209. {
  41210. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41211. i = jmin (i, listeners.size() - 1);
  41212. }
  41213. }
  41214. }
  41215. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41216. {
  41217. mouseDrag (e);
  41218. for (int i = columns.size(); --i >= 0;)
  41219. if (columns.getUnchecked (i)->isVisible())
  41220. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41221. columnIdBeingResized = 0;
  41222. repaint();
  41223. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41224. updateColumnUnderMouse (e.x, e.y);
  41225. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41226. columnClicked (columnIdUnderMouse, e.mods);
  41227. dragOverlayComp = 0;
  41228. }
  41229. const MouseCursor TableHeaderComponent::getMouseCursor()
  41230. {
  41231. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41232. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41233. return Component::getMouseCursor();
  41234. }
  41235. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41236. {
  41237. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41238. }
  41239. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41240. {
  41241. for (int i = columns.size(); --i >= 0;)
  41242. if (columns.getUnchecked(i)->id == id)
  41243. return columns.getUnchecked(i);
  41244. return 0;
  41245. }
  41246. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41247. {
  41248. int n = 0;
  41249. for (int i = 0; i < columns.size(); ++i)
  41250. {
  41251. if (columns.getUnchecked(i)->isVisible())
  41252. {
  41253. if (n == visibleIndex)
  41254. return i;
  41255. ++n;
  41256. }
  41257. }
  41258. return -1;
  41259. }
  41260. void TableHeaderComponent::sendColumnsChanged()
  41261. {
  41262. if (stretchToFit && lastDeliberateWidth > 0)
  41263. resizeAllColumnsToFit (lastDeliberateWidth);
  41264. repaint();
  41265. columnsChanged = true;
  41266. triggerAsyncUpdate();
  41267. }
  41268. void TableHeaderComponent::handleAsyncUpdate()
  41269. {
  41270. const bool changed = columnsChanged || sortChanged;
  41271. const bool sized = columnsResized || changed;
  41272. const bool sorted = sortChanged;
  41273. columnsChanged = false;
  41274. columnsResized = false;
  41275. sortChanged = false;
  41276. if (sorted)
  41277. {
  41278. for (int i = listeners.size(); --i >= 0;)
  41279. {
  41280. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41281. i = jmin (i, listeners.size() - 1);
  41282. }
  41283. }
  41284. if (changed)
  41285. {
  41286. for (int i = listeners.size(); --i >= 0;)
  41287. {
  41288. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41289. i = jmin (i, listeners.size() - 1);
  41290. }
  41291. }
  41292. if (sized)
  41293. {
  41294. for (int i = listeners.size(); --i >= 0;)
  41295. {
  41296. listeners.getUnchecked(i)->tableColumnsResized (this);
  41297. i = jmin (i, listeners.size() - 1);
  41298. }
  41299. }
  41300. }
  41301. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41302. {
  41303. if (isPositiveAndBelow (mouseX, getWidth()))
  41304. {
  41305. const int draggableDistance = 3;
  41306. int x = 0;
  41307. for (int i = 0; i < columns.size(); ++i)
  41308. {
  41309. const ColumnInfo* const ci = columns.getUnchecked(i);
  41310. if (ci->isVisible())
  41311. {
  41312. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41313. && (ci->propertyFlags & resizable) != 0)
  41314. return ci->id;
  41315. x += ci->width;
  41316. }
  41317. }
  41318. }
  41319. return 0;
  41320. }
  41321. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41322. {
  41323. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41324. ? getColumnIdAtX (x) : 0;
  41325. if (newCol != columnIdUnderMouse)
  41326. {
  41327. columnIdUnderMouse = newCol;
  41328. repaint();
  41329. }
  41330. }
  41331. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41332. {
  41333. PopupMenu m;
  41334. addMenuItems (m, columnIdClicked);
  41335. if (m.getNumItems() > 0)
  41336. {
  41337. m.setLookAndFeel (&getLookAndFeel());
  41338. const int result = m.show();
  41339. if (result != 0)
  41340. reactToMenuItem (result, columnIdClicked);
  41341. }
  41342. }
  41343. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41344. {
  41345. }
  41346. END_JUCE_NAMESPACE
  41347. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41348. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41349. BEGIN_JUCE_NAMESPACE
  41350. class TableListRowComp : public Component,
  41351. public TooltipClient
  41352. {
  41353. public:
  41354. TableListRowComp (TableListBox& owner_)
  41355. : owner (owner_), row (-1), isSelected (false)
  41356. {
  41357. }
  41358. void paint (Graphics& g)
  41359. {
  41360. TableListBoxModel* const model = owner.getModel();
  41361. if (model != 0)
  41362. {
  41363. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41364. const TableHeaderComponent& header = owner.getHeader();
  41365. const int numColumns = header.getNumColumns (true);
  41366. for (int i = 0; i < numColumns; ++i)
  41367. {
  41368. if (columnComponents[i] == 0)
  41369. {
  41370. const int columnId = header.getColumnIdOfIndex (i, true);
  41371. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41372. Graphics::ScopedSaveState ss (g);
  41373. g.reduceClipRegion (columnRect);
  41374. g.setOrigin (columnRect.getX(), 0);
  41375. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41376. }
  41377. }
  41378. }
  41379. }
  41380. void update (const int newRow, const bool isNowSelected)
  41381. {
  41382. jassert (newRow >= 0);
  41383. if (newRow != row || isNowSelected != isSelected)
  41384. {
  41385. row = newRow;
  41386. isSelected = isNowSelected;
  41387. repaint();
  41388. }
  41389. TableListBoxModel* const model = owner.getModel();
  41390. if (model != 0 && row < owner.getNumRows())
  41391. {
  41392. const Identifier columnProperty ("_tableColumnId");
  41393. const int numColumns = owner.getHeader().getNumColumns (true);
  41394. for (int i = 0; i < numColumns; ++i)
  41395. {
  41396. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41397. Component* comp = columnComponents[i];
  41398. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41399. {
  41400. columnComponents.set (i, 0);
  41401. comp = 0;
  41402. }
  41403. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41404. columnComponents.set (i, comp, false);
  41405. if (comp != 0)
  41406. {
  41407. comp->getProperties().set (columnProperty, columnId);
  41408. addAndMakeVisible (comp);
  41409. resizeCustomComp (i);
  41410. }
  41411. }
  41412. columnComponents.removeRange (numColumns, columnComponents.size());
  41413. }
  41414. else
  41415. {
  41416. columnComponents.clear();
  41417. }
  41418. }
  41419. void resized()
  41420. {
  41421. for (int i = columnComponents.size(); --i >= 0;)
  41422. resizeCustomComp (i);
  41423. }
  41424. void resizeCustomComp (const int index)
  41425. {
  41426. Component* const c = columnComponents.getUnchecked (index);
  41427. if (c != 0)
  41428. c->setBounds (owner.getHeader().getColumnPosition (index)
  41429. .withY (0).withHeight (getHeight()));
  41430. }
  41431. void mouseDown (const MouseEvent& e)
  41432. {
  41433. isDragging = false;
  41434. selectRowOnMouseUp = false;
  41435. if (isEnabled())
  41436. {
  41437. if (! isSelected)
  41438. {
  41439. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41440. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41441. if (columnId != 0 && owner.getModel() != 0)
  41442. owner.getModel()->cellClicked (row, columnId, e);
  41443. }
  41444. else
  41445. {
  41446. selectRowOnMouseUp = true;
  41447. }
  41448. }
  41449. }
  41450. void mouseDrag (const MouseEvent& e)
  41451. {
  41452. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41453. {
  41454. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41455. if (selectedRows.size() > 0)
  41456. {
  41457. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41458. if (dragDescription.isNotEmpty())
  41459. {
  41460. isDragging = true;
  41461. owner.startDragAndDrop (e, dragDescription);
  41462. }
  41463. }
  41464. }
  41465. }
  41466. void mouseUp (const MouseEvent& e)
  41467. {
  41468. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41469. {
  41470. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41471. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41472. if (columnId != 0 && owner.getModel() != 0)
  41473. owner.getModel()->cellClicked (row, columnId, e);
  41474. }
  41475. }
  41476. void mouseDoubleClick (const MouseEvent& e)
  41477. {
  41478. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41479. if (columnId != 0 && owner.getModel() != 0)
  41480. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41481. }
  41482. const String getTooltip()
  41483. {
  41484. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41485. if (columnId != 0 && owner.getModel() != 0)
  41486. return owner.getModel()->getCellTooltip (row, columnId);
  41487. return String::empty;
  41488. }
  41489. Component* findChildComponentForColumn (const int columnId) const
  41490. {
  41491. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41492. }
  41493. private:
  41494. TableListBox& owner;
  41495. OwnedArray<Component> columnComponents;
  41496. int row;
  41497. bool isSelected, isDragging, selectRowOnMouseUp;
  41498. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41499. };
  41500. class TableListBoxHeader : public TableHeaderComponent
  41501. {
  41502. public:
  41503. TableListBoxHeader (TableListBox& owner_)
  41504. : owner (owner_)
  41505. {
  41506. }
  41507. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41508. {
  41509. if (owner.isAutoSizeMenuOptionShown())
  41510. {
  41511. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41512. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41513. menu.addSeparator();
  41514. }
  41515. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41516. }
  41517. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41518. {
  41519. switch (menuReturnId)
  41520. {
  41521. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41522. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41523. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41524. }
  41525. }
  41526. private:
  41527. TableListBox& owner;
  41528. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41529. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41530. };
  41531. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41532. : ListBox (name, 0),
  41533. header (0), model (model_),
  41534. autoSizeOptionsShown (true)
  41535. {
  41536. ListBox::model = this;
  41537. setHeader (new TableListBoxHeader (*this));
  41538. }
  41539. TableListBox::~TableListBox()
  41540. {
  41541. header = 0;
  41542. }
  41543. void TableListBox::setModel (TableListBoxModel* const newModel)
  41544. {
  41545. if (model != newModel)
  41546. {
  41547. model = newModel;
  41548. updateContent();
  41549. }
  41550. }
  41551. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41552. {
  41553. jassert (newHeader != 0); // you need to supply a real header for a table!
  41554. Rectangle<int> newBounds (0, 0, 100, 28);
  41555. if (header != 0)
  41556. newBounds = header->getBounds();
  41557. header = newHeader;
  41558. header->setBounds (newBounds);
  41559. setHeaderComponent (header);
  41560. header->addListener (this);
  41561. }
  41562. int TableListBox::getHeaderHeight() const
  41563. {
  41564. return header->getHeight();
  41565. }
  41566. void TableListBox::setHeaderHeight (const int newHeight)
  41567. {
  41568. header->setSize (header->getWidth(), newHeight);
  41569. resized();
  41570. }
  41571. void TableListBox::autoSizeColumn (const int columnId)
  41572. {
  41573. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41574. if (width > 0)
  41575. header->setColumnWidth (columnId, width);
  41576. }
  41577. void TableListBox::autoSizeAllColumns()
  41578. {
  41579. for (int i = 0; i < header->getNumColumns (true); ++i)
  41580. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41581. }
  41582. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41583. {
  41584. autoSizeOptionsShown = shouldBeShown;
  41585. }
  41586. bool TableListBox::isAutoSizeMenuOptionShown() const
  41587. {
  41588. return autoSizeOptionsShown;
  41589. }
  41590. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41591. const bool relativeToComponentTopLeft) const
  41592. {
  41593. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41594. if (relativeToComponentTopLeft)
  41595. headerCell.translate (header->getX(), 0);
  41596. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41597. .withX (headerCell.getX())
  41598. .withWidth (headerCell.getWidth());
  41599. }
  41600. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41601. {
  41602. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41603. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41604. }
  41605. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41606. {
  41607. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41608. if (scrollbar != 0)
  41609. {
  41610. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41611. double x = scrollbar->getCurrentRangeStart();
  41612. const double w = scrollbar->getCurrentRangeSize();
  41613. if (pos.getX() < x)
  41614. x = pos.getX();
  41615. else if (pos.getRight() > x + w)
  41616. x += jmax (0.0, pos.getRight() - (x + w));
  41617. scrollbar->setCurrentRangeStart (x);
  41618. }
  41619. }
  41620. int TableListBox::getNumRows()
  41621. {
  41622. return model != 0 ? model->getNumRows() : 0;
  41623. }
  41624. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41625. {
  41626. }
  41627. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41628. {
  41629. if (existingComponentToUpdate == 0)
  41630. existingComponentToUpdate = new TableListRowComp (*this);
  41631. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41632. return existingComponentToUpdate;
  41633. }
  41634. void TableListBox::selectedRowsChanged (int row)
  41635. {
  41636. if (model != 0)
  41637. model->selectedRowsChanged (row);
  41638. }
  41639. void TableListBox::deleteKeyPressed (int row)
  41640. {
  41641. if (model != 0)
  41642. model->deleteKeyPressed (row);
  41643. }
  41644. void TableListBox::returnKeyPressed (int row)
  41645. {
  41646. if (model != 0)
  41647. model->returnKeyPressed (row);
  41648. }
  41649. void TableListBox::backgroundClicked()
  41650. {
  41651. if (model != 0)
  41652. model->backgroundClicked();
  41653. }
  41654. void TableListBox::listWasScrolled()
  41655. {
  41656. if (model != 0)
  41657. model->listWasScrolled();
  41658. }
  41659. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41660. {
  41661. setMinimumContentWidth (header->getTotalWidth());
  41662. repaint();
  41663. updateColumnComponents();
  41664. }
  41665. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41666. {
  41667. setMinimumContentWidth (header->getTotalWidth());
  41668. repaint();
  41669. updateColumnComponents();
  41670. }
  41671. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41672. {
  41673. if (model != 0)
  41674. model->sortOrderChanged (header->getSortColumnId(),
  41675. header->isSortedForwards());
  41676. }
  41677. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41678. {
  41679. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41680. repaint();
  41681. }
  41682. void TableListBox::resized()
  41683. {
  41684. ListBox::resized();
  41685. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41686. setMinimumContentWidth (header->getTotalWidth());
  41687. }
  41688. void TableListBox::updateColumnComponents() const
  41689. {
  41690. const int firstRow = getRowContainingPosition (0, 0);
  41691. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41692. {
  41693. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41694. if (rowComp != 0)
  41695. rowComp->resized();
  41696. }
  41697. }
  41698. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41699. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41700. void TableListBoxModel::backgroundClicked() {}
  41701. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41702. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41703. void TableListBoxModel::selectedRowsChanged (int) {}
  41704. void TableListBoxModel::deleteKeyPressed (int) {}
  41705. void TableListBoxModel::returnKeyPressed (int) {}
  41706. void TableListBoxModel::listWasScrolled() {}
  41707. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41708. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41709. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41710. {
  41711. (void) existingComponentToUpdate;
  41712. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41713. return 0;
  41714. }
  41715. END_JUCE_NAMESPACE
  41716. /*** End of inlined file: juce_TableListBox.cpp ***/
  41717. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41718. BEGIN_JUCE_NAMESPACE
  41719. // a word or space that can't be broken down any further
  41720. struct TextAtom
  41721. {
  41722. String atomText;
  41723. float width;
  41724. int numChars;
  41725. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41726. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41727. const String getText (const juce_wchar passwordCharacter) const
  41728. {
  41729. if (passwordCharacter == 0)
  41730. return atomText;
  41731. else
  41732. return String::repeatedString (String::charToString (passwordCharacter),
  41733. atomText.length());
  41734. }
  41735. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41736. {
  41737. if (passwordCharacter == 0)
  41738. return atomText.substring (0, numChars);
  41739. else if (isNewLine())
  41740. return String::empty;
  41741. else
  41742. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41743. }
  41744. };
  41745. // a run of text with a single font and colour
  41746. class TextEditor::UniformTextSection
  41747. {
  41748. public:
  41749. UniformTextSection (const String& text,
  41750. const Font& font_,
  41751. const Colour& colour_,
  41752. const juce_wchar passwordCharacter)
  41753. : font (font_),
  41754. colour (colour_)
  41755. {
  41756. initialiseAtoms (text, passwordCharacter);
  41757. }
  41758. UniformTextSection (const UniformTextSection& other)
  41759. : font (other.font),
  41760. colour (other.colour)
  41761. {
  41762. atoms.ensureStorageAllocated (other.atoms.size());
  41763. for (int i = 0; i < other.atoms.size(); ++i)
  41764. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41765. }
  41766. ~UniformTextSection()
  41767. {
  41768. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41769. }
  41770. void clear()
  41771. {
  41772. for (int i = atoms.size(); --i >= 0;)
  41773. delete getAtom(i);
  41774. atoms.clear();
  41775. }
  41776. int getNumAtoms() const
  41777. {
  41778. return atoms.size();
  41779. }
  41780. TextAtom* getAtom (const int index) const throw()
  41781. {
  41782. return atoms.getUnchecked (index);
  41783. }
  41784. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41785. {
  41786. if (other.atoms.size() > 0)
  41787. {
  41788. TextAtom* const lastAtom = atoms.getLast();
  41789. int i = 0;
  41790. if (lastAtom != 0)
  41791. {
  41792. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41793. {
  41794. TextAtom* const first = other.getAtom(0);
  41795. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41796. {
  41797. lastAtom->atomText += first->atomText;
  41798. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41799. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41800. delete first;
  41801. ++i;
  41802. }
  41803. }
  41804. }
  41805. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41806. while (i < other.atoms.size())
  41807. {
  41808. atoms.add (other.getAtom(i));
  41809. ++i;
  41810. }
  41811. }
  41812. }
  41813. UniformTextSection* split (const int indexToBreakAt,
  41814. const juce_wchar passwordCharacter)
  41815. {
  41816. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41817. font, colour,
  41818. passwordCharacter);
  41819. int index = 0;
  41820. for (int i = 0; i < atoms.size(); ++i)
  41821. {
  41822. TextAtom* const atom = getAtom(i);
  41823. const int nextIndex = index + atom->numChars;
  41824. if (index == indexToBreakAt)
  41825. {
  41826. int j;
  41827. for (j = i; j < atoms.size(); ++j)
  41828. section2->atoms.add (getAtom (j));
  41829. for (j = atoms.size(); --j >= i;)
  41830. atoms.remove (j);
  41831. break;
  41832. }
  41833. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41834. {
  41835. TextAtom* const secondAtom = new TextAtom();
  41836. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41837. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41838. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41839. section2->atoms.add (secondAtom);
  41840. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41841. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41842. atom->numChars = (uint16) (indexToBreakAt - index);
  41843. int j;
  41844. for (j = i + 1; j < atoms.size(); ++j)
  41845. section2->atoms.add (getAtom (j));
  41846. for (j = atoms.size(); --j > i;)
  41847. atoms.remove (j);
  41848. break;
  41849. }
  41850. index = nextIndex;
  41851. }
  41852. return section2;
  41853. }
  41854. void appendAllText (String::Concatenator& concatenator) const
  41855. {
  41856. for (int i = 0; i < atoms.size(); ++i)
  41857. concatenator.append (getAtom(i)->atomText);
  41858. }
  41859. void appendSubstring (String::Concatenator& concatenator,
  41860. const Range<int>& range) const
  41861. {
  41862. int index = 0;
  41863. for (int i = 0; i < atoms.size(); ++i)
  41864. {
  41865. const TextAtom* const atom = getAtom (i);
  41866. const int nextIndex = index + atom->numChars;
  41867. if (range.getStart() < nextIndex)
  41868. {
  41869. if (range.getEnd() <= index)
  41870. break;
  41871. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41872. if (! r.isEmpty())
  41873. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41874. }
  41875. index = nextIndex;
  41876. }
  41877. }
  41878. int getTotalLength() const
  41879. {
  41880. int total = 0;
  41881. for (int i = atoms.size(); --i >= 0;)
  41882. total += getAtom(i)->numChars;
  41883. return total;
  41884. }
  41885. void setFont (const Font& newFont,
  41886. const juce_wchar passwordCharacter)
  41887. {
  41888. if (font != newFont)
  41889. {
  41890. font = newFont;
  41891. for (int i = atoms.size(); --i >= 0;)
  41892. {
  41893. TextAtom* const atom = atoms.getUnchecked(i);
  41894. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41895. }
  41896. }
  41897. }
  41898. Font font;
  41899. Colour colour;
  41900. private:
  41901. Array <TextAtom*> atoms;
  41902. void initialiseAtoms (const String& textToParse,
  41903. const juce_wchar passwordCharacter)
  41904. {
  41905. int i = 0;
  41906. const int len = textToParse.length();
  41907. const juce_wchar* const text = textToParse;
  41908. while (i < len)
  41909. {
  41910. int start = i;
  41911. // create a whitespace atom unless it starts with non-ws
  41912. if (CharacterFunctions::isWhitespace (text[i])
  41913. && text[i] != '\r'
  41914. && text[i] != '\n')
  41915. {
  41916. while (i < len
  41917. && CharacterFunctions::isWhitespace (text[i])
  41918. && text[i] != '\r'
  41919. && text[i] != '\n')
  41920. {
  41921. ++i;
  41922. }
  41923. }
  41924. else
  41925. {
  41926. if (text[i] == '\r')
  41927. {
  41928. ++i;
  41929. if ((i < len) && (text[i] == '\n'))
  41930. {
  41931. ++start;
  41932. ++i;
  41933. }
  41934. }
  41935. else if (text[i] == '\n')
  41936. {
  41937. ++i;
  41938. }
  41939. else
  41940. {
  41941. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41942. ++i;
  41943. }
  41944. }
  41945. TextAtom* const atom = new TextAtom();
  41946. atom->atomText = String (text + start, i - start);
  41947. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41948. atom->numChars = (uint16) (i - start);
  41949. atoms.add (atom);
  41950. }
  41951. }
  41952. UniformTextSection& operator= (const UniformTextSection& other);
  41953. JUCE_LEAK_DETECTOR (UniformTextSection);
  41954. };
  41955. class TextEditor::Iterator
  41956. {
  41957. public:
  41958. Iterator (const Array <UniformTextSection*>& sections_,
  41959. const float wordWrapWidth_,
  41960. const juce_wchar passwordCharacter_)
  41961. : indexInText (0),
  41962. lineY (0),
  41963. lineHeight (0),
  41964. maxDescent (0),
  41965. atomX (0),
  41966. atomRight (0),
  41967. atom (0),
  41968. currentSection (0),
  41969. sections (sections_),
  41970. sectionIndex (0),
  41971. atomIndex (0),
  41972. wordWrapWidth (wordWrapWidth_),
  41973. passwordCharacter (passwordCharacter_)
  41974. {
  41975. jassert (wordWrapWidth_ > 0);
  41976. if (sections.size() > 0)
  41977. {
  41978. currentSection = sections.getUnchecked (sectionIndex);
  41979. if (currentSection != 0)
  41980. beginNewLine();
  41981. }
  41982. }
  41983. Iterator (const Iterator& other)
  41984. : indexInText (other.indexInText),
  41985. lineY (other.lineY),
  41986. lineHeight (other.lineHeight),
  41987. maxDescent (other.maxDescent),
  41988. atomX (other.atomX),
  41989. atomRight (other.atomRight),
  41990. atom (other.atom),
  41991. currentSection (other.currentSection),
  41992. sections (other.sections),
  41993. sectionIndex (other.sectionIndex),
  41994. atomIndex (other.atomIndex),
  41995. wordWrapWidth (other.wordWrapWidth),
  41996. passwordCharacter (other.passwordCharacter),
  41997. tempAtom (other.tempAtom)
  41998. {
  41999. }
  42000. bool next()
  42001. {
  42002. if (atom == &tempAtom)
  42003. {
  42004. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42005. if (numRemaining > 0)
  42006. {
  42007. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42008. atomX = 0;
  42009. if (tempAtom.numChars > 0)
  42010. lineY += lineHeight;
  42011. indexInText += tempAtom.numChars;
  42012. GlyphArrangement g;
  42013. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42014. int split;
  42015. for (split = 0; split < g.getNumGlyphs(); ++split)
  42016. if (shouldWrap (g.getGlyph (split).getRight()))
  42017. break;
  42018. if (split > 0 && split <= numRemaining)
  42019. {
  42020. tempAtom.numChars = (uint16) split;
  42021. tempAtom.width = g.getGlyph (split - 1).getRight();
  42022. atomRight = atomX + tempAtom.width;
  42023. return true;
  42024. }
  42025. }
  42026. }
  42027. bool forceNewLine = false;
  42028. if (sectionIndex >= sections.size())
  42029. {
  42030. moveToEndOfLastAtom();
  42031. return false;
  42032. }
  42033. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42034. {
  42035. if (atomIndex >= currentSection->getNumAtoms())
  42036. {
  42037. if (++sectionIndex >= sections.size())
  42038. {
  42039. moveToEndOfLastAtom();
  42040. return false;
  42041. }
  42042. atomIndex = 0;
  42043. currentSection = sections.getUnchecked (sectionIndex);
  42044. }
  42045. else
  42046. {
  42047. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42048. if (! lastAtom->isWhitespace())
  42049. {
  42050. // handle the case where the last atom in a section is actually part of the same
  42051. // word as the first atom of the next section...
  42052. float right = atomRight + lastAtom->width;
  42053. float lineHeight2 = lineHeight;
  42054. float maxDescent2 = maxDescent;
  42055. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42056. {
  42057. const UniformTextSection* const s = sections.getUnchecked (section);
  42058. if (s->getNumAtoms() == 0)
  42059. break;
  42060. const TextAtom* const nextAtom = s->getAtom (0);
  42061. if (nextAtom->isWhitespace())
  42062. break;
  42063. right += nextAtom->width;
  42064. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42065. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42066. if (shouldWrap (right))
  42067. {
  42068. lineHeight = lineHeight2;
  42069. maxDescent = maxDescent2;
  42070. forceNewLine = true;
  42071. break;
  42072. }
  42073. if (s->getNumAtoms() > 1)
  42074. break;
  42075. }
  42076. }
  42077. }
  42078. }
  42079. if (atom != 0)
  42080. {
  42081. atomX = atomRight;
  42082. indexInText += atom->numChars;
  42083. if (atom->isNewLine())
  42084. beginNewLine();
  42085. }
  42086. atom = currentSection->getAtom (atomIndex);
  42087. atomRight = atomX + atom->width;
  42088. ++atomIndex;
  42089. if (shouldWrap (atomRight) || forceNewLine)
  42090. {
  42091. if (atom->isWhitespace())
  42092. {
  42093. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42094. atomRight = jmin (atomRight, wordWrapWidth);
  42095. }
  42096. else
  42097. {
  42098. atomRight = atom->width;
  42099. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42100. {
  42101. tempAtom = *atom;
  42102. tempAtom.width = 0;
  42103. tempAtom.numChars = 0;
  42104. atom = &tempAtom;
  42105. if (atomX > 0)
  42106. beginNewLine();
  42107. return next();
  42108. }
  42109. beginNewLine();
  42110. return true;
  42111. }
  42112. }
  42113. return true;
  42114. }
  42115. void beginNewLine()
  42116. {
  42117. atomX = 0;
  42118. lineY += lineHeight;
  42119. int tempSectionIndex = sectionIndex;
  42120. int tempAtomIndex = atomIndex;
  42121. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42122. lineHeight = section->font.getHeight();
  42123. maxDescent = section->font.getDescent();
  42124. float x = (atom != 0) ? atom->width : 0;
  42125. while (! shouldWrap (x))
  42126. {
  42127. if (tempSectionIndex >= sections.size())
  42128. break;
  42129. bool checkSize = false;
  42130. if (tempAtomIndex >= section->getNumAtoms())
  42131. {
  42132. if (++tempSectionIndex >= sections.size())
  42133. break;
  42134. tempAtomIndex = 0;
  42135. section = sections.getUnchecked (tempSectionIndex);
  42136. checkSize = true;
  42137. }
  42138. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42139. if (nextAtom == 0)
  42140. break;
  42141. x += nextAtom->width;
  42142. if (shouldWrap (x) || nextAtom->isNewLine())
  42143. break;
  42144. if (checkSize)
  42145. {
  42146. lineHeight = jmax (lineHeight, section->font.getHeight());
  42147. maxDescent = jmax (maxDescent, section->font.getDescent());
  42148. }
  42149. ++tempAtomIndex;
  42150. }
  42151. }
  42152. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42153. {
  42154. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42155. {
  42156. if (lastSection != currentSection)
  42157. {
  42158. lastSection = currentSection;
  42159. g.setColour (currentSection->colour);
  42160. g.setFont (currentSection->font);
  42161. }
  42162. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42163. GlyphArrangement ga;
  42164. ga.addLineOfText (currentSection->font,
  42165. atom->getTrimmedText (passwordCharacter),
  42166. atomX,
  42167. (float) roundToInt (lineY + lineHeight - maxDescent));
  42168. ga.draw (g);
  42169. }
  42170. }
  42171. void drawSelection (Graphics& g,
  42172. const Range<int>& selection) const
  42173. {
  42174. const int startX = roundToInt (indexToX (selection.getStart()));
  42175. const int endX = roundToInt (indexToX (selection.getEnd()));
  42176. const int y = roundToInt (lineY);
  42177. const int nextY = roundToInt (lineY + lineHeight);
  42178. g.fillRect (startX, y, endX - startX, nextY - y);
  42179. }
  42180. void drawSelectedText (Graphics& g,
  42181. const Range<int>& selection,
  42182. const Colour& selectedTextColour) const
  42183. {
  42184. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42185. {
  42186. GlyphArrangement ga;
  42187. ga.addLineOfText (currentSection->font,
  42188. atom->getTrimmedText (passwordCharacter),
  42189. atomX,
  42190. (float) roundToInt (lineY + lineHeight - maxDescent));
  42191. if (selection.getEnd() < indexInText + atom->numChars)
  42192. {
  42193. GlyphArrangement ga2 (ga);
  42194. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42195. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42196. g.setColour (currentSection->colour);
  42197. ga2.draw (g);
  42198. }
  42199. if (selection.getStart() > indexInText)
  42200. {
  42201. GlyphArrangement ga2 (ga);
  42202. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42203. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42204. g.setColour (currentSection->colour);
  42205. ga2.draw (g);
  42206. }
  42207. g.setColour (selectedTextColour);
  42208. ga.draw (g);
  42209. }
  42210. }
  42211. float indexToX (const int indexToFind) const
  42212. {
  42213. if (indexToFind <= indexInText)
  42214. return atomX;
  42215. if (indexToFind >= indexInText + atom->numChars)
  42216. return atomRight;
  42217. GlyphArrangement g;
  42218. g.addLineOfText (currentSection->font,
  42219. atom->getText (passwordCharacter),
  42220. atomX, 0.0f);
  42221. if (indexToFind - indexInText >= g.getNumGlyphs())
  42222. return atomRight;
  42223. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42224. }
  42225. int xToIndex (const float xToFind) const
  42226. {
  42227. if (xToFind <= atomX || atom->isNewLine())
  42228. return indexInText;
  42229. if (xToFind >= atomRight)
  42230. return indexInText + atom->numChars;
  42231. GlyphArrangement g;
  42232. g.addLineOfText (currentSection->font,
  42233. atom->getText (passwordCharacter),
  42234. atomX, 0.0f);
  42235. int j;
  42236. for (j = 0; j < g.getNumGlyphs(); ++j)
  42237. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42238. break;
  42239. return indexInText + j;
  42240. }
  42241. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42242. {
  42243. while (next())
  42244. {
  42245. if (indexInText + atom->numChars > index)
  42246. {
  42247. cx = indexToX (index);
  42248. cy = lineY;
  42249. lineHeight_ = lineHeight;
  42250. return true;
  42251. }
  42252. }
  42253. cx = atomX;
  42254. cy = lineY;
  42255. lineHeight_ = lineHeight;
  42256. return false;
  42257. }
  42258. int indexInText;
  42259. float lineY, lineHeight, maxDescent;
  42260. float atomX, atomRight;
  42261. const TextAtom* atom;
  42262. const UniformTextSection* currentSection;
  42263. private:
  42264. const Array <UniformTextSection*>& sections;
  42265. int sectionIndex, atomIndex;
  42266. const float wordWrapWidth;
  42267. const juce_wchar passwordCharacter;
  42268. TextAtom tempAtom;
  42269. Iterator& operator= (const Iterator&);
  42270. void moveToEndOfLastAtom()
  42271. {
  42272. if (atom != 0)
  42273. {
  42274. atomX = atomRight;
  42275. if (atom->isNewLine())
  42276. {
  42277. atomX = 0.0f;
  42278. lineY += lineHeight;
  42279. }
  42280. }
  42281. }
  42282. bool shouldWrap (const float x) const
  42283. {
  42284. return (x - 0.0001f) >= wordWrapWidth;
  42285. }
  42286. JUCE_LEAK_DETECTOR (Iterator);
  42287. };
  42288. class TextEditor::InsertAction : public UndoableAction
  42289. {
  42290. public:
  42291. InsertAction (TextEditor& owner_,
  42292. const String& text_,
  42293. const int insertIndex_,
  42294. const Font& font_,
  42295. const Colour& colour_,
  42296. const int oldCaretPos_,
  42297. const int newCaretPos_)
  42298. : owner (owner_),
  42299. text (text_),
  42300. insertIndex (insertIndex_),
  42301. oldCaretPos (oldCaretPos_),
  42302. newCaretPos (newCaretPos_),
  42303. font (font_),
  42304. colour (colour_)
  42305. {
  42306. }
  42307. bool perform()
  42308. {
  42309. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42310. return true;
  42311. }
  42312. bool undo()
  42313. {
  42314. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42315. return true;
  42316. }
  42317. int getSizeInUnits()
  42318. {
  42319. return text.length() + 16;
  42320. }
  42321. private:
  42322. TextEditor& owner;
  42323. const String text;
  42324. const int insertIndex, oldCaretPos, newCaretPos;
  42325. const Font font;
  42326. const Colour colour;
  42327. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42328. };
  42329. class TextEditor::RemoveAction : public UndoableAction
  42330. {
  42331. public:
  42332. RemoveAction (TextEditor& owner_,
  42333. const Range<int> range_,
  42334. const int oldCaretPos_,
  42335. const int newCaretPos_,
  42336. const Array <UniformTextSection*>& removedSections_)
  42337. : owner (owner_),
  42338. range (range_),
  42339. oldCaretPos (oldCaretPos_),
  42340. newCaretPos (newCaretPos_),
  42341. removedSections (removedSections_)
  42342. {
  42343. }
  42344. ~RemoveAction()
  42345. {
  42346. for (int i = removedSections.size(); --i >= 0;)
  42347. {
  42348. UniformTextSection* const section = removedSections.getUnchecked (i);
  42349. section->clear();
  42350. delete section;
  42351. }
  42352. }
  42353. bool perform()
  42354. {
  42355. owner.remove (range, 0, newCaretPos);
  42356. return true;
  42357. }
  42358. bool undo()
  42359. {
  42360. owner.reinsert (range.getStart(), removedSections);
  42361. owner.moveCursorTo (oldCaretPos, false);
  42362. return true;
  42363. }
  42364. int getSizeInUnits()
  42365. {
  42366. int n = 0;
  42367. for (int i = removedSections.size(); --i >= 0;)
  42368. n += removedSections.getUnchecked (i)->getTotalLength();
  42369. return n + 16;
  42370. }
  42371. private:
  42372. TextEditor& owner;
  42373. const Range<int> range;
  42374. const int oldCaretPos, newCaretPos;
  42375. Array <UniformTextSection*> removedSections;
  42376. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42377. };
  42378. class TextEditor::TextHolderComponent : public Component,
  42379. public Timer,
  42380. public ValueListener
  42381. {
  42382. public:
  42383. TextHolderComponent (TextEditor& owner_)
  42384. : owner (owner_)
  42385. {
  42386. setWantsKeyboardFocus (false);
  42387. setInterceptsMouseClicks (false, true);
  42388. owner.getTextValue().addListener (this);
  42389. }
  42390. ~TextHolderComponent()
  42391. {
  42392. owner.getTextValue().removeListener (this);
  42393. }
  42394. void paint (Graphics& g)
  42395. {
  42396. owner.drawContent (g);
  42397. }
  42398. void timerCallback()
  42399. {
  42400. owner.timerCallbackInt();
  42401. }
  42402. const MouseCursor getMouseCursor()
  42403. {
  42404. return owner.getMouseCursor();
  42405. }
  42406. void valueChanged (Value&)
  42407. {
  42408. owner.textWasChangedByValue();
  42409. }
  42410. private:
  42411. TextEditor& owner;
  42412. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42413. };
  42414. class TextEditorViewport : public Viewport
  42415. {
  42416. public:
  42417. TextEditorViewport (TextEditor& owner_)
  42418. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42419. {
  42420. }
  42421. void visibleAreaChanged (const Rectangle<int>&)
  42422. {
  42423. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42424. // appear and disappear, causing the wrap width to change.
  42425. {
  42426. const float wordWrapWidth = owner.getWordWrapWidth();
  42427. if (wordWrapWidth != lastWordWrapWidth)
  42428. {
  42429. lastWordWrapWidth = wordWrapWidth;
  42430. rentrant = true;
  42431. owner.updateTextHolderSize();
  42432. rentrant = false;
  42433. }
  42434. }
  42435. }
  42436. private:
  42437. TextEditor& owner;
  42438. float lastWordWrapWidth;
  42439. bool rentrant;
  42440. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42441. };
  42442. namespace TextEditorDefs
  42443. {
  42444. const int flashSpeedIntervalMs = 380;
  42445. const int textChangeMessageId = 0x10003001;
  42446. const int returnKeyMessageId = 0x10003002;
  42447. const int escapeKeyMessageId = 0x10003003;
  42448. const int focusLossMessageId = 0x10003004;
  42449. const int maxActionsPerTransaction = 100;
  42450. int getCharacterCategory (const juce_wchar character)
  42451. {
  42452. return CharacterFunctions::isLetterOrDigit (character)
  42453. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42454. }
  42455. }
  42456. TextEditor::TextEditor (const String& name,
  42457. const juce_wchar passwordCharacter_)
  42458. : Component (name),
  42459. borderSize (1, 1, 1, 3),
  42460. readOnly (false),
  42461. multiline (false),
  42462. wordWrap (false),
  42463. returnKeyStartsNewLine (false),
  42464. caretVisible (true),
  42465. popupMenuEnabled (true),
  42466. selectAllTextWhenFocused (false),
  42467. scrollbarVisible (true),
  42468. wasFocused (false),
  42469. caretFlashState (true),
  42470. keepCursorOnScreen (true),
  42471. tabKeyUsed (false),
  42472. menuActive (false),
  42473. valueTextNeedsUpdating (false),
  42474. cursorX (0),
  42475. cursorY (0),
  42476. cursorHeight (0),
  42477. maxTextLength (0),
  42478. leftIndent (4),
  42479. topIndent (4),
  42480. lastTransactionTime (0),
  42481. currentFont (14.0f),
  42482. totalNumChars (0),
  42483. caretPosition (0),
  42484. passwordCharacter (passwordCharacter_),
  42485. dragType (notDragging)
  42486. {
  42487. setOpaque (true);
  42488. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42489. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42490. viewport->setWantsKeyboardFocus (false);
  42491. viewport->setScrollBarsShown (false, false);
  42492. setMouseCursor (MouseCursor::IBeamCursor);
  42493. setWantsKeyboardFocus (true);
  42494. }
  42495. TextEditor::~TextEditor()
  42496. {
  42497. textValue.referTo (Value());
  42498. clearInternal (0);
  42499. viewport = 0;
  42500. textHolder = 0;
  42501. }
  42502. void TextEditor::newTransaction()
  42503. {
  42504. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42505. undoManager.beginNewTransaction();
  42506. }
  42507. void TextEditor::doUndoRedo (const bool isRedo)
  42508. {
  42509. if (! isReadOnly())
  42510. {
  42511. if (isRedo ? undoManager.redo()
  42512. : undoManager.undo())
  42513. {
  42514. scrollToMakeSureCursorIsVisible();
  42515. repaint();
  42516. textChanged();
  42517. }
  42518. }
  42519. }
  42520. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42521. const bool shouldWordWrap)
  42522. {
  42523. if (multiline != shouldBeMultiLine
  42524. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42525. {
  42526. multiline = shouldBeMultiLine;
  42527. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42528. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42529. scrollbarVisible && multiline);
  42530. viewport->setViewPosition (0, 0);
  42531. resized();
  42532. scrollToMakeSureCursorIsVisible();
  42533. }
  42534. }
  42535. bool TextEditor::isMultiLine() const
  42536. {
  42537. return multiline;
  42538. }
  42539. void TextEditor::setScrollbarsShown (bool shown)
  42540. {
  42541. if (scrollbarVisible != shown)
  42542. {
  42543. scrollbarVisible = shown;
  42544. shown = shown && isMultiLine();
  42545. viewport->setScrollBarsShown (shown, shown);
  42546. }
  42547. }
  42548. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42549. {
  42550. if (readOnly != shouldBeReadOnly)
  42551. {
  42552. readOnly = shouldBeReadOnly;
  42553. enablementChanged();
  42554. }
  42555. }
  42556. bool TextEditor::isReadOnly() const
  42557. {
  42558. return readOnly || ! isEnabled();
  42559. }
  42560. bool TextEditor::isTextInputActive() const
  42561. {
  42562. return ! isReadOnly();
  42563. }
  42564. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42565. {
  42566. returnKeyStartsNewLine = shouldStartNewLine;
  42567. }
  42568. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42569. {
  42570. tabKeyUsed = shouldTabKeyBeUsed;
  42571. }
  42572. void TextEditor::setPopupMenuEnabled (const bool b)
  42573. {
  42574. popupMenuEnabled = b;
  42575. }
  42576. void TextEditor::setSelectAllWhenFocused (const bool b)
  42577. {
  42578. selectAllTextWhenFocused = b;
  42579. }
  42580. const Font TextEditor::getFont() const
  42581. {
  42582. return currentFont;
  42583. }
  42584. void TextEditor::setFont (const Font& newFont)
  42585. {
  42586. currentFont = newFont;
  42587. scrollToMakeSureCursorIsVisible();
  42588. }
  42589. void TextEditor::applyFontToAllText (const Font& newFont)
  42590. {
  42591. currentFont = newFont;
  42592. const Colour overallColour (findColour (textColourId));
  42593. for (int i = sections.size(); --i >= 0;)
  42594. {
  42595. UniformTextSection* const uts = sections.getUnchecked (i);
  42596. uts->setFont (newFont, passwordCharacter);
  42597. uts->colour = overallColour;
  42598. }
  42599. coalesceSimilarSections();
  42600. updateTextHolderSize();
  42601. scrollToMakeSureCursorIsVisible();
  42602. repaint();
  42603. }
  42604. void TextEditor::colourChanged()
  42605. {
  42606. setOpaque (findColour (backgroundColourId).isOpaque());
  42607. repaint();
  42608. }
  42609. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42610. {
  42611. caretVisible = shouldCaretBeVisible;
  42612. if (shouldCaretBeVisible)
  42613. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42614. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42615. : MouseCursor::NormalCursor);
  42616. }
  42617. void TextEditor::setInputRestrictions (const int maxLen,
  42618. const String& chars)
  42619. {
  42620. maxTextLength = jmax (0, maxLen);
  42621. allowedCharacters = chars;
  42622. }
  42623. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42624. {
  42625. textToShowWhenEmpty = text;
  42626. colourForTextWhenEmpty = colourToUse;
  42627. }
  42628. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42629. {
  42630. if (passwordCharacter != newPasswordCharacter)
  42631. {
  42632. passwordCharacter = newPasswordCharacter;
  42633. resized();
  42634. repaint();
  42635. }
  42636. }
  42637. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42638. {
  42639. viewport->setScrollBarThickness (newThicknessPixels);
  42640. }
  42641. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42642. {
  42643. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42644. }
  42645. void TextEditor::clear()
  42646. {
  42647. clearInternal (0);
  42648. updateTextHolderSize();
  42649. undoManager.clearUndoHistory();
  42650. }
  42651. void TextEditor::setText (const String& newText,
  42652. const bool sendTextChangeMessage)
  42653. {
  42654. const int newLength = newText.length();
  42655. if (newLength != getTotalNumChars() || getText() != newText)
  42656. {
  42657. const int oldCursorPos = caretPosition;
  42658. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42659. clearInternal (0);
  42660. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42661. // if you're adding text with line-feeds to a single-line text editor, it
  42662. // ain't gonna look right!
  42663. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42664. if (cursorWasAtEnd && ! isMultiLine())
  42665. moveCursorTo (getTotalNumChars(), false);
  42666. else
  42667. moveCursorTo (oldCursorPos, false);
  42668. if (sendTextChangeMessage)
  42669. textChanged();
  42670. updateTextHolderSize();
  42671. scrollToMakeSureCursorIsVisible();
  42672. undoManager.clearUndoHistory();
  42673. repaint();
  42674. }
  42675. }
  42676. Value& TextEditor::getTextValue()
  42677. {
  42678. if (valueTextNeedsUpdating)
  42679. {
  42680. valueTextNeedsUpdating = false;
  42681. textValue = getText();
  42682. }
  42683. return textValue;
  42684. }
  42685. void TextEditor::textWasChangedByValue()
  42686. {
  42687. if (textValue.getValueSource().getReferenceCount() > 1)
  42688. setText (textValue.getValue());
  42689. }
  42690. void TextEditor::textChanged()
  42691. {
  42692. updateTextHolderSize();
  42693. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42694. if (textValue.getValueSource().getReferenceCount() > 1)
  42695. {
  42696. valueTextNeedsUpdating = false;
  42697. textValue = getText();
  42698. }
  42699. }
  42700. void TextEditor::returnPressed()
  42701. {
  42702. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42703. }
  42704. void TextEditor::escapePressed()
  42705. {
  42706. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42707. }
  42708. void TextEditor::addListener (TextEditorListener* const newListener)
  42709. {
  42710. listeners.add (newListener);
  42711. }
  42712. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42713. {
  42714. listeners.remove (listenerToRemove);
  42715. }
  42716. void TextEditor::timerCallbackInt()
  42717. {
  42718. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42719. if (caretFlashState != newState)
  42720. {
  42721. caretFlashState = newState;
  42722. if (caretFlashState)
  42723. wasFocused = true;
  42724. if (caretVisible
  42725. && hasKeyboardFocus (false)
  42726. && ! isReadOnly())
  42727. {
  42728. repaintCaret();
  42729. }
  42730. }
  42731. const unsigned int now = Time::getApproximateMillisecondCounter();
  42732. if (now > lastTransactionTime + 200)
  42733. newTransaction();
  42734. }
  42735. void TextEditor::repaintCaret()
  42736. {
  42737. if (! findColour (caretColourId).isTransparent())
  42738. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42739. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42740. 4,
  42741. roundToInt (cursorHeight) + 2);
  42742. }
  42743. void TextEditor::repaintText (const Range<int>& range)
  42744. {
  42745. if (! range.isEmpty())
  42746. {
  42747. float x = 0, y = 0, lh = currentFont.getHeight();
  42748. const float wordWrapWidth = getWordWrapWidth();
  42749. if (wordWrapWidth > 0)
  42750. {
  42751. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42752. i.getCharPosition (range.getStart(), x, y, lh);
  42753. const int y1 = (int) y;
  42754. int y2;
  42755. if (range.getEnd() >= getTotalNumChars())
  42756. {
  42757. y2 = textHolder->getHeight();
  42758. }
  42759. else
  42760. {
  42761. i.getCharPosition (range.getEnd(), x, y, lh);
  42762. y2 = (int) (y + lh * 2.0f);
  42763. }
  42764. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42765. }
  42766. }
  42767. }
  42768. void TextEditor::moveCaret (int newCaretPos)
  42769. {
  42770. if (newCaretPos < 0)
  42771. newCaretPos = 0;
  42772. else if (newCaretPos > getTotalNumChars())
  42773. newCaretPos = getTotalNumChars();
  42774. if (newCaretPos != getCaretPosition())
  42775. {
  42776. repaintCaret();
  42777. caretFlashState = true;
  42778. caretPosition = newCaretPos;
  42779. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42780. scrollToMakeSureCursorIsVisible();
  42781. repaintCaret();
  42782. }
  42783. }
  42784. void TextEditor::setCaretPosition (const int newIndex)
  42785. {
  42786. moveCursorTo (newIndex, false);
  42787. }
  42788. int TextEditor::getCaretPosition() const
  42789. {
  42790. return caretPosition;
  42791. }
  42792. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42793. const int desiredCaretY)
  42794. {
  42795. updateCaretPosition();
  42796. int vx = roundToInt (cursorX) - desiredCaretX;
  42797. int vy = roundToInt (cursorY) - desiredCaretY;
  42798. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42799. {
  42800. vx += desiredCaretX - proportionOfWidth (0.2f);
  42801. }
  42802. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42803. {
  42804. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42805. }
  42806. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42807. if (! isMultiLine())
  42808. {
  42809. vy = viewport->getViewPositionY();
  42810. }
  42811. else
  42812. {
  42813. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42814. const int curH = roundToInt (cursorHeight);
  42815. if (desiredCaretY < 0)
  42816. {
  42817. vy = jmax (0, desiredCaretY + vy);
  42818. }
  42819. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42820. {
  42821. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42822. }
  42823. }
  42824. viewport->setViewPosition (vx, vy);
  42825. }
  42826. const Rectangle<int> TextEditor::getCaretRectangle()
  42827. {
  42828. updateCaretPosition();
  42829. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42830. roundToInt (cursorY) - viewport->getY(),
  42831. 1, roundToInt (cursorHeight));
  42832. }
  42833. float TextEditor::getWordWrapWidth() const
  42834. {
  42835. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42836. : 1.0e10f;
  42837. }
  42838. void TextEditor::updateTextHolderSize()
  42839. {
  42840. const float wordWrapWidth = getWordWrapWidth();
  42841. if (wordWrapWidth > 0)
  42842. {
  42843. float maxWidth = 0.0f;
  42844. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42845. while (i.next())
  42846. maxWidth = jmax (maxWidth, i.atomRight);
  42847. const int w = leftIndent + roundToInt (maxWidth);
  42848. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42849. currentFont.getHeight()));
  42850. textHolder->setSize (w + 1, h + 1);
  42851. }
  42852. }
  42853. int TextEditor::getTextWidth() const
  42854. {
  42855. return textHolder->getWidth();
  42856. }
  42857. int TextEditor::getTextHeight() const
  42858. {
  42859. return textHolder->getHeight();
  42860. }
  42861. void TextEditor::setIndents (const int newLeftIndent,
  42862. const int newTopIndent)
  42863. {
  42864. leftIndent = newLeftIndent;
  42865. topIndent = newTopIndent;
  42866. }
  42867. void TextEditor::setBorder (const BorderSize<int>& border)
  42868. {
  42869. borderSize = border;
  42870. resized();
  42871. }
  42872. const BorderSize<int> TextEditor::getBorder() const
  42873. {
  42874. return borderSize;
  42875. }
  42876. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42877. {
  42878. keepCursorOnScreen = shouldScrollToShowCursor;
  42879. }
  42880. void TextEditor::updateCaretPosition()
  42881. {
  42882. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42883. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42884. }
  42885. void TextEditor::scrollToMakeSureCursorIsVisible()
  42886. {
  42887. updateCaretPosition();
  42888. if (keepCursorOnScreen)
  42889. {
  42890. int x = viewport->getViewPositionX();
  42891. int y = viewport->getViewPositionY();
  42892. const int relativeCursorX = roundToInt (cursorX) - x;
  42893. const int relativeCursorY = roundToInt (cursorY) - y;
  42894. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42895. {
  42896. x += relativeCursorX - proportionOfWidth (0.2f);
  42897. }
  42898. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42899. {
  42900. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42901. }
  42902. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42903. if (! isMultiLine())
  42904. {
  42905. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42906. }
  42907. else
  42908. {
  42909. const int curH = roundToInt (cursorHeight);
  42910. if (relativeCursorY < 0)
  42911. {
  42912. y = jmax (0, relativeCursorY + y);
  42913. }
  42914. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42915. {
  42916. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42917. }
  42918. }
  42919. viewport->setViewPosition (x, y);
  42920. }
  42921. }
  42922. void TextEditor::moveCursorTo (const int newPosition,
  42923. const bool isSelecting)
  42924. {
  42925. if (isSelecting)
  42926. {
  42927. moveCaret (newPosition);
  42928. const Range<int> oldSelection (selection);
  42929. if (dragType == notDragging)
  42930. {
  42931. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42932. dragType = draggingSelectionStart;
  42933. else
  42934. dragType = draggingSelectionEnd;
  42935. }
  42936. if (dragType == draggingSelectionStart)
  42937. {
  42938. if (getCaretPosition() >= selection.getEnd())
  42939. dragType = draggingSelectionEnd;
  42940. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42941. }
  42942. else
  42943. {
  42944. if (getCaretPosition() < selection.getStart())
  42945. dragType = draggingSelectionStart;
  42946. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42947. }
  42948. repaintText (selection.getUnionWith (oldSelection));
  42949. }
  42950. else
  42951. {
  42952. dragType = notDragging;
  42953. repaintText (selection);
  42954. moveCaret (newPosition);
  42955. selection = Range<int>::emptyRange (getCaretPosition());
  42956. }
  42957. }
  42958. int TextEditor::getTextIndexAt (const int x,
  42959. const int y)
  42960. {
  42961. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42962. (float) (y + viewport->getViewPositionY() - topIndent));
  42963. }
  42964. void TextEditor::insertTextAtCaret (const String& newText_)
  42965. {
  42966. String newText (newText_);
  42967. if (allowedCharacters.isNotEmpty())
  42968. newText = newText.retainCharacters (allowedCharacters);
  42969. if (! isMultiLine())
  42970. newText = newText.replaceCharacters ("\r\n", " ");
  42971. else
  42972. newText = newText.replace ("\r\n", "\n");
  42973. const int newCaretPos = selection.getStart() + newText.length();
  42974. const int insertIndex = selection.getStart();
  42975. remove (selection, getUndoManager(),
  42976. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42977. if (maxTextLength > 0)
  42978. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42979. if (newText.isNotEmpty())
  42980. insert (newText,
  42981. insertIndex,
  42982. currentFont,
  42983. findColour (textColourId),
  42984. getUndoManager(),
  42985. newCaretPos);
  42986. textChanged();
  42987. }
  42988. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42989. {
  42990. moveCursorTo (newSelection.getStart(), false);
  42991. moveCursorTo (newSelection.getEnd(), true);
  42992. }
  42993. void TextEditor::copy()
  42994. {
  42995. if (passwordCharacter == 0)
  42996. {
  42997. const String selectedText (getHighlightedText());
  42998. if (selectedText.isNotEmpty())
  42999. SystemClipboard::copyTextToClipboard (selectedText);
  43000. }
  43001. }
  43002. void TextEditor::paste()
  43003. {
  43004. if (! isReadOnly())
  43005. {
  43006. const String clip (SystemClipboard::getTextFromClipboard());
  43007. if (clip.isNotEmpty())
  43008. insertTextAtCaret (clip);
  43009. }
  43010. }
  43011. void TextEditor::cut()
  43012. {
  43013. if (! isReadOnly())
  43014. {
  43015. moveCaret (selection.getEnd());
  43016. insertTextAtCaret (String::empty);
  43017. }
  43018. }
  43019. void TextEditor::drawContent (Graphics& g)
  43020. {
  43021. const float wordWrapWidth = getWordWrapWidth();
  43022. if (wordWrapWidth > 0)
  43023. {
  43024. g.setOrigin (leftIndent, topIndent);
  43025. const Rectangle<int> clip (g.getClipBounds());
  43026. Colour selectedTextColour;
  43027. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43028. while (i.lineY + 200.0 < clip.getY() && i.next())
  43029. {}
  43030. if (! selection.isEmpty())
  43031. {
  43032. g.setColour (findColour (highlightColourId)
  43033. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43034. selectedTextColour = findColour (highlightedTextColourId);
  43035. Iterator i2 (i);
  43036. while (i2.next() && i2.lineY < clip.getBottom())
  43037. {
  43038. if (i2.lineY + i2.lineHeight >= clip.getY()
  43039. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43040. {
  43041. i2.drawSelection (g, selection);
  43042. }
  43043. }
  43044. }
  43045. const UniformTextSection* lastSection = 0;
  43046. while (i.next() && i.lineY < clip.getBottom())
  43047. {
  43048. if (i.lineY + i.lineHeight >= clip.getY())
  43049. {
  43050. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43051. {
  43052. i.drawSelectedText (g, selection, selectedTextColour);
  43053. lastSection = 0;
  43054. }
  43055. else
  43056. {
  43057. i.draw (g, lastSection);
  43058. }
  43059. }
  43060. }
  43061. }
  43062. }
  43063. void TextEditor::paint (Graphics& g)
  43064. {
  43065. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43066. }
  43067. void TextEditor::paintOverChildren (Graphics& g)
  43068. {
  43069. if (caretFlashState
  43070. && hasKeyboardFocus (false)
  43071. && caretVisible
  43072. && ! isReadOnly())
  43073. {
  43074. g.setColour (findColour (caretColourId));
  43075. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43076. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43077. 2.0f, cursorHeight);
  43078. }
  43079. if (textToShowWhenEmpty.isNotEmpty()
  43080. && (! hasKeyboardFocus (false))
  43081. && getTotalNumChars() == 0)
  43082. {
  43083. g.setColour (colourForTextWhenEmpty);
  43084. g.setFont (getFont());
  43085. if (isMultiLine())
  43086. {
  43087. g.drawText (textToShowWhenEmpty,
  43088. 0, 0, getWidth(), getHeight(),
  43089. Justification::centred, true);
  43090. }
  43091. else
  43092. {
  43093. g.drawText (textToShowWhenEmpty,
  43094. leftIndent, topIndent,
  43095. viewport->getWidth() - leftIndent,
  43096. viewport->getHeight() - topIndent,
  43097. Justification::centredLeft, true);
  43098. }
  43099. }
  43100. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43101. }
  43102. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43103. {
  43104. public:
  43105. TextEditorMenuPerformer (TextEditor* const editor_)
  43106. : editor (editor_)
  43107. {
  43108. }
  43109. void modalStateFinished (int returnValue)
  43110. {
  43111. if (editor != 0 && returnValue != 0)
  43112. editor->performPopupMenuAction (returnValue);
  43113. }
  43114. private:
  43115. Component::SafePointer<TextEditor> editor;
  43116. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43117. };
  43118. void TextEditor::mouseDown (const MouseEvent& e)
  43119. {
  43120. beginDragAutoRepeat (100);
  43121. newTransaction();
  43122. if (wasFocused || ! selectAllTextWhenFocused)
  43123. {
  43124. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43125. {
  43126. moveCursorTo (getTextIndexAt (e.x, e.y),
  43127. e.mods.isShiftDown());
  43128. }
  43129. else
  43130. {
  43131. PopupMenu m;
  43132. m.setLookAndFeel (&getLookAndFeel());
  43133. addPopupMenuItems (m, &e);
  43134. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43135. }
  43136. }
  43137. }
  43138. void TextEditor::mouseDrag (const MouseEvent& e)
  43139. {
  43140. if (wasFocused || ! selectAllTextWhenFocused)
  43141. {
  43142. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43143. {
  43144. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43145. }
  43146. }
  43147. }
  43148. void TextEditor::mouseUp (const MouseEvent& e)
  43149. {
  43150. newTransaction();
  43151. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43152. if (wasFocused || ! selectAllTextWhenFocused)
  43153. {
  43154. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43155. {
  43156. moveCaret (getTextIndexAt (e.x, e.y));
  43157. }
  43158. }
  43159. wasFocused = true;
  43160. }
  43161. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43162. {
  43163. int tokenEnd = getTextIndexAt (e.x, e.y);
  43164. int tokenStart = tokenEnd;
  43165. if (e.getNumberOfClicks() > 3)
  43166. {
  43167. tokenStart = 0;
  43168. tokenEnd = getTotalNumChars();
  43169. }
  43170. else
  43171. {
  43172. const String t (getText());
  43173. const int totalLength = getTotalNumChars();
  43174. while (tokenEnd < totalLength)
  43175. {
  43176. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43177. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43178. ++tokenEnd;
  43179. else
  43180. break;
  43181. }
  43182. tokenStart = tokenEnd;
  43183. while (tokenStart > 0)
  43184. {
  43185. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43186. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43187. --tokenStart;
  43188. else
  43189. break;
  43190. }
  43191. if (e.getNumberOfClicks() > 2)
  43192. {
  43193. while (tokenEnd < totalLength)
  43194. {
  43195. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43196. ++tokenEnd;
  43197. else
  43198. break;
  43199. }
  43200. while (tokenStart > 0)
  43201. {
  43202. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43203. --tokenStart;
  43204. else
  43205. break;
  43206. }
  43207. }
  43208. }
  43209. moveCursorTo (tokenEnd, false);
  43210. moveCursorTo (tokenStart, true);
  43211. }
  43212. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43213. {
  43214. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43215. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43216. }
  43217. bool TextEditor::keyPressed (const KeyPress& key)
  43218. {
  43219. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43220. return false;
  43221. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43222. if (key.isKeyCode (KeyPress::leftKey)
  43223. || key.isKeyCode (KeyPress::upKey))
  43224. {
  43225. newTransaction();
  43226. int newPos;
  43227. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43228. newPos = indexAtPosition (cursorX, cursorY - 1);
  43229. else if (moveInWholeWordSteps)
  43230. newPos = findWordBreakBefore (getCaretPosition());
  43231. else
  43232. newPos = getCaretPosition() - 1;
  43233. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43234. }
  43235. else if (key.isKeyCode (KeyPress::rightKey)
  43236. || key.isKeyCode (KeyPress::downKey))
  43237. {
  43238. newTransaction();
  43239. int newPos;
  43240. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43241. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43242. else if (moveInWholeWordSteps)
  43243. newPos = findWordBreakAfter (getCaretPosition());
  43244. else
  43245. newPos = getCaretPosition() + 1;
  43246. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43247. }
  43248. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43249. {
  43250. newTransaction();
  43251. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43252. key.getModifiers().isShiftDown());
  43253. }
  43254. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43255. {
  43256. newTransaction();
  43257. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43258. key.getModifiers().isShiftDown());
  43259. }
  43260. else if (key.isKeyCode (KeyPress::homeKey))
  43261. {
  43262. newTransaction();
  43263. if (isMultiLine() && ! moveInWholeWordSteps)
  43264. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43265. key.getModifiers().isShiftDown());
  43266. else
  43267. moveCursorTo (0, key.getModifiers().isShiftDown());
  43268. }
  43269. else if (key.isKeyCode (KeyPress::endKey))
  43270. {
  43271. newTransaction();
  43272. if (isMultiLine() && ! moveInWholeWordSteps)
  43273. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43274. key.getModifiers().isShiftDown());
  43275. else
  43276. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43277. }
  43278. else if (key.isKeyCode (KeyPress::backspaceKey))
  43279. {
  43280. if (moveInWholeWordSteps)
  43281. {
  43282. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43283. }
  43284. else
  43285. {
  43286. if (selection.isEmpty() && selection.getStart() > 0)
  43287. selection.setStart (selection.getEnd() - 1);
  43288. }
  43289. cut();
  43290. }
  43291. else if (key.isKeyCode (KeyPress::deleteKey))
  43292. {
  43293. if (key.getModifiers().isShiftDown())
  43294. copy();
  43295. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43296. selection.setEnd (selection.getStart() + 1);
  43297. cut();
  43298. }
  43299. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43300. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43301. {
  43302. newTransaction();
  43303. copy();
  43304. }
  43305. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43306. {
  43307. newTransaction();
  43308. copy();
  43309. cut();
  43310. }
  43311. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43312. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43313. {
  43314. newTransaction();
  43315. paste();
  43316. }
  43317. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43318. {
  43319. newTransaction();
  43320. doUndoRedo (false);
  43321. }
  43322. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43323. {
  43324. newTransaction();
  43325. doUndoRedo (true);
  43326. }
  43327. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43328. {
  43329. newTransaction();
  43330. moveCursorTo (getTotalNumChars(), false);
  43331. moveCursorTo (0, true);
  43332. }
  43333. else if (key == KeyPress::returnKey)
  43334. {
  43335. newTransaction();
  43336. if (returnKeyStartsNewLine)
  43337. insertTextAtCaret ("\n");
  43338. else
  43339. returnPressed();
  43340. }
  43341. else if (key.isKeyCode (KeyPress::escapeKey))
  43342. {
  43343. newTransaction();
  43344. moveCursorTo (getCaretPosition(), false);
  43345. escapePressed();
  43346. }
  43347. else if (key.getTextCharacter() >= ' '
  43348. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43349. {
  43350. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43351. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43352. }
  43353. else
  43354. {
  43355. return false;
  43356. }
  43357. return true;
  43358. }
  43359. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43360. {
  43361. if (! isKeyDown)
  43362. return false;
  43363. #if JUCE_WINDOWS
  43364. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43365. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43366. #endif
  43367. // (overridden to avoid forwarding key events to the parent)
  43368. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43369. }
  43370. const int baseMenuItemID = 0x7fff0000;
  43371. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43372. {
  43373. const bool writable = ! isReadOnly();
  43374. if (passwordCharacter == 0)
  43375. {
  43376. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43377. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43378. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43379. }
  43380. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43381. m.addSeparator();
  43382. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43383. m.addSeparator();
  43384. if (getUndoManager() != 0)
  43385. {
  43386. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43387. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43388. }
  43389. }
  43390. void TextEditor::performPopupMenuAction (const int menuItemID)
  43391. {
  43392. switch (menuItemID)
  43393. {
  43394. case baseMenuItemID + 1:
  43395. copy();
  43396. cut();
  43397. break;
  43398. case baseMenuItemID + 2:
  43399. copy();
  43400. break;
  43401. case baseMenuItemID + 3:
  43402. paste();
  43403. break;
  43404. case baseMenuItemID + 4:
  43405. cut();
  43406. break;
  43407. case baseMenuItemID + 5:
  43408. moveCursorTo (getTotalNumChars(), false);
  43409. moveCursorTo (0, true);
  43410. break;
  43411. case baseMenuItemID + 6:
  43412. doUndoRedo (false);
  43413. break;
  43414. case baseMenuItemID + 7:
  43415. doUndoRedo (true);
  43416. break;
  43417. default:
  43418. break;
  43419. }
  43420. }
  43421. void TextEditor::focusGained (FocusChangeType)
  43422. {
  43423. newTransaction();
  43424. caretFlashState = true;
  43425. if (selectAllTextWhenFocused)
  43426. {
  43427. moveCursorTo (0, false);
  43428. moveCursorTo (getTotalNumChars(), true);
  43429. }
  43430. repaint();
  43431. if (caretVisible)
  43432. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43433. ComponentPeer* const peer = getPeer();
  43434. if (peer != 0 && ! isReadOnly())
  43435. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43436. }
  43437. void TextEditor::focusLost (FocusChangeType)
  43438. {
  43439. newTransaction();
  43440. wasFocused = false;
  43441. textHolder->stopTimer();
  43442. caretFlashState = false;
  43443. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43444. repaint();
  43445. }
  43446. void TextEditor::resized()
  43447. {
  43448. viewport->setBoundsInset (borderSize);
  43449. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43450. updateTextHolderSize();
  43451. if (! isMultiLine())
  43452. {
  43453. scrollToMakeSureCursorIsVisible();
  43454. }
  43455. else
  43456. {
  43457. updateCaretPosition();
  43458. }
  43459. }
  43460. void TextEditor::handleCommandMessage (const int commandId)
  43461. {
  43462. Component::BailOutChecker checker (this);
  43463. switch (commandId)
  43464. {
  43465. case TextEditorDefs::textChangeMessageId:
  43466. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43467. break;
  43468. case TextEditorDefs::returnKeyMessageId:
  43469. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43470. break;
  43471. case TextEditorDefs::escapeKeyMessageId:
  43472. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43473. break;
  43474. case TextEditorDefs::focusLossMessageId:
  43475. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43476. break;
  43477. default:
  43478. jassertfalse;
  43479. break;
  43480. }
  43481. }
  43482. void TextEditor::enablementChanged()
  43483. {
  43484. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43485. : MouseCursor::IBeamCursor);
  43486. repaint();
  43487. }
  43488. UndoManager* TextEditor::getUndoManager() throw()
  43489. {
  43490. return isReadOnly() ? 0 : &undoManager;
  43491. }
  43492. void TextEditor::clearInternal (UndoManager* const um)
  43493. {
  43494. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43495. }
  43496. void TextEditor::insert (const String& text,
  43497. const int insertIndex,
  43498. const Font& font,
  43499. const Colour& colour,
  43500. UndoManager* const um,
  43501. const int caretPositionToMoveTo)
  43502. {
  43503. if (text.isNotEmpty())
  43504. {
  43505. if (um != 0)
  43506. {
  43507. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43508. newTransaction();
  43509. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43510. caretPosition, caretPositionToMoveTo));
  43511. }
  43512. else
  43513. {
  43514. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43515. // a line gets moved due to word wrap
  43516. int index = 0;
  43517. int nextIndex = 0;
  43518. for (int i = 0; i < sections.size(); ++i)
  43519. {
  43520. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43521. if (insertIndex == index)
  43522. {
  43523. sections.insert (i, new UniformTextSection (text,
  43524. font, colour,
  43525. passwordCharacter));
  43526. break;
  43527. }
  43528. else if (insertIndex > index && insertIndex < nextIndex)
  43529. {
  43530. splitSection (i, insertIndex - index);
  43531. sections.insert (i + 1, new UniformTextSection (text,
  43532. font, colour,
  43533. passwordCharacter));
  43534. break;
  43535. }
  43536. index = nextIndex;
  43537. }
  43538. if (nextIndex == insertIndex)
  43539. sections.add (new UniformTextSection (text,
  43540. font, colour,
  43541. passwordCharacter));
  43542. coalesceSimilarSections();
  43543. totalNumChars = -1;
  43544. valueTextNeedsUpdating = true;
  43545. moveCursorTo (caretPositionToMoveTo, false);
  43546. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43547. }
  43548. }
  43549. }
  43550. void TextEditor::reinsert (const int insertIndex,
  43551. const Array <UniformTextSection*>& sectionsToInsert)
  43552. {
  43553. int index = 0;
  43554. int nextIndex = 0;
  43555. for (int i = 0; i < sections.size(); ++i)
  43556. {
  43557. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43558. if (insertIndex == index)
  43559. {
  43560. for (int j = sectionsToInsert.size(); --j >= 0;)
  43561. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43562. break;
  43563. }
  43564. else if (insertIndex > index && insertIndex < nextIndex)
  43565. {
  43566. splitSection (i, insertIndex - index);
  43567. for (int j = sectionsToInsert.size(); --j >= 0;)
  43568. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43569. break;
  43570. }
  43571. index = nextIndex;
  43572. }
  43573. if (nextIndex == insertIndex)
  43574. {
  43575. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43576. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43577. }
  43578. coalesceSimilarSections();
  43579. totalNumChars = -1;
  43580. valueTextNeedsUpdating = true;
  43581. }
  43582. void TextEditor::remove (const Range<int>& range,
  43583. UndoManager* const um,
  43584. const int caretPositionToMoveTo)
  43585. {
  43586. if (! range.isEmpty())
  43587. {
  43588. int index = 0;
  43589. for (int i = 0; i < sections.size(); ++i)
  43590. {
  43591. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43592. if (range.getStart() > index && range.getStart() < nextIndex)
  43593. {
  43594. splitSection (i, range.getStart() - index);
  43595. --i;
  43596. }
  43597. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43598. {
  43599. splitSection (i, range.getEnd() - index);
  43600. --i;
  43601. }
  43602. else
  43603. {
  43604. index = nextIndex;
  43605. if (index > range.getEnd())
  43606. break;
  43607. }
  43608. }
  43609. index = 0;
  43610. if (um != 0)
  43611. {
  43612. Array <UniformTextSection*> removedSections;
  43613. for (int i = 0; i < sections.size(); ++i)
  43614. {
  43615. if (range.getEnd() <= range.getStart())
  43616. break;
  43617. UniformTextSection* const section = sections.getUnchecked (i);
  43618. const int nextIndex = index + section->getTotalLength();
  43619. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43620. removedSections.add (new UniformTextSection (*section));
  43621. index = nextIndex;
  43622. }
  43623. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43624. newTransaction();
  43625. um->perform (new RemoveAction (*this, range, caretPosition,
  43626. caretPositionToMoveTo, removedSections));
  43627. }
  43628. else
  43629. {
  43630. Range<int> remainingRange (range);
  43631. for (int i = 0; i < sections.size(); ++i)
  43632. {
  43633. UniformTextSection* const section = sections.getUnchecked (i);
  43634. const int nextIndex = index + section->getTotalLength();
  43635. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43636. {
  43637. sections.remove(i);
  43638. section->clear();
  43639. delete section;
  43640. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43641. if (remainingRange.isEmpty())
  43642. break;
  43643. --i;
  43644. }
  43645. else
  43646. {
  43647. index = nextIndex;
  43648. }
  43649. }
  43650. coalesceSimilarSections();
  43651. totalNumChars = -1;
  43652. valueTextNeedsUpdating = true;
  43653. moveCursorTo (caretPositionToMoveTo, false);
  43654. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43655. }
  43656. }
  43657. }
  43658. const String TextEditor::getText() const
  43659. {
  43660. String t;
  43661. t.preallocateStorage (getTotalNumChars());
  43662. String::Concatenator concatenator (t);
  43663. for (int i = 0; i < sections.size(); ++i)
  43664. sections.getUnchecked (i)->appendAllText (concatenator);
  43665. return t;
  43666. }
  43667. const String TextEditor::getTextInRange (const Range<int>& range) const
  43668. {
  43669. String t;
  43670. if (! range.isEmpty())
  43671. {
  43672. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43673. String::Concatenator concatenator (t);
  43674. int index = 0;
  43675. for (int i = 0; i < sections.size(); ++i)
  43676. {
  43677. const UniformTextSection* const s = sections.getUnchecked (i);
  43678. const int nextIndex = index + s->getTotalLength();
  43679. if (range.getStart() < nextIndex)
  43680. {
  43681. if (range.getEnd() <= index)
  43682. break;
  43683. s->appendSubstring (concatenator, range - index);
  43684. }
  43685. index = nextIndex;
  43686. }
  43687. }
  43688. return t;
  43689. }
  43690. const String TextEditor::getHighlightedText() const
  43691. {
  43692. return getTextInRange (selection);
  43693. }
  43694. int TextEditor::getTotalNumChars() const
  43695. {
  43696. if (totalNumChars < 0)
  43697. {
  43698. totalNumChars = 0;
  43699. for (int i = sections.size(); --i >= 0;)
  43700. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43701. }
  43702. return totalNumChars;
  43703. }
  43704. bool TextEditor::isEmpty() const
  43705. {
  43706. return getTotalNumChars() == 0;
  43707. }
  43708. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43709. {
  43710. const float wordWrapWidth = getWordWrapWidth();
  43711. if (wordWrapWidth > 0 && sections.size() > 0)
  43712. {
  43713. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43714. i.getCharPosition (index, cx, cy, lineHeight);
  43715. }
  43716. else
  43717. {
  43718. cx = cy = 0;
  43719. lineHeight = currentFont.getHeight();
  43720. }
  43721. }
  43722. int TextEditor::indexAtPosition (const float x, const float y)
  43723. {
  43724. const float wordWrapWidth = getWordWrapWidth();
  43725. if (wordWrapWidth > 0)
  43726. {
  43727. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43728. while (i.next())
  43729. {
  43730. if (i.lineY + i.lineHeight > y)
  43731. {
  43732. if (i.lineY > y)
  43733. return jmax (0, i.indexInText - 1);
  43734. if (i.atomX >= x)
  43735. return i.indexInText;
  43736. if (x < i.atomRight)
  43737. return i.xToIndex (x);
  43738. }
  43739. }
  43740. }
  43741. return getTotalNumChars();
  43742. }
  43743. int TextEditor::findWordBreakAfter (const int position) const
  43744. {
  43745. const String t (getTextInRange (Range<int> (position, position + 512)));
  43746. const int totalLength = t.length();
  43747. int i = 0;
  43748. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43749. ++i;
  43750. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43751. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43752. ++i;
  43753. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43754. ++i;
  43755. return position + i;
  43756. }
  43757. int TextEditor::findWordBreakBefore (const int position) const
  43758. {
  43759. if (position <= 0)
  43760. return 0;
  43761. const int startOfBuffer = jmax (0, position - 512);
  43762. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43763. int i = position - startOfBuffer;
  43764. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43765. --i;
  43766. if (i > 0)
  43767. {
  43768. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43769. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43770. --i;
  43771. }
  43772. jassert (startOfBuffer + i >= 0);
  43773. return startOfBuffer + i;
  43774. }
  43775. void TextEditor::splitSection (const int sectionIndex,
  43776. const int charToSplitAt)
  43777. {
  43778. jassert (sections[sectionIndex] != 0);
  43779. sections.insert (sectionIndex + 1,
  43780. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43781. }
  43782. void TextEditor::coalesceSimilarSections()
  43783. {
  43784. for (int i = 0; i < sections.size() - 1; ++i)
  43785. {
  43786. UniformTextSection* const s1 = sections.getUnchecked (i);
  43787. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43788. if (s1->font == s2->font
  43789. && s1->colour == s2->colour)
  43790. {
  43791. s1->append (*s2, passwordCharacter);
  43792. sections.remove (i + 1);
  43793. delete s2;
  43794. --i;
  43795. }
  43796. }
  43797. }
  43798. END_JUCE_NAMESPACE
  43799. /*** End of inlined file: juce_TextEditor.cpp ***/
  43800. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43801. BEGIN_JUCE_NAMESPACE
  43802. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43803. class ToolbarSpacerComp : public ToolbarItemComponent
  43804. {
  43805. public:
  43806. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43807. : ToolbarItemComponent (itemId_, String::empty, false),
  43808. fixedSize (fixedSize_),
  43809. drawBar (drawBar_)
  43810. {
  43811. }
  43812. ~ToolbarSpacerComp()
  43813. {
  43814. }
  43815. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43816. int& preferredSize, int& minSize, int& maxSize)
  43817. {
  43818. if (fixedSize <= 0)
  43819. {
  43820. preferredSize = toolbarThickness * 2;
  43821. minSize = 4;
  43822. maxSize = 32768;
  43823. }
  43824. else
  43825. {
  43826. maxSize = roundToInt (toolbarThickness * fixedSize);
  43827. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43828. preferredSize = maxSize;
  43829. if (getEditingMode() == editableOnPalette)
  43830. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43831. }
  43832. return true;
  43833. }
  43834. void paintButtonArea (Graphics&, int, int, bool, bool)
  43835. {
  43836. }
  43837. void contentAreaChanged (const Rectangle<int>&)
  43838. {
  43839. }
  43840. int getResizeOrder() const throw()
  43841. {
  43842. return fixedSize <= 0 ? 0 : 1;
  43843. }
  43844. void paint (Graphics& g)
  43845. {
  43846. const int w = getWidth();
  43847. const int h = getHeight();
  43848. if (drawBar)
  43849. {
  43850. g.setColour (findColour (Toolbar::separatorColourId, true));
  43851. const float thickness = 0.2f;
  43852. if (isToolbarVertical())
  43853. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43854. else
  43855. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43856. }
  43857. if (getEditingMode() != normalMode && ! drawBar)
  43858. {
  43859. g.setColour (findColour (Toolbar::separatorColourId, true));
  43860. const int indentX = jmin (2, (w - 3) / 2);
  43861. const int indentY = jmin (2, (h - 3) / 2);
  43862. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43863. if (fixedSize <= 0)
  43864. {
  43865. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43866. if (isToolbarVertical())
  43867. {
  43868. x1 = w * 0.5f;
  43869. y1 = h * 0.4f;
  43870. x2 = x1;
  43871. y2 = indentX * 2.0f;
  43872. x3 = x1;
  43873. y3 = h * 0.6f;
  43874. x4 = x1;
  43875. y4 = h - y2;
  43876. hw = w * 0.15f;
  43877. hl = w * 0.2f;
  43878. }
  43879. else
  43880. {
  43881. x1 = w * 0.4f;
  43882. y1 = h * 0.5f;
  43883. x2 = indentX * 2.0f;
  43884. y2 = y1;
  43885. x3 = w * 0.6f;
  43886. y3 = y1;
  43887. x4 = w - x2;
  43888. y4 = y1;
  43889. hw = h * 0.15f;
  43890. hl = h * 0.2f;
  43891. }
  43892. Path p;
  43893. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43894. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43895. g.fillPath (p);
  43896. }
  43897. }
  43898. }
  43899. private:
  43900. const float fixedSize;
  43901. const bool drawBar;
  43902. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  43903. };
  43904. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  43905. {
  43906. public:
  43907. MissingItemsComponent (Toolbar& owner_, const int height_)
  43908. : PopupMenu::CustomComponent (true),
  43909. owner (&owner_),
  43910. height (height_)
  43911. {
  43912. for (int i = owner_.items.size(); --i >= 0;)
  43913. {
  43914. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43915. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43916. {
  43917. oldIndexes.insert (0, i);
  43918. addAndMakeVisible (tc, 0);
  43919. }
  43920. }
  43921. layout (400);
  43922. }
  43923. ~MissingItemsComponent()
  43924. {
  43925. if (owner != 0)
  43926. {
  43927. for (int i = 0; i < getNumChildComponents(); ++i)
  43928. {
  43929. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43930. if (tc != 0)
  43931. {
  43932. tc->setVisible (false);
  43933. const int index = oldIndexes.remove (i);
  43934. owner->addChildComponent (tc, index);
  43935. --i;
  43936. }
  43937. }
  43938. owner->resized();
  43939. }
  43940. }
  43941. void layout (const int preferredWidth)
  43942. {
  43943. const int indent = 8;
  43944. int x = indent;
  43945. int y = indent;
  43946. int maxX = 0;
  43947. for (int i = 0; i < getNumChildComponents(); ++i)
  43948. {
  43949. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43950. if (tc != 0)
  43951. {
  43952. int preferredSize = 1, minSize = 1, maxSize = 1;
  43953. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43954. {
  43955. if (x + preferredSize > preferredWidth && x > indent)
  43956. {
  43957. x = indent;
  43958. y += height;
  43959. }
  43960. tc->setBounds (x, y, preferredSize, height);
  43961. x += preferredSize;
  43962. maxX = jmax (maxX, x);
  43963. }
  43964. }
  43965. }
  43966. setSize (maxX + 8, y + height + 8);
  43967. }
  43968. void getIdealSize (int& idealWidth, int& idealHeight)
  43969. {
  43970. idealWidth = getWidth();
  43971. idealHeight = getHeight();
  43972. }
  43973. private:
  43974. Component::SafePointer<Toolbar> owner;
  43975. const int height;
  43976. Array <int> oldIndexes;
  43977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  43978. };
  43979. Toolbar::Toolbar()
  43980. : vertical (false),
  43981. isEditingActive (false),
  43982. toolbarStyle (Toolbar::iconsOnly)
  43983. {
  43984. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43985. missingItemsButton->setAlwaysOnTop (true);
  43986. missingItemsButton->addListener (this);
  43987. }
  43988. Toolbar::~Toolbar()
  43989. {
  43990. items.clear();
  43991. }
  43992. void Toolbar::setVertical (const bool shouldBeVertical)
  43993. {
  43994. if (vertical != shouldBeVertical)
  43995. {
  43996. vertical = shouldBeVertical;
  43997. resized();
  43998. }
  43999. }
  44000. void Toolbar::clear()
  44001. {
  44002. items.clear();
  44003. resized();
  44004. }
  44005. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44006. {
  44007. if (itemId == ToolbarItemFactory::separatorBarId)
  44008. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44009. else if (itemId == ToolbarItemFactory::spacerId)
  44010. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44011. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44012. return new ToolbarSpacerComp (itemId, 0, false);
  44013. return factory.createItem (itemId);
  44014. }
  44015. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44016. const int itemId,
  44017. const int insertIndex)
  44018. {
  44019. // An ID can't be zero - this might indicate a mistake somewhere?
  44020. jassert (itemId != 0);
  44021. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44022. if (tc != 0)
  44023. {
  44024. #if JUCE_DEBUG
  44025. Array <int> allowedIds;
  44026. factory.getAllToolbarItemIds (allowedIds);
  44027. // If your factory can create an item for a given ID, it must also return
  44028. // that ID from its getAllToolbarItemIds() method!
  44029. jassert (allowedIds.contains (itemId));
  44030. #endif
  44031. items.insert (insertIndex, tc);
  44032. addAndMakeVisible (tc, insertIndex);
  44033. }
  44034. }
  44035. void Toolbar::addItem (ToolbarItemFactory& factory,
  44036. const int itemId,
  44037. const int insertIndex)
  44038. {
  44039. addItemInternal (factory, itemId, insertIndex);
  44040. resized();
  44041. }
  44042. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44043. {
  44044. Array <int> ids;
  44045. factoryToUse.getDefaultItemSet (ids);
  44046. clear();
  44047. for (int i = 0; i < ids.size(); ++i)
  44048. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44049. resized();
  44050. }
  44051. void Toolbar::removeToolbarItem (const int itemIndex)
  44052. {
  44053. items.remove (itemIndex);
  44054. resized();
  44055. }
  44056. int Toolbar::getNumItems() const throw()
  44057. {
  44058. return items.size();
  44059. }
  44060. int Toolbar::getItemId (const int itemIndex) const throw()
  44061. {
  44062. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44063. return tc != 0 ? tc->getItemId() : 0;
  44064. }
  44065. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44066. {
  44067. return items [itemIndex];
  44068. }
  44069. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44070. {
  44071. for (;;)
  44072. {
  44073. index += delta;
  44074. ToolbarItemComponent* const tc = getItemComponent (index);
  44075. if (tc == 0)
  44076. break;
  44077. if (tc->isActive)
  44078. return tc;
  44079. }
  44080. return 0;
  44081. }
  44082. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44083. {
  44084. if (toolbarStyle != newStyle)
  44085. {
  44086. toolbarStyle = newStyle;
  44087. updateAllItemPositions (false);
  44088. }
  44089. }
  44090. const String Toolbar::toString() const
  44091. {
  44092. String s ("TB:");
  44093. for (int i = 0; i < getNumItems(); ++i)
  44094. s << getItemId(i) << ' ';
  44095. return s.trimEnd();
  44096. }
  44097. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44098. const String& savedVersion)
  44099. {
  44100. if (! savedVersion.startsWith ("TB:"))
  44101. return false;
  44102. StringArray tokens;
  44103. tokens.addTokens (savedVersion.substring (3), false);
  44104. clear();
  44105. for (int i = 0; i < tokens.size(); ++i)
  44106. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44107. resized();
  44108. return true;
  44109. }
  44110. void Toolbar::paint (Graphics& g)
  44111. {
  44112. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44113. }
  44114. int Toolbar::getThickness() const throw()
  44115. {
  44116. return vertical ? getWidth() : getHeight();
  44117. }
  44118. int Toolbar::getLength() const throw()
  44119. {
  44120. return vertical ? getHeight() : getWidth();
  44121. }
  44122. void Toolbar::setEditingActive (const bool active)
  44123. {
  44124. if (isEditingActive != active)
  44125. {
  44126. isEditingActive = active;
  44127. updateAllItemPositions (false);
  44128. }
  44129. }
  44130. void Toolbar::resized()
  44131. {
  44132. updateAllItemPositions (false);
  44133. }
  44134. void Toolbar::updateAllItemPositions (const bool animate)
  44135. {
  44136. if (getWidth() > 0 && getHeight() > 0)
  44137. {
  44138. StretchableObjectResizer resizer;
  44139. int i;
  44140. for (i = 0; i < items.size(); ++i)
  44141. {
  44142. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44143. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44144. : ToolbarItemComponent::normalMode);
  44145. tc->setStyle (toolbarStyle);
  44146. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44147. int preferredSize = 1, minSize = 1, maxSize = 1;
  44148. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44149. preferredSize, minSize, maxSize))
  44150. {
  44151. tc->isActive = true;
  44152. resizer.addItem (preferredSize, minSize, maxSize,
  44153. spacer != 0 ? spacer->getResizeOrder() : 2);
  44154. }
  44155. else
  44156. {
  44157. tc->isActive = false;
  44158. tc->setVisible (false);
  44159. }
  44160. }
  44161. resizer.resizeToFit (getLength());
  44162. int totalLength = 0;
  44163. for (i = 0; i < resizer.getNumItems(); ++i)
  44164. totalLength += (int) resizer.getItemSize (i);
  44165. const bool itemsOffTheEnd = totalLength > getLength();
  44166. const int extrasButtonSize = getThickness() / 2;
  44167. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44168. missingItemsButton->setVisible (itemsOffTheEnd);
  44169. missingItemsButton->setEnabled (! isEditingActive);
  44170. if (vertical)
  44171. missingItemsButton->setCentrePosition (getWidth() / 2,
  44172. getHeight() - 4 - extrasButtonSize / 2);
  44173. else
  44174. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44175. getHeight() / 2);
  44176. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44177. : missingItemsButton->getX()) - 4
  44178. : getLength();
  44179. int pos = 0, activeIndex = 0;
  44180. for (i = 0; i < items.size(); ++i)
  44181. {
  44182. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44183. if (tc->isActive)
  44184. {
  44185. const int size = (int) resizer.getItemSize (activeIndex++);
  44186. Rectangle<int> newBounds;
  44187. if (vertical)
  44188. newBounds.setBounds (0, pos, getWidth(), size);
  44189. else
  44190. newBounds.setBounds (pos, 0, size, getHeight());
  44191. if (animate)
  44192. {
  44193. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44194. }
  44195. else
  44196. {
  44197. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44198. tc->setBounds (newBounds);
  44199. }
  44200. pos += size;
  44201. tc->setVisible (pos <= maxLength
  44202. && ((! tc->isBeingDragged)
  44203. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44204. }
  44205. }
  44206. }
  44207. }
  44208. void Toolbar::buttonClicked (Button*)
  44209. {
  44210. jassert (missingItemsButton->isShowing());
  44211. if (missingItemsButton->isShowing())
  44212. {
  44213. PopupMenu m;
  44214. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44215. m.showAt (missingItemsButton);
  44216. }
  44217. }
  44218. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44219. Component* /*sourceComponent*/)
  44220. {
  44221. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44222. }
  44223. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44224. {
  44225. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44226. if (tc != 0)
  44227. {
  44228. if (! items.contains (tc))
  44229. {
  44230. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44231. {
  44232. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44233. if (palette != 0)
  44234. palette->replaceComponent (tc);
  44235. }
  44236. else
  44237. {
  44238. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44239. }
  44240. items.add (tc);
  44241. addChildComponent (tc);
  44242. updateAllItemPositions (true);
  44243. }
  44244. for (int i = getNumItems(); --i >= 0;)
  44245. {
  44246. const int currentIndex = items.indexOf (tc);
  44247. int newIndex = currentIndex;
  44248. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44249. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44250. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44251. .getComponentDestination (getChildComponent (newIndex)));
  44252. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44253. if (prev != 0)
  44254. {
  44255. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44256. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44257. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44258. {
  44259. newIndex = getIndexOfChildComponent (prev);
  44260. }
  44261. }
  44262. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44263. if (next != 0)
  44264. {
  44265. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44266. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44267. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44268. {
  44269. newIndex = getIndexOfChildComponent (next) + 1;
  44270. }
  44271. }
  44272. if (newIndex == currentIndex)
  44273. break;
  44274. items.removeObject (tc, false);
  44275. removeChildComponent (tc);
  44276. addChildComponent (tc, newIndex);
  44277. items.insert (newIndex, tc);
  44278. updateAllItemPositions (true);
  44279. }
  44280. }
  44281. }
  44282. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44283. {
  44284. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44285. if (tc != 0 && isParentOf (tc))
  44286. {
  44287. items.removeObject (tc, false);
  44288. removeChildComponent (tc);
  44289. updateAllItemPositions (true);
  44290. }
  44291. }
  44292. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44293. {
  44294. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44295. if (tc != 0)
  44296. tc->setState (Button::buttonNormal);
  44297. }
  44298. void Toolbar::mouseDown (const MouseEvent&)
  44299. {
  44300. }
  44301. class ToolbarCustomisationDialog : public DialogWindow
  44302. {
  44303. public:
  44304. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44305. Toolbar* const toolbar_,
  44306. const int optionFlags)
  44307. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44308. toolbar (toolbar_)
  44309. {
  44310. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44311. setResizable (true, true);
  44312. setResizeLimits (400, 300, 1500, 1000);
  44313. positionNearBar();
  44314. }
  44315. ~ToolbarCustomisationDialog()
  44316. {
  44317. setContentComponent (0, true);
  44318. }
  44319. void closeButtonPressed()
  44320. {
  44321. setVisible (false);
  44322. }
  44323. bool canModalEventBeSentToComponent (const Component* comp)
  44324. {
  44325. return toolbar->isParentOf (comp);
  44326. }
  44327. void positionNearBar()
  44328. {
  44329. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44330. const int tbx = toolbar->getScreenX();
  44331. const int tby = toolbar->getScreenY();
  44332. const int gap = 8;
  44333. int x, y;
  44334. if (toolbar->isVertical())
  44335. {
  44336. y = tby;
  44337. if (tbx > screenSize.getCentreX())
  44338. x = tbx - getWidth() - gap;
  44339. else
  44340. x = tbx + toolbar->getWidth() + gap;
  44341. }
  44342. else
  44343. {
  44344. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44345. if (tby > screenSize.getCentreY())
  44346. y = tby - getHeight() - gap;
  44347. else
  44348. y = tby + toolbar->getHeight() + gap;
  44349. }
  44350. setTopLeftPosition (x, y);
  44351. }
  44352. private:
  44353. Toolbar* const toolbar;
  44354. class CustomiserPanel : public Component,
  44355. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44356. private ButtonListener
  44357. {
  44358. public:
  44359. CustomiserPanel (ToolbarItemFactory& factory_,
  44360. Toolbar* const toolbar_,
  44361. const int optionFlags)
  44362. : factory (factory_),
  44363. toolbar (toolbar_),
  44364. palette (factory_, toolbar_),
  44365. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44366. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44367. defaultButton (TRANS ("Restore to default set of items"))
  44368. {
  44369. addAndMakeVisible (&palette);
  44370. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44371. | Toolbar::allowIconsWithTextChoice
  44372. | Toolbar::allowTextOnlyChoice)) != 0)
  44373. {
  44374. addAndMakeVisible (&styleBox);
  44375. styleBox.setEditableText (false);
  44376. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44377. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44378. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44379. int selectedStyle = 0;
  44380. switch (toolbar_->getStyle())
  44381. {
  44382. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44383. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44384. case Toolbar::textOnly: selectedStyle = 3; break;
  44385. }
  44386. styleBox.setSelectedId (selectedStyle);
  44387. styleBox.addListener (this);
  44388. }
  44389. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44390. {
  44391. addAndMakeVisible (&defaultButton);
  44392. defaultButton.addListener (this);
  44393. }
  44394. addAndMakeVisible (&instructions);
  44395. instructions.setFont (Font (13.0f));
  44396. setSize (500, 300);
  44397. }
  44398. void comboBoxChanged (ComboBox*)
  44399. {
  44400. switch (styleBox.getSelectedId())
  44401. {
  44402. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44403. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44404. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44405. }
  44406. palette.resized(); // to make it update the styles
  44407. }
  44408. void buttonClicked (Button*)
  44409. {
  44410. toolbar->addDefaultItems (factory);
  44411. }
  44412. void paint (Graphics& g)
  44413. {
  44414. Colour background;
  44415. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44416. if (dw != 0)
  44417. background = dw->getBackgroundColour();
  44418. g.setColour (background.contrasting().withAlpha (0.3f));
  44419. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44420. }
  44421. void resized()
  44422. {
  44423. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44424. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44425. defaultButton.changeWidthToFitText (22);
  44426. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44427. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44428. }
  44429. private:
  44430. ToolbarItemFactory& factory;
  44431. Toolbar* const toolbar;
  44432. ToolbarItemPalette palette;
  44433. Label instructions;
  44434. ComboBox styleBox;
  44435. TextButton defaultButton;
  44436. };
  44437. };
  44438. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44439. {
  44440. setEditingActive (true);
  44441. #if JUCE_DEBUG
  44442. WeakReference<Component> checker (this);
  44443. #endif
  44444. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44445. dw.runModalLoop();
  44446. #if JUCE_DEBUG
  44447. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44448. #endif
  44449. setEditingActive (false);
  44450. }
  44451. END_JUCE_NAMESPACE
  44452. /*** End of inlined file: juce_Toolbar.cpp ***/
  44453. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44454. BEGIN_JUCE_NAMESPACE
  44455. ToolbarItemFactory::ToolbarItemFactory()
  44456. {
  44457. }
  44458. ToolbarItemFactory::~ToolbarItemFactory()
  44459. {
  44460. }
  44461. class ItemDragAndDropOverlayComponent : public Component
  44462. {
  44463. public:
  44464. ItemDragAndDropOverlayComponent()
  44465. : isDragging (false)
  44466. {
  44467. setAlwaysOnTop (true);
  44468. setRepaintsOnMouseActivity (true);
  44469. setMouseCursor (MouseCursor::DraggingHandCursor);
  44470. }
  44471. void paint (Graphics& g)
  44472. {
  44473. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44474. if (isMouseOverOrDragging()
  44475. && tc != 0
  44476. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44477. {
  44478. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44479. g.drawRect (0, 0, getWidth(), getHeight(),
  44480. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44481. }
  44482. }
  44483. void mouseDown (const MouseEvent& e)
  44484. {
  44485. isDragging = false;
  44486. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44487. if (tc != 0)
  44488. {
  44489. tc->dragOffsetX = e.x;
  44490. tc->dragOffsetY = e.y;
  44491. }
  44492. }
  44493. void mouseDrag (const MouseEvent& e)
  44494. {
  44495. if (! (isDragging || e.mouseWasClicked()))
  44496. {
  44497. isDragging = true;
  44498. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44499. if (dnd != 0)
  44500. {
  44501. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44502. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44503. if (tc != 0)
  44504. {
  44505. tc->isBeingDragged = true;
  44506. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44507. tc->setVisible (false);
  44508. }
  44509. }
  44510. }
  44511. }
  44512. void mouseUp (const MouseEvent&)
  44513. {
  44514. isDragging = false;
  44515. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44516. if (tc != 0)
  44517. {
  44518. tc->isBeingDragged = false;
  44519. Toolbar* const tb = tc->getToolbar();
  44520. if (tb != 0)
  44521. tb->updateAllItemPositions (true);
  44522. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44523. delete tc;
  44524. }
  44525. }
  44526. void parentSizeChanged()
  44527. {
  44528. setBounds (0, 0, getParentWidth(), getParentHeight());
  44529. }
  44530. private:
  44531. bool isDragging;
  44532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44533. };
  44534. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44535. const String& labelText,
  44536. const bool isBeingUsedAsAButton_)
  44537. : Button (labelText),
  44538. itemId (itemId_),
  44539. mode (normalMode),
  44540. toolbarStyle (Toolbar::iconsOnly),
  44541. dragOffsetX (0),
  44542. dragOffsetY (0),
  44543. isActive (true),
  44544. isBeingDragged (false),
  44545. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44546. {
  44547. // Your item ID can't be 0!
  44548. jassert (itemId_ != 0);
  44549. }
  44550. ToolbarItemComponent::~ToolbarItemComponent()
  44551. {
  44552. overlayComp = 0;
  44553. }
  44554. Toolbar* ToolbarItemComponent::getToolbar() const
  44555. {
  44556. return dynamic_cast <Toolbar*> (getParentComponent());
  44557. }
  44558. bool ToolbarItemComponent::isToolbarVertical() const
  44559. {
  44560. const Toolbar* const t = getToolbar();
  44561. return t != 0 && t->isVertical();
  44562. }
  44563. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44564. {
  44565. if (toolbarStyle != newStyle)
  44566. {
  44567. toolbarStyle = newStyle;
  44568. repaint();
  44569. resized();
  44570. }
  44571. }
  44572. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44573. {
  44574. if (isBeingUsedAsAButton)
  44575. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44576. over, down, *this);
  44577. if (toolbarStyle != Toolbar::iconsOnly)
  44578. {
  44579. const int indent = contentArea.getX();
  44580. int y = indent;
  44581. int h = getHeight() - indent * 2;
  44582. if (toolbarStyle == Toolbar::iconsWithText)
  44583. {
  44584. y = contentArea.getBottom() + indent / 2;
  44585. h -= contentArea.getHeight();
  44586. }
  44587. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44588. getButtonText(), *this);
  44589. }
  44590. if (! contentArea.isEmpty())
  44591. {
  44592. Graphics::ScopedSaveState ss (g);
  44593. g.reduceClipRegion (contentArea);
  44594. g.setOrigin (contentArea.getX(), contentArea.getY());
  44595. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44596. }
  44597. }
  44598. void ToolbarItemComponent::resized()
  44599. {
  44600. if (toolbarStyle != Toolbar::textOnly)
  44601. {
  44602. const int indent = jmin (proportionOfWidth (0.08f),
  44603. proportionOfHeight (0.08f));
  44604. contentArea = Rectangle<int> (indent, indent,
  44605. getWidth() - indent * 2,
  44606. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44607. : (getHeight() - indent * 2));
  44608. }
  44609. else
  44610. {
  44611. contentArea = Rectangle<int>();
  44612. }
  44613. contentAreaChanged (contentArea);
  44614. }
  44615. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44616. {
  44617. if (mode != newMode)
  44618. {
  44619. mode = newMode;
  44620. repaint();
  44621. if (mode == normalMode)
  44622. {
  44623. overlayComp = 0;
  44624. }
  44625. else if (overlayComp == 0)
  44626. {
  44627. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44628. overlayComp->parentSizeChanged();
  44629. }
  44630. resized();
  44631. }
  44632. }
  44633. END_JUCE_NAMESPACE
  44634. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44635. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44636. BEGIN_JUCE_NAMESPACE
  44637. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44638. Toolbar* const toolbar_)
  44639. : factory (factory_),
  44640. toolbar (toolbar_)
  44641. {
  44642. Component* const itemHolder = new Component();
  44643. viewport.setViewedComponent (itemHolder);
  44644. Array <int> allIds;
  44645. factory.getAllToolbarItemIds (allIds);
  44646. for (int i = 0; i < allIds.size(); ++i)
  44647. addComponent (allIds.getUnchecked (i), -1);
  44648. addAndMakeVisible (&viewport);
  44649. }
  44650. ToolbarItemPalette::~ToolbarItemPalette()
  44651. {
  44652. }
  44653. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44654. {
  44655. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44656. jassert (tc != 0);
  44657. if (tc != 0)
  44658. {
  44659. items.insert (index, tc);
  44660. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44661. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44662. }
  44663. }
  44664. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44665. {
  44666. const int index = items.indexOf (comp);
  44667. jassert (index >= 0);
  44668. items.removeObject (comp, false);
  44669. addComponent (comp->getItemId(), index);
  44670. resized();
  44671. }
  44672. void ToolbarItemPalette::resized()
  44673. {
  44674. viewport.setBoundsInset (BorderSize<int> (1));
  44675. Component* const itemHolder = viewport.getViewedComponent();
  44676. const int indent = 8;
  44677. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44678. const int height = toolbar->getThickness();
  44679. int x = indent;
  44680. int y = indent;
  44681. int maxX = 0;
  44682. for (int i = 0; i < items.size(); ++i)
  44683. {
  44684. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44685. tc->setStyle (toolbar->getStyle());
  44686. int preferredSize = 1, minSize = 1, maxSize = 1;
  44687. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44688. {
  44689. if (x + preferredSize > preferredWidth && x > indent)
  44690. {
  44691. x = indent;
  44692. y += height;
  44693. }
  44694. tc->setBounds (x, y, preferredSize, height);
  44695. x += preferredSize + 8;
  44696. maxX = jmax (maxX, x);
  44697. }
  44698. }
  44699. itemHolder->setSize (maxX, y + height + 8);
  44700. }
  44701. END_JUCE_NAMESPACE
  44702. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44703. /*** Start of inlined file: juce_TreeView.cpp ***/
  44704. BEGIN_JUCE_NAMESPACE
  44705. class TreeViewContentComponent : public Component,
  44706. public TooltipClient
  44707. {
  44708. public:
  44709. TreeViewContentComponent (TreeView& owner_)
  44710. : owner (owner_),
  44711. buttonUnderMouse (0),
  44712. isDragging (false)
  44713. {
  44714. }
  44715. void mouseDown (const MouseEvent& e)
  44716. {
  44717. updateButtonUnderMouse (e);
  44718. isDragging = false;
  44719. needSelectionOnMouseUp = false;
  44720. Rectangle<int> pos;
  44721. TreeViewItem* const item = findItemAt (e.y, pos);
  44722. if (item == 0)
  44723. return;
  44724. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44725. // as selection clicks)
  44726. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44727. {
  44728. if (e.x >= pos.getX() - owner.getIndentSize())
  44729. item->setOpen (! item->isOpen());
  44730. // (clicks to the left of an open/close button are ignored)
  44731. }
  44732. else
  44733. {
  44734. // mouse-down inside the body of the item..
  44735. if (! owner.isMultiSelectEnabled())
  44736. item->setSelected (true, true);
  44737. else if (item->isSelected())
  44738. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44739. else
  44740. selectBasedOnModifiers (item, e.mods);
  44741. if (e.x >= pos.getX())
  44742. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44743. }
  44744. }
  44745. void mouseUp (const MouseEvent& e)
  44746. {
  44747. updateButtonUnderMouse (e);
  44748. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44749. {
  44750. Rectangle<int> pos;
  44751. TreeViewItem* const item = findItemAt (e.y, pos);
  44752. if (item != 0)
  44753. selectBasedOnModifiers (item, e.mods);
  44754. }
  44755. }
  44756. void mouseDoubleClick (const MouseEvent& e)
  44757. {
  44758. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44759. {
  44760. Rectangle<int> pos;
  44761. TreeViewItem* const item = findItemAt (e.y, pos);
  44762. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44763. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44764. }
  44765. }
  44766. void mouseDrag (const MouseEvent& e)
  44767. {
  44768. if (isEnabled()
  44769. && ! (isDragging || e.mouseWasClicked()
  44770. || e.getDistanceFromDragStart() < 5
  44771. || e.mods.isPopupMenu()))
  44772. {
  44773. isDragging = true;
  44774. Rectangle<int> pos;
  44775. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44776. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44777. {
  44778. const String dragDescription (item->getDragSourceDescription());
  44779. if (dragDescription.isNotEmpty())
  44780. {
  44781. DragAndDropContainer* const dragContainer
  44782. = DragAndDropContainer::findParentDragContainerFor (this);
  44783. if (dragContainer != 0)
  44784. {
  44785. pos.setSize (pos.getWidth(), item->itemHeight);
  44786. Image dragImage (Component::createComponentSnapshot (pos, true));
  44787. dragImage.multiplyAllAlphas (0.6f);
  44788. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44789. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44790. }
  44791. else
  44792. {
  44793. // to be able to do a drag-and-drop operation, the treeview needs to
  44794. // be inside a component which is also a DragAndDropContainer.
  44795. jassertfalse;
  44796. }
  44797. }
  44798. }
  44799. }
  44800. }
  44801. void mouseMove (const MouseEvent& e)
  44802. {
  44803. updateButtonUnderMouse (e);
  44804. }
  44805. void mouseExit (const MouseEvent& e)
  44806. {
  44807. updateButtonUnderMouse (e);
  44808. }
  44809. void paint (Graphics& g)
  44810. {
  44811. if (owner.rootItem != 0)
  44812. {
  44813. owner.handleAsyncUpdate();
  44814. if (! owner.rootItemVisible)
  44815. g.setOrigin (0, -owner.rootItem->itemHeight);
  44816. owner.rootItem->paintRecursively (g, getWidth());
  44817. }
  44818. }
  44819. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44820. {
  44821. if (owner.rootItem != 0)
  44822. {
  44823. owner.handleAsyncUpdate();
  44824. if (! owner.rootItemVisible)
  44825. y += owner.rootItem->itemHeight;
  44826. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44827. if (ti != 0)
  44828. itemPosition = ti->getItemPosition (false);
  44829. return ti;
  44830. }
  44831. return 0;
  44832. }
  44833. void updateComponents()
  44834. {
  44835. const int visibleTop = -getY();
  44836. const int visibleBottom = visibleTop + getParentHeight();
  44837. {
  44838. for (int i = items.size(); --i >= 0;)
  44839. items.getUnchecked(i)->shouldKeep = false;
  44840. }
  44841. {
  44842. TreeViewItem* item = owner.rootItem;
  44843. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44844. while (item != 0 && y < visibleBottom)
  44845. {
  44846. y += item->itemHeight;
  44847. if (y >= visibleTop)
  44848. {
  44849. RowItem* const ri = findItem (item->uid);
  44850. if (ri != 0)
  44851. {
  44852. ri->shouldKeep = true;
  44853. }
  44854. else
  44855. {
  44856. Component* const comp = item->createItemComponent();
  44857. if (comp != 0)
  44858. {
  44859. items.add (new RowItem (item, comp, item->uid));
  44860. addAndMakeVisible (comp);
  44861. }
  44862. }
  44863. }
  44864. item = item->getNextVisibleItem (true);
  44865. }
  44866. }
  44867. for (int i = items.size(); --i >= 0;)
  44868. {
  44869. RowItem* const ri = items.getUnchecked(i);
  44870. bool keep = false;
  44871. if (isParentOf (ri->component))
  44872. {
  44873. if (ri->shouldKeep)
  44874. {
  44875. Rectangle<int> pos (ri->item->getItemPosition (false));
  44876. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  44877. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44878. {
  44879. keep = true;
  44880. ri->component->setBounds (pos);
  44881. }
  44882. }
  44883. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  44884. {
  44885. keep = true;
  44886. ri->component->setSize (0, 0);
  44887. }
  44888. }
  44889. if (! keep)
  44890. items.remove (i);
  44891. }
  44892. }
  44893. void updateButtonUnderMouse (const MouseEvent& e)
  44894. {
  44895. TreeViewItem* newItem = 0;
  44896. if (owner.openCloseButtonsVisible)
  44897. {
  44898. Rectangle<int> pos;
  44899. TreeViewItem* item = findItemAt (e.y, pos);
  44900. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44901. {
  44902. newItem = item;
  44903. if (! newItem->mightContainSubItems())
  44904. newItem = 0;
  44905. }
  44906. }
  44907. if (buttonUnderMouse != newItem)
  44908. {
  44909. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44910. {
  44911. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44912. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44913. }
  44914. buttonUnderMouse = newItem;
  44915. if (buttonUnderMouse != 0)
  44916. {
  44917. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44918. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44919. }
  44920. }
  44921. }
  44922. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44923. {
  44924. return item == buttonUnderMouse;
  44925. }
  44926. void resized()
  44927. {
  44928. owner.itemsChanged();
  44929. }
  44930. const String getTooltip()
  44931. {
  44932. Rectangle<int> pos;
  44933. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44934. if (item != 0)
  44935. return item->getTooltip();
  44936. return owner.getTooltip();
  44937. }
  44938. private:
  44939. TreeView& owner;
  44940. struct RowItem
  44941. {
  44942. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  44943. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  44944. {
  44945. }
  44946. ~RowItem()
  44947. {
  44948. delete component.get();
  44949. }
  44950. WeakReference<Component> component;
  44951. TreeViewItem* item;
  44952. int uid;
  44953. bool shouldKeep;
  44954. };
  44955. OwnedArray <RowItem> items;
  44956. TreeViewItem* buttonUnderMouse;
  44957. bool isDragging, needSelectionOnMouseUp;
  44958. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44959. {
  44960. TreeViewItem* firstSelected = 0;
  44961. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44962. {
  44963. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44964. jassert (lastSelected != 0);
  44965. int rowStart = firstSelected->getRowNumberInTree();
  44966. int rowEnd = lastSelected->getRowNumberInTree();
  44967. if (rowStart > rowEnd)
  44968. swapVariables (rowStart, rowEnd);
  44969. int ourRow = item->getRowNumberInTree();
  44970. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44971. if (ourRow > otherEnd)
  44972. swapVariables (ourRow, otherEnd);
  44973. for (int i = ourRow; i <= otherEnd; ++i)
  44974. owner.getItemOnRow (i)->setSelected (true, false);
  44975. }
  44976. else
  44977. {
  44978. const bool cmd = modifiers.isCommandDown();
  44979. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44980. }
  44981. }
  44982. bool containsItem (TreeViewItem* const item) const throw()
  44983. {
  44984. for (int i = items.size(); --i >= 0;)
  44985. if (items.getUnchecked(i)->item == item)
  44986. return true;
  44987. return false;
  44988. }
  44989. RowItem* findItem (const int uid) const throw()
  44990. {
  44991. for (int i = items.size(); --i >= 0;)
  44992. {
  44993. RowItem* const ri = items.getUnchecked(i);
  44994. if (ri->uid == uid)
  44995. return ri;
  44996. }
  44997. return 0;
  44998. }
  44999. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45000. {
  45001. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45002. {
  45003. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45004. if (source->isDragging())
  45005. {
  45006. Component* const underMouse = source->getComponentUnderMouse();
  45007. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45008. return true;
  45009. }
  45010. }
  45011. return false;
  45012. }
  45013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45014. };
  45015. class TreeView::TreeViewport : public Viewport
  45016. {
  45017. public:
  45018. TreeViewport() throw() : lastX (-1) {}
  45019. void updateComponents (const bool triggerResize = false)
  45020. {
  45021. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45022. if (tvc != 0)
  45023. {
  45024. if (triggerResize)
  45025. tvc->resized();
  45026. else
  45027. tvc->updateComponents();
  45028. }
  45029. repaint();
  45030. }
  45031. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45032. {
  45033. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45034. lastX = newVisibleArea.getX();
  45035. updateComponents (hasScrolledSideways);
  45036. }
  45037. private:
  45038. int lastX;
  45039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45040. };
  45041. TreeView::TreeView (const String& componentName)
  45042. : Component (componentName),
  45043. rootItem (0),
  45044. indentSize (24),
  45045. defaultOpenness (false),
  45046. needsRecalculating (true),
  45047. rootItemVisible (true),
  45048. multiSelectEnabled (false),
  45049. openCloseButtonsVisible (true)
  45050. {
  45051. addAndMakeVisible (viewport = new TreeViewport());
  45052. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45053. viewport->setWantsKeyboardFocus (false);
  45054. setWantsKeyboardFocus (true);
  45055. }
  45056. TreeView::~TreeView()
  45057. {
  45058. if (rootItem != 0)
  45059. rootItem->setOwnerView (0);
  45060. }
  45061. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45062. {
  45063. if (rootItem != newRootItem)
  45064. {
  45065. if (newRootItem != 0)
  45066. {
  45067. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45068. if (newRootItem->ownerView != 0)
  45069. newRootItem->ownerView->setRootItem (0);
  45070. }
  45071. if (rootItem != 0)
  45072. rootItem->setOwnerView (0);
  45073. rootItem = newRootItem;
  45074. if (newRootItem != 0)
  45075. newRootItem->setOwnerView (this);
  45076. needsRecalculating = true;
  45077. handleAsyncUpdate();
  45078. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45079. {
  45080. rootItem->setOpen (false); // force a re-open
  45081. rootItem->setOpen (true);
  45082. }
  45083. }
  45084. }
  45085. void TreeView::deleteRootItem()
  45086. {
  45087. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45088. setRootItem (0);
  45089. }
  45090. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45091. {
  45092. rootItemVisible = shouldBeVisible;
  45093. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45094. {
  45095. rootItem->setOpen (false); // force a re-open
  45096. rootItem->setOpen (true);
  45097. }
  45098. itemsChanged();
  45099. }
  45100. void TreeView::colourChanged()
  45101. {
  45102. setOpaque (findColour (backgroundColourId).isOpaque());
  45103. repaint();
  45104. }
  45105. void TreeView::setIndentSize (const int newIndentSize)
  45106. {
  45107. if (indentSize != newIndentSize)
  45108. {
  45109. indentSize = newIndentSize;
  45110. resized();
  45111. }
  45112. }
  45113. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45114. {
  45115. if (defaultOpenness != isOpenByDefault)
  45116. {
  45117. defaultOpenness = isOpenByDefault;
  45118. itemsChanged();
  45119. }
  45120. }
  45121. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45122. {
  45123. multiSelectEnabled = canMultiSelect;
  45124. }
  45125. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45126. {
  45127. if (openCloseButtonsVisible != shouldBeVisible)
  45128. {
  45129. openCloseButtonsVisible = shouldBeVisible;
  45130. itemsChanged();
  45131. }
  45132. }
  45133. Viewport* TreeView::getViewport() const throw()
  45134. {
  45135. return viewport;
  45136. }
  45137. void TreeView::clearSelectedItems()
  45138. {
  45139. if (rootItem != 0)
  45140. rootItem->deselectAllRecursively();
  45141. }
  45142. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45143. {
  45144. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45145. }
  45146. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45147. {
  45148. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45149. }
  45150. int TreeView::getNumRowsInTree() const
  45151. {
  45152. if (rootItem != 0)
  45153. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45154. return 0;
  45155. }
  45156. TreeViewItem* TreeView::getItemOnRow (int index) const
  45157. {
  45158. if (! rootItemVisible)
  45159. ++index;
  45160. if (rootItem != 0 && index >= 0)
  45161. return rootItem->getItemOnRow (index);
  45162. return 0;
  45163. }
  45164. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45165. {
  45166. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45167. Rectangle<int> pos;
  45168. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45169. }
  45170. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45171. {
  45172. if (rootItem == 0)
  45173. return 0;
  45174. return rootItem->findItemFromIdentifierString (identifierString);
  45175. }
  45176. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45177. {
  45178. XmlElement* e = 0;
  45179. if (rootItem != 0)
  45180. {
  45181. e = rootItem->getOpennessState();
  45182. if (e != 0 && alsoIncludeScrollPosition)
  45183. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45184. }
  45185. return e;
  45186. }
  45187. void TreeView::restoreOpennessState (const XmlElement& newState)
  45188. {
  45189. if (rootItem != 0)
  45190. {
  45191. rootItem->restoreOpennessState (newState);
  45192. if (newState.hasAttribute ("scrollPos"))
  45193. viewport->setViewPosition (viewport->getViewPositionX(),
  45194. newState.getIntAttribute ("scrollPos"));
  45195. }
  45196. }
  45197. void TreeView::paint (Graphics& g)
  45198. {
  45199. g.fillAll (findColour (backgroundColourId));
  45200. }
  45201. void TreeView::resized()
  45202. {
  45203. viewport->setBounds (getLocalBounds());
  45204. itemsChanged();
  45205. handleAsyncUpdate();
  45206. }
  45207. void TreeView::enablementChanged()
  45208. {
  45209. repaint();
  45210. }
  45211. void TreeView::moveSelectedRow (int delta)
  45212. {
  45213. if (delta == 0)
  45214. return;
  45215. int rowSelected = 0;
  45216. TreeViewItem* const firstSelected = getSelectedItem (0);
  45217. if (firstSelected != 0)
  45218. rowSelected = firstSelected->getRowNumberInTree();
  45219. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45220. for (;;)
  45221. {
  45222. TreeViewItem* item = getItemOnRow (rowSelected);
  45223. if (item != 0)
  45224. {
  45225. if (! item->canBeSelected())
  45226. {
  45227. // if the row we want to highlight doesn't allow it, try skipping
  45228. // to the next item..
  45229. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45230. rowSelected + (delta < 0 ? -1 : 1));
  45231. if (rowSelected != nextRowToTry)
  45232. {
  45233. rowSelected = nextRowToTry;
  45234. continue;
  45235. }
  45236. else
  45237. {
  45238. break;
  45239. }
  45240. }
  45241. item->setSelected (true, true);
  45242. scrollToKeepItemVisible (item);
  45243. }
  45244. break;
  45245. }
  45246. }
  45247. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45248. {
  45249. if (item != 0 && item->ownerView == this)
  45250. {
  45251. handleAsyncUpdate();
  45252. item = item->getDeepestOpenParentItem();
  45253. int y = item->y;
  45254. int viewTop = viewport->getViewPositionY();
  45255. if (y < viewTop)
  45256. {
  45257. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45258. }
  45259. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45260. {
  45261. viewport->setViewPosition (viewport->getViewPositionX(),
  45262. (y + item->itemHeight) - viewport->getViewHeight());
  45263. }
  45264. }
  45265. }
  45266. bool TreeView::keyPressed (const KeyPress& key)
  45267. {
  45268. if (key.isKeyCode (KeyPress::upKey))
  45269. {
  45270. moveSelectedRow (-1);
  45271. }
  45272. else if (key.isKeyCode (KeyPress::downKey))
  45273. {
  45274. moveSelectedRow (1);
  45275. }
  45276. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45277. {
  45278. if (rootItem != 0)
  45279. {
  45280. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45281. if (key.isKeyCode (KeyPress::pageUpKey))
  45282. rowsOnScreen = -rowsOnScreen;
  45283. moveSelectedRow (rowsOnScreen);
  45284. }
  45285. }
  45286. else if (key.isKeyCode (KeyPress::homeKey))
  45287. {
  45288. moveSelectedRow (-0x3fffffff);
  45289. }
  45290. else if (key.isKeyCode (KeyPress::endKey))
  45291. {
  45292. moveSelectedRow (0x3fffffff);
  45293. }
  45294. else if (key.isKeyCode (KeyPress::returnKey))
  45295. {
  45296. TreeViewItem* const firstSelected = getSelectedItem (0);
  45297. if (firstSelected != 0)
  45298. firstSelected->setOpen (! firstSelected->isOpen());
  45299. }
  45300. else if (key.isKeyCode (KeyPress::leftKey))
  45301. {
  45302. TreeViewItem* const firstSelected = getSelectedItem (0);
  45303. if (firstSelected != 0)
  45304. {
  45305. if (firstSelected->isOpen())
  45306. {
  45307. firstSelected->setOpen (false);
  45308. }
  45309. else
  45310. {
  45311. TreeViewItem* parent = firstSelected->parentItem;
  45312. if ((! rootItemVisible) && parent == rootItem)
  45313. parent = 0;
  45314. if (parent != 0)
  45315. {
  45316. parent->setSelected (true, true);
  45317. scrollToKeepItemVisible (parent);
  45318. }
  45319. }
  45320. }
  45321. }
  45322. else if (key.isKeyCode (KeyPress::rightKey))
  45323. {
  45324. TreeViewItem* const firstSelected = getSelectedItem (0);
  45325. if (firstSelected != 0)
  45326. {
  45327. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45328. moveSelectedRow (1);
  45329. else
  45330. firstSelected->setOpen (true);
  45331. }
  45332. }
  45333. else
  45334. {
  45335. return false;
  45336. }
  45337. return true;
  45338. }
  45339. void TreeView::itemsChanged() throw()
  45340. {
  45341. needsRecalculating = true;
  45342. repaint();
  45343. triggerAsyncUpdate();
  45344. }
  45345. void TreeView::handleAsyncUpdate()
  45346. {
  45347. if (needsRecalculating)
  45348. {
  45349. needsRecalculating = false;
  45350. const ScopedLock sl (nodeAlterationLock);
  45351. if (rootItem != 0)
  45352. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45353. viewport->updateComponents();
  45354. if (rootItem != 0)
  45355. {
  45356. viewport->getViewedComponent()
  45357. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45358. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45359. }
  45360. else
  45361. {
  45362. viewport->getViewedComponent()->setSize (0, 0);
  45363. }
  45364. }
  45365. }
  45366. class TreeView::InsertPointHighlight : public Component
  45367. {
  45368. public:
  45369. InsertPointHighlight()
  45370. : lastItem (0)
  45371. {
  45372. setSize (100, 12);
  45373. setAlwaysOnTop (true);
  45374. setInterceptsMouseClicks (false, false);
  45375. }
  45376. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45377. {
  45378. lastItem = item;
  45379. lastIndex = insertIndex;
  45380. const int offset = getHeight() / 2;
  45381. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45382. }
  45383. void paint (Graphics& g)
  45384. {
  45385. Path p;
  45386. const float h = (float) getHeight();
  45387. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45388. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45389. p.lineTo ((float) getWidth(), h / 2.0f);
  45390. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45391. g.strokePath (p, PathStrokeType (2.0f));
  45392. }
  45393. TreeViewItem* lastItem;
  45394. int lastIndex;
  45395. private:
  45396. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45397. };
  45398. class TreeView::TargetGroupHighlight : public Component
  45399. {
  45400. public:
  45401. TargetGroupHighlight()
  45402. {
  45403. setAlwaysOnTop (true);
  45404. setInterceptsMouseClicks (false, false);
  45405. }
  45406. void setTargetPosition (TreeViewItem* const item) throw()
  45407. {
  45408. Rectangle<int> r (item->getItemPosition (true));
  45409. r.setHeight (item->getItemHeight());
  45410. setBounds (r);
  45411. }
  45412. void paint (Graphics& g)
  45413. {
  45414. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45415. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45416. }
  45417. private:
  45418. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45419. };
  45420. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45421. {
  45422. beginDragAutoRepeat (100);
  45423. if (dragInsertPointHighlight == 0)
  45424. {
  45425. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45426. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45427. }
  45428. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45429. dragTargetGroupHighlight->setTargetPosition (item);
  45430. }
  45431. void TreeView::hideDragHighlight() throw()
  45432. {
  45433. dragInsertPointHighlight = 0;
  45434. dragTargetGroupHighlight = 0;
  45435. }
  45436. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45437. const StringArray& files, const String& sourceDescription,
  45438. Component* sourceComponent) const throw()
  45439. {
  45440. insertIndex = 0;
  45441. TreeViewItem* item = getItemAt (y);
  45442. if (item == 0)
  45443. return 0;
  45444. Rectangle<int> itemPos (item->getItemPosition (true));
  45445. insertIndex = item->getIndexInParent();
  45446. const int oldY = y;
  45447. y = itemPos.getY();
  45448. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45449. {
  45450. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45451. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45452. {
  45453. // Check if we're trying to drag into an empty group item..
  45454. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45455. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45456. {
  45457. insertIndex = 0;
  45458. x = itemPos.getX() + getIndentSize();
  45459. y = itemPos.getBottom();
  45460. return item;
  45461. }
  45462. }
  45463. }
  45464. if (oldY > itemPos.getCentreY())
  45465. {
  45466. y += item->getItemHeight();
  45467. while (item->isLastOfSiblings() && item->parentItem != 0
  45468. && item->parentItem->parentItem != 0)
  45469. {
  45470. if (x > itemPos.getX())
  45471. break;
  45472. item = item->parentItem;
  45473. itemPos = item->getItemPosition (true);
  45474. insertIndex = item->getIndexInParent();
  45475. }
  45476. ++insertIndex;
  45477. }
  45478. x = itemPos.getX();
  45479. return item->parentItem;
  45480. }
  45481. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45482. {
  45483. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45484. int insertIndex;
  45485. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45486. if (item != 0)
  45487. {
  45488. if (scrolled || dragInsertPointHighlight == 0
  45489. || dragInsertPointHighlight->lastItem != item
  45490. || dragInsertPointHighlight->lastIndex != insertIndex)
  45491. {
  45492. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45493. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45494. showDragHighlight (item, insertIndex, x, y);
  45495. else
  45496. hideDragHighlight();
  45497. }
  45498. }
  45499. else
  45500. {
  45501. hideDragHighlight();
  45502. }
  45503. }
  45504. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45505. {
  45506. hideDragHighlight();
  45507. int insertIndex;
  45508. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45509. if (item != 0)
  45510. {
  45511. if (files.size() > 0)
  45512. {
  45513. if (item->isInterestedInFileDrag (files))
  45514. item->filesDropped (files, insertIndex);
  45515. }
  45516. else
  45517. {
  45518. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45519. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45520. }
  45521. }
  45522. }
  45523. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45524. {
  45525. return true;
  45526. }
  45527. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45528. {
  45529. fileDragMove (files, x, y);
  45530. }
  45531. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45532. {
  45533. handleDrag (files, String::empty, 0, x, y);
  45534. }
  45535. void TreeView::fileDragExit (const StringArray&)
  45536. {
  45537. hideDragHighlight();
  45538. }
  45539. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45540. {
  45541. handleDrop (files, String::empty, 0, x, y);
  45542. }
  45543. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45544. {
  45545. return true;
  45546. }
  45547. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45548. {
  45549. itemDragMove (sourceDescription, sourceComponent, x, y);
  45550. }
  45551. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45552. {
  45553. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45554. }
  45555. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45556. {
  45557. hideDragHighlight();
  45558. }
  45559. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45560. {
  45561. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45562. }
  45563. enum TreeViewOpenness
  45564. {
  45565. opennessDefault = 0,
  45566. opennessClosed = 1,
  45567. opennessOpen = 2
  45568. };
  45569. TreeViewItem::TreeViewItem()
  45570. : ownerView (0),
  45571. parentItem (0),
  45572. y (0),
  45573. itemHeight (0),
  45574. totalHeight (0),
  45575. selected (false),
  45576. redrawNeeded (true),
  45577. drawLinesInside (true),
  45578. drawsInLeftMargin (false),
  45579. openness (opennessDefault)
  45580. {
  45581. static int nextUID = 0;
  45582. uid = nextUID++;
  45583. }
  45584. TreeViewItem::~TreeViewItem()
  45585. {
  45586. }
  45587. const String TreeViewItem::getUniqueName() const
  45588. {
  45589. return String::empty;
  45590. }
  45591. void TreeViewItem::itemOpennessChanged (bool)
  45592. {
  45593. }
  45594. int TreeViewItem::getNumSubItems() const throw()
  45595. {
  45596. return subItems.size();
  45597. }
  45598. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45599. {
  45600. return subItems [index];
  45601. }
  45602. void TreeViewItem::clearSubItems()
  45603. {
  45604. if (subItems.size() > 0)
  45605. {
  45606. if (ownerView != 0)
  45607. {
  45608. const ScopedLock sl (ownerView->nodeAlterationLock);
  45609. subItems.clear();
  45610. treeHasChanged();
  45611. }
  45612. else
  45613. {
  45614. subItems.clear();
  45615. }
  45616. }
  45617. }
  45618. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45619. {
  45620. if (newItem != 0)
  45621. {
  45622. newItem->parentItem = this;
  45623. newItem->setOwnerView (ownerView);
  45624. newItem->y = 0;
  45625. newItem->itemHeight = newItem->getItemHeight();
  45626. newItem->totalHeight = 0;
  45627. newItem->itemWidth = newItem->getItemWidth();
  45628. newItem->totalWidth = 0;
  45629. if (ownerView != 0)
  45630. {
  45631. const ScopedLock sl (ownerView->nodeAlterationLock);
  45632. subItems.insert (insertPosition, newItem);
  45633. treeHasChanged();
  45634. if (newItem->isOpen())
  45635. newItem->itemOpennessChanged (true);
  45636. }
  45637. else
  45638. {
  45639. subItems.insert (insertPosition, newItem);
  45640. if (newItem->isOpen())
  45641. newItem->itemOpennessChanged (true);
  45642. }
  45643. }
  45644. }
  45645. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45646. {
  45647. if (ownerView != 0)
  45648. {
  45649. const ScopedLock sl (ownerView->nodeAlterationLock);
  45650. if (isPositiveAndBelow (index, subItems.size()))
  45651. {
  45652. subItems.remove (index, deleteItem);
  45653. treeHasChanged();
  45654. }
  45655. }
  45656. else
  45657. {
  45658. subItems.remove (index, deleteItem);
  45659. }
  45660. }
  45661. bool TreeViewItem::isOpen() const throw()
  45662. {
  45663. if (openness == opennessDefault)
  45664. return ownerView != 0 && ownerView->defaultOpenness;
  45665. else
  45666. return openness == opennessOpen;
  45667. }
  45668. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45669. {
  45670. if (isOpen() != shouldBeOpen)
  45671. {
  45672. openness = shouldBeOpen ? opennessOpen
  45673. : opennessClosed;
  45674. treeHasChanged();
  45675. itemOpennessChanged (isOpen());
  45676. }
  45677. }
  45678. bool TreeViewItem::isSelected() const throw()
  45679. {
  45680. return selected;
  45681. }
  45682. void TreeViewItem::deselectAllRecursively()
  45683. {
  45684. setSelected (false, false);
  45685. for (int i = 0; i < subItems.size(); ++i)
  45686. subItems.getUnchecked(i)->deselectAllRecursively();
  45687. }
  45688. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45689. const bool deselectOtherItemsFirst)
  45690. {
  45691. if (shouldBeSelected && ! canBeSelected())
  45692. return;
  45693. if (deselectOtherItemsFirst)
  45694. getTopLevelItem()->deselectAllRecursively();
  45695. if (shouldBeSelected != selected)
  45696. {
  45697. selected = shouldBeSelected;
  45698. if (ownerView != 0)
  45699. ownerView->repaint();
  45700. itemSelectionChanged (shouldBeSelected);
  45701. }
  45702. }
  45703. void TreeViewItem::paintItem (Graphics&, int, int)
  45704. {
  45705. }
  45706. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45707. {
  45708. ownerView->getLookAndFeel()
  45709. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45710. }
  45711. void TreeViewItem::itemClicked (const MouseEvent&)
  45712. {
  45713. }
  45714. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45715. {
  45716. if (mightContainSubItems())
  45717. setOpen (! isOpen());
  45718. }
  45719. void TreeViewItem::itemSelectionChanged (bool)
  45720. {
  45721. }
  45722. const String TreeViewItem::getTooltip()
  45723. {
  45724. return String::empty;
  45725. }
  45726. const String TreeViewItem::getDragSourceDescription()
  45727. {
  45728. return String::empty;
  45729. }
  45730. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45731. {
  45732. return false;
  45733. }
  45734. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45735. {
  45736. }
  45737. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45738. {
  45739. return false;
  45740. }
  45741. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45742. {
  45743. }
  45744. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45745. {
  45746. const int indentX = getIndentX();
  45747. int width = itemWidth;
  45748. if (ownerView != 0 && width < 0)
  45749. width = ownerView->viewport->getViewWidth() - indentX;
  45750. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45751. if (relativeToTreeViewTopLeft)
  45752. r -= ownerView->viewport->getViewPosition();
  45753. return r;
  45754. }
  45755. void TreeViewItem::treeHasChanged() const throw()
  45756. {
  45757. if (ownerView != 0)
  45758. ownerView->itemsChanged();
  45759. }
  45760. void TreeViewItem::repaintItem() const
  45761. {
  45762. if (ownerView != 0 && areAllParentsOpen())
  45763. {
  45764. Rectangle<int> r (getItemPosition (true));
  45765. r.setLeft (0);
  45766. ownerView->viewport->repaint (r);
  45767. }
  45768. }
  45769. bool TreeViewItem::areAllParentsOpen() const throw()
  45770. {
  45771. return parentItem == 0
  45772. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45773. }
  45774. void TreeViewItem::updatePositions (int newY)
  45775. {
  45776. y = newY;
  45777. itemHeight = getItemHeight();
  45778. totalHeight = itemHeight;
  45779. itemWidth = getItemWidth();
  45780. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45781. if (isOpen())
  45782. {
  45783. newY += totalHeight;
  45784. for (int i = 0; i < subItems.size(); ++i)
  45785. {
  45786. TreeViewItem* const ti = subItems.getUnchecked(i);
  45787. ti->updatePositions (newY);
  45788. newY += ti->totalHeight;
  45789. totalHeight += ti->totalHeight;
  45790. totalWidth = jmax (totalWidth, ti->totalWidth);
  45791. }
  45792. }
  45793. }
  45794. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45795. {
  45796. TreeViewItem* result = this;
  45797. TreeViewItem* item = this;
  45798. while (item->parentItem != 0)
  45799. {
  45800. item = item->parentItem;
  45801. if (! item->isOpen())
  45802. result = item;
  45803. }
  45804. return result;
  45805. }
  45806. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45807. {
  45808. ownerView = newOwner;
  45809. for (int i = subItems.size(); --i >= 0;)
  45810. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45811. }
  45812. int TreeViewItem::getIndentX() const throw()
  45813. {
  45814. const int indentWidth = ownerView->getIndentSize();
  45815. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45816. if (! ownerView->openCloseButtonsVisible)
  45817. x -= indentWidth;
  45818. TreeViewItem* p = parentItem;
  45819. while (p != 0)
  45820. {
  45821. x += indentWidth;
  45822. p = p->parentItem;
  45823. }
  45824. return x;
  45825. }
  45826. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45827. {
  45828. drawsInLeftMargin = canDrawInLeftMargin;
  45829. }
  45830. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45831. {
  45832. jassert (ownerView != 0);
  45833. if (ownerView == 0)
  45834. return;
  45835. const int indent = getIndentX();
  45836. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45837. {
  45838. Graphics::ScopedSaveState ss (g);
  45839. g.setOrigin (indent, 0);
  45840. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45841. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45842. paintItem (g, itemW, itemHeight);
  45843. }
  45844. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45845. const float halfH = itemHeight * 0.5f;
  45846. int depth = 0;
  45847. TreeViewItem* p = parentItem;
  45848. while (p != 0)
  45849. {
  45850. ++depth;
  45851. p = p->parentItem;
  45852. }
  45853. if (! ownerView->rootItemVisible)
  45854. --depth;
  45855. const int indentWidth = ownerView->getIndentSize();
  45856. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45857. {
  45858. float x = (depth + 0.5f) * indentWidth;
  45859. if (depth >= 0)
  45860. {
  45861. if (parentItem != 0 && parentItem->drawLinesInside)
  45862. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45863. if ((parentItem != 0 && parentItem->drawLinesInside)
  45864. || (parentItem == 0 && drawLinesInside))
  45865. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45866. }
  45867. p = parentItem;
  45868. int d = depth;
  45869. while (p != 0 && --d >= 0)
  45870. {
  45871. x -= (float) indentWidth;
  45872. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45873. && ! p->isLastOfSiblings())
  45874. {
  45875. g.drawLine (x, 0, x, (float) itemHeight);
  45876. }
  45877. p = p->parentItem;
  45878. }
  45879. if (mightContainSubItems())
  45880. {
  45881. Graphics::ScopedSaveState ss (g);
  45882. g.setOrigin (depth * indentWidth, 0);
  45883. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45884. paintOpenCloseButton (g, indentWidth, itemHeight,
  45885. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45886. ->isMouseOverButton (this));
  45887. }
  45888. }
  45889. if (isOpen())
  45890. {
  45891. const Rectangle<int> clip (g.getClipBounds());
  45892. for (int i = 0; i < subItems.size(); ++i)
  45893. {
  45894. TreeViewItem* const ti = subItems.getUnchecked(i);
  45895. const int relY = ti->y - y;
  45896. if (relY >= clip.getBottom())
  45897. break;
  45898. if (relY + ti->totalHeight >= clip.getY())
  45899. {
  45900. Graphics::ScopedSaveState ss (g);
  45901. g.setOrigin (0, relY);
  45902. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45903. ti->paintRecursively (g, width);
  45904. }
  45905. }
  45906. }
  45907. }
  45908. bool TreeViewItem::isLastOfSiblings() const throw()
  45909. {
  45910. return parentItem == 0
  45911. || parentItem->subItems.getLast() == this;
  45912. }
  45913. int TreeViewItem::getIndexInParent() const throw()
  45914. {
  45915. return parentItem == 0 ? 0
  45916. : parentItem->subItems.indexOf (this);
  45917. }
  45918. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45919. {
  45920. return parentItem == 0 ? this
  45921. : parentItem->getTopLevelItem();
  45922. }
  45923. int TreeViewItem::getNumRows() const throw()
  45924. {
  45925. int num = 1;
  45926. if (isOpen())
  45927. {
  45928. for (int i = subItems.size(); --i >= 0;)
  45929. num += subItems.getUnchecked(i)->getNumRows();
  45930. }
  45931. return num;
  45932. }
  45933. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45934. {
  45935. if (index == 0)
  45936. return this;
  45937. if (index > 0 && isOpen())
  45938. {
  45939. --index;
  45940. for (int i = 0; i < subItems.size(); ++i)
  45941. {
  45942. TreeViewItem* const item = subItems.getUnchecked(i);
  45943. if (index == 0)
  45944. return item;
  45945. const int numRows = item->getNumRows();
  45946. if (numRows > index)
  45947. return item->getItemOnRow (index);
  45948. index -= numRows;
  45949. }
  45950. }
  45951. return 0;
  45952. }
  45953. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45954. {
  45955. if (isPositiveAndBelow (targetY, totalHeight))
  45956. {
  45957. const int h = itemHeight;
  45958. if (targetY < h)
  45959. return this;
  45960. if (isOpen())
  45961. {
  45962. targetY -= h;
  45963. for (int i = 0; i < subItems.size(); ++i)
  45964. {
  45965. TreeViewItem* const ti = subItems.getUnchecked(i);
  45966. if (targetY < ti->totalHeight)
  45967. return ti->findItemRecursively (targetY);
  45968. targetY -= ti->totalHeight;
  45969. }
  45970. }
  45971. }
  45972. return 0;
  45973. }
  45974. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  45975. {
  45976. int total = isSelected() ? 1 : 0;
  45977. if (depth != 0)
  45978. for (int i = subItems.size(); --i >= 0;)
  45979. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  45980. return total;
  45981. }
  45982. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45983. {
  45984. if (isSelected())
  45985. {
  45986. if (index == 0)
  45987. return this;
  45988. --index;
  45989. }
  45990. if (index >= 0)
  45991. {
  45992. for (int i = 0; i < subItems.size(); ++i)
  45993. {
  45994. TreeViewItem* const item = subItems.getUnchecked(i);
  45995. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45996. if (found != 0)
  45997. return found;
  45998. index -= item->countSelectedItemsRecursively (-1);
  45999. }
  46000. }
  46001. return 0;
  46002. }
  46003. int TreeViewItem::getRowNumberInTree() const throw()
  46004. {
  46005. if (parentItem != 0 && ownerView != 0)
  46006. {
  46007. int n = 1 + parentItem->getRowNumberInTree();
  46008. int ourIndex = parentItem->subItems.indexOf (this);
  46009. jassert (ourIndex >= 0);
  46010. while (--ourIndex >= 0)
  46011. n += parentItem->subItems [ourIndex]->getNumRows();
  46012. if (parentItem->parentItem == 0
  46013. && ! ownerView->rootItemVisible)
  46014. --n;
  46015. return n;
  46016. }
  46017. else
  46018. {
  46019. return 0;
  46020. }
  46021. }
  46022. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46023. {
  46024. drawLinesInside = drawLines;
  46025. }
  46026. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46027. {
  46028. if (recurse && isOpen() && subItems.size() > 0)
  46029. return subItems [0];
  46030. if (parentItem != 0)
  46031. {
  46032. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46033. if (nextIndex >= parentItem->subItems.size())
  46034. return parentItem->getNextVisibleItem (false);
  46035. return parentItem->subItems [nextIndex];
  46036. }
  46037. return 0;
  46038. }
  46039. const String TreeViewItem::getItemIdentifierString() const
  46040. {
  46041. String s;
  46042. if (parentItem != 0)
  46043. s = parentItem->getItemIdentifierString();
  46044. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46045. }
  46046. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46047. {
  46048. const String thisId (getUniqueName());
  46049. if (thisId == identifierString)
  46050. return this;
  46051. if (identifierString.startsWith (thisId + "/"))
  46052. {
  46053. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46054. bool wasOpen = isOpen();
  46055. setOpen (true);
  46056. for (int i = subItems.size(); --i >= 0;)
  46057. {
  46058. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46059. if (item != 0)
  46060. return item;
  46061. }
  46062. setOpen (wasOpen);
  46063. }
  46064. return 0;
  46065. }
  46066. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46067. {
  46068. if (e.hasTagName ("CLOSED"))
  46069. {
  46070. setOpen (false);
  46071. }
  46072. else if (e.hasTagName ("OPEN"))
  46073. {
  46074. setOpen (true);
  46075. forEachXmlChildElement (e, n)
  46076. {
  46077. const String id (n->getStringAttribute ("id"));
  46078. for (int i = 0; i < subItems.size(); ++i)
  46079. {
  46080. TreeViewItem* const ti = subItems.getUnchecked(i);
  46081. if (ti->getUniqueName() == id)
  46082. {
  46083. ti->restoreOpennessState (*n);
  46084. break;
  46085. }
  46086. }
  46087. }
  46088. }
  46089. }
  46090. XmlElement* TreeViewItem::getOpennessState() const throw()
  46091. {
  46092. const String name (getUniqueName());
  46093. if (name.isNotEmpty())
  46094. {
  46095. XmlElement* e;
  46096. if (isOpen())
  46097. {
  46098. e = new XmlElement ("OPEN");
  46099. for (int i = 0; i < subItems.size(); ++i)
  46100. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46101. }
  46102. else
  46103. {
  46104. e = new XmlElement ("CLOSED");
  46105. }
  46106. e->setAttribute ("id", name);
  46107. return e;
  46108. }
  46109. else
  46110. {
  46111. // trying to save the openness for an element that has no name - this won't
  46112. // work because it needs the names to identify what to open.
  46113. jassertfalse;
  46114. }
  46115. return 0;
  46116. }
  46117. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46118. : treeViewItem (treeViewItem_),
  46119. oldOpenness (treeViewItem_.getOpennessState())
  46120. {
  46121. }
  46122. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46123. {
  46124. if (oldOpenness != 0)
  46125. treeViewItem.restoreOpennessState (*oldOpenness);
  46126. }
  46127. END_JUCE_NAMESPACE
  46128. /*** End of inlined file: juce_TreeView.cpp ***/
  46129. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46130. BEGIN_JUCE_NAMESPACE
  46131. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46132. : fileList (listToShow)
  46133. {
  46134. }
  46135. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46136. {
  46137. }
  46138. FileBrowserListener::~FileBrowserListener()
  46139. {
  46140. }
  46141. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46142. {
  46143. listeners.add (listener);
  46144. }
  46145. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46146. {
  46147. listeners.remove (listener);
  46148. }
  46149. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46150. {
  46151. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46152. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46153. }
  46154. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46155. {
  46156. if (fileList.getDirectory().exists())
  46157. {
  46158. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46159. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46160. }
  46161. }
  46162. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46163. {
  46164. if (fileList.getDirectory().exists())
  46165. {
  46166. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46167. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46168. }
  46169. }
  46170. END_JUCE_NAMESPACE
  46171. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46172. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46173. BEGIN_JUCE_NAMESPACE
  46174. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46175. TimeSliceThread& thread_)
  46176. : fileFilter (fileFilter_),
  46177. thread (thread_),
  46178. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46179. fileFindHandle (0),
  46180. shouldStop (true)
  46181. {
  46182. }
  46183. DirectoryContentsList::~DirectoryContentsList()
  46184. {
  46185. clear();
  46186. }
  46187. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46188. {
  46189. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46190. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46191. }
  46192. bool DirectoryContentsList::ignoresHiddenFiles() const
  46193. {
  46194. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46195. }
  46196. const File& DirectoryContentsList::getDirectory() const
  46197. {
  46198. return root;
  46199. }
  46200. void DirectoryContentsList::setDirectory (const File& directory,
  46201. const bool includeDirectories,
  46202. const bool includeFiles)
  46203. {
  46204. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46205. if (directory != root)
  46206. {
  46207. clear();
  46208. root = directory;
  46209. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46210. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46211. }
  46212. int newFlags = fileTypeFlags;
  46213. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46214. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46215. setTypeFlags (newFlags);
  46216. }
  46217. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46218. {
  46219. if (fileTypeFlags != newFlags)
  46220. {
  46221. fileTypeFlags = newFlags;
  46222. refresh();
  46223. }
  46224. }
  46225. void DirectoryContentsList::clear()
  46226. {
  46227. shouldStop = true;
  46228. thread.removeTimeSliceClient (this);
  46229. fileFindHandle = 0;
  46230. if (files.size() > 0)
  46231. {
  46232. files.clear();
  46233. changed();
  46234. }
  46235. }
  46236. void DirectoryContentsList::refresh()
  46237. {
  46238. clear();
  46239. if (root.isDirectory())
  46240. {
  46241. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46242. shouldStop = false;
  46243. thread.addTimeSliceClient (this);
  46244. }
  46245. }
  46246. int DirectoryContentsList::getNumFiles() const
  46247. {
  46248. return files.size();
  46249. }
  46250. bool DirectoryContentsList::getFileInfo (const int index,
  46251. FileInfo& result) const
  46252. {
  46253. const ScopedLock sl (fileListLock);
  46254. const FileInfo* const info = files [index];
  46255. if (info != 0)
  46256. {
  46257. result = *info;
  46258. return true;
  46259. }
  46260. return false;
  46261. }
  46262. const File DirectoryContentsList::getFile (const int index) const
  46263. {
  46264. const ScopedLock sl (fileListLock);
  46265. const FileInfo* const info = files [index];
  46266. if (info != 0)
  46267. return root.getChildFile (info->filename);
  46268. return File::nonexistent;
  46269. }
  46270. bool DirectoryContentsList::isStillLoading() const
  46271. {
  46272. return fileFindHandle != 0;
  46273. }
  46274. void DirectoryContentsList::changed()
  46275. {
  46276. sendChangeMessage();
  46277. }
  46278. int DirectoryContentsList::useTimeSlice()
  46279. {
  46280. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46281. bool hasChanged = false;
  46282. for (int i = 100; --i >= 0;)
  46283. {
  46284. if (! checkNextFile (hasChanged))
  46285. {
  46286. if (hasChanged)
  46287. changed();
  46288. return 500;
  46289. }
  46290. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46291. break;
  46292. }
  46293. if (hasChanged)
  46294. changed();
  46295. return 0;
  46296. }
  46297. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46298. {
  46299. if (fileFindHandle != 0)
  46300. {
  46301. bool fileFoundIsDir, isHidden, isReadOnly;
  46302. int64 fileSize;
  46303. Time modTime, creationTime;
  46304. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46305. &modTime, &creationTime, &isReadOnly))
  46306. {
  46307. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46308. fileSize, modTime, creationTime, isReadOnly))
  46309. {
  46310. hasChanged = true;
  46311. }
  46312. return true;
  46313. }
  46314. else
  46315. {
  46316. fileFindHandle = 0;
  46317. }
  46318. }
  46319. return false;
  46320. }
  46321. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46322. const DirectoryContentsList::FileInfo* const second)
  46323. {
  46324. #if JUCE_WINDOWS
  46325. if (first->isDirectory != second->isDirectory)
  46326. return first->isDirectory ? -1 : 1;
  46327. #endif
  46328. return first->filename.compareIgnoreCase (second->filename);
  46329. }
  46330. bool DirectoryContentsList::addFile (const File& file,
  46331. const bool isDir,
  46332. const int64 fileSize,
  46333. const Time& modTime,
  46334. const Time& creationTime,
  46335. const bool isReadOnly)
  46336. {
  46337. if (fileFilter == 0
  46338. || ((! isDir) && fileFilter->isFileSuitable (file))
  46339. || (isDir && fileFilter->isDirectorySuitable (file)))
  46340. {
  46341. ScopedPointer <FileInfo> info (new FileInfo());
  46342. info->filename = file.getFileName();
  46343. info->fileSize = fileSize;
  46344. info->modificationTime = modTime;
  46345. info->creationTime = creationTime;
  46346. info->isDirectory = isDir;
  46347. info->isReadOnly = isReadOnly;
  46348. const ScopedLock sl (fileListLock);
  46349. for (int i = files.size(); --i >= 0;)
  46350. if (files.getUnchecked(i)->filename == info->filename)
  46351. return false;
  46352. files.addSorted (*this, info.release());
  46353. return true;
  46354. }
  46355. return false;
  46356. }
  46357. END_JUCE_NAMESPACE
  46358. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46359. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46360. BEGIN_JUCE_NAMESPACE
  46361. FileBrowserComponent::FileBrowserComponent (int flags_,
  46362. const File& initialFileOrDirectory,
  46363. const FileFilter* fileFilter_,
  46364. FilePreviewComponent* previewComp_)
  46365. : FileFilter (String::empty),
  46366. fileFilter (fileFilter_),
  46367. flags (flags_),
  46368. previewComp (previewComp_),
  46369. currentPathBox ("path"),
  46370. fileLabel ("f", TRANS ("file:")),
  46371. thread ("Juce FileBrowser")
  46372. {
  46373. // You need to specify one or other of the open/save flags..
  46374. jassert ((flags & (saveMode | openMode)) != 0);
  46375. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46376. // You need to specify at least one of these flags..
  46377. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46378. String filename;
  46379. if (initialFileOrDirectory == File::nonexistent)
  46380. {
  46381. currentRoot = File::getCurrentWorkingDirectory();
  46382. }
  46383. else if (initialFileOrDirectory.isDirectory())
  46384. {
  46385. currentRoot = initialFileOrDirectory;
  46386. }
  46387. else
  46388. {
  46389. chosenFiles.add (initialFileOrDirectory);
  46390. currentRoot = initialFileOrDirectory.getParentDirectory();
  46391. filename = initialFileOrDirectory.getFileName();
  46392. }
  46393. fileList = new DirectoryContentsList (this, thread);
  46394. if ((flags & useTreeView) != 0)
  46395. {
  46396. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46397. fileListComponent = tree;
  46398. if ((flags & canSelectMultipleItems) != 0)
  46399. tree->setMultiSelectEnabled (true);
  46400. addAndMakeVisible (tree);
  46401. }
  46402. else
  46403. {
  46404. FileListComponent* const list = new FileListComponent (*fileList);
  46405. fileListComponent = list;
  46406. list->setOutlineThickness (1);
  46407. if ((flags & canSelectMultipleItems) != 0)
  46408. list->setMultipleSelectionEnabled (true);
  46409. addAndMakeVisible (list);
  46410. }
  46411. fileListComponent->addListener (this);
  46412. addAndMakeVisible (&currentPathBox);
  46413. currentPathBox.setEditableText (true);
  46414. StringArray rootNames, rootPaths;
  46415. getRoots (rootNames, rootPaths);
  46416. for (int i = 0; i < rootNames.size(); ++i)
  46417. {
  46418. if (rootNames[i].isEmpty())
  46419. currentPathBox.addSeparator();
  46420. else
  46421. currentPathBox.addItem (rootNames[i], i + 1);
  46422. }
  46423. currentPathBox.addSeparator();
  46424. currentPathBox.addListener (this);
  46425. addAndMakeVisible (&filenameBox);
  46426. filenameBox.setMultiLine (false);
  46427. filenameBox.setSelectAllWhenFocused (true);
  46428. filenameBox.setText (filename, false);
  46429. filenameBox.addListener (this);
  46430. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46431. addAndMakeVisible (&fileLabel);
  46432. fileLabel.attachToComponent (&filenameBox, true);
  46433. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46434. goUpButton->addListener (this);
  46435. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46436. if (previewComp != 0)
  46437. addAndMakeVisible (previewComp);
  46438. setRoot (currentRoot);
  46439. thread.startThread (4);
  46440. }
  46441. FileBrowserComponent::~FileBrowserComponent()
  46442. {
  46443. fileListComponent = 0;
  46444. fileList = 0;
  46445. thread.stopThread (10000);
  46446. }
  46447. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46448. {
  46449. listeners.add (newListener);
  46450. }
  46451. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46452. {
  46453. listeners.remove (listener);
  46454. }
  46455. bool FileBrowserComponent::isSaveMode() const throw()
  46456. {
  46457. return (flags & saveMode) != 0;
  46458. }
  46459. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46460. {
  46461. if (chosenFiles.size() == 0 && currentFileIsValid())
  46462. return 1;
  46463. return chosenFiles.size();
  46464. }
  46465. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46466. {
  46467. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46468. return currentRoot;
  46469. if (! filenameBox.isReadOnly())
  46470. return currentRoot.getChildFile (filenameBox.getText());
  46471. return chosenFiles[index];
  46472. }
  46473. bool FileBrowserComponent::currentFileIsValid() const
  46474. {
  46475. if (isSaveMode())
  46476. return ! getSelectedFile (0).isDirectory();
  46477. else
  46478. return getSelectedFile (0).exists();
  46479. }
  46480. const File FileBrowserComponent::getHighlightedFile() const throw()
  46481. {
  46482. return fileListComponent->getSelectedFile (0);
  46483. }
  46484. void FileBrowserComponent::deselectAllFiles()
  46485. {
  46486. fileListComponent->deselectAllFiles();
  46487. }
  46488. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46489. {
  46490. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46491. }
  46492. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46493. {
  46494. return true;
  46495. }
  46496. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46497. {
  46498. if (f.isDirectory())
  46499. return (flags & canSelectDirectories) != 0
  46500. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46501. return (flags & canSelectFiles) != 0 && f.exists()
  46502. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46503. }
  46504. const File FileBrowserComponent::getRoot() const
  46505. {
  46506. return currentRoot;
  46507. }
  46508. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46509. {
  46510. if (currentRoot != newRootDirectory)
  46511. {
  46512. fileListComponent->scrollToTop();
  46513. String path (newRootDirectory.getFullPathName());
  46514. if (path.isEmpty())
  46515. path = File::separatorString;
  46516. StringArray rootNames, rootPaths;
  46517. getRoots (rootNames, rootPaths);
  46518. if (! rootPaths.contains (path, true))
  46519. {
  46520. bool alreadyListed = false;
  46521. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46522. {
  46523. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46524. {
  46525. alreadyListed = true;
  46526. break;
  46527. }
  46528. }
  46529. if (! alreadyListed)
  46530. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46531. }
  46532. }
  46533. currentRoot = newRootDirectory;
  46534. fileList->setDirectory (currentRoot, true, true);
  46535. String currentRootName (currentRoot.getFullPathName());
  46536. if (currentRootName.isEmpty())
  46537. currentRootName = File::separatorString;
  46538. currentPathBox.setText (currentRootName, true);
  46539. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46540. && currentRoot.getParentDirectory() != currentRoot);
  46541. }
  46542. void FileBrowserComponent::goUp()
  46543. {
  46544. setRoot (getRoot().getParentDirectory());
  46545. }
  46546. void FileBrowserComponent::refresh()
  46547. {
  46548. fileList->refresh();
  46549. }
  46550. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46551. {
  46552. if (fileFilter != newFileFilter)
  46553. {
  46554. fileFilter = newFileFilter;
  46555. refresh();
  46556. }
  46557. }
  46558. const String FileBrowserComponent::getActionVerb() const
  46559. {
  46560. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46561. }
  46562. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46563. {
  46564. return previewComp;
  46565. }
  46566. void FileBrowserComponent::resized()
  46567. {
  46568. getLookAndFeel()
  46569. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46570. &currentPathBox, &filenameBox, goUpButton);
  46571. }
  46572. void FileBrowserComponent::sendListenerChangeMessage()
  46573. {
  46574. Component::BailOutChecker checker (this);
  46575. if (previewComp != 0)
  46576. previewComp->selectedFileChanged (getSelectedFile (0));
  46577. // You shouldn't delete the browser when the file gets changed!
  46578. jassert (! checker.shouldBailOut());
  46579. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46580. }
  46581. void FileBrowserComponent::selectionChanged()
  46582. {
  46583. StringArray newFilenames;
  46584. bool resetChosenFiles = true;
  46585. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46586. {
  46587. const File f (fileListComponent->getSelectedFile (i));
  46588. if (isFileOrDirSuitable (f))
  46589. {
  46590. if (resetChosenFiles)
  46591. {
  46592. chosenFiles.clear();
  46593. resetChosenFiles = false;
  46594. }
  46595. chosenFiles.add (f);
  46596. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46597. }
  46598. }
  46599. if (newFilenames.size() > 0)
  46600. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46601. sendListenerChangeMessage();
  46602. }
  46603. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46604. {
  46605. Component::BailOutChecker checker (this);
  46606. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46607. }
  46608. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46609. {
  46610. if (f.isDirectory())
  46611. {
  46612. setRoot (f);
  46613. if ((flags & canSelectDirectories) != 0)
  46614. filenameBox.setText (String::empty);
  46615. }
  46616. else
  46617. {
  46618. Component::BailOutChecker checker (this);
  46619. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46620. }
  46621. }
  46622. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46623. {
  46624. (void) key;
  46625. #if JUCE_LINUX || JUCE_WINDOWS
  46626. if (key.getModifiers().isCommandDown()
  46627. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46628. {
  46629. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46630. fileList->refresh();
  46631. return true;
  46632. }
  46633. #endif
  46634. return false;
  46635. }
  46636. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46637. {
  46638. sendListenerChangeMessage();
  46639. }
  46640. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46641. {
  46642. if (filenameBox.getText().containsChar (File::separator))
  46643. {
  46644. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46645. if (f.isDirectory())
  46646. {
  46647. setRoot (f);
  46648. chosenFiles.clear();
  46649. filenameBox.setText (String::empty);
  46650. }
  46651. else
  46652. {
  46653. setRoot (f.getParentDirectory());
  46654. chosenFiles.clear();
  46655. chosenFiles.add (f);
  46656. filenameBox.setText (f.getFileName());
  46657. }
  46658. }
  46659. else
  46660. {
  46661. fileDoubleClicked (getSelectedFile (0));
  46662. }
  46663. }
  46664. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46665. {
  46666. }
  46667. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46668. {
  46669. if (! isSaveMode())
  46670. selectionChanged();
  46671. }
  46672. void FileBrowserComponent::buttonClicked (Button*)
  46673. {
  46674. goUp();
  46675. }
  46676. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46677. {
  46678. const String newText (currentPathBox.getText().trim().unquoted());
  46679. if (newText.isNotEmpty())
  46680. {
  46681. const int index = currentPathBox.getSelectedId() - 1;
  46682. StringArray rootNames, rootPaths;
  46683. getRoots (rootNames, rootPaths);
  46684. if (rootPaths [index].isNotEmpty())
  46685. {
  46686. setRoot (File (rootPaths [index]));
  46687. }
  46688. else
  46689. {
  46690. File f (newText);
  46691. for (;;)
  46692. {
  46693. if (f.isDirectory())
  46694. {
  46695. setRoot (f);
  46696. break;
  46697. }
  46698. if (f.getParentDirectory() == f)
  46699. break;
  46700. f = f.getParentDirectory();
  46701. }
  46702. }
  46703. }
  46704. }
  46705. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46706. {
  46707. #if JUCE_WINDOWS
  46708. Array<File> roots;
  46709. File::findFileSystemRoots (roots);
  46710. rootPaths.clear();
  46711. for (int i = 0; i < roots.size(); ++i)
  46712. {
  46713. const File& drive = roots.getReference(i);
  46714. String name (drive.getFullPathName());
  46715. rootPaths.add (name);
  46716. if (drive.isOnHardDisk())
  46717. {
  46718. String volume (drive.getVolumeLabel());
  46719. if (volume.isEmpty())
  46720. volume = TRANS("Hard Drive");
  46721. name << " [" << volume << ']';
  46722. }
  46723. else if (drive.isOnCDRomDrive())
  46724. {
  46725. name << TRANS(" [CD/DVD drive]");
  46726. }
  46727. rootNames.add (name);
  46728. }
  46729. rootPaths.add (String::empty);
  46730. rootNames.add (String::empty);
  46731. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46732. rootNames.add ("Documents");
  46733. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46734. rootNames.add ("Desktop");
  46735. #endif
  46736. #if JUCE_MAC
  46737. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46738. rootNames.add ("Home folder");
  46739. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46740. rootNames.add ("Documents");
  46741. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46742. rootNames.add ("Desktop");
  46743. rootPaths.add (String::empty);
  46744. rootNames.add (String::empty);
  46745. Array <File> volumes;
  46746. File vol ("/Volumes");
  46747. vol.findChildFiles (volumes, File::findDirectories, false);
  46748. for (int i = 0; i < volumes.size(); ++i)
  46749. {
  46750. const File& volume = volumes.getReference(i);
  46751. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46752. {
  46753. rootPaths.add (volume.getFullPathName());
  46754. rootNames.add (volume.getFileName());
  46755. }
  46756. }
  46757. #endif
  46758. #if JUCE_LINUX
  46759. rootPaths.add ("/");
  46760. rootNames.add ("/");
  46761. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46762. rootNames.add ("Home folder");
  46763. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46764. rootNames.add ("Desktop");
  46765. #endif
  46766. }
  46767. END_JUCE_NAMESPACE
  46768. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46769. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46770. BEGIN_JUCE_NAMESPACE
  46771. FileChooser::FileChooser (const String& chooserBoxTitle,
  46772. const File& currentFileOrDirectory,
  46773. const String& fileFilters,
  46774. const bool useNativeDialogBox_)
  46775. : title (chooserBoxTitle),
  46776. filters (fileFilters),
  46777. startingFile (currentFileOrDirectory),
  46778. useNativeDialogBox (useNativeDialogBox_)
  46779. {
  46780. #if JUCE_LINUX
  46781. useNativeDialogBox = false;
  46782. #endif
  46783. if (! fileFilters.containsNonWhitespaceChars())
  46784. filters = "*";
  46785. }
  46786. FileChooser::~FileChooser()
  46787. {
  46788. }
  46789. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46790. {
  46791. return showDialog (false, true, false, false, false, previewComponent);
  46792. }
  46793. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46794. {
  46795. return showDialog (false, true, false, false, true, previewComponent);
  46796. }
  46797. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46798. {
  46799. return showDialog (true, true, false, false, true, previewComponent);
  46800. }
  46801. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46802. {
  46803. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46804. }
  46805. bool FileChooser::browseForDirectory()
  46806. {
  46807. return showDialog (true, false, false, false, false, 0);
  46808. }
  46809. const File FileChooser::getResult() const
  46810. {
  46811. // if you've used a multiple-file select, you should use the getResults() method
  46812. // to retrieve all the files that were chosen.
  46813. jassert (results.size() <= 1);
  46814. return results.getFirst();
  46815. }
  46816. const Array<File>& FileChooser::getResults() const
  46817. {
  46818. return results;
  46819. }
  46820. bool FileChooser::showDialog (const bool selectsDirectories,
  46821. const bool selectsFiles,
  46822. const bool isSave,
  46823. const bool warnAboutOverwritingExistingFiles,
  46824. const bool selectMultipleFiles,
  46825. FilePreviewComponent* const previewComponent)
  46826. {
  46827. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46828. results.clear();
  46829. // the preview component needs to be the right size before you pass it in here..
  46830. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46831. && previewComponent->getHeight() > 10));
  46832. #if JUCE_WINDOWS
  46833. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46834. #elif JUCE_MAC
  46835. if (useNativeDialogBox && (previewComponent == 0))
  46836. #else
  46837. if (false)
  46838. #endif
  46839. {
  46840. showPlatformDialog (results, title, startingFile, filters,
  46841. selectsDirectories, selectsFiles, isSave,
  46842. warnAboutOverwritingExistingFiles,
  46843. selectMultipleFiles,
  46844. previewComponent);
  46845. }
  46846. else
  46847. {
  46848. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46849. selectsDirectories ? "*" : String::empty,
  46850. String::empty);
  46851. int flags = isSave ? FileBrowserComponent::saveMode
  46852. : FileBrowserComponent::openMode;
  46853. if (selectsFiles)
  46854. flags |= FileBrowserComponent::canSelectFiles;
  46855. if (selectsDirectories)
  46856. {
  46857. flags |= FileBrowserComponent::canSelectDirectories;
  46858. if (! isSave)
  46859. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46860. }
  46861. if (selectMultipleFiles)
  46862. flags |= FileBrowserComponent::canSelectMultipleItems;
  46863. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46864. FileChooserDialogBox box (title, String::empty,
  46865. browserComponent,
  46866. warnAboutOverwritingExistingFiles,
  46867. browserComponent.findColour (AlertWindow::backgroundColourId));
  46868. if (box.show())
  46869. {
  46870. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46871. results.add (browserComponent.getSelectedFile (i));
  46872. }
  46873. }
  46874. if (previouslyFocused != 0)
  46875. previouslyFocused->grabKeyboardFocus();
  46876. return results.size() > 0;
  46877. }
  46878. FilePreviewComponent::FilePreviewComponent()
  46879. {
  46880. }
  46881. FilePreviewComponent::~FilePreviewComponent()
  46882. {
  46883. }
  46884. END_JUCE_NAMESPACE
  46885. /*** End of inlined file: juce_FileChooser.cpp ***/
  46886. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46887. BEGIN_JUCE_NAMESPACE
  46888. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46889. const String& instructions,
  46890. FileBrowserComponent& chooserComponent,
  46891. const bool warnAboutOverwritingExistingFiles_,
  46892. const Colour& backgroundColour)
  46893. : ResizableWindow (name, backgroundColour, true),
  46894. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46895. {
  46896. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  46897. setResizable (true, true);
  46898. setResizeLimits (300, 300, 1200, 1000);
  46899. content->okButton.addListener (this);
  46900. content->cancelButton.addListener (this);
  46901. content->newFolderButton.addListener (this);
  46902. content->chooserComponent.addListener (this);
  46903. selectionChanged();
  46904. }
  46905. FileChooserDialogBox::~FileChooserDialogBox()
  46906. {
  46907. content->chooserComponent.removeListener (this);
  46908. }
  46909. bool FileChooserDialogBox::show (int w, int h)
  46910. {
  46911. return showAt (-1, -1, w, h);
  46912. }
  46913. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46914. {
  46915. if (w <= 0)
  46916. {
  46917. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  46918. if (previewComp != 0)
  46919. w = 400 + previewComp->getWidth();
  46920. else
  46921. w = 600;
  46922. }
  46923. if (h <= 0)
  46924. h = 500;
  46925. if (x < 0 || y < 0)
  46926. centreWithSize (w, h);
  46927. else
  46928. setBounds (x, y, w, h);
  46929. const bool ok = (runModalLoop() != 0);
  46930. setVisible (false);
  46931. return ok;
  46932. }
  46933. void FileChooserDialogBox::buttonClicked (Button* button)
  46934. {
  46935. if (button == &(content->okButton))
  46936. {
  46937. okButtonPressed();
  46938. }
  46939. else if (button == &(content->cancelButton))
  46940. {
  46941. closeButtonPressed();
  46942. }
  46943. else if (button == &(content->newFolderButton))
  46944. {
  46945. createNewFolder();
  46946. }
  46947. }
  46948. void FileChooserDialogBox::closeButtonPressed()
  46949. {
  46950. setVisible (false);
  46951. }
  46952. void FileChooserDialogBox::selectionChanged()
  46953. {
  46954. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  46955. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  46956. && content->chooserComponent.getRoot().isDirectory());
  46957. }
  46958. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46959. {
  46960. }
  46961. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46962. {
  46963. selectionChanged();
  46964. content->okButton.triggerClick();
  46965. }
  46966. void FileChooserDialogBox::okButtonPressed()
  46967. {
  46968. if ((! (warnAboutOverwritingExistingFiles
  46969. && content->chooserComponent.isSaveMode()
  46970. && content->chooserComponent.getSelectedFile(0).exists()))
  46971. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46972. TRANS("File already exists"),
  46973. TRANS("There's already a file called:")
  46974. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  46975. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46976. TRANS("overwrite"),
  46977. TRANS("cancel")))
  46978. {
  46979. exitModalState (1);
  46980. }
  46981. }
  46982. void FileChooserDialogBox::createNewFolder()
  46983. {
  46984. File parent (content->chooserComponent.getRoot());
  46985. if (parent.isDirectory())
  46986. {
  46987. AlertWindow aw (TRANS("New Folder"),
  46988. TRANS("Please enter the name for the folder"),
  46989. AlertWindow::NoIcon, this);
  46990. aw.addTextEditor ("name", String::empty, String::empty, false);
  46991. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  46992. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  46993. if (aw.runModalLoop() != 0)
  46994. {
  46995. aw.setVisible (false);
  46996. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  46997. if (! name.isEmpty())
  46998. {
  46999. if (! parent.getChildFile (name).createDirectory())
  47000. {
  47001. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47002. TRANS ("New Folder"),
  47003. TRANS ("Couldn't create the folder!"));
  47004. }
  47005. content->chooserComponent.refresh();
  47006. }
  47007. }
  47008. }
  47009. }
  47010. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47011. : Component (name), instructions (instructions_),
  47012. chooserComponent (chooserComponent_),
  47013. okButton (chooserComponent_.getActionVerb()),
  47014. cancelButton (TRANS ("Cancel")),
  47015. newFolderButton (TRANS ("New Folder"))
  47016. {
  47017. addAndMakeVisible (&chooserComponent);
  47018. addAndMakeVisible (&okButton);
  47019. okButton.addShortcut (KeyPress::returnKey);
  47020. addAndMakeVisible (&cancelButton);
  47021. cancelButton.addShortcut (KeyPress::escapeKey);
  47022. addChildComponent (&newFolderButton);
  47023. setInterceptsMouseClicks (false, true);
  47024. }
  47025. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47026. {
  47027. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47028. text.draw (g);
  47029. }
  47030. void FileChooserDialogBox::ContentComponent::resized()
  47031. {
  47032. const int buttonHeight = 26;
  47033. Rectangle<int> area (getLocalBounds());
  47034. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47035. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47036. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47037. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47038. Rectangle<int> buttonArea (area.reduced (16, 10));
  47039. okButton.changeWidthToFitText (buttonHeight);
  47040. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47041. buttonArea.removeFromRight (16);
  47042. cancelButton.changeWidthToFitText (buttonHeight);
  47043. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47044. newFolderButton.changeWidthToFitText (buttonHeight);
  47045. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47046. }
  47047. END_JUCE_NAMESPACE
  47048. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47049. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47050. BEGIN_JUCE_NAMESPACE
  47051. FileFilter::FileFilter (const String& filterDescription)
  47052. : description (filterDescription)
  47053. {
  47054. }
  47055. FileFilter::~FileFilter()
  47056. {
  47057. }
  47058. const String& FileFilter::getDescription() const throw()
  47059. {
  47060. return description;
  47061. }
  47062. END_JUCE_NAMESPACE
  47063. /*** End of inlined file: juce_FileFilter.cpp ***/
  47064. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47065. BEGIN_JUCE_NAMESPACE
  47066. const Image juce_createIconForFile (const File& file);
  47067. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47068. : ListBox (String::empty, 0),
  47069. DirectoryContentsDisplayComponent (listToShow)
  47070. {
  47071. setModel (this);
  47072. fileList.addChangeListener (this);
  47073. }
  47074. FileListComponent::~FileListComponent()
  47075. {
  47076. fileList.removeChangeListener (this);
  47077. }
  47078. int FileListComponent::getNumSelectedFiles() const
  47079. {
  47080. return getNumSelectedRows();
  47081. }
  47082. const File FileListComponent::getSelectedFile (int index) const
  47083. {
  47084. return fileList.getFile (getSelectedRow (index));
  47085. }
  47086. void FileListComponent::deselectAllFiles()
  47087. {
  47088. deselectAllRows();
  47089. }
  47090. void FileListComponent::scrollToTop()
  47091. {
  47092. getVerticalScrollBar()->setCurrentRangeStart (0);
  47093. }
  47094. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47095. {
  47096. updateContent();
  47097. if (lastDirectory != fileList.getDirectory())
  47098. {
  47099. lastDirectory = fileList.getDirectory();
  47100. deselectAllRows();
  47101. }
  47102. }
  47103. class FileListItemComponent : public Component,
  47104. public TimeSliceClient,
  47105. public AsyncUpdater
  47106. {
  47107. public:
  47108. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47109. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47110. {
  47111. }
  47112. ~FileListItemComponent()
  47113. {
  47114. thread.removeTimeSliceClient (this);
  47115. }
  47116. void paint (Graphics& g)
  47117. {
  47118. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47119. file.getFileName(),
  47120. &icon, fileSize, modTime,
  47121. isDirectory, highlighted,
  47122. index, owner);
  47123. }
  47124. void mouseDown (const MouseEvent& e)
  47125. {
  47126. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47127. owner.sendMouseClickMessage (file, e);
  47128. }
  47129. void mouseDoubleClick (const MouseEvent&)
  47130. {
  47131. owner.sendDoubleClickMessage (file);
  47132. }
  47133. void update (const File& root,
  47134. const DirectoryContentsList::FileInfo* const fileInfo,
  47135. const int index_,
  47136. const bool highlighted_)
  47137. {
  47138. thread.removeTimeSliceClient (this);
  47139. if (highlighted_ != highlighted || index_ != index)
  47140. {
  47141. index = index_;
  47142. highlighted = highlighted_;
  47143. repaint();
  47144. }
  47145. File newFile;
  47146. String newFileSize, newModTime;
  47147. if (fileInfo != 0)
  47148. {
  47149. newFile = root.getChildFile (fileInfo->filename);
  47150. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47151. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47152. }
  47153. if (newFile != file
  47154. || fileSize != newFileSize
  47155. || modTime != newModTime)
  47156. {
  47157. file = newFile;
  47158. fileSize = newFileSize;
  47159. modTime = newModTime;
  47160. icon = Image::null;
  47161. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47162. repaint();
  47163. }
  47164. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47165. {
  47166. updateIcon (true);
  47167. if (! icon.isValid())
  47168. thread.addTimeSliceClient (this);
  47169. }
  47170. }
  47171. int useTimeSlice()
  47172. {
  47173. updateIcon (false);
  47174. return -1;
  47175. }
  47176. void handleAsyncUpdate()
  47177. {
  47178. repaint();
  47179. }
  47180. private:
  47181. FileListComponent& owner;
  47182. TimeSliceThread& thread;
  47183. File file;
  47184. String fileSize, modTime;
  47185. Image icon;
  47186. int index;
  47187. bool highlighted, isDirectory;
  47188. void updateIcon (const bool onlyUpdateIfCached)
  47189. {
  47190. if (icon.isNull())
  47191. {
  47192. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47193. Image im (ImageCache::getFromHashCode (hashCode));
  47194. if (im.isNull() && ! onlyUpdateIfCached)
  47195. {
  47196. im = juce_createIconForFile (file);
  47197. if (im.isValid())
  47198. ImageCache::addImageToCache (im, hashCode);
  47199. }
  47200. if (im.isValid())
  47201. {
  47202. icon = im;
  47203. triggerAsyncUpdate();
  47204. }
  47205. }
  47206. }
  47207. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47208. };
  47209. int FileListComponent::getNumRows()
  47210. {
  47211. return fileList.getNumFiles();
  47212. }
  47213. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47214. {
  47215. }
  47216. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47217. {
  47218. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47219. if (comp == 0)
  47220. {
  47221. delete existingComponentToUpdate;
  47222. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47223. }
  47224. DirectoryContentsList::FileInfo fileInfo;
  47225. if (fileList.getFileInfo (row, fileInfo))
  47226. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47227. else
  47228. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47229. return comp;
  47230. }
  47231. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47232. {
  47233. sendSelectionChangeMessage();
  47234. }
  47235. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47236. {
  47237. }
  47238. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47239. {
  47240. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47241. }
  47242. END_JUCE_NAMESPACE
  47243. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47244. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47245. BEGIN_JUCE_NAMESPACE
  47246. FilenameComponent::FilenameComponent (const String& name,
  47247. const File& currentFile,
  47248. const bool canEditFilename,
  47249. const bool isDirectory,
  47250. const bool isForSaving,
  47251. const String& fileBrowserWildcard,
  47252. const String& enforcedSuffix_,
  47253. const String& textWhenNothingSelected)
  47254. : Component (name),
  47255. maxRecentFiles (30),
  47256. isDir (isDirectory),
  47257. isSaving (isForSaving),
  47258. isFileDragOver (false),
  47259. wildcard (fileBrowserWildcard),
  47260. enforcedSuffix (enforcedSuffix_)
  47261. {
  47262. addAndMakeVisible (&filenameBox);
  47263. filenameBox.setEditableText (canEditFilename);
  47264. filenameBox.addListener (this);
  47265. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47266. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47267. setBrowseButtonText ("...");
  47268. setCurrentFile (currentFile, true);
  47269. }
  47270. FilenameComponent::~FilenameComponent()
  47271. {
  47272. }
  47273. void FilenameComponent::paintOverChildren (Graphics& g)
  47274. {
  47275. if (isFileDragOver)
  47276. {
  47277. g.setColour (Colours::red.withAlpha (0.2f));
  47278. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47279. }
  47280. }
  47281. void FilenameComponent::resized()
  47282. {
  47283. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47284. }
  47285. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47286. {
  47287. browseButtonText = newBrowseButtonText;
  47288. lookAndFeelChanged();
  47289. }
  47290. void FilenameComponent::lookAndFeelChanged()
  47291. {
  47292. browseButton = 0;
  47293. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47294. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47295. resized();
  47296. browseButton->addListener (this);
  47297. }
  47298. void FilenameComponent::setTooltip (const String& newTooltip)
  47299. {
  47300. SettableTooltipClient::setTooltip (newTooltip);
  47301. filenameBox.setTooltip (newTooltip);
  47302. }
  47303. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47304. {
  47305. defaultBrowseFile = newDefaultDirectory;
  47306. }
  47307. void FilenameComponent::buttonClicked (Button*)
  47308. {
  47309. FileChooser fc (TRANS("Choose a new file"),
  47310. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47311. : getCurrentFile(),
  47312. wildcard);
  47313. if (isDir ? fc.browseForDirectory()
  47314. : (isSaving ? fc.browseForFileToSave (false)
  47315. : fc.browseForFileToOpen()))
  47316. {
  47317. setCurrentFile (fc.getResult(), true);
  47318. }
  47319. }
  47320. void FilenameComponent::comboBoxChanged (ComboBox*)
  47321. {
  47322. setCurrentFile (getCurrentFile(), true);
  47323. }
  47324. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47325. {
  47326. return true;
  47327. }
  47328. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47329. {
  47330. isFileDragOver = false;
  47331. repaint();
  47332. const File f (filenames[0]);
  47333. if (f.exists() && (f.isDirectory() == isDir))
  47334. setCurrentFile (f, true);
  47335. }
  47336. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47337. {
  47338. isFileDragOver = true;
  47339. repaint();
  47340. }
  47341. void FilenameComponent::fileDragExit (const StringArray&)
  47342. {
  47343. isFileDragOver = false;
  47344. repaint();
  47345. }
  47346. const File FilenameComponent::getCurrentFile() const
  47347. {
  47348. File f (filenameBox.getText());
  47349. if (enforcedSuffix.isNotEmpty())
  47350. f = f.withFileExtension (enforcedSuffix);
  47351. return f;
  47352. }
  47353. void FilenameComponent::setCurrentFile (File newFile,
  47354. const bool addToRecentlyUsedList,
  47355. const bool sendChangeNotification)
  47356. {
  47357. if (enforcedSuffix.isNotEmpty())
  47358. newFile = newFile.withFileExtension (enforcedSuffix);
  47359. if (newFile.getFullPathName() != lastFilename)
  47360. {
  47361. lastFilename = newFile.getFullPathName();
  47362. if (addToRecentlyUsedList)
  47363. addRecentlyUsedFile (newFile);
  47364. filenameBox.setText (lastFilename, true);
  47365. if (sendChangeNotification)
  47366. triggerAsyncUpdate();
  47367. }
  47368. }
  47369. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47370. {
  47371. filenameBox.setEditableText (shouldBeEditable);
  47372. }
  47373. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47374. {
  47375. StringArray names;
  47376. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47377. names.add (filenameBox.getItemText (i));
  47378. return names;
  47379. }
  47380. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47381. {
  47382. if (filenames != getRecentlyUsedFilenames())
  47383. {
  47384. filenameBox.clear();
  47385. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47386. filenameBox.addItem (filenames[i], i + 1);
  47387. }
  47388. }
  47389. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47390. {
  47391. maxRecentFiles = jmax (1, newMaximum);
  47392. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47393. }
  47394. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47395. {
  47396. StringArray files (getRecentlyUsedFilenames());
  47397. if (file.getFullPathName().isNotEmpty())
  47398. {
  47399. files.removeString (file.getFullPathName(), true);
  47400. files.insert (0, file.getFullPathName());
  47401. setRecentlyUsedFilenames (files);
  47402. }
  47403. }
  47404. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47405. {
  47406. listeners.add (listener);
  47407. }
  47408. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47409. {
  47410. listeners.remove (listener);
  47411. }
  47412. void FilenameComponent::handleAsyncUpdate()
  47413. {
  47414. Component::BailOutChecker checker (this);
  47415. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47416. }
  47417. END_JUCE_NAMESPACE
  47418. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47419. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47420. BEGIN_JUCE_NAMESPACE
  47421. FileSearchPathListComponent::FileSearchPathListComponent()
  47422. : addButton ("+"),
  47423. removeButton ("-"),
  47424. changeButton (TRANS ("change...")),
  47425. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47426. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47427. {
  47428. listBox.setModel (this);
  47429. addAndMakeVisible (&listBox);
  47430. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47431. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47432. listBox.setOutlineThickness (1);
  47433. addAndMakeVisible (&addButton);
  47434. addButton.addListener (this);
  47435. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47436. addAndMakeVisible (&removeButton);
  47437. removeButton.addListener (this);
  47438. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47439. addAndMakeVisible (&changeButton);
  47440. changeButton.addListener (this);
  47441. addAndMakeVisible (&upButton);
  47442. upButton.addListener (this);
  47443. {
  47444. Path arrowPath;
  47445. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47446. DrawablePath arrowImage;
  47447. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47448. arrowImage.setPath (arrowPath);
  47449. upButton.setImages (&arrowImage);
  47450. }
  47451. addAndMakeVisible (&downButton);
  47452. downButton.addListener (this);
  47453. {
  47454. Path arrowPath;
  47455. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47456. DrawablePath arrowImage;
  47457. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47458. arrowImage.setPath (arrowPath);
  47459. downButton.setImages (&arrowImage);
  47460. }
  47461. updateButtons();
  47462. }
  47463. FileSearchPathListComponent::~FileSearchPathListComponent()
  47464. {
  47465. }
  47466. void FileSearchPathListComponent::updateButtons()
  47467. {
  47468. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47469. removeButton.setEnabled (anythingSelected);
  47470. changeButton.setEnabled (anythingSelected);
  47471. upButton.setEnabled (anythingSelected);
  47472. downButton.setEnabled (anythingSelected);
  47473. }
  47474. void FileSearchPathListComponent::changed()
  47475. {
  47476. listBox.updateContent();
  47477. listBox.repaint();
  47478. updateButtons();
  47479. }
  47480. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47481. {
  47482. if (newPath.toString() != path.toString())
  47483. {
  47484. path = newPath;
  47485. changed();
  47486. }
  47487. }
  47488. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47489. {
  47490. defaultBrowseTarget = newDefaultDirectory;
  47491. }
  47492. int FileSearchPathListComponent::getNumRows()
  47493. {
  47494. return path.getNumPaths();
  47495. }
  47496. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47497. {
  47498. if (rowIsSelected)
  47499. g.fillAll (findColour (TextEditor::highlightColourId));
  47500. g.setColour (findColour (ListBox::textColourId));
  47501. Font f (height * 0.7f);
  47502. f.setHorizontalScale (0.9f);
  47503. g.setFont (f);
  47504. g.drawText (path [rowNumber].getFullPathName(),
  47505. 4, 0, width - 6, height,
  47506. Justification::centredLeft, true);
  47507. }
  47508. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47509. {
  47510. if (isPositiveAndBelow (row, path.getNumPaths()))
  47511. {
  47512. path.remove (row);
  47513. changed();
  47514. }
  47515. }
  47516. void FileSearchPathListComponent::returnKeyPressed (int row)
  47517. {
  47518. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47519. if (chooser.browseForDirectory())
  47520. {
  47521. path.remove (row);
  47522. path.add (chooser.getResult(), row);
  47523. changed();
  47524. }
  47525. }
  47526. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47527. {
  47528. returnKeyPressed (row);
  47529. }
  47530. void FileSearchPathListComponent::selectedRowsChanged (int)
  47531. {
  47532. updateButtons();
  47533. }
  47534. void FileSearchPathListComponent::paint (Graphics& g)
  47535. {
  47536. g.fillAll (findColour (backgroundColourId));
  47537. }
  47538. void FileSearchPathListComponent::resized()
  47539. {
  47540. const int buttonH = 22;
  47541. const int buttonY = getHeight() - buttonH - 4;
  47542. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47543. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47544. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47545. changeButton.changeWidthToFitText (buttonH);
  47546. downButton.setSize (buttonH * 2, buttonH);
  47547. upButton.setSize (buttonH * 2, buttonH);
  47548. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47549. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47550. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47551. }
  47552. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47553. {
  47554. return true;
  47555. }
  47556. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47557. {
  47558. for (int i = filenames.size(); --i >= 0;)
  47559. {
  47560. const File f (filenames[i]);
  47561. if (f.isDirectory())
  47562. {
  47563. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47564. path.add (f, row);
  47565. changed();
  47566. }
  47567. }
  47568. }
  47569. void FileSearchPathListComponent::buttonClicked (Button* button)
  47570. {
  47571. const int currentRow = listBox.getSelectedRow();
  47572. if (button == &removeButton)
  47573. {
  47574. deleteKeyPressed (currentRow);
  47575. }
  47576. else if (button == &addButton)
  47577. {
  47578. File start (defaultBrowseTarget);
  47579. if (start == File::nonexistent)
  47580. start = path [0];
  47581. if (start == File::nonexistent)
  47582. start = File::getCurrentWorkingDirectory();
  47583. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47584. if (chooser.browseForDirectory())
  47585. {
  47586. path.add (chooser.getResult(), currentRow);
  47587. }
  47588. }
  47589. else if (button == &changeButton)
  47590. {
  47591. returnKeyPressed (currentRow);
  47592. }
  47593. else if (button == &upButton)
  47594. {
  47595. if (currentRow > 0 && currentRow < path.getNumPaths())
  47596. {
  47597. const File f (path[currentRow]);
  47598. path.remove (currentRow);
  47599. path.add (f, currentRow - 1);
  47600. listBox.selectRow (currentRow - 1);
  47601. }
  47602. }
  47603. else if (button == &downButton)
  47604. {
  47605. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47606. {
  47607. const File f (path[currentRow]);
  47608. path.remove (currentRow);
  47609. path.add (f, currentRow + 1);
  47610. listBox.selectRow (currentRow + 1);
  47611. }
  47612. }
  47613. changed();
  47614. }
  47615. END_JUCE_NAMESPACE
  47616. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47617. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47618. BEGIN_JUCE_NAMESPACE
  47619. const Image juce_createIconForFile (const File& file);
  47620. class FileListTreeItem : public TreeViewItem,
  47621. public TimeSliceClient,
  47622. public AsyncUpdater,
  47623. public ChangeListener
  47624. {
  47625. public:
  47626. FileListTreeItem (FileTreeComponent& owner_,
  47627. DirectoryContentsList* const parentContentsList_,
  47628. const int indexInContentsList_,
  47629. const File& file_,
  47630. TimeSliceThread& thread_)
  47631. : file (file_),
  47632. owner (owner_),
  47633. parentContentsList (parentContentsList_),
  47634. indexInContentsList (indexInContentsList_),
  47635. subContentsList (0),
  47636. canDeleteSubContentsList (false),
  47637. thread (thread_),
  47638. icon (0)
  47639. {
  47640. DirectoryContentsList::FileInfo fileInfo;
  47641. if (parentContentsList_ != 0
  47642. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47643. {
  47644. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47645. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47646. isDirectory = fileInfo.isDirectory;
  47647. }
  47648. else
  47649. {
  47650. isDirectory = true;
  47651. }
  47652. }
  47653. ~FileListTreeItem()
  47654. {
  47655. thread.removeTimeSliceClient (this);
  47656. clearSubItems();
  47657. if (canDeleteSubContentsList)
  47658. delete subContentsList;
  47659. }
  47660. bool mightContainSubItems() { return isDirectory; }
  47661. const String getUniqueName() const { return file.getFullPathName(); }
  47662. int getItemHeight() const { return 22; }
  47663. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47664. void itemOpennessChanged (bool isNowOpen)
  47665. {
  47666. if (isNowOpen)
  47667. {
  47668. clearSubItems();
  47669. isDirectory = file.isDirectory();
  47670. if (isDirectory)
  47671. {
  47672. if (subContentsList == 0)
  47673. {
  47674. jassert (parentContentsList != 0);
  47675. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47676. l->setDirectory (file, true, true);
  47677. setSubContentsList (l);
  47678. canDeleteSubContentsList = true;
  47679. }
  47680. changeListenerCallback (0);
  47681. }
  47682. }
  47683. }
  47684. void setSubContentsList (DirectoryContentsList* newList)
  47685. {
  47686. jassert (subContentsList == 0);
  47687. subContentsList = newList;
  47688. newList->addChangeListener (this);
  47689. }
  47690. void changeListenerCallback (ChangeBroadcaster*)
  47691. {
  47692. clearSubItems();
  47693. if (isOpen() && subContentsList != 0)
  47694. {
  47695. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47696. {
  47697. FileListTreeItem* const item
  47698. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47699. addSubItem (item);
  47700. }
  47701. }
  47702. }
  47703. void paintItem (Graphics& g, int width, int height)
  47704. {
  47705. if (file != File::nonexistent)
  47706. {
  47707. updateIcon (true);
  47708. if (icon.isNull())
  47709. thread.addTimeSliceClient (this);
  47710. }
  47711. owner.getLookAndFeel()
  47712. .drawFileBrowserRow (g, width, height,
  47713. file.getFileName(),
  47714. &icon, fileSize, modTime,
  47715. isDirectory, isSelected(),
  47716. indexInContentsList, owner);
  47717. }
  47718. void itemClicked (const MouseEvent& e)
  47719. {
  47720. owner.sendMouseClickMessage (file, e);
  47721. }
  47722. void itemDoubleClicked (const MouseEvent& e)
  47723. {
  47724. TreeViewItem::itemDoubleClicked (e);
  47725. owner.sendDoubleClickMessage (file);
  47726. }
  47727. void itemSelectionChanged (bool)
  47728. {
  47729. owner.sendSelectionChangeMessage();
  47730. }
  47731. int useTimeSlice()
  47732. {
  47733. updateIcon (false);
  47734. return -1;
  47735. }
  47736. void handleAsyncUpdate()
  47737. {
  47738. owner.repaint();
  47739. }
  47740. const File file;
  47741. private:
  47742. FileTreeComponent& owner;
  47743. DirectoryContentsList* parentContentsList;
  47744. int indexInContentsList;
  47745. DirectoryContentsList* subContentsList;
  47746. bool isDirectory, canDeleteSubContentsList;
  47747. TimeSliceThread& thread;
  47748. Image icon;
  47749. String fileSize;
  47750. String modTime;
  47751. void updateIcon (const bool onlyUpdateIfCached)
  47752. {
  47753. if (icon.isNull())
  47754. {
  47755. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47756. Image im (ImageCache::getFromHashCode (hashCode));
  47757. if (im.isNull() && ! onlyUpdateIfCached)
  47758. {
  47759. im = juce_createIconForFile (file);
  47760. if (im.isValid())
  47761. ImageCache::addImageToCache (im, hashCode);
  47762. }
  47763. if (im.isValid())
  47764. {
  47765. icon = im;
  47766. triggerAsyncUpdate();
  47767. }
  47768. }
  47769. }
  47770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47771. };
  47772. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47773. : DirectoryContentsDisplayComponent (listToShow)
  47774. {
  47775. FileListTreeItem* const root
  47776. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47777. listToShow.getTimeSliceThread());
  47778. root->setSubContentsList (&listToShow);
  47779. setRootItemVisible (false);
  47780. setRootItem (root);
  47781. }
  47782. FileTreeComponent::~FileTreeComponent()
  47783. {
  47784. deleteRootItem();
  47785. }
  47786. const File FileTreeComponent::getSelectedFile (const int index) const
  47787. {
  47788. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47789. return item != 0 ? item->file
  47790. : File::nonexistent;
  47791. }
  47792. void FileTreeComponent::deselectAllFiles()
  47793. {
  47794. clearSelectedItems();
  47795. }
  47796. void FileTreeComponent::scrollToTop()
  47797. {
  47798. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47799. }
  47800. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47801. {
  47802. dragAndDropDescription = description;
  47803. }
  47804. END_JUCE_NAMESPACE
  47805. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47806. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47807. BEGIN_JUCE_NAMESPACE
  47808. ImagePreviewComponent::ImagePreviewComponent()
  47809. {
  47810. }
  47811. ImagePreviewComponent::~ImagePreviewComponent()
  47812. {
  47813. }
  47814. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47815. {
  47816. const int availableW = proportionOfWidth (0.97f);
  47817. const int availableH = getHeight() - 13 * 4;
  47818. const double scale = jmin (1.0,
  47819. availableW / (double) w,
  47820. availableH / (double) h);
  47821. w = roundToInt (scale * w);
  47822. h = roundToInt (scale * h);
  47823. }
  47824. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47825. {
  47826. if (fileToLoad != file)
  47827. {
  47828. fileToLoad = file;
  47829. startTimer (100);
  47830. }
  47831. }
  47832. void ImagePreviewComponent::timerCallback()
  47833. {
  47834. stopTimer();
  47835. currentThumbnail = Image::null;
  47836. currentDetails = String::empty;
  47837. repaint();
  47838. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47839. if (in != 0)
  47840. {
  47841. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47842. if (format != 0)
  47843. {
  47844. currentThumbnail = format->decodeImage (*in);
  47845. if (currentThumbnail.isValid())
  47846. {
  47847. int w = currentThumbnail.getWidth();
  47848. int h = currentThumbnail.getHeight();
  47849. currentDetails
  47850. << fileToLoad.getFileName() << "\n"
  47851. << format->getFormatName() << "\n"
  47852. << w << " x " << h << " pixels\n"
  47853. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47854. getThumbSize (w, h);
  47855. currentThumbnail = currentThumbnail.rescaled (w, h);
  47856. }
  47857. }
  47858. }
  47859. }
  47860. void ImagePreviewComponent::paint (Graphics& g)
  47861. {
  47862. if (currentThumbnail.isValid())
  47863. {
  47864. g.setFont (13.0f);
  47865. int w = currentThumbnail.getWidth();
  47866. int h = currentThumbnail.getHeight();
  47867. getThumbSize (w, h);
  47868. const int numLines = 4;
  47869. const int totalH = 13 * numLines + h + 4;
  47870. const int y = (getHeight() - totalH) / 2;
  47871. g.drawImageWithin (currentThumbnail,
  47872. (getWidth() - w) / 2, y, w, h,
  47873. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47874. false);
  47875. g.drawFittedText (currentDetails,
  47876. 0, y + h + 4, getWidth(), 100,
  47877. Justification::centredTop, numLines);
  47878. }
  47879. }
  47880. END_JUCE_NAMESPACE
  47881. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47882. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47883. BEGIN_JUCE_NAMESPACE
  47884. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47885. const String& directoryWildcardPatterns,
  47886. const String& description_)
  47887. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47888. : (description_ + " (" + fileWildcardPatterns + ")"))
  47889. {
  47890. parse (fileWildcardPatterns, fileWildcards);
  47891. parse (directoryWildcardPatterns, directoryWildcards);
  47892. }
  47893. WildcardFileFilter::~WildcardFileFilter()
  47894. {
  47895. }
  47896. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47897. {
  47898. return match (file, fileWildcards);
  47899. }
  47900. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47901. {
  47902. return match (file, directoryWildcards);
  47903. }
  47904. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47905. {
  47906. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47907. result.trim();
  47908. result.removeEmptyStrings();
  47909. // special case for *.*, because people use it to mean "any file", but it
  47910. // would actually ignore files with no extension.
  47911. for (int i = result.size(); --i >= 0;)
  47912. if (result[i] == "*.*")
  47913. result.set (i, "*");
  47914. }
  47915. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47916. {
  47917. const String filename (file.getFileName());
  47918. for (int i = wildcards.size(); --i >= 0;)
  47919. if (filename.matchesWildcard (wildcards[i], true))
  47920. return true;
  47921. return false;
  47922. }
  47923. END_JUCE_NAMESPACE
  47924. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47925. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47926. BEGIN_JUCE_NAMESPACE
  47927. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47928. {
  47929. }
  47930. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47931. {
  47932. }
  47933. namespace KeyboardFocusHelpers
  47934. {
  47935. // This will sort a set of components, so that they are ordered in terms of
  47936. // left-to-right and then top-to-bottom.
  47937. class ScreenPositionComparator
  47938. {
  47939. public:
  47940. ScreenPositionComparator() {}
  47941. static int compareElements (const Component* const first, const Component* const second)
  47942. {
  47943. int explicitOrder1 = first->getExplicitFocusOrder();
  47944. if (explicitOrder1 <= 0)
  47945. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47946. int explicitOrder2 = second->getExplicitFocusOrder();
  47947. if (explicitOrder2 <= 0)
  47948. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47949. if (explicitOrder1 != explicitOrder2)
  47950. return explicitOrder1 - explicitOrder2;
  47951. const int diff = first->getY() - second->getY();
  47952. return (diff == 0) ? first->getX() - second->getX()
  47953. : diff;
  47954. }
  47955. };
  47956. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47957. {
  47958. if (parent->getNumChildComponents() > 0)
  47959. {
  47960. Array <Component*> localComps;
  47961. ScreenPositionComparator comparator;
  47962. int i;
  47963. for (i = parent->getNumChildComponents(); --i >= 0;)
  47964. {
  47965. Component* const c = parent->getChildComponent (i);
  47966. if (c->isVisible() && c->isEnabled())
  47967. localComps.addSorted (comparator, c);
  47968. }
  47969. for (i = 0; i < localComps.size(); ++i)
  47970. {
  47971. Component* const c = localComps.getUnchecked (i);
  47972. if (c->getWantsKeyboardFocus())
  47973. comps.add (c);
  47974. if (! c->isFocusContainer())
  47975. findAllFocusableComponents (c, comps);
  47976. }
  47977. }
  47978. }
  47979. }
  47980. namespace KeyboardFocusHelpers
  47981. {
  47982. Component* getIncrementedComponent (Component* const current, const int delta)
  47983. {
  47984. Component* focusContainer = current->getParentComponent();
  47985. if (focusContainer != 0)
  47986. {
  47987. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47988. focusContainer = focusContainer->getParentComponent();
  47989. if (focusContainer != 0)
  47990. {
  47991. Array <Component*> comps;
  47992. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47993. if (comps.size() > 0)
  47994. {
  47995. const int index = comps.indexOf (current);
  47996. return comps [(index + comps.size() + delta) % comps.size()];
  47997. }
  47998. }
  47999. }
  48000. return 0;
  48001. }
  48002. }
  48003. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48004. {
  48005. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48006. }
  48007. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48008. {
  48009. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48010. }
  48011. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48012. {
  48013. Array <Component*> comps;
  48014. if (parentComponent != 0)
  48015. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48016. return comps.getFirst();
  48017. }
  48018. END_JUCE_NAMESPACE
  48019. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48020. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48021. BEGIN_JUCE_NAMESPACE
  48022. bool KeyListener::keyStateChanged (const bool, Component*)
  48023. {
  48024. return false;
  48025. }
  48026. END_JUCE_NAMESPACE
  48027. /*** End of inlined file: juce_KeyListener.cpp ***/
  48028. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48029. BEGIN_JUCE_NAMESPACE
  48030. // N.B. these two includes are put here deliberately to avoid problems with
  48031. // old GCCs failing on long include paths
  48032. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48033. {
  48034. public:
  48035. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48036. const CommandID commandID_,
  48037. const String& keyName,
  48038. const int keyNum_)
  48039. : Button (keyName),
  48040. owner (owner_),
  48041. commandID (commandID_),
  48042. keyNum (keyNum_)
  48043. {
  48044. setWantsKeyboardFocus (false);
  48045. setTriggeredOnMouseDown (keyNum >= 0);
  48046. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48047. : TRANS("click to change this key-mapping"));
  48048. }
  48049. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48050. {
  48051. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48052. keyNum >= 0 ? getName() : String::empty);
  48053. }
  48054. void clicked()
  48055. {
  48056. if (keyNum >= 0)
  48057. {
  48058. // existing key clicked..
  48059. PopupMenu m;
  48060. m.addItem (1, TRANS("change this key-mapping"));
  48061. m.addSeparator();
  48062. m.addItem (2, TRANS("remove this key-mapping"));
  48063. switch (m.show())
  48064. {
  48065. case 1: assignNewKey(); break;
  48066. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48067. default: break;
  48068. }
  48069. }
  48070. else
  48071. {
  48072. assignNewKey(); // + button pressed..
  48073. }
  48074. }
  48075. void fitToContent (const int h) throw()
  48076. {
  48077. if (keyNum < 0)
  48078. {
  48079. setSize (h, h);
  48080. }
  48081. else
  48082. {
  48083. Font f (h * 0.6f);
  48084. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48085. }
  48086. }
  48087. class KeyEntryWindow : public AlertWindow
  48088. {
  48089. public:
  48090. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48091. : AlertWindow (TRANS("New key-mapping"),
  48092. TRANS("Please press a key combination now..."),
  48093. AlertWindow::NoIcon),
  48094. owner (owner_)
  48095. {
  48096. addButton (TRANS("Ok"), 1);
  48097. addButton (TRANS("Cancel"), 0);
  48098. // (avoid return + escape keys getting processed by the buttons..)
  48099. for (int i = getNumChildComponents(); --i >= 0;)
  48100. getChildComponent (i)->setWantsKeyboardFocus (false);
  48101. setWantsKeyboardFocus (true);
  48102. grabKeyboardFocus();
  48103. }
  48104. bool keyPressed (const KeyPress& key)
  48105. {
  48106. lastPress = key;
  48107. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48108. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48109. if (previousCommand != 0)
  48110. message << "\n\n" << TRANS("(Currently assigned to \"")
  48111. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48112. setMessage (message);
  48113. return true;
  48114. }
  48115. bool keyStateChanged (bool)
  48116. {
  48117. return true;
  48118. }
  48119. KeyPress lastPress;
  48120. private:
  48121. KeyMappingEditorComponent& owner;
  48122. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48123. };
  48124. void assignNewKey()
  48125. {
  48126. KeyEntryWindow entryWindow (owner);
  48127. if (entryWindow.runModalLoop() != 0)
  48128. {
  48129. entryWindow.setVisible (false);
  48130. if (entryWindow.lastPress.isValid())
  48131. {
  48132. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48133. if (previousCommand == 0
  48134. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48135. TRANS("Change key-mapping"),
  48136. TRANS("This key is already assigned to the command \"")
  48137. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48138. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48139. TRANS("Re-assign"),
  48140. TRANS("Cancel")))
  48141. {
  48142. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48143. if (keyNum >= 0)
  48144. owner.getMappings().removeKeyPress (commandID, keyNum);
  48145. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48146. }
  48147. }
  48148. }
  48149. }
  48150. private:
  48151. KeyMappingEditorComponent& owner;
  48152. const CommandID commandID;
  48153. const int keyNum;
  48154. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48155. };
  48156. class KeyMappingEditorComponent::ItemComponent : public Component
  48157. {
  48158. public:
  48159. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48160. : owner (owner_), commandID (commandID_)
  48161. {
  48162. setInterceptsMouseClicks (false, true);
  48163. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48164. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48165. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48166. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48167. addKeyPressButton (String::empty, -1, isReadOnly);
  48168. }
  48169. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48170. {
  48171. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48172. keyChangeButtons.add (b);
  48173. b->setEnabled (! isReadOnly);
  48174. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48175. addChildComponent (b);
  48176. }
  48177. void paint (Graphics& g)
  48178. {
  48179. g.setFont (getHeight() * 0.7f);
  48180. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48181. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48182. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48183. Justification::centredLeft, true);
  48184. }
  48185. void resized()
  48186. {
  48187. int x = getWidth() - 4;
  48188. for (int i = keyChangeButtons.size(); --i >= 0;)
  48189. {
  48190. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48191. b->fitToContent (getHeight() - 2);
  48192. b->setTopRightPosition (x, 1);
  48193. x = b->getX() - 5;
  48194. }
  48195. }
  48196. private:
  48197. KeyMappingEditorComponent& owner;
  48198. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48199. const CommandID commandID;
  48200. enum { maxNumAssignments = 3 };
  48201. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48202. };
  48203. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48204. {
  48205. public:
  48206. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48207. : owner (owner_), commandID (commandID_)
  48208. {
  48209. }
  48210. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48211. bool mightContainSubItems() { return false; }
  48212. int getItemHeight() const { return 20; }
  48213. Component* createItemComponent()
  48214. {
  48215. return new ItemComponent (owner, commandID);
  48216. }
  48217. private:
  48218. KeyMappingEditorComponent& owner;
  48219. const CommandID commandID;
  48220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48221. };
  48222. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48223. {
  48224. public:
  48225. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48226. : owner (owner_), categoryName (name)
  48227. {
  48228. }
  48229. const String getUniqueName() const { return categoryName + "_cat"; }
  48230. bool mightContainSubItems() { return true; }
  48231. int getItemHeight() const { return 28; }
  48232. void paintItem (Graphics& g, int width, int height)
  48233. {
  48234. g.setFont (height * 0.6f, Font::bold);
  48235. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48236. g.drawText (categoryName,
  48237. 2, 0, width - 2, height,
  48238. Justification::centredLeft, true);
  48239. }
  48240. void itemOpennessChanged (bool isNowOpen)
  48241. {
  48242. if (isNowOpen)
  48243. {
  48244. if (getNumSubItems() == 0)
  48245. {
  48246. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48247. for (int i = 0; i < commands.size(); ++i)
  48248. {
  48249. if (owner.shouldCommandBeIncluded (commands[i]))
  48250. addSubItem (new MappingItem (owner, commands[i]));
  48251. }
  48252. }
  48253. }
  48254. else
  48255. {
  48256. clearSubItems();
  48257. }
  48258. }
  48259. private:
  48260. KeyMappingEditorComponent& owner;
  48261. String categoryName;
  48262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48263. };
  48264. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48265. public ChangeListener,
  48266. public ButtonListener
  48267. {
  48268. public:
  48269. TopLevelItem (KeyMappingEditorComponent& owner_)
  48270. : owner (owner_)
  48271. {
  48272. setLinesDrawnForSubItems (false);
  48273. owner.getMappings().addChangeListener (this);
  48274. }
  48275. ~TopLevelItem()
  48276. {
  48277. owner.getMappings().removeChangeListener (this);
  48278. }
  48279. bool mightContainSubItems() { return true; }
  48280. const String getUniqueName() const { return "keys"; }
  48281. void changeListenerCallback (ChangeBroadcaster*)
  48282. {
  48283. const OpennessRestorer openness (*this);
  48284. clearSubItems();
  48285. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48286. for (int i = 0; i < categories.size(); ++i)
  48287. {
  48288. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48289. int count = 0;
  48290. for (int j = 0; j < commands.size(); ++j)
  48291. if (owner.shouldCommandBeIncluded (commands[j]))
  48292. ++count;
  48293. if (count > 0)
  48294. addSubItem (new CategoryItem (owner, categories[i]));
  48295. }
  48296. }
  48297. void buttonClicked (Button*)
  48298. {
  48299. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48300. TRANS("Reset to defaults"),
  48301. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48302. TRANS("Reset")))
  48303. {
  48304. owner.getMappings().resetToDefaultMappings();
  48305. }
  48306. }
  48307. private:
  48308. KeyMappingEditorComponent& owner;
  48309. };
  48310. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48311. const bool showResetToDefaultButton)
  48312. : mappings (mappingManager),
  48313. resetButton (TRANS ("reset to defaults"))
  48314. {
  48315. treeItem = new TopLevelItem (*this);
  48316. if (showResetToDefaultButton)
  48317. {
  48318. addAndMakeVisible (&resetButton);
  48319. resetButton.addListener (treeItem);
  48320. }
  48321. addAndMakeVisible (&tree);
  48322. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48323. tree.setRootItemVisible (false);
  48324. tree.setDefaultOpenness (true);
  48325. tree.setRootItem (treeItem);
  48326. }
  48327. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48328. {
  48329. tree.setRootItem (0);
  48330. }
  48331. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48332. const Colour& textColour)
  48333. {
  48334. setColour (backgroundColourId, mainBackground);
  48335. setColour (textColourId, textColour);
  48336. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48337. }
  48338. void KeyMappingEditorComponent::parentHierarchyChanged()
  48339. {
  48340. treeItem->changeListenerCallback (0);
  48341. }
  48342. void KeyMappingEditorComponent::resized()
  48343. {
  48344. int h = getHeight();
  48345. if (resetButton.isVisible())
  48346. {
  48347. const int buttonHeight = 20;
  48348. h -= buttonHeight + 8;
  48349. int x = getWidth() - 8;
  48350. resetButton.changeWidthToFitText (buttonHeight);
  48351. resetButton.setTopRightPosition (x, h + 6);
  48352. }
  48353. tree.setBounds (0, 0, getWidth(), h);
  48354. }
  48355. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48356. {
  48357. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48358. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48359. }
  48360. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48361. {
  48362. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48363. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48364. }
  48365. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48366. {
  48367. return key.getTextDescription();
  48368. }
  48369. END_JUCE_NAMESPACE
  48370. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48371. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48372. BEGIN_JUCE_NAMESPACE
  48373. KeyPress::KeyPress() throw()
  48374. : keyCode (0),
  48375. mods (0),
  48376. textCharacter (0)
  48377. {
  48378. }
  48379. KeyPress::KeyPress (const int keyCode_,
  48380. const ModifierKeys& mods_,
  48381. const juce_wchar textCharacter_) throw()
  48382. : keyCode (keyCode_),
  48383. mods (mods_),
  48384. textCharacter (textCharacter_)
  48385. {
  48386. }
  48387. KeyPress::KeyPress (const int keyCode_) throw()
  48388. : keyCode (keyCode_),
  48389. textCharacter (0)
  48390. {
  48391. }
  48392. KeyPress::KeyPress (const KeyPress& other) throw()
  48393. : keyCode (other.keyCode),
  48394. mods (other.mods),
  48395. textCharacter (other.textCharacter)
  48396. {
  48397. }
  48398. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48399. {
  48400. keyCode = other.keyCode;
  48401. mods = other.mods;
  48402. textCharacter = other.textCharacter;
  48403. return *this;
  48404. }
  48405. bool KeyPress::operator== (const KeyPress& other) const throw()
  48406. {
  48407. return mods.getRawFlags() == other.mods.getRawFlags()
  48408. && (textCharacter == other.textCharacter
  48409. || textCharacter == 0
  48410. || other.textCharacter == 0)
  48411. && (keyCode == other.keyCode
  48412. || (keyCode < 256
  48413. && other.keyCode < 256
  48414. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48415. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48416. }
  48417. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48418. {
  48419. return ! operator== (other);
  48420. }
  48421. bool KeyPress::isCurrentlyDown() const
  48422. {
  48423. return isKeyCurrentlyDown (keyCode)
  48424. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48425. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48426. }
  48427. namespace KeyPressHelpers
  48428. {
  48429. struct KeyNameAndCode
  48430. {
  48431. const char* name;
  48432. int code;
  48433. };
  48434. const KeyNameAndCode translations[] =
  48435. {
  48436. { "spacebar", KeyPress::spaceKey },
  48437. { "return", KeyPress::returnKey },
  48438. { "escape", KeyPress::escapeKey },
  48439. { "backspace", KeyPress::backspaceKey },
  48440. { "cursor left", KeyPress::leftKey },
  48441. { "cursor right", KeyPress::rightKey },
  48442. { "cursor up", KeyPress::upKey },
  48443. { "cursor down", KeyPress::downKey },
  48444. { "page up", KeyPress::pageUpKey },
  48445. { "page down", KeyPress::pageDownKey },
  48446. { "home", KeyPress::homeKey },
  48447. { "end", KeyPress::endKey },
  48448. { "delete", KeyPress::deleteKey },
  48449. { "insert", KeyPress::insertKey },
  48450. { "tab", KeyPress::tabKey },
  48451. { "play", KeyPress::playKey },
  48452. { "stop", KeyPress::stopKey },
  48453. { "fast forward", KeyPress::fastForwardKey },
  48454. { "rewind", KeyPress::rewindKey }
  48455. };
  48456. const String numberPadPrefix() { return "numpad "; }
  48457. }
  48458. const KeyPress KeyPress::createFromDescription (const String& desc)
  48459. {
  48460. int modifiers = 0;
  48461. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48462. || desc.containsWholeWordIgnoreCase ("control")
  48463. || desc.containsWholeWordIgnoreCase ("ctl"))
  48464. modifiers |= ModifierKeys::ctrlModifier;
  48465. if (desc.containsWholeWordIgnoreCase ("shift")
  48466. || desc.containsWholeWordIgnoreCase ("shft"))
  48467. modifiers |= ModifierKeys::shiftModifier;
  48468. if (desc.containsWholeWordIgnoreCase ("alt")
  48469. || desc.containsWholeWordIgnoreCase ("option"))
  48470. modifiers |= ModifierKeys::altModifier;
  48471. if (desc.containsWholeWordIgnoreCase ("command")
  48472. || desc.containsWholeWordIgnoreCase ("cmd"))
  48473. modifiers |= ModifierKeys::commandModifier;
  48474. int key = 0;
  48475. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48476. {
  48477. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48478. {
  48479. key = KeyPressHelpers::translations[i].code;
  48480. break;
  48481. }
  48482. }
  48483. if (key == 0)
  48484. {
  48485. // see if it's a numpad key..
  48486. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48487. {
  48488. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48489. if (lastChar >= '0' && lastChar <= '9')
  48490. key = numberPad0 + lastChar - '0';
  48491. else if (lastChar == '+')
  48492. key = numberPadAdd;
  48493. else if (lastChar == '-')
  48494. key = numberPadSubtract;
  48495. else if (lastChar == '*')
  48496. key = numberPadMultiply;
  48497. else if (lastChar == '/')
  48498. key = numberPadDivide;
  48499. else if (lastChar == '.')
  48500. key = numberPadDecimalPoint;
  48501. else if (lastChar == '=')
  48502. key = numberPadEquals;
  48503. else if (desc.endsWith ("separator"))
  48504. key = numberPadSeparator;
  48505. else if (desc.endsWith ("delete"))
  48506. key = numberPadDelete;
  48507. }
  48508. if (key == 0)
  48509. {
  48510. // see if it's a function key..
  48511. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48512. for (int i = 1; i <= 12; ++i)
  48513. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48514. key = F1Key + i - 1;
  48515. if (key == 0)
  48516. {
  48517. // give up and use the hex code..
  48518. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48519. .toLowerCase()
  48520. .retainCharacters ("0123456789abcdef")
  48521. .getHexValue32();
  48522. if (hexCode > 0)
  48523. key = hexCode;
  48524. else
  48525. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48526. }
  48527. }
  48528. }
  48529. return KeyPress (key, ModifierKeys (modifiers), 0);
  48530. }
  48531. const String KeyPress::getTextDescription() const
  48532. {
  48533. String desc;
  48534. if (keyCode > 0)
  48535. {
  48536. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48537. // want to store it as being a slash, not shift+whatever.
  48538. if (textCharacter == '/')
  48539. return "/";
  48540. if (mods.isCtrlDown())
  48541. desc << "ctrl + ";
  48542. if (mods.isShiftDown())
  48543. desc << "shift + ";
  48544. #if JUCE_MAC
  48545. // only do this on the mac, because on Windows ctrl and command are the same,
  48546. // and this would get confusing
  48547. if (mods.isCommandDown())
  48548. desc << "command + ";
  48549. if (mods.isAltDown())
  48550. desc << "option + ";
  48551. #else
  48552. if (mods.isAltDown())
  48553. desc << "alt + ";
  48554. #endif
  48555. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48556. if (keyCode == KeyPressHelpers::translations[i].code)
  48557. return desc + KeyPressHelpers::translations[i].name;
  48558. if (keyCode >= F1Key && keyCode <= F16Key)
  48559. desc << 'F' << (1 + keyCode - F1Key);
  48560. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48561. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48562. else if (keyCode >= 33 && keyCode < 176)
  48563. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48564. else if (keyCode == numberPadAdd)
  48565. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48566. else if (keyCode == numberPadSubtract)
  48567. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48568. else if (keyCode == numberPadMultiply)
  48569. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48570. else if (keyCode == numberPadDivide)
  48571. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48572. else if (keyCode == numberPadSeparator)
  48573. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48574. else if (keyCode == numberPadDecimalPoint)
  48575. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48576. else if (keyCode == numberPadDelete)
  48577. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48578. else
  48579. desc << '#' << String::toHexString (keyCode);
  48580. }
  48581. return desc;
  48582. }
  48583. END_JUCE_NAMESPACE
  48584. /*** End of inlined file: juce_KeyPress.cpp ***/
  48585. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48586. BEGIN_JUCE_NAMESPACE
  48587. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48588. : commandManager (commandManager_)
  48589. {
  48590. // A manager is needed to get the descriptions of commands, and will be called when
  48591. // a command is invoked. So you can't leave this null..
  48592. jassert (commandManager_ != 0);
  48593. Desktop::getInstance().addFocusChangeListener (this);
  48594. }
  48595. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48596. : commandManager (other.commandManager)
  48597. {
  48598. Desktop::getInstance().addFocusChangeListener (this);
  48599. }
  48600. KeyPressMappingSet::~KeyPressMappingSet()
  48601. {
  48602. Desktop::getInstance().removeFocusChangeListener (this);
  48603. }
  48604. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48605. {
  48606. for (int i = 0; i < mappings.size(); ++i)
  48607. if (mappings.getUnchecked(i)->commandID == commandID)
  48608. return mappings.getUnchecked (i)->keypresses;
  48609. return Array <KeyPress> ();
  48610. }
  48611. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48612. const KeyPress& newKeyPress,
  48613. int insertIndex)
  48614. {
  48615. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48616. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48617. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48618. && ! newKeyPress.getModifiers().isShiftDown()));
  48619. if (findCommandForKeyPress (newKeyPress) != commandID)
  48620. {
  48621. removeKeyPress (newKeyPress);
  48622. if (newKeyPress.isValid())
  48623. {
  48624. for (int i = mappings.size(); --i >= 0;)
  48625. {
  48626. if (mappings.getUnchecked(i)->commandID == commandID)
  48627. {
  48628. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48629. sendChangeMessage();
  48630. return;
  48631. }
  48632. }
  48633. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48634. if (ci != 0)
  48635. {
  48636. CommandMapping* const cm = new CommandMapping();
  48637. cm->commandID = commandID;
  48638. cm->keypresses.add (newKeyPress);
  48639. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48640. mappings.add (cm);
  48641. sendChangeMessage();
  48642. }
  48643. }
  48644. }
  48645. }
  48646. void KeyPressMappingSet::resetToDefaultMappings()
  48647. {
  48648. mappings.clear();
  48649. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48650. {
  48651. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48652. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48653. {
  48654. addKeyPress (ci->commandID,
  48655. ci->defaultKeypresses.getReference (j));
  48656. }
  48657. }
  48658. sendChangeMessage();
  48659. }
  48660. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48661. {
  48662. clearAllKeyPresses (commandID);
  48663. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48664. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48665. {
  48666. addKeyPress (ci->commandID,
  48667. ci->defaultKeypresses.getReference (j));
  48668. }
  48669. }
  48670. void KeyPressMappingSet::clearAllKeyPresses()
  48671. {
  48672. if (mappings.size() > 0)
  48673. {
  48674. sendChangeMessage();
  48675. mappings.clear();
  48676. }
  48677. }
  48678. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48679. {
  48680. for (int i = mappings.size(); --i >= 0;)
  48681. {
  48682. if (mappings.getUnchecked(i)->commandID == commandID)
  48683. {
  48684. mappings.remove (i);
  48685. sendChangeMessage();
  48686. }
  48687. }
  48688. }
  48689. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48690. {
  48691. if (keypress.isValid())
  48692. {
  48693. for (int i = mappings.size(); --i >= 0;)
  48694. {
  48695. CommandMapping* const cm = mappings.getUnchecked(i);
  48696. for (int j = cm->keypresses.size(); --j >= 0;)
  48697. {
  48698. if (keypress == cm->keypresses [j])
  48699. {
  48700. cm->keypresses.remove (j);
  48701. sendChangeMessage();
  48702. }
  48703. }
  48704. }
  48705. }
  48706. }
  48707. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48708. {
  48709. for (int i = mappings.size(); --i >= 0;)
  48710. {
  48711. if (mappings.getUnchecked(i)->commandID == commandID)
  48712. {
  48713. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48714. sendChangeMessage();
  48715. break;
  48716. }
  48717. }
  48718. }
  48719. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48720. {
  48721. for (int i = 0; i < mappings.size(); ++i)
  48722. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48723. return mappings.getUnchecked(i)->commandID;
  48724. return 0;
  48725. }
  48726. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48727. {
  48728. for (int i = mappings.size(); --i >= 0;)
  48729. if (mappings.getUnchecked(i)->commandID == commandID)
  48730. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48731. return false;
  48732. }
  48733. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48734. const KeyPress& key,
  48735. const bool isKeyDown,
  48736. const int millisecsSinceKeyPressed,
  48737. Component* const originatingComponent) const
  48738. {
  48739. ApplicationCommandTarget::InvocationInfo info (commandID);
  48740. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48741. info.isKeyDown = isKeyDown;
  48742. info.keyPress = key;
  48743. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48744. info.originatingComponent = originatingComponent;
  48745. commandManager->invoke (info, false);
  48746. }
  48747. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48748. {
  48749. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48750. {
  48751. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48752. {
  48753. // if the XML was created as a set of differences from the default mappings,
  48754. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48755. resetToDefaultMappings();
  48756. }
  48757. else
  48758. {
  48759. // if the XML was created calling createXml (false), then we need to clear all
  48760. // the keys and treat the xml as describing the entire set of mappings.
  48761. clearAllKeyPresses();
  48762. }
  48763. forEachXmlChildElement (xmlVersion, map)
  48764. {
  48765. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48766. if (commandId != 0)
  48767. {
  48768. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48769. if (map->hasTagName ("MAPPING"))
  48770. {
  48771. addKeyPress (commandId, key);
  48772. }
  48773. else if (map->hasTagName ("UNMAPPING"))
  48774. {
  48775. if (containsMapping (commandId, key))
  48776. removeKeyPress (key);
  48777. }
  48778. }
  48779. }
  48780. return true;
  48781. }
  48782. return false;
  48783. }
  48784. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48785. {
  48786. ScopedPointer <KeyPressMappingSet> defaultSet;
  48787. if (saveDifferencesFromDefaultSet)
  48788. {
  48789. defaultSet = new KeyPressMappingSet (commandManager);
  48790. defaultSet->resetToDefaultMappings();
  48791. }
  48792. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48793. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48794. int i;
  48795. for (i = 0; i < mappings.size(); ++i)
  48796. {
  48797. const CommandMapping* const cm = mappings.getUnchecked(i);
  48798. for (int j = 0; j < cm->keypresses.size(); ++j)
  48799. {
  48800. if (defaultSet == 0
  48801. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48802. {
  48803. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48804. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48805. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48806. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48807. }
  48808. }
  48809. }
  48810. if (defaultSet != 0)
  48811. {
  48812. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48813. {
  48814. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48815. for (int j = 0; j < cm->keypresses.size(); ++j)
  48816. {
  48817. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48818. {
  48819. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48820. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48821. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48822. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48823. }
  48824. }
  48825. }
  48826. }
  48827. return doc;
  48828. }
  48829. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48830. Component* originatingComponent)
  48831. {
  48832. bool used = false;
  48833. const CommandID commandID = findCommandForKeyPress (key);
  48834. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48835. if (ci != 0
  48836. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48837. {
  48838. ApplicationCommandInfo info (0);
  48839. if (commandManager->getTargetForCommand (commandID, info) != 0
  48840. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48841. {
  48842. invokeCommand (commandID, key, true, 0, originatingComponent);
  48843. used = true;
  48844. }
  48845. else
  48846. {
  48847. if (originatingComponent != 0)
  48848. originatingComponent->getLookAndFeel().playAlertSound();
  48849. }
  48850. }
  48851. return used;
  48852. }
  48853. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48854. {
  48855. bool used = false;
  48856. const uint32 now = Time::getMillisecondCounter();
  48857. for (int i = mappings.size(); --i >= 0;)
  48858. {
  48859. CommandMapping* const cm = mappings.getUnchecked(i);
  48860. if (cm->wantsKeyUpDownCallbacks)
  48861. {
  48862. for (int j = cm->keypresses.size(); --j >= 0;)
  48863. {
  48864. const KeyPress key (cm->keypresses.getReference (j));
  48865. const bool isDown = key.isCurrentlyDown();
  48866. int keyPressEntryIndex = 0;
  48867. bool wasDown = false;
  48868. for (int k = keysDown.size(); --k >= 0;)
  48869. {
  48870. if (key == keysDown.getUnchecked(k)->key)
  48871. {
  48872. keyPressEntryIndex = k;
  48873. wasDown = true;
  48874. used = true;
  48875. break;
  48876. }
  48877. }
  48878. if (isDown != wasDown)
  48879. {
  48880. int millisecs = 0;
  48881. if (isDown)
  48882. {
  48883. KeyPressTime* const k = new KeyPressTime();
  48884. k->key = key;
  48885. k->timeWhenPressed = now;
  48886. keysDown.add (k);
  48887. }
  48888. else
  48889. {
  48890. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48891. if (now > pressTime)
  48892. millisecs = now - pressTime;
  48893. keysDown.remove (keyPressEntryIndex);
  48894. }
  48895. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48896. used = true;
  48897. }
  48898. }
  48899. }
  48900. }
  48901. return used;
  48902. }
  48903. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48904. {
  48905. if (focusedComponent != 0)
  48906. focusedComponent->keyStateChanged (false);
  48907. }
  48908. END_JUCE_NAMESPACE
  48909. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48910. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48911. BEGIN_JUCE_NAMESPACE
  48912. ModifierKeys::ModifierKeys (const int flags_) throw()
  48913. : flags (flags_)
  48914. {
  48915. }
  48916. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48917. : flags (other.flags)
  48918. {
  48919. }
  48920. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48921. {
  48922. flags = other.flags;
  48923. return *this;
  48924. }
  48925. ModifierKeys ModifierKeys::currentModifiers;
  48926. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48927. {
  48928. return currentModifiers;
  48929. }
  48930. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48931. {
  48932. int num = 0;
  48933. if (isLeftButtonDown()) ++num;
  48934. if (isRightButtonDown()) ++num;
  48935. if (isMiddleButtonDown()) ++num;
  48936. return num;
  48937. }
  48938. END_JUCE_NAMESPACE
  48939. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48940. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48941. BEGIN_JUCE_NAMESPACE
  48942. class ComponentAnimator::AnimationTask
  48943. {
  48944. public:
  48945. AnimationTask (Component* const comp)
  48946. : component (comp)
  48947. {
  48948. }
  48949. void reset (const Rectangle<int>& finalBounds,
  48950. float finalAlpha,
  48951. int millisecondsToSpendMoving,
  48952. bool useProxyComponent,
  48953. double startSpeed_, double endSpeed_)
  48954. {
  48955. msElapsed = 0;
  48956. msTotal = jmax (1, millisecondsToSpendMoving);
  48957. lastProgress = 0;
  48958. destination = finalBounds;
  48959. destAlpha = finalAlpha;
  48960. isMoving = (finalBounds != component->getBounds());
  48961. isChangingAlpha = (finalAlpha != component->getAlpha());
  48962. left = component->getX();
  48963. top = component->getY();
  48964. right = component->getRight();
  48965. bottom = component->getBottom();
  48966. alpha = component->getAlpha();
  48967. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  48968. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  48969. midSpeed = invTotalDistance;
  48970. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  48971. if (useProxyComponent)
  48972. proxy = new ProxyComponent (*component);
  48973. else
  48974. proxy = 0;
  48975. component->setVisible (! useProxyComponent);
  48976. }
  48977. bool useTimeslice (const int elapsed)
  48978. {
  48979. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  48980. : static_cast <Component*> (component);
  48981. if (c != 0)
  48982. {
  48983. msElapsed += elapsed;
  48984. double newProgress = msElapsed / (double) msTotal;
  48985. if (newProgress >= 0 && newProgress < 1.0)
  48986. {
  48987. newProgress = timeToDistance (newProgress);
  48988. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48989. jassert (newProgress >= lastProgress);
  48990. lastProgress = newProgress;
  48991. if (delta < 1.0)
  48992. {
  48993. bool stillBusy = false;
  48994. if (isMoving)
  48995. {
  48996. left += (destination.getX() - left) * delta;
  48997. top += (destination.getY() - top) * delta;
  48998. right += (destination.getRight() - right) * delta;
  48999. bottom += (destination.getBottom() - bottom) * delta;
  49000. const Rectangle<int> newBounds (roundToInt (left),
  49001. roundToInt (top),
  49002. roundToInt (right - left),
  49003. roundToInt (bottom - top));
  49004. if (newBounds != destination)
  49005. {
  49006. c->setBounds (newBounds);
  49007. stillBusy = true;
  49008. }
  49009. }
  49010. if (isChangingAlpha)
  49011. {
  49012. alpha += (destAlpha - alpha) * delta;
  49013. c->setAlpha ((float) alpha);
  49014. stillBusy = true;
  49015. }
  49016. if (stillBusy)
  49017. return true;
  49018. }
  49019. }
  49020. }
  49021. moveToFinalDestination();
  49022. return false;
  49023. }
  49024. void moveToFinalDestination()
  49025. {
  49026. if (component != 0)
  49027. {
  49028. component->setAlpha ((float) destAlpha);
  49029. component->setBounds (destination);
  49030. }
  49031. }
  49032. class ProxyComponent : public Component
  49033. {
  49034. public:
  49035. ProxyComponent (Component& component)
  49036. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49037. {
  49038. setBounds (component.getBounds());
  49039. setAlpha (component.getAlpha());
  49040. setInterceptsMouseClicks (false, false);
  49041. Component* const parent = component.getParentComponent();
  49042. if (parent != 0)
  49043. parent->addAndMakeVisible (this);
  49044. else if (component.isOnDesktop() && component.getPeer() != 0)
  49045. addToDesktop (component.getPeer()->getStyleFlags());
  49046. else
  49047. jassertfalse; // seem to be trying to animate a component that's not visible..
  49048. setVisible (true);
  49049. toBehind (&component);
  49050. }
  49051. void paint (Graphics& g)
  49052. {
  49053. g.setOpacity (1.0f);
  49054. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49055. 0, 0, image.getWidth(), image.getHeight());
  49056. }
  49057. private:
  49058. Image image;
  49059. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49060. };
  49061. WeakReference<Component> component;
  49062. ScopedPointer<Component> proxy;
  49063. Rectangle<int> destination;
  49064. double destAlpha;
  49065. int msElapsed, msTotal;
  49066. double startSpeed, midSpeed, endSpeed, lastProgress;
  49067. double left, top, right, bottom, alpha;
  49068. bool isMoving, isChangingAlpha;
  49069. private:
  49070. double timeToDistance (const double time) const throw()
  49071. {
  49072. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49073. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49074. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49075. }
  49076. };
  49077. ComponentAnimator::ComponentAnimator()
  49078. : lastTime (0)
  49079. {
  49080. }
  49081. ComponentAnimator::~ComponentAnimator()
  49082. {
  49083. }
  49084. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49085. {
  49086. for (int i = tasks.size(); --i >= 0;)
  49087. if (component == tasks.getUnchecked(i)->component.get())
  49088. return tasks.getUnchecked(i);
  49089. return 0;
  49090. }
  49091. void ComponentAnimator::animateComponent (Component* const component,
  49092. const Rectangle<int>& finalBounds,
  49093. const float finalAlpha,
  49094. const int millisecondsToSpendMoving,
  49095. const bool useProxyComponent,
  49096. const double startSpeed,
  49097. const double endSpeed)
  49098. {
  49099. // the speeds must be 0 or greater!
  49100. jassert (startSpeed >= 0 && endSpeed >= 0)
  49101. if (component != 0)
  49102. {
  49103. AnimationTask* at = findTaskFor (component);
  49104. if (at == 0)
  49105. {
  49106. at = new AnimationTask (component);
  49107. tasks.add (at);
  49108. sendChangeMessage();
  49109. }
  49110. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49111. useProxyComponent, startSpeed, endSpeed);
  49112. if (! isTimerRunning())
  49113. {
  49114. lastTime = Time::getMillisecondCounter();
  49115. startTimer (1000 / 50);
  49116. }
  49117. }
  49118. }
  49119. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49120. {
  49121. if (component != 0)
  49122. {
  49123. if (component->isShowing() && millisecondsToTake > 0)
  49124. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49125. component->setVisible (false);
  49126. }
  49127. }
  49128. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49129. {
  49130. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49131. {
  49132. component->setAlpha (0.0f);
  49133. component->setVisible (true);
  49134. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49135. }
  49136. }
  49137. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49138. {
  49139. if (tasks.size() > 0)
  49140. {
  49141. if (moveComponentsToTheirFinalPositions)
  49142. for (int i = tasks.size(); --i >= 0;)
  49143. tasks.getUnchecked(i)->moveToFinalDestination();
  49144. tasks.clear();
  49145. sendChangeMessage();
  49146. }
  49147. }
  49148. void ComponentAnimator::cancelAnimation (Component* const component,
  49149. const bool moveComponentToItsFinalPosition)
  49150. {
  49151. AnimationTask* const at = findTaskFor (component);
  49152. if (at != 0)
  49153. {
  49154. if (moveComponentToItsFinalPosition)
  49155. at->moveToFinalDestination();
  49156. tasks.removeObject (at);
  49157. sendChangeMessage();
  49158. }
  49159. }
  49160. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49161. {
  49162. jassert (component != 0);
  49163. AnimationTask* const at = findTaskFor (component);
  49164. if (at != 0)
  49165. return at->destination;
  49166. return component->getBounds();
  49167. }
  49168. bool ComponentAnimator::isAnimating (Component* component) const
  49169. {
  49170. return findTaskFor (component) != 0;
  49171. }
  49172. void ComponentAnimator::timerCallback()
  49173. {
  49174. const uint32 timeNow = Time::getMillisecondCounter();
  49175. if (lastTime == 0 || lastTime == timeNow)
  49176. lastTime = timeNow;
  49177. const int elapsed = timeNow - lastTime;
  49178. for (int i = tasks.size(); --i >= 0;)
  49179. {
  49180. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49181. {
  49182. tasks.remove (i);
  49183. sendChangeMessage();
  49184. }
  49185. }
  49186. lastTime = timeNow;
  49187. if (tasks.size() == 0)
  49188. stopTimer();
  49189. }
  49190. END_JUCE_NAMESPACE
  49191. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49192. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49193. BEGIN_JUCE_NAMESPACE
  49194. namespace ComponentBuilderHelpers
  49195. {
  49196. const String getStateId (const ValueTree& state)
  49197. {
  49198. return state [ComponentBuilder::idProperty].toString();
  49199. }
  49200. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49201. {
  49202. jassert (compId.isNotEmpty());
  49203. for (int i = components.size(); --i >= 0;)
  49204. {
  49205. Component* const c = components.getUnchecked (i);
  49206. if (c->getComponentID() == compId)
  49207. return components.removeAndReturn (i);
  49208. }
  49209. return 0;
  49210. }
  49211. Component* findComponentWithID (Component* const c, const String& compId)
  49212. {
  49213. jassert (compId.isNotEmpty());
  49214. if (c->getComponentID() == compId)
  49215. return c;
  49216. for (int i = c->getNumChildComponents(); --i >= 0;)
  49217. {
  49218. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49219. if (child != 0)
  49220. return child;
  49221. }
  49222. return 0;
  49223. }
  49224. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49225. const ValueTree& state, Component* parent)
  49226. {
  49227. Component* const c = type.addNewComponentFromState (state, parent);
  49228. jassert (c != 0 && c->getParentComponent() == parent);
  49229. c->setComponentID (getStateId (state));
  49230. return c;
  49231. }
  49232. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49233. {
  49234. Component* topLevelComp = builder.getManagedComponent();
  49235. if (topLevelComp != 0)
  49236. {
  49237. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49238. const String uid (getStateId (state));
  49239. if (type == 0 || uid.isEmpty())
  49240. {
  49241. // ..handle the case where a child of the actual state node has changed.
  49242. if (state.getParent().isValid())
  49243. updateComponent (builder, state.getParent());
  49244. }
  49245. else
  49246. {
  49247. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49248. if (changedComp != 0)
  49249. type->updateComponentFromState (changedComp, state);
  49250. }
  49251. }
  49252. }
  49253. }
  49254. const Identifier ComponentBuilder::idProperty ("id");
  49255. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49256. : state (state_), imageProvider (0)
  49257. {
  49258. state.addListener (this);
  49259. }
  49260. ComponentBuilder::~ComponentBuilder()
  49261. {
  49262. state.removeListener (this);
  49263. #if JUCE_DEBUG
  49264. // Don't delete the managed component!! The builder owns that component, and will delete
  49265. // it automatically when it gets deleted.
  49266. jassert (componentRef.get() == static_cast <Component*> (component));
  49267. #endif
  49268. }
  49269. Component* ComponentBuilder::getManagedComponent()
  49270. {
  49271. if (component == 0)
  49272. {
  49273. component = createComponent();
  49274. #if JUCE_DEBUG
  49275. componentRef = component;
  49276. #endif
  49277. }
  49278. return component;
  49279. }
  49280. Component* ComponentBuilder::createComponent()
  49281. {
  49282. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49283. TypeHandler* const type = getHandlerForState (state);
  49284. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49285. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49286. }
  49287. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49288. {
  49289. jassert (type != 0);
  49290. // Don't try to move your types around! Once a type has been added to a builder, the
  49291. // builder owns it, and you should leave it alone!
  49292. jassert (type->builder == 0);
  49293. types.add (type);
  49294. type->builder = this;
  49295. }
  49296. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49297. {
  49298. const Identifier targetType (s.getType());
  49299. for (int i = 0; i < types.size(); ++i)
  49300. {
  49301. TypeHandler* const t = types.getUnchecked(i);
  49302. if (t->getType() == targetType)
  49303. return t;
  49304. }
  49305. return 0;
  49306. }
  49307. int ComponentBuilder::getNumHandlers() const throw()
  49308. {
  49309. return types.size();
  49310. }
  49311. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49312. {
  49313. return types [index];
  49314. }
  49315. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49316. {
  49317. imageProvider = newImageProvider;
  49318. }
  49319. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49320. {
  49321. return imageProvider;
  49322. }
  49323. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49324. {
  49325. ComponentBuilderHelpers::updateComponent (*this, tree);
  49326. }
  49327. void ComponentBuilder::valueTreeChildrenChanged (ValueTree& tree)
  49328. {
  49329. ComponentBuilderHelpers::updateComponent (*this, tree);
  49330. }
  49331. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49332. {
  49333. ComponentBuilderHelpers::updateComponent (*this, tree);
  49334. }
  49335. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49336. : builder (0), valueTreeType (valueTreeType_)
  49337. {
  49338. }
  49339. ComponentBuilder::TypeHandler::~TypeHandler()
  49340. {
  49341. }
  49342. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49343. {
  49344. // A type handler needs to be registered with a ComponentBuilder before using it!
  49345. jassert (builder != 0);
  49346. return builder;
  49347. }
  49348. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49349. {
  49350. using namespace ComponentBuilderHelpers;
  49351. const int numExistingChildComps = parent.getNumChildComponents();
  49352. Array <Component*> componentsInOrder;
  49353. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49354. {
  49355. OwnedArray<Component> existingComponents;
  49356. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49357. int i;
  49358. for (i = 0; i < numExistingChildComps; ++i)
  49359. existingComponents.add (parent.getChildComponent (i));
  49360. const int newNumChildren = children.getNumChildren();
  49361. for (i = 0; i < newNumChildren; ++i)
  49362. {
  49363. const ValueTree childState (children.getChild (i));
  49364. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49365. jassert (type != 0);
  49366. if (type != 0)
  49367. {
  49368. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49369. if (c == 0)
  49370. c = createNewComponent (*type, childState, &parent);
  49371. componentsInOrder.add (c);
  49372. }
  49373. }
  49374. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49375. }
  49376. // Make sure the z-order is correct..
  49377. if (componentsInOrder.size() > 0)
  49378. {
  49379. componentsInOrder.getLast()->toFront (false);
  49380. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49381. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49382. }
  49383. }
  49384. END_JUCE_NAMESPACE
  49385. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49386. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49387. BEGIN_JUCE_NAMESPACE
  49388. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49389. : minW (0),
  49390. maxW (0x3fffffff),
  49391. minH (0),
  49392. maxH (0x3fffffff),
  49393. minOffTop (0),
  49394. minOffLeft (0),
  49395. minOffBottom (0),
  49396. minOffRight (0),
  49397. aspectRatio (0.0)
  49398. {
  49399. }
  49400. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49401. {
  49402. }
  49403. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49404. {
  49405. minW = minimumWidth;
  49406. }
  49407. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49408. {
  49409. maxW = maximumWidth;
  49410. }
  49411. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49412. {
  49413. minH = minimumHeight;
  49414. }
  49415. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49416. {
  49417. maxH = maximumHeight;
  49418. }
  49419. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49420. {
  49421. jassert (maxW >= minimumWidth);
  49422. jassert (maxH >= minimumHeight);
  49423. jassert (minimumWidth > 0 && minimumHeight > 0);
  49424. minW = minimumWidth;
  49425. minH = minimumHeight;
  49426. if (minW > maxW)
  49427. maxW = minW;
  49428. if (minH > maxH)
  49429. maxH = minH;
  49430. }
  49431. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49432. {
  49433. jassert (maximumWidth >= minW);
  49434. jassert (maximumHeight >= minH);
  49435. jassert (maximumWidth > 0 && maximumHeight > 0);
  49436. maxW = jmax (minW, maximumWidth);
  49437. maxH = jmax (minH, maximumHeight);
  49438. }
  49439. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49440. const int minimumHeight,
  49441. const int maximumWidth,
  49442. const int maximumHeight) throw()
  49443. {
  49444. jassert (maximumWidth >= minimumWidth);
  49445. jassert (maximumHeight >= minimumHeight);
  49446. jassert (maximumWidth > 0 && maximumHeight > 0);
  49447. jassert (minimumWidth > 0 && minimumHeight > 0);
  49448. minW = jmax (0, minimumWidth);
  49449. minH = jmax (0, minimumHeight);
  49450. maxW = jmax (minW, maximumWidth);
  49451. maxH = jmax (minH, maximumHeight);
  49452. }
  49453. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49454. const int minimumWhenOffTheLeft,
  49455. const int minimumWhenOffTheBottom,
  49456. const int minimumWhenOffTheRight) throw()
  49457. {
  49458. minOffTop = minimumWhenOffTheTop;
  49459. minOffLeft = minimumWhenOffTheLeft;
  49460. minOffBottom = minimumWhenOffTheBottom;
  49461. minOffRight = minimumWhenOffTheRight;
  49462. }
  49463. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49464. {
  49465. aspectRatio = jmax (0.0, widthOverHeight);
  49466. }
  49467. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49468. {
  49469. return aspectRatio;
  49470. }
  49471. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49472. const Rectangle<int>& targetBounds,
  49473. const bool isStretchingTop,
  49474. const bool isStretchingLeft,
  49475. const bool isStretchingBottom,
  49476. const bool isStretchingRight)
  49477. {
  49478. jassert (component != 0);
  49479. Rectangle<int> limits, bounds (targetBounds);
  49480. BorderSize<int> border;
  49481. Component* const parent = component->getParentComponent();
  49482. if (parent == 0)
  49483. {
  49484. ComponentPeer* peer = component->getPeer();
  49485. if (peer != 0)
  49486. border = peer->getFrameSize();
  49487. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49488. }
  49489. else
  49490. {
  49491. limits.setSize (parent->getWidth(), parent->getHeight());
  49492. }
  49493. border.addTo (bounds);
  49494. checkBounds (bounds,
  49495. border.addedTo (component->getBounds()), limits,
  49496. isStretchingTop, isStretchingLeft,
  49497. isStretchingBottom, isStretchingRight);
  49498. border.subtractFrom (bounds);
  49499. applyBoundsToComponent (component, bounds);
  49500. }
  49501. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49502. {
  49503. setBoundsForComponent (component, component->getBounds(),
  49504. false, false, false, false);
  49505. }
  49506. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49507. const Rectangle<int>& bounds)
  49508. {
  49509. component->setBounds (bounds);
  49510. }
  49511. void ComponentBoundsConstrainer::resizeStart()
  49512. {
  49513. }
  49514. void ComponentBoundsConstrainer::resizeEnd()
  49515. {
  49516. }
  49517. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49518. const Rectangle<int>& old,
  49519. const Rectangle<int>& limits,
  49520. const bool isStretchingTop,
  49521. const bool isStretchingLeft,
  49522. const bool isStretchingBottom,
  49523. const bool isStretchingRight)
  49524. {
  49525. // constrain the size if it's being stretched..
  49526. if (isStretchingLeft)
  49527. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49528. if (isStretchingRight)
  49529. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49530. if (isStretchingTop)
  49531. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49532. if (isStretchingBottom)
  49533. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49534. if (bounds.isEmpty())
  49535. return;
  49536. if (minOffTop > 0)
  49537. {
  49538. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49539. if (bounds.getY() < limit)
  49540. {
  49541. if (isStretchingTop)
  49542. bounds.setTop (limits.getY());
  49543. else
  49544. bounds.setY (limit);
  49545. }
  49546. }
  49547. if (minOffLeft > 0)
  49548. {
  49549. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49550. if (bounds.getX() < limit)
  49551. {
  49552. if (isStretchingLeft)
  49553. bounds.setLeft (limits.getX());
  49554. else
  49555. bounds.setX (limit);
  49556. }
  49557. }
  49558. if (minOffBottom > 0)
  49559. {
  49560. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49561. if (bounds.getY() > limit)
  49562. {
  49563. if (isStretchingBottom)
  49564. bounds.setBottom (limits.getBottom());
  49565. else
  49566. bounds.setY (limit);
  49567. }
  49568. }
  49569. if (minOffRight > 0)
  49570. {
  49571. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49572. if (bounds.getX() > limit)
  49573. {
  49574. if (isStretchingRight)
  49575. bounds.setRight (limits.getRight());
  49576. else
  49577. bounds.setX (limit);
  49578. }
  49579. }
  49580. // constrain the aspect ratio if one has been specified..
  49581. if (aspectRatio > 0.0)
  49582. {
  49583. bool adjustWidth;
  49584. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49585. {
  49586. adjustWidth = true;
  49587. }
  49588. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49589. {
  49590. adjustWidth = false;
  49591. }
  49592. else
  49593. {
  49594. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49595. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49596. adjustWidth = (oldRatio > newRatio);
  49597. }
  49598. if (adjustWidth)
  49599. {
  49600. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49601. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49602. {
  49603. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49604. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49605. }
  49606. }
  49607. else
  49608. {
  49609. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49610. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49611. {
  49612. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49613. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49614. }
  49615. }
  49616. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49617. {
  49618. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49619. }
  49620. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49621. {
  49622. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49623. }
  49624. else
  49625. {
  49626. if (isStretchingLeft)
  49627. bounds.setX (old.getRight() - bounds.getWidth());
  49628. if (isStretchingTop)
  49629. bounds.setY (old.getBottom() - bounds.getHeight());
  49630. }
  49631. }
  49632. jassert (! bounds.isEmpty());
  49633. }
  49634. END_JUCE_NAMESPACE
  49635. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49636. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49637. BEGIN_JUCE_NAMESPACE
  49638. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49639. : component (component_),
  49640. lastPeer (0),
  49641. reentrant (false),
  49642. wasShowing (component_->isShowing())
  49643. {
  49644. jassert (component != 0); // can't use this with a null pointer..
  49645. component->addComponentListener (this);
  49646. registerWithParentComps();
  49647. }
  49648. ComponentMovementWatcher::~ComponentMovementWatcher()
  49649. {
  49650. if (component != 0)
  49651. component->removeComponentListener (this);
  49652. unregister();
  49653. }
  49654. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49655. {
  49656. if (component != 0 && ! reentrant)
  49657. {
  49658. const ScopedValueSetter<bool> setter (reentrant, true);
  49659. ComponentPeer* const peer = component->getPeer();
  49660. if (peer != lastPeer)
  49661. {
  49662. componentPeerChanged();
  49663. if (component == 0)
  49664. return;
  49665. lastPeer = peer;
  49666. }
  49667. unregister();
  49668. registerWithParentComps();
  49669. componentMovedOrResized (*component, true, true);
  49670. if (component != 0)
  49671. componentVisibilityChanged (*component);
  49672. }
  49673. }
  49674. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49675. {
  49676. if (component != 0)
  49677. {
  49678. if (wasMoved)
  49679. {
  49680. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49681. wasMoved = lastBounds.getPosition() != pos;
  49682. lastBounds.setPosition (pos);
  49683. }
  49684. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49685. lastBounds.setSize (component->getWidth(), component->getHeight());
  49686. if (wasMoved || wasResized)
  49687. componentMovedOrResized (wasMoved, wasResized);
  49688. }
  49689. }
  49690. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49691. {
  49692. registeredParentComps.removeValue (&comp);
  49693. if (component == &comp)
  49694. unregister();
  49695. }
  49696. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49697. {
  49698. if (component != 0)
  49699. {
  49700. const bool isShowingNow = component->isShowing();
  49701. if (wasShowing != isShowingNow)
  49702. {
  49703. wasShowing = isShowingNow;
  49704. componentVisibilityChanged();
  49705. }
  49706. }
  49707. }
  49708. void ComponentMovementWatcher::registerWithParentComps()
  49709. {
  49710. Component* p = component->getParentComponent();
  49711. while (p != 0)
  49712. {
  49713. p->addComponentListener (this);
  49714. registeredParentComps.add (p);
  49715. p = p->getParentComponent();
  49716. }
  49717. }
  49718. void ComponentMovementWatcher::unregister()
  49719. {
  49720. for (int i = registeredParentComps.size(); --i >= 0;)
  49721. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49722. registeredParentComps.clear();
  49723. }
  49724. END_JUCE_NAMESPACE
  49725. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49726. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49727. BEGIN_JUCE_NAMESPACE
  49728. GroupComponent::GroupComponent (const String& componentName,
  49729. const String& labelText)
  49730. : Component (componentName),
  49731. text (labelText),
  49732. justification (Justification::left)
  49733. {
  49734. setInterceptsMouseClicks (false, true);
  49735. }
  49736. GroupComponent::~GroupComponent()
  49737. {
  49738. }
  49739. void GroupComponent::setText (const String& newText)
  49740. {
  49741. if (text != newText)
  49742. {
  49743. text = newText;
  49744. repaint();
  49745. }
  49746. }
  49747. const String GroupComponent::getText() const
  49748. {
  49749. return text;
  49750. }
  49751. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49752. {
  49753. if (justification != newJustification)
  49754. {
  49755. justification = newJustification;
  49756. repaint();
  49757. }
  49758. }
  49759. void GroupComponent::paint (Graphics& g)
  49760. {
  49761. getLookAndFeel()
  49762. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49763. text, justification,
  49764. *this);
  49765. }
  49766. void GroupComponent::enablementChanged()
  49767. {
  49768. repaint();
  49769. }
  49770. void GroupComponent::colourChanged()
  49771. {
  49772. repaint();
  49773. }
  49774. END_JUCE_NAMESPACE
  49775. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49776. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49777. BEGIN_JUCE_NAMESPACE
  49778. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49779. : DocumentWindow (String::empty, backgroundColour,
  49780. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49781. {
  49782. }
  49783. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49784. {
  49785. }
  49786. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49787. {
  49788. MultiDocumentPanel* const owner = getOwner();
  49789. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49790. if (owner != 0)
  49791. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49792. }
  49793. void MultiDocumentPanelWindow::closeButtonPressed()
  49794. {
  49795. MultiDocumentPanel* const owner = getOwner();
  49796. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49797. if (owner != 0)
  49798. owner->closeDocument (getContentComponent(), true);
  49799. }
  49800. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49801. {
  49802. DocumentWindow::activeWindowStatusChanged();
  49803. updateOrder();
  49804. }
  49805. void MultiDocumentPanelWindow::broughtToFront()
  49806. {
  49807. DocumentWindow::broughtToFront();
  49808. updateOrder();
  49809. }
  49810. void MultiDocumentPanelWindow::updateOrder()
  49811. {
  49812. MultiDocumentPanel* const owner = getOwner();
  49813. if (owner != 0)
  49814. owner->updateOrder();
  49815. }
  49816. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49817. {
  49818. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49819. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49820. }
  49821. class MDITabbedComponentInternal : public TabbedComponent
  49822. {
  49823. public:
  49824. MDITabbedComponentInternal()
  49825. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49826. {
  49827. }
  49828. ~MDITabbedComponentInternal()
  49829. {
  49830. }
  49831. void currentTabChanged (int, const String&)
  49832. {
  49833. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49834. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49835. if (owner != 0)
  49836. owner->updateOrder();
  49837. }
  49838. };
  49839. MultiDocumentPanel::MultiDocumentPanel()
  49840. : mode (MaximisedWindowsWithTabs),
  49841. backgroundColour (Colours::lightblue),
  49842. maximumNumDocuments (0),
  49843. numDocsBeforeTabsUsed (0)
  49844. {
  49845. setOpaque (true);
  49846. }
  49847. MultiDocumentPanel::~MultiDocumentPanel()
  49848. {
  49849. closeAllDocuments (false);
  49850. }
  49851. namespace MultiDocHelpers
  49852. {
  49853. bool shouldDeleteComp (Component* const c)
  49854. {
  49855. return c->getProperties() ["mdiDocumentDelete_"];
  49856. }
  49857. }
  49858. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49859. {
  49860. while (components.size() > 0)
  49861. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49862. return false;
  49863. return true;
  49864. }
  49865. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49866. {
  49867. return new MultiDocumentPanelWindow (backgroundColour);
  49868. }
  49869. void MultiDocumentPanel::addWindow (Component* component)
  49870. {
  49871. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49872. dw->setResizable (true, false);
  49873. dw->setContentComponent (component, false, true);
  49874. dw->setName (component->getName());
  49875. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49876. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49877. int x = 4;
  49878. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49879. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49880. x += 16;
  49881. dw->setTopLeftPosition (x, x);
  49882. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49883. if (pos.toString().isNotEmpty())
  49884. dw->restoreWindowStateFromString (pos.toString());
  49885. addAndMakeVisible (dw);
  49886. dw->toFront (true);
  49887. }
  49888. bool MultiDocumentPanel::addDocument (Component* const component,
  49889. const Colour& docColour,
  49890. const bool deleteWhenRemoved)
  49891. {
  49892. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49893. // with a frame-within-a-frame! Just pass in the bare content component.
  49894. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49895. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49896. return false;
  49897. components.add (component);
  49898. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49899. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49900. component->addComponentListener (this);
  49901. if (mode == FloatingWindows)
  49902. {
  49903. if (isFullscreenWhenOneDocument())
  49904. {
  49905. if (components.size() == 1)
  49906. {
  49907. addAndMakeVisible (component);
  49908. }
  49909. else
  49910. {
  49911. if (components.size() == 2)
  49912. addWindow (components.getFirst());
  49913. addWindow (component);
  49914. }
  49915. }
  49916. else
  49917. {
  49918. addWindow (component);
  49919. }
  49920. }
  49921. else
  49922. {
  49923. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49924. {
  49925. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49926. Array <Component*> temp (components);
  49927. for (int i = 0; i < temp.size(); ++i)
  49928. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49929. resized();
  49930. }
  49931. else
  49932. {
  49933. if (tabComponent != 0)
  49934. tabComponent->addTab (component->getName(), docColour, component, false);
  49935. else
  49936. addAndMakeVisible (component);
  49937. }
  49938. setActiveDocument (component);
  49939. }
  49940. resized();
  49941. activeDocumentChanged();
  49942. return true;
  49943. }
  49944. bool MultiDocumentPanel::closeDocument (Component* component,
  49945. const bool checkItsOkToCloseFirst)
  49946. {
  49947. if (components.contains (component))
  49948. {
  49949. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49950. return false;
  49951. component->removeComponentListener (this);
  49952. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  49953. component->getProperties().remove ("mdiDocumentDelete_");
  49954. component->getProperties().remove ("mdiDocumentBkg_");
  49955. if (mode == FloatingWindows)
  49956. {
  49957. for (int i = getNumChildComponents(); --i >= 0;)
  49958. {
  49959. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49960. if (dw != 0 && dw->getContentComponent() == component)
  49961. {
  49962. dw->setContentComponent (0, false);
  49963. delete dw;
  49964. break;
  49965. }
  49966. }
  49967. if (shouldDelete)
  49968. delete component;
  49969. components.removeValue (component);
  49970. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49971. {
  49972. for (int i = getNumChildComponents(); --i >= 0;)
  49973. {
  49974. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49975. if (dw != 0)
  49976. {
  49977. dw->setContentComponent (0, false);
  49978. delete dw;
  49979. }
  49980. }
  49981. addAndMakeVisible (components.getFirst());
  49982. }
  49983. }
  49984. else
  49985. {
  49986. jassert (components.indexOf (component) >= 0);
  49987. if (tabComponent != 0)
  49988. {
  49989. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49990. if (tabComponent->getTabContentComponent (i) == component)
  49991. tabComponent->removeTab (i);
  49992. }
  49993. else
  49994. {
  49995. removeChildComponent (component);
  49996. }
  49997. if (shouldDelete)
  49998. delete component;
  49999. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50000. tabComponent = 0;
  50001. components.removeValue (component);
  50002. if (components.size() > 0 && tabComponent == 0)
  50003. addAndMakeVisible (components.getFirst());
  50004. }
  50005. resized();
  50006. activeDocumentChanged();
  50007. }
  50008. else
  50009. {
  50010. jassertfalse;
  50011. }
  50012. return true;
  50013. }
  50014. int MultiDocumentPanel::getNumDocuments() const throw()
  50015. {
  50016. return components.size();
  50017. }
  50018. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50019. {
  50020. return components [index];
  50021. }
  50022. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50023. {
  50024. if (mode == FloatingWindows)
  50025. {
  50026. for (int i = getNumChildComponents(); --i >= 0;)
  50027. {
  50028. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50029. if (dw != 0 && dw->isActiveWindow())
  50030. return dw->getContentComponent();
  50031. }
  50032. }
  50033. return components.getLast();
  50034. }
  50035. void MultiDocumentPanel::setActiveDocument (Component* component)
  50036. {
  50037. if (mode == FloatingWindows)
  50038. {
  50039. component = getContainerComp (component);
  50040. if (component != 0)
  50041. component->toFront (true);
  50042. }
  50043. else if (tabComponent != 0)
  50044. {
  50045. jassert (components.indexOf (component) >= 0);
  50046. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50047. {
  50048. if (tabComponent->getTabContentComponent (i) == component)
  50049. {
  50050. tabComponent->setCurrentTabIndex (i);
  50051. break;
  50052. }
  50053. }
  50054. }
  50055. else
  50056. {
  50057. component->grabKeyboardFocus();
  50058. }
  50059. }
  50060. void MultiDocumentPanel::activeDocumentChanged()
  50061. {
  50062. }
  50063. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50064. {
  50065. maximumNumDocuments = newNumber;
  50066. }
  50067. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50068. {
  50069. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50070. }
  50071. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50072. {
  50073. return numDocsBeforeTabsUsed != 0;
  50074. }
  50075. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50076. {
  50077. if (mode != newLayoutMode)
  50078. {
  50079. mode = newLayoutMode;
  50080. if (mode == FloatingWindows)
  50081. {
  50082. tabComponent = 0;
  50083. }
  50084. else
  50085. {
  50086. for (int i = getNumChildComponents(); --i >= 0;)
  50087. {
  50088. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50089. if (dw != 0)
  50090. {
  50091. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50092. dw->setContentComponent (0, false);
  50093. delete dw;
  50094. }
  50095. }
  50096. }
  50097. resized();
  50098. const Array <Component*> tempComps (components);
  50099. components.clear();
  50100. for (int i = 0; i < tempComps.size(); ++i)
  50101. {
  50102. Component* const c = tempComps.getUnchecked(i);
  50103. addDocument (c,
  50104. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50105. MultiDocHelpers::shouldDeleteComp (c));
  50106. }
  50107. }
  50108. }
  50109. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50110. {
  50111. if (backgroundColour != newBackgroundColour)
  50112. {
  50113. backgroundColour = newBackgroundColour;
  50114. setOpaque (newBackgroundColour.isOpaque());
  50115. repaint();
  50116. }
  50117. }
  50118. void MultiDocumentPanel::paint (Graphics& g)
  50119. {
  50120. g.fillAll (backgroundColour);
  50121. }
  50122. void MultiDocumentPanel::resized()
  50123. {
  50124. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50125. {
  50126. for (int i = getNumChildComponents(); --i >= 0;)
  50127. getChildComponent (i)->setBounds (getLocalBounds());
  50128. }
  50129. setWantsKeyboardFocus (components.size() == 0);
  50130. }
  50131. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50132. {
  50133. if (mode == FloatingWindows)
  50134. {
  50135. for (int i = 0; i < getNumChildComponents(); ++i)
  50136. {
  50137. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50138. if (dw != 0 && dw->getContentComponent() == c)
  50139. {
  50140. c = dw;
  50141. break;
  50142. }
  50143. }
  50144. }
  50145. return c;
  50146. }
  50147. void MultiDocumentPanel::componentNameChanged (Component&)
  50148. {
  50149. if (mode == FloatingWindows)
  50150. {
  50151. for (int i = 0; i < getNumChildComponents(); ++i)
  50152. {
  50153. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50154. if (dw != 0)
  50155. dw->setName (dw->getContentComponent()->getName());
  50156. }
  50157. }
  50158. else if (tabComponent != 0)
  50159. {
  50160. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50161. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50162. }
  50163. }
  50164. void MultiDocumentPanel::updateOrder()
  50165. {
  50166. const Array <Component*> oldList (components);
  50167. if (mode == FloatingWindows)
  50168. {
  50169. components.clear();
  50170. for (int i = 0; i < getNumChildComponents(); ++i)
  50171. {
  50172. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50173. if (dw != 0)
  50174. components.add (dw->getContentComponent());
  50175. }
  50176. }
  50177. else
  50178. {
  50179. if (tabComponent != 0)
  50180. {
  50181. Component* const current = tabComponent->getCurrentContentComponent();
  50182. if (current != 0)
  50183. {
  50184. components.removeValue (current);
  50185. components.add (current);
  50186. }
  50187. }
  50188. }
  50189. if (components != oldList)
  50190. activeDocumentChanged();
  50191. }
  50192. END_JUCE_NAMESPACE
  50193. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50194. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50195. BEGIN_JUCE_NAMESPACE
  50196. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50197. : zone (zoneFlags)
  50198. {}
  50199. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50200. : zone (other.zone)
  50201. {}
  50202. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50203. {
  50204. zone = other.zone;
  50205. return *this;
  50206. }
  50207. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50208. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50209. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50210. const BorderSize<int>& border,
  50211. const Point<int>& position)
  50212. {
  50213. int z = 0;
  50214. if (totalSize.contains (position)
  50215. && ! border.subtractedFrom (totalSize).contains (position))
  50216. {
  50217. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50218. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50219. z |= left;
  50220. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50221. z |= right;
  50222. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50223. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50224. z |= top;
  50225. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50226. z |= bottom;
  50227. }
  50228. return Zone (z);
  50229. }
  50230. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50231. {
  50232. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50233. switch (zone)
  50234. {
  50235. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50236. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50237. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50238. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50239. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50240. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50241. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50242. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50243. default: break;
  50244. }
  50245. return mc;
  50246. }
  50247. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50248. ComponentBoundsConstrainer* const constrainer_)
  50249. : component (componentToResize),
  50250. constrainer (constrainer_),
  50251. borderSize (5),
  50252. mouseZone (0)
  50253. {
  50254. }
  50255. ResizableBorderComponent::~ResizableBorderComponent()
  50256. {
  50257. }
  50258. void ResizableBorderComponent::paint (Graphics& g)
  50259. {
  50260. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50261. }
  50262. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50263. {
  50264. updateMouseZone (e);
  50265. }
  50266. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50267. {
  50268. updateMouseZone (e);
  50269. }
  50270. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50271. {
  50272. if (component == 0)
  50273. {
  50274. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50275. return;
  50276. }
  50277. updateMouseZone (e);
  50278. originalBounds = component->getBounds();
  50279. if (constrainer != 0)
  50280. constrainer->resizeStart();
  50281. }
  50282. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50283. {
  50284. if (component == 0)
  50285. {
  50286. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50287. return;
  50288. }
  50289. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50290. if (constrainer != 0)
  50291. constrainer->setBoundsForComponent (component, bounds,
  50292. mouseZone.isDraggingTopEdge(),
  50293. mouseZone.isDraggingLeftEdge(),
  50294. mouseZone.isDraggingBottomEdge(),
  50295. mouseZone.isDraggingRightEdge());
  50296. else
  50297. component->setBounds (bounds);
  50298. }
  50299. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50300. {
  50301. if (constrainer != 0)
  50302. constrainer->resizeEnd();
  50303. }
  50304. bool ResizableBorderComponent::hitTest (int x, int y)
  50305. {
  50306. return x < borderSize.getLeft()
  50307. || x >= getWidth() - borderSize.getRight()
  50308. || y < borderSize.getTop()
  50309. || y >= getHeight() - borderSize.getBottom();
  50310. }
  50311. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50312. {
  50313. if (borderSize != newBorderSize)
  50314. {
  50315. borderSize = newBorderSize;
  50316. repaint();
  50317. }
  50318. }
  50319. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50320. {
  50321. return borderSize;
  50322. }
  50323. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50324. {
  50325. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50326. if (mouseZone != newZone)
  50327. {
  50328. mouseZone = newZone;
  50329. setMouseCursor (newZone.getMouseCursor());
  50330. }
  50331. }
  50332. END_JUCE_NAMESPACE
  50333. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50334. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50335. BEGIN_JUCE_NAMESPACE
  50336. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50337. ComponentBoundsConstrainer* const constrainer_)
  50338. : component (componentToResize),
  50339. constrainer (constrainer_)
  50340. {
  50341. setRepaintsOnMouseActivity (true);
  50342. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50343. }
  50344. ResizableCornerComponent::~ResizableCornerComponent()
  50345. {
  50346. }
  50347. void ResizableCornerComponent::paint (Graphics& g)
  50348. {
  50349. getLookAndFeel()
  50350. .drawCornerResizer (g, getWidth(), getHeight(),
  50351. isMouseOverOrDragging(),
  50352. isMouseButtonDown());
  50353. }
  50354. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50355. {
  50356. if (component == 0)
  50357. {
  50358. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50359. return;
  50360. }
  50361. originalBounds = component->getBounds();
  50362. if (constrainer != 0)
  50363. constrainer->resizeStart();
  50364. }
  50365. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50366. {
  50367. if (component == 0)
  50368. {
  50369. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50370. return;
  50371. }
  50372. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50373. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50374. if (constrainer != 0)
  50375. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50376. else
  50377. component->setBounds (r);
  50378. }
  50379. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50380. {
  50381. if (constrainer != 0)
  50382. constrainer->resizeStart();
  50383. }
  50384. bool ResizableCornerComponent::hitTest (int x, int y)
  50385. {
  50386. if (getWidth() <= 0)
  50387. return false;
  50388. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50389. return y >= yAtX - getHeight() / 4;
  50390. }
  50391. END_JUCE_NAMESPACE
  50392. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50393. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50394. BEGIN_JUCE_NAMESPACE
  50395. class ScrollBar::ScrollbarButton : public Button
  50396. {
  50397. public:
  50398. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50399. : Button (String::empty),
  50400. direction (direction_),
  50401. owner (owner_)
  50402. {
  50403. setWantsKeyboardFocus (false);
  50404. }
  50405. void paintButton (Graphics& g, bool over, bool down)
  50406. {
  50407. getLookAndFeel()
  50408. .drawScrollbarButton (g, owner,
  50409. getWidth(), getHeight(),
  50410. direction,
  50411. owner.isVertical(),
  50412. over, down);
  50413. }
  50414. void clicked()
  50415. {
  50416. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50417. }
  50418. int direction;
  50419. private:
  50420. ScrollBar& owner;
  50421. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50422. };
  50423. ScrollBar::ScrollBar (const bool vertical_,
  50424. const bool buttonsAreVisible)
  50425. : totalRange (0.0, 1.0),
  50426. visibleRange (0.0, 0.1),
  50427. singleStepSize (0.1),
  50428. thumbAreaStart (0),
  50429. thumbAreaSize (0),
  50430. thumbStart (0),
  50431. thumbSize (0),
  50432. initialDelayInMillisecs (100),
  50433. repeatDelayInMillisecs (50),
  50434. minimumDelayInMillisecs (10),
  50435. vertical (vertical_),
  50436. isDraggingThumb (false),
  50437. autohides (true)
  50438. {
  50439. setButtonVisibility (buttonsAreVisible);
  50440. setRepaintsOnMouseActivity (true);
  50441. setFocusContainer (true);
  50442. }
  50443. ScrollBar::~ScrollBar()
  50444. {
  50445. upButton = 0;
  50446. downButton = 0;
  50447. }
  50448. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50449. {
  50450. if (totalRange != newRangeLimit)
  50451. {
  50452. totalRange = newRangeLimit;
  50453. setCurrentRange (visibleRange);
  50454. updateThumbPosition();
  50455. }
  50456. }
  50457. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50458. {
  50459. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50460. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50461. }
  50462. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50463. {
  50464. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50465. if (visibleRange != constrainedRange)
  50466. {
  50467. visibleRange = constrainedRange;
  50468. updateThumbPosition();
  50469. triggerAsyncUpdate();
  50470. }
  50471. }
  50472. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50473. {
  50474. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50475. }
  50476. void ScrollBar::setCurrentRangeStart (const double newStart)
  50477. {
  50478. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50479. }
  50480. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50481. {
  50482. singleStepSize = newSingleStepSize;
  50483. }
  50484. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50485. {
  50486. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50487. }
  50488. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50489. {
  50490. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50491. }
  50492. void ScrollBar::scrollToTop()
  50493. {
  50494. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50495. }
  50496. void ScrollBar::scrollToBottom()
  50497. {
  50498. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50499. }
  50500. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50501. const int repeatDelayInMillisecs_,
  50502. const int minimumDelayInMillisecs_)
  50503. {
  50504. initialDelayInMillisecs = initialDelayInMillisecs_;
  50505. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50506. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50507. if (upButton != 0)
  50508. {
  50509. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50510. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50511. }
  50512. }
  50513. void ScrollBar::addListener (Listener* const listener)
  50514. {
  50515. listeners.add (listener);
  50516. }
  50517. void ScrollBar::removeListener (Listener* const listener)
  50518. {
  50519. listeners.remove (listener);
  50520. }
  50521. void ScrollBar::handleAsyncUpdate()
  50522. {
  50523. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50524. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50525. }
  50526. void ScrollBar::updateThumbPosition()
  50527. {
  50528. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50529. : thumbAreaSize);
  50530. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50531. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50532. if (newThumbSize > thumbAreaSize)
  50533. newThumbSize = thumbAreaSize;
  50534. int newThumbStart = thumbAreaStart;
  50535. if (totalRange.getLength() > visibleRange.getLength())
  50536. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50537. / (totalRange.getLength() - visibleRange.getLength()));
  50538. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50539. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50540. {
  50541. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50542. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50543. if (vertical)
  50544. repaint (0, repaintStart, getWidth(), repaintSize);
  50545. else
  50546. repaint (repaintStart, 0, repaintSize, getHeight());
  50547. thumbStart = newThumbStart;
  50548. thumbSize = newThumbSize;
  50549. }
  50550. }
  50551. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50552. {
  50553. if (vertical != shouldBeVertical)
  50554. {
  50555. vertical = shouldBeVertical;
  50556. if (upButton != 0)
  50557. {
  50558. upButton->direction = vertical ? 0 : 3;
  50559. downButton->direction = vertical ? 2 : 1;
  50560. }
  50561. updateThumbPosition();
  50562. }
  50563. }
  50564. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50565. {
  50566. upButton = 0;
  50567. downButton = 0;
  50568. if (buttonsAreVisible)
  50569. {
  50570. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50571. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50572. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50573. }
  50574. updateThumbPosition();
  50575. }
  50576. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50577. {
  50578. autohides = shouldHideWhenFullRange;
  50579. updateThumbPosition();
  50580. }
  50581. bool ScrollBar::autoHides() const throw()
  50582. {
  50583. return autohides;
  50584. }
  50585. void ScrollBar::paint (Graphics& g)
  50586. {
  50587. if (thumbAreaSize > 0)
  50588. {
  50589. LookAndFeel& lf = getLookAndFeel();
  50590. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50591. ? thumbSize : 0;
  50592. if (vertical)
  50593. {
  50594. lf.drawScrollbar (g, *this,
  50595. 0, thumbAreaStart,
  50596. getWidth(), thumbAreaSize,
  50597. vertical,
  50598. thumbStart, thumb,
  50599. isMouseOver(), isMouseButtonDown());
  50600. }
  50601. else
  50602. {
  50603. lf.drawScrollbar (g, *this,
  50604. thumbAreaStart, 0,
  50605. thumbAreaSize, getHeight(),
  50606. vertical,
  50607. thumbStart, thumb,
  50608. isMouseOver(), isMouseButtonDown());
  50609. }
  50610. }
  50611. }
  50612. void ScrollBar::lookAndFeelChanged()
  50613. {
  50614. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50615. }
  50616. void ScrollBar::resized()
  50617. {
  50618. const int length = ((vertical) ? getHeight() : getWidth());
  50619. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50620. : 0;
  50621. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50622. {
  50623. thumbAreaStart = length >> 1;
  50624. thumbAreaSize = 0;
  50625. }
  50626. else
  50627. {
  50628. thumbAreaStart = buttonSize;
  50629. thumbAreaSize = length - (buttonSize << 1);
  50630. }
  50631. if (upButton != 0)
  50632. {
  50633. if (vertical)
  50634. {
  50635. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50636. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50637. }
  50638. else
  50639. {
  50640. upButton->setBounds (0, 0, buttonSize, getHeight());
  50641. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50642. }
  50643. }
  50644. updateThumbPosition();
  50645. }
  50646. void ScrollBar::mouseDown (const MouseEvent& e)
  50647. {
  50648. isDraggingThumb = false;
  50649. lastMousePos = vertical ? e.y : e.x;
  50650. dragStartMousePos = lastMousePos;
  50651. dragStartRange = visibleRange.getStart();
  50652. if (dragStartMousePos < thumbStart)
  50653. {
  50654. moveScrollbarInPages (-1);
  50655. startTimer (400);
  50656. }
  50657. else if (dragStartMousePos >= thumbStart + thumbSize)
  50658. {
  50659. moveScrollbarInPages (1);
  50660. startTimer (400);
  50661. }
  50662. else
  50663. {
  50664. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50665. && (thumbAreaSize > thumbSize);
  50666. }
  50667. }
  50668. void ScrollBar::mouseDrag (const MouseEvent& e)
  50669. {
  50670. const int mousePos = vertical ? e.y : e.x;
  50671. if (isDraggingThumb && lastMousePos != mousePos)
  50672. {
  50673. const int deltaPixels = mousePos - dragStartMousePos;
  50674. setCurrentRangeStart (dragStartRange
  50675. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50676. / (thumbAreaSize - thumbSize));
  50677. }
  50678. lastMousePos = mousePos;
  50679. }
  50680. void ScrollBar::mouseUp (const MouseEvent&)
  50681. {
  50682. isDraggingThumb = false;
  50683. stopTimer();
  50684. repaint();
  50685. }
  50686. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50687. float wheelIncrementX,
  50688. float wheelIncrementY)
  50689. {
  50690. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50691. if (increment < 0)
  50692. increment = jmin (increment * 10.0f, -1.0f);
  50693. else if (increment > 0)
  50694. increment = jmax (increment * 10.0f, 1.0f);
  50695. setCurrentRange (visibleRange - singleStepSize * increment);
  50696. }
  50697. void ScrollBar::timerCallback()
  50698. {
  50699. if (isMouseButtonDown())
  50700. {
  50701. startTimer (40);
  50702. if (lastMousePos < thumbStart)
  50703. setCurrentRange (visibleRange - visibleRange.getLength());
  50704. else if (lastMousePos > thumbStart + thumbSize)
  50705. setCurrentRangeStart (visibleRange.getEnd());
  50706. }
  50707. else
  50708. {
  50709. stopTimer();
  50710. }
  50711. }
  50712. bool ScrollBar::keyPressed (const KeyPress& key)
  50713. {
  50714. if (! isVisible())
  50715. return false;
  50716. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50717. moveScrollbarInSteps (-1);
  50718. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50719. moveScrollbarInSteps (1);
  50720. else if (key.isKeyCode (KeyPress::pageUpKey))
  50721. moveScrollbarInPages (-1);
  50722. else if (key.isKeyCode (KeyPress::pageDownKey))
  50723. moveScrollbarInPages (1);
  50724. else if (key.isKeyCode (KeyPress::homeKey))
  50725. scrollToTop();
  50726. else if (key.isKeyCode (KeyPress::endKey))
  50727. scrollToBottom();
  50728. else
  50729. return false;
  50730. return true;
  50731. }
  50732. END_JUCE_NAMESPACE
  50733. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50734. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50735. BEGIN_JUCE_NAMESPACE
  50736. StretchableLayoutManager::StretchableLayoutManager()
  50737. : totalSize (0)
  50738. {
  50739. }
  50740. StretchableLayoutManager::~StretchableLayoutManager()
  50741. {
  50742. }
  50743. void StretchableLayoutManager::clearAllItems()
  50744. {
  50745. items.clear();
  50746. totalSize = 0;
  50747. }
  50748. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50749. const double minimumSize,
  50750. const double maximumSize,
  50751. const double preferredSize)
  50752. {
  50753. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50754. if (layout == 0)
  50755. {
  50756. layout = new ItemLayoutProperties();
  50757. layout->itemIndex = itemIndex;
  50758. int i;
  50759. for (i = 0; i < items.size(); ++i)
  50760. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50761. break;
  50762. items.insert (i, layout);
  50763. }
  50764. layout->minSize = minimumSize;
  50765. layout->maxSize = maximumSize;
  50766. layout->preferredSize = preferredSize;
  50767. layout->currentSize = 0;
  50768. }
  50769. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50770. double& minimumSize,
  50771. double& maximumSize,
  50772. double& preferredSize) const
  50773. {
  50774. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50775. if (layout != 0)
  50776. {
  50777. minimumSize = layout->minSize;
  50778. maximumSize = layout->maxSize;
  50779. preferredSize = layout->preferredSize;
  50780. return true;
  50781. }
  50782. return false;
  50783. }
  50784. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50785. {
  50786. totalSize = newTotalSize;
  50787. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50788. }
  50789. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50790. {
  50791. int pos = 0;
  50792. for (int i = 0; i < itemIndex; ++i)
  50793. {
  50794. const ItemLayoutProperties* const layout = getInfoFor (i);
  50795. if (layout != 0)
  50796. pos += layout->currentSize;
  50797. }
  50798. return pos;
  50799. }
  50800. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50801. {
  50802. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50803. if (layout != 0)
  50804. return layout->currentSize;
  50805. return 0;
  50806. }
  50807. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50808. {
  50809. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50810. if (layout != 0)
  50811. return -layout->currentSize / (double) totalSize;
  50812. return 0;
  50813. }
  50814. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50815. int newPosition)
  50816. {
  50817. for (int i = items.size(); --i >= 0;)
  50818. {
  50819. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50820. if (layout->itemIndex == itemIndex)
  50821. {
  50822. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50823. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50824. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50825. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50826. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50827. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50828. endPos += layout->currentSize;
  50829. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50830. updatePrefSizesToMatchCurrentPositions();
  50831. break;
  50832. }
  50833. }
  50834. }
  50835. void StretchableLayoutManager::layOutComponents (Component** const components,
  50836. int numComponents,
  50837. int x, int y, int w, int h,
  50838. const bool vertically,
  50839. const bool resizeOtherDimension)
  50840. {
  50841. setTotalSize (vertically ? h : w);
  50842. int pos = vertically ? y : x;
  50843. for (int i = 0; i < numComponents; ++i)
  50844. {
  50845. const ItemLayoutProperties* const layout = getInfoFor (i);
  50846. if (layout != 0)
  50847. {
  50848. Component* const c = components[i];
  50849. if (c != 0)
  50850. {
  50851. if (i == numComponents - 1)
  50852. {
  50853. // if it's the last item, crop it to exactly fit the available space..
  50854. if (resizeOtherDimension)
  50855. {
  50856. if (vertically)
  50857. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50858. else
  50859. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50860. }
  50861. else
  50862. {
  50863. if (vertically)
  50864. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50865. else
  50866. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50867. }
  50868. }
  50869. else
  50870. {
  50871. if (resizeOtherDimension)
  50872. {
  50873. if (vertically)
  50874. c->setBounds (x, pos, w, layout->currentSize);
  50875. else
  50876. c->setBounds (pos, y, layout->currentSize, h);
  50877. }
  50878. else
  50879. {
  50880. if (vertically)
  50881. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50882. else
  50883. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50884. }
  50885. }
  50886. }
  50887. pos += layout->currentSize;
  50888. }
  50889. }
  50890. }
  50891. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50892. {
  50893. for (int i = items.size(); --i >= 0;)
  50894. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50895. return items.getUnchecked(i);
  50896. return 0;
  50897. }
  50898. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50899. const int endIndex,
  50900. const int availableSpace,
  50901. int startPos)
  50902. {
  50903. // calculate the total sizes
  50904. int i;
  50905. double totalIdealSize = 0.0;
  50906. int totalMinimums = 0;
  50907. for (i = startIndex; i < endIndex; ++i)
  50908. {
  50909. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50910. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50911. totalMinimums += layout->currentSize;
  50912. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50913. }
  50914. if (totalIdealSize <= 0)
  50915. totalIdealSize = 1.0;
  50916. // now calc the best sizes..
  50917. int extraSpace = availableSpace - totalMinimums;
  50918. while (extraSpace > 0)
  50919. {
  50920. int numWantingMoreSpace = 0;
  50921. int numHavingTakenExtraSpace = 0;
  50922. // first figure out how many comps want a slice of the extra space..
  50923. for (i = startIndex; i < endIndex; ++i)
  50924. {
  50925. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50926. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50927. const int bestSize = jlimit (layout->currentSize,
  50928. jmax (layout->currentSize,
  50929. sizeToRealSize (layout->maxSize, totalSize)),
  50930. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50931. if (bestSize > layout->currentSize)
  50932. ++numWantingMoreSpace;
  50933. }
  50934. // ..share out the extra space..
  50935. for (i = startIndex; i < endIndex; ++i)
  50936. {
  50937. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50938. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50939. int bestSize = jlimit (layout->currentSize,
  50940. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50941. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50942. const int extraWanted = bestSize - layout->currentSize;
  50943. if (extraWanted > 0)
  50944. {
  50945. const int extraAllowed = jmin (extraWanted,
  50946. extraSpace / jmax (1, numWantingMoreSpace));
  50947. if (extraAllowed > 0)
  50948. {
  50949. ++numHavingTakenExtraSpace;
  50950. --numWantingMoreSpace;
  50951. layout->currentSize += extraAllowed;
  50952. extraSpace -= extraAllowed;
  50953. }
  50954. }
  50955. }
  50956. if (numHavingTakenExtraSpace <= 0)
  50957. break;
  50958. }
  50959. // ..and calculate the end position
  50960. for (i = startIndex; i < endIndex; ++i)
  50961. {
  50962. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50963. startPos += layout->currentSize;
  50964. }
  50965. return startPos;
  50966. }
  50967. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50968. const int endIndex) const
  50969. {
  50970. int totalMinimums = 0;
  50971. for (int i = startIndex; i < endIndex; ++i)
  50972. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50973. return totalMinimums;
  50974. }
  50975. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50976. {
  50977. int totalMaximums = 0;
  50978. for (int i = startIndex; i < endIndex; ++i)
  50979. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50980. return totalMaximums;
  50981. }
  50982. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50983. {
  50984. for (int i = 0; i < items.size(); ++i)
  50985. {
  50986. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50987. layout->preferredSize
  50988. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50989. : getItemCurrentAbsoluteSize (i);
  50990. }
  50991. }
  50992. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50993. {
  50994. if (size < 0)
  50995. size *= -totalSpace;
  50996. return roundToInt (size);
  50997. }
  50998. END_JUCE_NAMESPACE
  50999. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51000. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51001. BEGIN_JUCE_NAMESPACE
  51002. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51003. const int itemIndex_,
  51004. const bool isVertical_)
  51005. : layout (layout_),
  51006. itemIndex (itemIndex_),
  51007. isVertical (isVertical_)
  51008. {
  51009. setRepaintsOnMouseActivity (true);
  51010. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51011. : MouseCursor::UpDownResizeCursor));
  51012. }
  51013. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51014. {
  51015. }
  51016. void StretchableLayoutResizerBar::paint (Graphics& g)
  51017. {
  51018. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51019. getWidth(), getHeight(),
  51020. isVertical,
  51021. isMouseOver(),
  51022. isMouseButtonDown());
  51023. }
  51024. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51025. {
  51026. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51027. }
  51028. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51029. {
  51030. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51031. : e.getDistanceFromDragStartY());
  51032. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51033. {
  51034. layout->setItemPosition (itemIndex, desiredPos);
  51035. hasBeenMoved();
  51036. }
  51037. }
  51038. void StretchableLayoutResizerBar::hasBeenMoved()
  51039. {
  51040. if (getParentComponent() != 0)
  51041. getParentComponent()->resized();
  51042. }
  51043. END_JUCE_NAMESPACE
  51044. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51045. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51046. BEGIN_JUCE_NAMESPACE
  51047. StretchableObjectResizer::StretchableObjectResizer()
  51048. {
  51049. }
  51050. StretchableObjectResizer::~StretchableObjectResizer()
  51051. {
  51052. }
  51053. void StretchableObjectResizer::addItem (const double size,
  51054. const double minSize, const double maxSize,
  51055. const int order)
  51056. {
  51057. // the order must be >= 0 but less than the maximum integer value.
  51058. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51059. Item* const item = new Item();
  51060. item->size = size;
  51061. item->minSize = minSize;
  51062. item->maxSize = maxSize;
  51063. item->order = order;
  51064. items.add (item);
  51065. }
  51066. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51067. {
  51068. const Item* const it = items [index];
  51069. return it != 0 ? it->size : 0;
  51070. }
  51071. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51072. {
  51073. int order = 0;
  51074. for (;;)
  51075. {
  51076. double currentSize = 0;
  51077. double minSize = 0;
  51078. double maxSize = 0;
  51079. int nextHighestOrder = std::numeric_limits<int>::max();
  51080. for (int i = 0; i < items.size(); ++i)
  51081. {
  51082. const Item* const it = items.getUnchecked(i);
  51083. currentSize += it->size;
  51084. if (it->order <= order)
  51085. {
  51086. minSize += it->minSize;
  51087. maxSize += it->maxSize;
  51088. }
  51089. else
  51090. {
  51091. minSize += it->size;
  51092. maxSize += it->size;
  51093. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51094. }
  51095. }
  51096. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51097. if (thisIterationTarget >= currentSize)
  51098. {
  51099. const double availableExtraSpace = maxSize - currentSize;
  51100. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51101. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51102. for (int i = 0; i < items.size(); ++i)
  51103. {
  51104. Item* const it = items.getUnchecked(i);
  51105. if (it->order <= order)
  51106. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51107. }
  51108. }
  51109. else
  51110. {
  51111. const double amountOfSlack = currentSize - minSize;
  51112. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51113. const double scale = targetAmountOfSlack / amountOfSlack;
  51114. for (int i = 0; i < items.size(); ++i)
  51115. {
  51116. Item* const it = items.getUnchecked(i);
  51117. if (it->order <= order)
  51118. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51119. }
  51120. }
  51121. if (nextHighestOrder < std::numeric_limits<int>::max())
  51122. order = nextHighestOrder;
  51123. else
  51124. break;
  51125. }
  51126. }
  51127. END_JUCE_NAMESPACE
  51128. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51129. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51130. BEGIN_JUCE_NAMESPACE
  51131. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51132. : Button (name),
  51133. owner (owner_),
  51134. overlapPixels (0)
  51135. {
  51136. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51137. setComponentEffect (&shadow);
  51138. setWantsKeyboardFocus (false);
  51139. }
  51140. TabBarButton::~TabBarButton()
  51141. {
  51142. }
  51143. int TabBarButton::getIndex() const
  51144. {
  51145. return owner.indexOfTabButton (this);
  51146. }
  51147. void TabBarButton::paintButton (Graphics& g,
  51148. bool isMouseOverButton,
  51149. bool isButtonDown)
  51150. {
  51151. const Rectangle<int> area (getActiveArea());
  51152. g.setOrigin (area.getX(), area.getY());
  51153. getLookAndFeel()
  51154. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51155. owner.getTabBackgroundColour (getIndex()),
  51156. getIndex(), getButtonText(), *this,
  51157. owner.getOrientation(),
  51158. isMouseOverButton, isButtonDown,
  51159. getToggleState());
  51160. }
  51161. void TabBarButton::clicked (const ModifierKeys& mods)
  51162. {
  51163. if (mods.isPopupMenu())
  51164. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51165. else
  51166. owner.setCurrentTabIndex (getIndex());
  51167. }
  51168. bool TabBarButton::hitTest (int mx, int my)
  51169. {
  51170. const Rectangle<int> area (getActiveArea());
  51171. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51172. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51173. {
  51174. if (isPositiveAndBelow (mx, getWidth())
  51175. && my >= area.getY() + overlapPixels
  51176. && my < area.getBottom() - overlapPixels)
  51177. return true;
  51178. }
  51179. else
  51180. {
  51181. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51182. && isPositiveAndBelow (my, getHeight()))
  51183. return true;
  51184. }
  51185. Path p;
  51186. getLookAndFeel()
  51187. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51188. owner.getOrientation(), false, false, getToggleState());
  51189. return p.contains ((float) (mx - area.getX()),
  51190. (float) (my - area.getY()));
  51191. }
  51192. int TabBarButton::getBestTabLength (const int depth)
  51193. {
  51194. return jlimit (depth * 2,
  51195. depth * 7,
  51196. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51197. }
  51198. const Rectangle<int> TabBarButton::getActiveArea()
  51199. {
  51200. Rectangle<int> r (getLocalBounds());
  51201. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51202. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51203. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51204. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51205. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51206. return r;
  51207. }
  51208. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51209. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51210. {
  51211. public:
  51212. BehindFrontTabComp (TabbedButtonBar& owner_)
  51213. : owner (owner_)
  51214. {
  51215. setInterceptsMouseClicks (false, false);
  51216. }
  51217. void paint (Graphics& g)
  51218. {
  51219. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51220. owner, owner.getOrientation());
  51221. }
  51222. void enablementChanged()
  51223. {
  51224. repaint();
  51225. }
  51226. void buttonClicked (Button*)
  51227. {
  51228. owner.showExtraItemsMenu();
  51229. }
  51230. private:
  51231. TabbedButtonBar& owner;
  51232. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51233. };
  51234. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51235. : orientation (orientation_),
  51236. minimumScale (0.7),
  51237. currentTabIndex (-1)
  51238. {
  51239. setInterceptsMouseClicks (false, true);
  51240. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51241. setFocusContainer (true);
  51242. }
  51243. TabbedButtonBar::~TabbedButtonBar()
  51244. {
  51245. tabs.clear();
  51246. extraTabsButton = 0;
  51247. }
  51248. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51249. {
  51250. orientation = newOrientation;
  51251. for (int i = getNumChildComponents(); --i >= 0;)
  51252. getChildComponent (i)->resized();
  51253. resized();
  51254. }
  51255. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51256. {
  51257. return new TabBarButton (name, *this);
  51258. }
  51259. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51260. {
  51261. minimumScale = newMinimumScale;
  51262. resized();
  51263. }
  51264. void TabbedButtonBar::clearTabs()
  51265. {
  51266. tabs.clear();
  51267. extraTabsButton = 0;
  51268. setCurrentTabIndex (-1);
  51269. }
  51270. void TabbedButtonBar::addTab (const String& tabName,
  51271. const Colour& tabBackgroundColour,
  51272. int insertIndex)
  51273. {
  51274. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51275. if (tabName.isNotEmpty())
  51276. {
  51277. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51278. insertIndex = tabs.size();
  51279. TabInfo* newTab = new TabInfo();
  51280. newTab->name = tabName;
  51281. newTab->colour = tabBackgroundColour;
  51282. newTab->component = createTabButton (tabName, insertIndex);
  51283. jassert (newTab->component != 0);
  51284. tabs.insert (insertIndex, newTab);
  51285. addAndMakeVisible (newTab->component, insertIndex);
  51286. resized();
  51287. if (currentTabIndex < 0)
  51288. setCurrentTabIndex (0);
  51289. }
  51290. }
  51291. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51292. {
  51293. TabInfo* const tab = tabs [tabIndex];
  51294. if (tab != 0 && tab->name != newName)
  51295. {
  51296. tab->name = newName;
  51297. tab->component->setButtonText (newName);
  51298. resized();
  51299. }
  51300. }
  51301. void TabbedButtonBar::removeTab (const int tabIndex)
  51302. {
  51303. if (tabs [tabIndex] != 0)
  51304. {
  51305. const int oldTabIndex = currentTabIndex;
  51306. if (currentTabIndex == tabIndex)
  51307. currentTabIndex = -1;
  51308. tabs.remove (tabIndex);
  51309. resized();
  51310. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51311. }
  51312. }
  51313. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51314. {
  51315. tabs.move (currentIndex, newIndex);
  51316. resized();
  51317. }
  51318. int TabbedButtonBar::getNumTabs() const
  51319. {
  51320. return tabs.size();
  51321. }
  51322. const String TabbedButtonBar::getCurrentTabName() const
  51323. {
  51324. TabInfo* tab = tabs [currentTabIndex];
  51325. return tab == 0 ? String::empty : tab->name;
  51326. }
  51327. const StringArray TabbedButtonBar::getTabNames() const
  51328. {
  51329. StringArray names;
  51330. for (int i = 0; i < tabs.size(); ++i)
  51331. names.add (tabs.getUnchecked(i)->name);
  51332. return names;
  51333. }
  51334. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51335. {
  51336. if (currentTabIndex != newIndex)
  51337. {
  51338. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51339. newIndex = -1;
  51340. currentTabIndex = newIndex;
  51341. for (int i = 0; i < tabs.size(); ++i)
  51342. {
  51343. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51344. tb->setToggleState (i == newIndex, false);
  51345. }
  51346. resized();
  51347. if (sendChangeMessage_)
  51348. sendChangeMessage();
  51349. currentTabChanged (newIndex, getCurrentTabName());
  51350. }
  51351. }
  51352. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51353. {
  51354. TabInfo* const tab = tabs[index];
  51355. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51356. }
  51357. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51358. {
  51359. for (int i = tabs.size(); --i >= 0;)
  51360. if (tabs.getUnchecked(i)->component == button)
  51361. return i;
  51362. return -1;
  51363. }
  51364. void TabbedButtonBar::lookAndFeelChanged()
  51365. {
  51366. extraTabsButton = 0;
  51367. resized();
  51368. }
  51369. void TabbedButtonBar::resized()
  51370. {
  51371. int depth = getWidth();
  51372. int length = getHeight();
  51373. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51374. swapVariables (depth, length);
  51375. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51376. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51377. int i, totalLength = overlap;
  51378. int numVisibleButtons = tabs.size();
  51379. for (i = 0; i < tabs.size(); ++i)
  51380. {
  51381. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51382. totalLength += tb->getBestTabLength (depth) - overlap;
  51383. tb->overlapPixels = overlap / 2;
  51384. }
  51385. double scale = 1.0;
  51386. if (totalLength > length)
  51387. scale = jmax (minimumScale, length / (double) totalLength);
  51388. const bool isTooBig = totalLength * scale > length;
  51389. int tabsButtonPos = 0;
  51390. if (isTooBig)
  51391. {
  51392. if (extraTabsButton == 0)
  51393. {
  51394. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51395. extraTabsButton->addListener (behindFrontTab);
  51396. extraTabsButton->setAlwaysOnTop (true);
  51397. extraTabsButton->setTriggeredOnMouseDown (true);
  51398. }
  51399. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51400. extraTabsButton->setSize (buttonSize, buttonSize);
  51401. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51402. {
  51403. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51404. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51405. }
  51406. else
  51407. {
  51408. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51409. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51410. }
  51411. totalLength = 0;
  51412. for (i = 0; i < tabs.size(); ++i)
  51413. {
  51414. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51415. const int newLength = totalLength + tb->getBestTabLength (depth);
  51416. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51417. {
  51418. totalLength += overlap;
  51419. break;
  51420. }
  51421. numVisibleButtons = i + 1;
  51422. totalLength = newLength - overlap;
  51423. }
  51424. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51425. }
  51426. else
  51427. {
  51428. extraTabsButton = 0;
  51429. }
  51430. int pos = 0;
  51431. TabBarButton* frontTab = 0;
  51432. for (i = 0; i < tabs.size(); ++i)
  51433. {
  51434. TabBarButton* const tb = getTabButton (i);
  51435. if (tb != 0)
  51436. {
  51437. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51438. if (i < numVisibleButtons)
  51439. {
  51440. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51441. tb->setBounds (pos, 0, bestLength, getHeight());
  51442. else
  51443. tb->setBounds (0, pos, getWidth(), bestLength);
  51444. tb->toBack();
  51445. if (i == currentTabIndex)
  51446. frontTab = tb;
  51447. tb->setVisible (true);
  51448. }
  51449. else
  51450. {
  51451. tb->setVisible (false);
  51452. }
  51453. pos += bestLength - overlap;
  51454. }
  51455. }
  51456. behindFrontTab->setBounds (getLocalBounds());
  51457. if (frontTab != 0)
  51458. {
  51459. frontTab->toFront (false);
  51460. behindFrontTab->toBehind (frontTab);
  51461. }
  51462. }
  51463. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51464. {
  51465. TabInfo* const tab = tabs [tabIndex];
  51466. return tab == 0 ? Colours::white : tab->colour;
  51467. }
  51468. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51469. {
  51470. TabInfo* const tab = tabs [tabIndex];
  51471. if (tab != 0 && tab->colour != newColour)
  51472. {
  51473. tab->colour = newColour;
  51474. repaint();
  51475. }
  51476. }
  51477. void TabbedButtonBar::showExtraItemsMenu()
  51478. {
  51479. PopupMenu m;
  51480. for (int i = 0; i < tabs.size(); ++i)
  51481. {
  51482. const TabInfo* const tab = tabs.getUnchecked(i);
  51483. if (! tab->component->isVisible())
  51484. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51485. }
  51486. const int res = m.showAt (extraTabsButton);
  51487. if (res != 0)
  51488. setCurrentTabIndex (res - 1);
  51489. }
  51490. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51491. {
  51492. }
  51493. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51494. {
  51495. }
  51496. END_JUCE_NAMESPACE
  51497. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51498. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51499. BEGIN_JUCE_NAMESPACE
  51500. namespace TabbedComponentHelpers
  51501. {
  51502. const Identifier deleteComponentId ("deleteByTabComp_");
  51503. void deleteIfNecessary (Component* const comp)
  51504. {
  51505. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51506. delete comp;
  51507. }
  51508. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51509. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51510. {
  51511. switch (orientation)
  51512. {
  51513. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51514. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51515. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51516. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51517. default: jassertfalse; break;
  51518. }
  51519. return Rectangle<int>();
  51520. }
  51521. }
  51522. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51523. {
  51524. public:
  51525. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51526. : TabbedButtonBar (orientation_),
  51527. owner (owner_)
  51528. {
  51529. }
  51530. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51531. {
  51532. owner.changeCallback (newCurrentTabIndex, newTabName);
  51533. }
  51534. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51535. {
  51536. owner.popupMenuClickOnTab (tabIndex, tabName);
  51537. }
  51538. const Colour getTabBackgroundColour (const int tabIndex)
  51539. {
  51540. return owner.tabs->getTabBackgroundColour (tabIndex);
  51541. }
  51542. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51543. {
  51544. return owner.createTabButton (tabName, tabIndex);
  51545. }
  51546. private:
  51547. TabbedComponent& owner;
  51548. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51549. };
  51550. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51551. : tabDepth (30),
  51552. outlineThickness (1),
  51553. edgeIndent (0)
  51554. {
  51555. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51556. }
  51557. TabbedComponent::~TabbedComponent()
  51558. {
  51559. clearTabs();
  51560. tabs = 0;
  51561. }
  51562. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51563. {
  51564. tabs->setOrientation (orientation);
  51565. resized();
  51566. }
  51567. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51568. {
  51569. return tabs->getOrientation();
  51570. }
  51571. void TabbedComponent::setTabBarDepth (const int newDepth)
  51572. {
  51573. if (tabDepth != newDepth)
  51574. {
  51575. tabDepth = newDepth;
  51576. resized();
  51577. }
  51578. }
  51579. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51580. {
  51581. return new TabBarButton (tabName, *tabs);
  51582. }
  51583. void TabbedComponent::clearTabs()
  51584. {
  51585. if (panelComponent != 0)
  51586. {
  51587. panelComponent->setVisible (false);
  51588. removeChildComponent (panelComponent);
  51589. panelComponent = 0;
  51590. }
  51591. tabs->clearTabs();
  51592. for (int i = contentComponents.size(); --i >= 0;)
  51593. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51594. contentComponents.clear();
  51595. }
  51596. void TabbedComponent::addTab (const String& tabName,
  51597. const Colour& tabBackgroundColour,
  51598. Component* const contentComponent,
  51599. const bool deleteComponentWhenNotNeeded,
  51600. const int insertIndex)
  51601. {
  51602. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51603. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51604. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51605. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51606. }
  51607. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51608. {
  51609. tabs->setTabName (tabIndex, newName);
  51610. }
  51611. void TabbedComponent::removeTab (const int tabIndex)
  51612. {
  51613. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51614. {
  51615. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51616. contentComponents.remove (tabIndex);
  51617. tabs->removeTab (tabIndex);
  51618. }
  51619. }
  51620. int TabbedComponent::getNumTabs() const
  51621. {
  51622. return tabs->getNumTabs();
  51623. }
  51624. const StringArray TabbedComponent::getTabNames() const
  51625. {
  51626. return tabs->getTabNames();
  51627. }
  51628. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51629. {
  51630. return contentComponents [tabIndex];
  51631. }
  51632. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51633. {
  51634. return tabs->getTabBackgroundColour (tabIndex);
  51635. }
  51636. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51637. {
  51638. tabs->setTabBackgroundColour (tabIndex, newColour);
  51639. if (getCurrentTabIndex() == tabIndex)
  51640. repaint();
  51641. }
  51642. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51643. {
  51644. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51645. }
  51646. int TabbedComponent::getCurrentTabIndex() const
  51647. {
  51648. return tabs->getCurrentTabIndex();
  51649. }
  51650. const String TabbedComponent::getCurrentTabName() const
  51651. {
  51652. return tabs->getCurrentTabName();
  51653. }
  51654. void TabbedComponent::setOutline (const int thickness)
  51655. {
  51656. outlineThickness = thickness;
  51657. resized();
  51658. repaint();
  51659. }
  51660. void TabbedComponent::setIndent (const int indentThickness)
  51661. {
  51662. edgeIndent = indentThickness;
  51663. resized();
  51664. repaint();
  51665. }
  51666. void TabbedComponent::paint (Graphics& g)
  51667. {
  51668. g.fillAll (findColour (backgroundColourId));
  51669. Rectangle<int> content (getLocalBounds());
  51670. BorderSize<int> outline (outlineThickness);
  51671. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51672. g.reduceClipRegion (content);
  51673. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51674. if (outlineThickness > 0)
  51675. {
  51676. RectangleList rl (content);
  51677. rl.subtract (outline.subtractedFrom (content));
  51678. g.reduceClipRegion (rl);
  51679. g.fillAll (findColour (outlineColourId));
  51680. }
  51681. }
  51682. void TabbedComponent::resized()
  51683. {
  51684. Rectangle<int> content (getLocalBounds());
  51685. BorderSize<int> outline (outlineThickness);
  51686. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51687. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51688. for (int i = contentComponents.size(); --i >= 0;)
  51689. if (contentComponents.getReference (i) != 0)
  51690. contentComponents.getReference (i)->setBounds (content);
  51691. }
  51692. void TabbedComponent::lookAndFeelChanged()
  51693. {
  51694. for (int i = contentComponents.size(); --i >= 0;)
  51695. if (contentComponents.getReference (i) != 0)
  51696. contentComponents.getReference (i)->lookAndFeelChanged();
  51697. }
  51698. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51699. {
  51700. if (panelComponent != 0)
  51701. {
  51702. panelComponent->setVisible (false);
  51703. removeChildComponent (panelComponent);
  51704. panelComponent = 0;
  51705. }
  51706. if (getCurrentTabIndex() >= 0)
  51707. {
  51708. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51709. if (panelComponent != 0)
  51710. {
  51711. // do these ops as two stages instead of addAndMakeVisible() so that the
  51712. // component has always got a parent when it gets the visibilityChanged() callback
  51713. addChildComponent (panelComponent);
  51714. panelComponent->setVisible (true);
  51715. panelComponent->toFront (true);
  51716. }
  51717. repaint();
  51718. }
  51719. resized();
  51720. currentTabChanged (newCurrentTabIndex, newTabName);
  51721. }
  51722. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51723. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51724. END_JUCE_NAMESPACE
  51725. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51726. /*** Start of inlined file: juce_Viewport.cpp ***/
  51727. BEGIN_JUCE_NAMESPACE
  51728. Viewport::Viewport (const String& componentName)
  51729. : Component (componentName),
  51730. scrollBarThickness (0),
  51731. singleStepX (16),
  51732. singleStepY (16),
  51733. showHScrollbar (true),
  51734. showVScrollbar (true),
  51735. verticalScrollBar (true),
  51736. horizontalScrollBar (false)
  51737. {
  51738. // content holder is used to clip the contents so they don't overlap the scrollbars
  51739. addAndMakeVisible (&contentHolder);
  51740. contentHolder.setInterceptsMouseClicks (false, true);
  51741. addChildComponent (&verticalScrollBar);
  51742. addChildComponent (&horizontalScrollBar);
  51743. verticalScrollBar.addListener (this);
  51744. horizontalScrollBar.addListener (this);
  51745. setInterceptsMouseClicks (false, true);
  51746. setWantsKeyboardFocus (true);
  51747. }
  51748. Viewport::~Viewport()
  51749. {
  51750. deleteContentComp();
  51751. }
  51752. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51753. {
  51754. }
  51755. void Viewport::deleteContentComp()
  51756. {
  51757. // This sets the content comp to a null pointer before deleting the old one, in case
  51758. // anything tries to use the old one while it's in mid-deletion..
  51759. ScopedPointer<Component> oldCompDeleter (contentComp);
  51760. contentComp = 0;
  51761. }
  51762. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51763. {
  51764. if (contentComp.get() != newViewedComponent)
  51765. {
  51766. deleteContentComp();
  51767. contentComp = newViewedComponent;
  51768. if (contentComp != 0)
  51769. {
  51770. contentHolder.addAndMakeVisible (contentComp);
  51771. setViewPosition (0, 0);
  51772. contentComp->addComponentListener (this);
  51773. }
  51774. updateVisibleArea();
  51775. }
  51776. }
  51777. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51778. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51779. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51780. {
  51781. if (contentComp != 0)
  51782. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51783. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51784. }
  51785. void Viewport::setViewPosition (const Point<int>& newPosition)
  51786. {
  51787. setViewPosition (newPosition.getX(), newPosition.getY());
  51788. }
  51789. void Viewport::setViewPositionProportionately (const double x, const double y)
  51790. {
  51791. if (contentComp != 0)
  51792. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51793. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51794. }
  51795. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51796. {
  51797. if (contentComp != 0)
  51798. {
  51799. int dx = 0, dy = 0;
  51800. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51801. {
  51802. if (mouseX < activeBorderThickness)
  51803. dx = activeBorderThickness - mouseX;
  51804. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51805. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51806. if (dx < 0)
  51807. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51808. else
  51809. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51810. }
  51811. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51812. {
  51813. if (mouseY < activeBorderThickness)
  51814. dy = activeBorderThickness - mouseY;
  51815. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51816. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51817. if (dy < 0)
  51818. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51819. else
  51820. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51821. }
  51822. if (dx != 0 || dy != 0)
  51823. {
  51824. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51825. contentComp->getY() + dy);
  51826. return true;
  51827. }
  51828. }
  51829. return false;
  51830. }
  51831. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51832. {
  51833. updateVisibleArea();
  51834. }
  51835. void Viewport::resized()
  51836. {
  51837. updateVisibleArea();
  51838. }
  51839. void Viewport::updateVisibleArea()
  51840. {
  51841. const int scrollbarWidth = getScrollBarThickness();
  51842. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51843. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51844. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51845. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51846. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51847. Rectangle<int> contentArea (getLocalBounds());
  51848. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51849. {
  51850. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51851. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51852. if (vBarVisible)
  51853. contentArea.setWidth (getWidth() - scrollbarWidth);
  51854. if (hBarVisible)
  51855. contentArea.setHeight (getHeight() - scrollbarWidth);
  51856. if (! contentArea.contains (contentComp->getBounds()))
  51857. {
  51858. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51859. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51860. }
  51861. }
  51862. if (vBarVisible)
  51863. contentArea.setWidth (getWidth() - scrollbarWidth);
  51864. if (hBarVisible)
  51865. contentArea.setHeight (getHeight() - scrollbarWidth);
  51866. contentHolder.setBounds (contentArea);
  51867. Rectangle<int> contentBounds;
  51868. if (contentComp != 0)
  51869. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  51870. Point<int> visibleOrigin (-contentBounds.getPosition());
  51871. if (hBarVisible)
  51872. {
  51873. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51874. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51875. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51876. horizontalScrollBar.setSingleStepSize (singleStepX);
  51877. horizontalScrollBar.cancelPendingUpdate();
  51878. }
  51879. else if (canShowHBar)
  51880. {
  51881. visibleOrigin.setX (0);
  51882. }
  51883. if (vBarVisible)
  51884. {
  51885. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51886. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51887. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51888. verticalScrollBar.setSingleStepSize (singleStepY);
  51889. verticalScrollBar.cancelPendingUpdate();
  51890. }
  51891. else if (canShowVBar)
  51892. {
  51893. visibleOrigin.setY (0);
  51894. }
  51895. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51896. horizontalScrollBar.setVisible (hBarVisible);
  51897. verticalScrollBar.setVisible (vBarVisible);
  51898. setViewPosition (visibleOrigin);
  51899. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51900. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51901. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51902. if (lastVisibleArea != visibleArea)
  51903. {
  51904. lastVisibleArea = visibleArea;
  51905. visibleAreaChanged (visibleArea);
  51906. }
  51907. horizontalScrollBar.handleUpdateNowIfNeeded();
  51908. verticalScrollBar.handleUpdateNowIfNeeded();
  51909. }
  51910. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51911. {
  51912. if (singleStepX != stepX || singleStepY != stepY)
  51913. {
  51914. singleStepX = stepX;
  51915. singleStepY = stepY;
  51916. updateVisibleArea();
  51917. }
  51918. }
  51919. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51920. const bool showHorizontalScrollbarIfNeeded)
  51921. {
  51922. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51923. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51924. {
  51925. showVScrollbar = showVerticalScrollbarIfNeeded;
  51926. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51927. updateVisibleArea();
  51928. }
  51929. }
  51930. void Viewport::setScrollBarThickness (const int thickness)
  51931. {
  51932. if (scrollBarThickness != thickness)
  51933. {
  51934. scrollBarThickness = thickness;
  51935. updateVisibleArea();
  51936. }
  51937. }
  51938. int Viewport::getScrollBarThickness() const
  51939. {
  51940. return scrollBarThickness > 0 ? scrollBarThickness
  51941. : getLookAndFeel().getDefaultScrollbarWidth();
  51942. }
  51943. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51944. {
  51945. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51946. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51947. }
  51948. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51949. {
  51950. const int newRangeStartInt = roundToInt (newRangeStart);
  51951. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51952. {
  51953. setViewPosition (newRangeStartInt, getViewPositionY());
  51954. }
  51955. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51956. {
  51957. setViewPosition (getViewPositionX(), newRangeStartInt);
  51958. }
  51959. }
  51960. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51961. {
  51962. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51963. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51964. }
  51965. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51966. {
  51967. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51968. {
  51969. const bool hasVertBar = verticalScrollBar.isVisible();
  51970. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51971. if (hasHorzBar || hasVertBar)
  51972. {
  51973. if (wheelIncrementX != 0)
  51974. {
  51975. wheelIncrementX *= 14.0f * singleStepX;
  51976. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51977. : jmax (wheelIncrementX, 1.0f);
  51978. }
  51979. if (wheelIncrementY != 0)
  51980. {
  51981. wheelIncrementY *= 14.0f * singleStepY;
  51982. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51983. : jmax (wheelIncrementY, 1.0f);
  51984. }
  51985. Point<int> pos (getViewPosition());
  51986. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51987. {
  51988. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51989. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51990. }
  51991. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51992. {
  51993. if (wheelIncrementX == 0 && ! hasVertBar)
  51994. wheelIncrementX = wheelIncrementY;
  51995. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51996. }
  51997. else if (hasVertBar && wheelIncrementY != 0)
  51998. {
  51999. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52000. }
  52001. if (pos != getViewPosition())
  52002. {
  52003. setViewPosition (pos);
  52004. return true;
  52005. }
  52006. }
  52007. }
  52008. return false;
  52009. }
  52010. bool Viewport::keyPressed (const KeyPress& key)
  52011. {
  52012. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52013. || key.isKeyCode (KeyPress::downKey)
  52014. || key.isKeyCode (KeyPress::pageUpKey)
  52015. || key.isKeyCode (KeyPress::pageDownKey)
  52016. || key.isKeyCode (KeyPress::homeKey)
  52017. || key.isKeyCode (KeyPress::endKey);
  52018. if (verticalScrollBar.isVisible() && isUpDownKey)
  52019. return verticalScrollBar.keyPressed (key);
  52020. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52021. || key.isKeyCode (KeyPress::rightKey);
  52022. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52023. return horizontalScrollBar.keyPressed (key);
  52024. return false;
  52025. }
  52026. END_JUCE_NAMESPACE
  52027. /*** End of inlined file: juce_Viewport.cpp ***/
  52028. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52029. BEGIN_JUCE_NAMESPACE
  52030. namespace LookAndFeelHelpers
  52031. {
  52032. void createRoundedPath (Path& p,
  52033. const float x, const float y,
  52034. const float w, const float h,
  52035. const float cs,
  52036. const bool curveTopLeft, const bool curveTopRight,
  52037. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52038. {
  52039. const float cs2 = 2.0f * cs;
  52040. if (curveTopLeft)
  52041. {
  52042. p.startNewSubPath (x, y + cs);
  52043. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52044. }
  52045. else
  52046. {
  52047. p.startNewSubPath (x, y);
  52048. }
  52049. if (curveTopRight)
  52050. {
  52051. p.lineTo (x + w - cs, y);
  52052. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52053. }
  52054. else
  52055. {
  52056. p.lineTo (x + w, y);
  52057. }
  52058. if (curveBottomRight)
  52059. {
  52060. p.lineTo (x + w, y + h - cs);
  52061. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52062. }
  52063. else
  52064. {
  52065. p.lineTo (x + w, y + h);
  52066. }
  52067. if (curveBottomLeft)
  52068. {
  52069. p.lineTo (x + cs, y + h);
  52070. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52071. }
  52072. else
  52073. {
  52074. p.lineTo (x, y + h);
  52075. }
  52076. p.closeSubPath();
  52077. }
  52078. const Colour createBaseColour (const Colour& buttonColour,
  52079. const bool hasKeyboardFocus,
  52080. const bool isMouseOverButton,
  52081. const bool isButtonDown) throw()
  52082. {
  52083. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52084. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52085. if (isButtonDown)
  52086. return baseColour.contrasting (0.2f);
  52087. else if (isMouseOverButton)
  52088. return baseColour.contrasting (0.1f);
  52089. return baseColour;
  52090. }
  52091. const TextLayout layoutTooltipText (const String& text) throw()
  52092. {
  52093. const float tooltipFontSize = 12.0f;
  52094. const int maxToolTipWidth = 400;
  52095. const Font f (tooltipFontSize, Font::bold);
  52096. TextLayout tl (text, f);
  52097. tl.layout (maxToolTipWidth, Justification::left, true);
  52098. return tl;
  52099. }
  52100. LookAndFeel* defaultLF = 0;
  52101. LookAndFeel* currentDefaultLF = 0;
  52102. }
  52103. LookAndFeel::LookAndFeel()
  52104. {
  52105. /* if this fails it means you're trying to create a LookAndFeel object before
  52106. the static Colours have been initialised. That ain't gonna work. It probably
  52107. means that you're using a static LookAndFeel object and that your compiler has
  52108. decided to intialise it before the Colours class.
  52109. */
  52110. jassert (Colours::white == Colour (0xffffffff));
  52111. // set up the standard set of colours..
  52112. const int textButtonColour = 0xffbbbbff;
  52113. const int textHighlightColour = 0x401111ee;
  52114. const int standardOutlineColour = 0xb2808080;
  52115. static const int standardColours[] =
  52116. {
  52117. TextButton::buttonColourId, textButtonColour,
  52118. TextButton::buttonOnColourId, 0xff4444ff,
  52119. TextButton::textColourOnId, 0xff000000,
  52120. TextButton::textColourOffId, 0xff000000,
  52121. ComboBox::buttonColourId, 0xffbbbbff,
  52122. ComboBox::outlineColourId, standardOutlineColour,
  52123. ToggleButton::textColourId, 0xff000000,
  52124. TextEditor::backgroundColourId, 0xffffffff,
  52125. TextEditor::textColourId, 0xff000000,
  52126. TextEditor::highlightColourId, textHighlightColour,
  52127. TextEditor::highlightedTextColourId, 0xff000000,
  52128. TextEditor::caretColourId, 0xff000000,
  52129. TextEditor::outlineColourId, 0x00000000,
  52130. TextEditor::focusedOutlineColourId, textButtonColour,
  52131. TextEditor::shadowColourId, 0x38000000,
  52132. Label::backgroundColourId, 0x00000000,
  52133. Label::textColourId, 0xff000000,
  52134. Label::outlineColourId, 0x00000000,
  52135. ScrollBar::backgroundColourId, 0x00000000,
  52136. ScrollBar::thumbColourId, 0xffffffff,
  52137. TreeView::linesColourId, 0x4c000000,
  52138. TreeView::backgroundColourId, 0x00000000,
  52139. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52140. PopupMenu::backgroundColourId, 0xffffffff,
  52141. PopupMenu::textColourId, 0xff000000,
  52142. PopupMenu::headerTextColourId, 0xff000000,
  52143. PopupMenu::highlightedTextColourId, 0xffffffff,
  52144. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52145. ComboBox::textColourId, 0xff000000,
  52146. ComboBox::backgroundColourId, 0xffffffff,
  52147. ComboBox::arrowColourId, 0x99000000,
  52148. ListBox::backgroundColourId, 0xffffffff,
  52149. ListBox::outlineColourId, standardOutlineColour,
  52150. ListBox::textColourId, 0xff000000,
  52151. Slider::backgroundColourId, 0x00000000,
  52152. Slider::thumbColourId, textButtonColour,
  52153. Slider::trackColourId, 0x7fffffff,
  52154. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52155. Slider::rotarySliderOutlineColourId, 0x66000000,
  52156. Slider::textBoxTextColourId, 0xff000000,
  52157. Slider::textBoxBackgroundColourId, 0xffffffff,
  52158. Slider::textBoxHighlightColourId, textHighlightColour,
  52159. Slider::textBoxOutlineColourId, standardOutlineColour,
  52160. ResizableWindow::backgroundColourId, 0xff777777,
  52161. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52162. AlertWindow::backgroundColourId, 0xffededed,
  52163. AlertWindow::textColourId, 0xff000000,
  52164. AlertWindow::outlineColourId, 0xff666666,
  52165. ProgressBar::backgroundColourId, 0xffeeeeee,
  52166. ProgressBar::foregroundColourId, 0xffaaaaee,
  52167. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52168. TooltipWindow::textColourId, 0xff000000,
  52169. TooltipWindow::outlineColourId, 0x4c000000,
  52170. TabbedComponent::backgroundColourId, 0x00000000,
  52171. TabbedComponent::outlineColourId, 0xff777777,
  52172. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52173. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52174. Toolbar::backgroundColourId, 0xfff6f8f9,
  52175. Toolbar::separatorColourId, 0x4c000000,
  52176. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52177. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52178. Toolbar::labelTextColourId, 0xff000000,
  52179. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52180. HyperlinkButton::textColourId, 0xcc1111ee,
  52181. GroupComponent::outlineColourId, 0x66000000,
  52182. GroupComponent::textColourId, 0xff000000,
  52183. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52184. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52185. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52186. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52187. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52188. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52189. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52190. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52191. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52192. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52193. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52194. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52195. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52196. CodeEditorComponent::caretColourId, 0xff000000,
  52197. CodeEditorComponent::highlightColourId, textHighlightColour,
  52198. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52199. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52200. ColourSelector::labelTextColourId, 0xff000000,
  52201. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52202. KeyMappingEditorComponent::textColourId, 0xff000000,
  52203. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52204. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52205. DrawableButton::textColourId, 0xff000000,
  52206. };
  52207. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52208. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52209. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52210. if (defaultSansName.isEmpty())
  52211. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52212. defaultSans = defaultSansName;
  52213. defaultSerif = defaultSerifName;
  52214. defaultFixed = defaultFixedName;
  52215. Font::setFallbackFontName (defaultFallback);
  52216. }
  52217. LookAndFeel::~LookAndFeel()
  52218. {
  52219. if (this == LookAndFeelHelpers::currentDefaultLF)
  52220. setDefaultLookAndFeel (0);
  52221. }
  52222. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52223. {
  52224. const int index = colourIds.indexOf (colourId);
  52225. if (index >= 0)
  52226. return colours [index];
  52227. jassertfalse;
  52228. return Colours::black;
  52229. }
  52230. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52231. {
  52232. const int index = colourIds.indexOf (colourId);
  52233. if (index >= 0)
  52234. {
  52235. colours.set (index, colour);
  52236. }
  52237. else
  52238. {
  52239. colourIds.add (colourId);
  52240. colours.add (colour);
  52241. }
  52242. }
  52243. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52244. {
  52245. return colourIds.contains (colourId);
  52246. }
  52247. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52248. {
  52249. // if this happens, your app hasn't initialised itself properly.. if you're
  52250. // trying to hack your own main() function, have a look at
  52251. // JUCEApplication::initialiseForGUI()
  52252. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52253. return *LookAndFeelHelpers::currentDefaultLF;
  52254. }
  52255. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52256. {
  52257. using namespace LookAndFeelHelpers;
  52258. if (newDefaultLookAndFeel == 0)
  52259. {
  52260. if (defaultLF == 0)
  52261. defaultLF = new LookAndFeel();
  52262. newDefaultLookAndFeel = defaultLF;
  52263. }
  52264. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52265. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52266. {
  52267. Component* const c = Desktop::getInstance().getComponent (i);
  52268. if (c != 0)
  52269. c->sendLookAndFeelChange();
  52270. }
  52271. }
  52272. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52273. {
  52274. using namespace LookAndFeelHelpers;
  52275. if (currentDefaultLF == defaultLF)
  52276. currentDefaultLF = 0;
  52277. deleteAndZero (defaultLF);
  52278. }
  52279. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52280. {
  52281. String faceName (font.getTypefaceName());
  52282. if (faceName == Font::getDefaultSansSerifFontName())
  52283. faceName = defaultSans;
  52284. else if (faceName == Font::getDefaultSerifFontName())
  52285. faceName = defaultSerif;
  52286. else if (faceName == Font::getDefaultMonospacedFontName())
  52287. faceName = defaultFixed;
  52288. Font f (font);
  52289. f.setTypefaceName (faceName);
  52290. return Typeface::createSystemTypefaceFor (f);
  52291. }
  52292. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52293. {
  52294. defaultSans = newName;
  52295. }
  52296. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52297. {
  52298. return component.getMouseCursor();
  52299. }
  52300. void LookAndFeel::drawButtonBackground (Graphics& g,
  52301. Button& button,
  52302. const Colour& backgroundColour,
  52303. bool isMouseOverButton,
  52304. bool isButtonDown)
  52305. {
  52306. const int width = button.getWidth();
  52307. const int height = button.getHeight();
  52308. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52309. const float halfThickness = outlineThickness * 0.5f;
  52310. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52311. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52312. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52313. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52314. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52315. button.hasKeyboardFocus (true),
  52316. isMouseOverButton, isButtonDown)
  52317. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52318. drawGlassLozenge (g,
  52319. indentL,
  52320. indentT,
  52321. width - indentL - indentR,
  52322. height - indentT - indentB,
  52323. baseColour, outlineThickness, -1.0f,
  52324. button.isConnectedOnLeft(),
  52325. button.isConnectedOnRight(),
  52326. button.isConnectedOnTop(),
  52327. button.isConnectedOnBottom());
  52328. }
  52329. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52330. {
  52331. return button.getFont();
  52332. }
  52333. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52334. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52335. {
  52336. Font font (getFontForTextButton (button));
  52337. g.setFont (font);
  52338. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52339. : TextButton::textColourOffId)
  52340. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52341. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52342. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52343. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52344. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52345. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52346. g.drawFittedText (button.getButtonText(),
  52347. leftIndent,
  52348. yIndent,
  52349. button.getWidth() - leftIndent - rightIndent,
  52350. button.getHeight() - yIndent * 2,
  52351. Justification::centred, 2);
  52352. }
  52353. void LookAndFeel::drawTickBox (Graphics& g,
  52354. Component& component,
  52355. float x, float y, float w, float h,
  52356. const bool ticked,
  52357. const bool isEnabled,
  52358. const bool isMouseOverButton,
  52359. const bool isButtonDown)
  52360. {
  52361. const float boxSize = w * 0.7f;
  52362. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52363. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52364. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52365. true, isMouseOverButton, isButtonDown),
  52366. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52367. if (ticked)
  52368. {
  52369. Path tick;
  52370. tick.startNewSubPath (1.5f, 3.0f);
  52371. tick.lineTo (3.0f, 6.0f);
  52372. tick.lineTo (6.0f, 0.0f);
  52373. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52374. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52375. .translated (x, y));
  52376. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52377. }
  52378. }
  52379. void LookAndFeel::drawToggleButton (Graphics& g,
  52380. ToggleButton& button,
  52381. bool isMouseOverButton,
  52382. bool isButtonDown)
  52383. {
  52384. if (button.hasKeyboardFocus (true))
  52385. {
  52386. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52387. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52388. }
  52389. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52390. const float tickWidth = fontSize * 1.1f;
  52391. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52392. tickWidth, tickWidth,
  52393. button.getToggleState(),
  52394. button.isEnabled(),
  52395. isMouseOverButton,
  52396. isButtonDown);
  52397. g.setColour (button.findColour (ToggleButton::textColourId));
  52398. g.setFont (fontSize);
  52399. if (! button.isEnabled())
  52400. g.setOpacity (0.5f);
  52401. const int textX = (int) tickWidth + 5;
  52402. g.drawFittedText (button.getButtonText(),
  52403. textX, 0,
  52404. button.getWidth() - textX - 2, button.getHeight(),
  52405. Justification::centredLeft, 10);
  52406. }
  52407. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52408. {
  52409. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52410. const int tickWidth = jmin (24, button.getHeight());
  52411. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52412. button.getHeight());
  52413. }
  52414. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52415. const String& message,
  52416. const String& button1,
  52417. const String& button2,
  52418. const String& button3,
  52419. AlertWindow::AlertIconType iconType,
  52420. int numButtons,
  52421. Component* associatedComponent)
  52422. {
  52423. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52424. if (numButtons == 1)
  52425. {
  52426. aw->addButton (button1, 0,
  52427. KeyPress (KeyPress::escapeKey, 0, 0),
  52428. KeyPress (KeyPress::returnKey, 0, 0));
  52429. }
  52430. else
  52431. {
  52432. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52433. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52434. if (button1ShortCut == button2ShortCut)
  52435. button2ShortCut = KeyPress();
  52436. if (numButtons == 2)
  52437. {
  52438. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52439. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52440. }
  52441. else if (numButtons == 3)
  52442. {
  52443. aw->addButton (button1, 1, button1ShortCut);
  52444. aw->addButton (button2, 2, button2ShortCut);
  52445. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52446. }
  52447. }
  52448. return aw;
  52449. }
  52450. void LookAndFeel::drawAlertBox (Graphics& g,
  52451. AlertWindow& alert,
  52452. const Rectangle<int>& textArea,
  52453. TextLayout& textLayout)
  52454. {
  52455. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52456. int iconSpaceUsed = 0;
  52457. Justification alignment (Justification::horizontallyCentred);
  52458. const int iconWidth = 80;
  52459. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52460. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52461. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52462. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52463. iconSize, iconSize);
  52464. if (alert.getAlertType() != AlertWindow::NoIcon)
  52465. {
  52466. Path icon;
  52467. uint32 colour;
  52468. char character;
  52469. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52470. {
  52471. colour = 0x55ff5555;
  52472. character = '!';
  52473. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52474. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52475. (float) iconRect.getX(), (float) iconRect.getBottom());
  52476. icon = icon.createPathWithRoundedCorners (5.0f);
  52477. }
  52478. else
  52479. {
  52480. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52481. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52482. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52483. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52484. }
  52485. GlyphArrangement ga;
  52486. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52487. String::charToString (character),
  52488. (float) iconRect.getX(), (float) iconRect.getY(),
  52489. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52490. Justification::centred, false);
  52491. ga.createPath (icon);
  52492. icon.setUsingNonZeroWinding (false);
  52493. g.setColour (Colour (colour));
  52494. g.fillPath (icon);
  52495. iconSpaceUsed = iconWidth;
  52496. alignment = Justification::left;
  52497. }
  52498. g.setColour (alert.findColour (AlertWindow::textColourId));
  52499. textLayout.drawWithin (g,
  52500. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52501. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52502. alignment.getFlags() | Justification::top);
  52503. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52504. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52505. }
  52506. int LookAndFeel::getAlertBoxWindowFlags()
  52507. {
  52508. return ComponentPeer::windowAppearsOnTaskbar
  52509. | ComponentPeer::windowHasDropShadow;
  52510. }
  52511. int LookAndFeel::getAlertWindowButtonHeight()
  52512. {
  52513. return 28;
  52514. }
  52515. const Font LookAndFeel::getAlertWindowMessageFont()
  52516. {
  52517. return Font (15.0f);
  52518. }
  52519. const Font LookAndFeel::getAlertWindowFont()
  52520. {
  52521. return Font (12.0f);
  52522. }
  52523. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52524. int width, int height,
  52525. double progress, const String& textToShow)
  52526. {
  52527. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52528. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52529. g.fillAll (background);
  52530. if (progress >= 0.0f && progress < 1.0f)
  52531. {
  52532. drawGlassLozenge (g, 1.0f, 1.0f,
  52533. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52534. (float) (height - 2),
  52535. foreground,
  52536. 0.5f, 0.0f,
  52537. true, true, true, true);
  52538. }
  52539. else
  52540. {
  52541. // spinning bar..
  52542. g.setColour (foreground);
  52543. const int stripeWidth = height * 2;
  52544. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52545. Path p;
  52546. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52547. p.addQuadrilateral (x, 0.0f,
  52548. x + stripeWidth * 0.5f, 0.0f,
  52549. x, (float) height,
  52550. x - stripeWidth * 0.5f, (float) height);
  52551. Image im (Image::ARGB, width, height, true);
  52552. {
  52553. Graphics g2 (im);
  52554. drawGlassLozenge (g2, 1.0f, 1.0f,
  52555. (float) (width - 2),
  52556. (float) (height - 2),
  52557. foreground,
  52558. 0.5f, 0.0f,
  52559. true, true, true, true);
  52560. }
  52561. g.setTiledImageFill (im, 0, 0, 0.85f);
  52562. g.fillPath (p);
  52563. }
  52564. if (textToShow.isNotEmpty())
  52565. {
  52566. g.setColour (Colour::contrasting (background, foreground));
  52567. g.setFont (height * 0.6f);
  52568. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52569. }
  52570. }
  52571. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52572. {
  52573. const float radius = jmin (w, h) * 0.4f;
  52574. const float thickness = radius * 0.15f;
  52575. Path p;
  52576. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52577. radius * 0.6f, thickness,
  52578. thickness * 0.5f);
  52579. const float cx = x + w * 0.5f;
  52580. const float cy = y + h * 0.5f;
  52581. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52582. for (int i = 0; i < 12; ++i)
  52583. {
  52584. const int n = (i + 12 - animationIndex) % 12;
  52585. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52586. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52587. .translated (cx, cy));
  52588. }
  52589. }
  52590. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52591. ScrollBar& scrollbar,
  52592. int width, int height,
  52593. int buttonDirection,
  52594. bool /*isScrollbarVertical*/,
  52595. bool /*isMouseOverButton*/,
  52596. bool isButtonDown)
  52597. {
  52598. Path p;
  52599. if (buttonDirection == 0)
  52600. p.addTriangle (width * 0.5f, height * 0.2f,
  52601. width * 0.1f, height * 0.7f,
  52602. width * 0.9f, height * 0.7f);
  52603. else if (buttonDirection == 1)
  52604. p.addTriangle (width * 0.8f, height * 0.5f,
  52605. width * 0.3f, height * 0.1f,
  52606. width * 0.3f, height * 0.9f);
  52607. else if (buttonDirection == 2)
  52608. p.addTriangle (width * 0.5f, height * 0.8f,
  52609. width * 0.1f, height * 0.3f,
  52610. width * 0.9f, height * 0.3f);
  52611. else if (buttonDirection == 3)
  52612. p.addTriangle (width * 0.2f, height * 0.5f,
  52613. width * 0.7f, height * 0.1f,
  52614. width * 0.7f, height * 0.9f);
  52615. if (isButtonDown)
  52616. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52617. else
  52618. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52619. g.fillPath (p);
  52620. g.setColour (Colour (0x80000000));
  52621. g.strokePath (p, PathStrokeType (0.5f));
  52622. }
  52623. void LookAndFeel::drawScrollbar (Graphics& g,
  52624. ScrollBar& scrollbar,
  52625. int x, int y,
  52626. int width, int height,
  52627. bool isScrollbarVertical,
  52628. int thumbStartPosition,
  52629. int thumbSize,
  52630. bool /*isMouseOver*/,
  52631. bool /*isMouseDown*/)
  52632. {
  52633. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52634. Path slotPath, thumbPath;
  52635. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52636. const float slotIndentx2 = slotIndent * 2.0f;
  52637. const float thumbIndent = slotIndent + 1.0f;
  52638. const float thumbIndentx2 = thumbIndent * 2.0f;
  52639. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52640. if (isScrollbarVertical)
  52641. {
  52642. slotPath.addRoundedRectangle (x + slotIndent,
  52643. y + slotIndent,
  52644. width - slotIndentx2,
  52645. height - slotIndentx2,
  52646. (width - slotIndentx2) * 0.5f);
  52647. if (thumbSize > 0)
  52648. thumbPath.addRoundedRectangle (x + thumbIndent,
  52649. thumbStartPosition + thumbIndent,
  52650. width - thumbIndentx2,
  52651. thumbSize - thumbIndentx2,
  52652. (width - thumbIndentx2) * 0.5f);
  52653. gx1 = (float) x;
  52654. gx2 = x + width * 0.7f;
  52655. }
  52656. else
  52657. {
  52658. slotPath.addRoundedRectangle (x + slotIndent,
  52659. y + slotIndent,
  52660. width - slotIndentx2,
  52661. height - slotIndentx2,
  52662. (height - slotIndentx2) * 0.5f);
  52663. if (thumbSize > 0)
  52664. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52665. y + thumbIndent,
  52666. thumbSize - thumbIndentx2,
  52667. height - thumbIndentx2,
  52668. (height - thumbIndentx2) * 0.5f);
  52669. gy1 = (float) y;
  52670. gy2 = y + height * 0.7f;
  52671. }
  52672. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52673. Colour trackColour1, trackColour2;
  52674. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52675. {
  52676. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52677. }
  52678. else
  52679. {
  52680. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52681. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52682. }
  52683. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52684. trackColour2, gx2, gy2, false));
  52685. g.fillPath (slotPath);
  52686. if (isScrollbarVertical)
  52687. {
  52688. gx1 = x + width * 0.6f;
  52689. gx2 = (float) x + width;
  52690. }
  52691. else
  52692. {
  52693. gy1 = y + height * 0.6f;
  52694. gy2 = (float) y + height;
  52695. }
  52696. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52697. Colour (0x19000000), gx2, gy2, false));
  52698. g.fillPath (slotPath);
  52699. g.setColour (thumbColour);
  52700. g.fillPath (thumbPath);
  52701. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52702. Colours::transparentBlack, gx2, gy2, false));
  52703. g.saveState();
  52704. if (isScrollbarVertical)
  52705. g.reduceClipRegion (x + width / 2, y, width, height);
  52706. else
  52707. g.reduceClipRegion (x, y + height / 2, width, height);
  52708. g.fillPath (thumbPath);
  52709. g.restoreState();
  52710. g.setColour (Colour (0x4c000000));
  52711. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52712. }
  52713. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52714. {
  52715. return 0;
  52716. }
  52717. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52718. {
  52719. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52720. }
  52721. int LookAndFeel::getDefaultScrollbarWidth()
  52722. {
  52723. return 18;
  52724. }
  52725. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52726. {
  52727. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52728. : scrollbar.getHeight());
  52729. }
  52730. const Path LookAndFeel::getTickShape (const float height)
  52731. {
  52732. static const unsigned char tickShapeData[] =
  52733. {
  52734. 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,
  52735. 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,
  52736. 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,
  52737. 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,
  52738. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52739. };
  52740. Path p;
  52741. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52742. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52743. return p;
  52744. }
  52745. const Path LookAndFeel::getCrossShape (const float height)
  52746. {
  52747. static const unsigned char crossShapeData[] =
  52748. {
  52749. 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,
  52750. 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,
  52751. 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,
  52752. 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,
  52753. 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,
  52754. 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,
  52755. 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
  52756. };
  52757. Path p;
  52758. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52759. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52760. return p;
  52761. }
  52762. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52763. {
  52764. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52765. x += (w - boxSize) >> 1;
  52766. y += (h - boxSize) >> 1;
  52767. w = boxSize;
  52768. h = boxSize;
  52769. g.setColour (Colour (0xe5ffffff));
  52770. g.fillRect (x, y, w, h);
  52771. g.setColour (Colour (0x80000000));
  52772. g.drawRect (x, y, w, h);
  52773. const float size = boxSize / 2 + 1.0f;
  52774. const float centre = (float) (boxSize / 2);
  52775. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52776. if (isPlus)
  52777. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52778. }
  52779. void LookAndFeel::drawBubble (Graphics& g,
  52780. float tipX, float tipY,
  52781. float boxX, float boxY,
  52782. float boxW, float boxH)
  52783. {
  52784. int side = 0;
  52785. if (tipX < boxX)
  52786. side = 1;
  52787. else if (tipX > boxX + boxW)
  52788. side = 3;
  52789. else if (tipY > boxY + boxH)
  52790. side = 2;
  52791. const float indent = 2.0f;
  52792. Path p;
  52793. p.addBubble (boxX + indent,
  52794. boxY + indent,
  52795. boxW - indent * 2.0f,
  52796. boxH - indent * 2.0f,
  52797. 5.0f,
  52798. tipX, tipY,
  52799. side,
  52800. 0.5f,
  52801. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52802. //xxx need to take comp as param for colour
  52803. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52804. g.fillPath (p);
  52805. //xxx as above
  52806. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52807. g.strokePath (p, PathStrokeType (1.33f));
  52808. }
  52809. const Font LookAndFeel::getPopupMenuFont()
  52810. {
  52811. return Font (17.0f);
  52812. }
  52813. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52814. const bool isSeparator,
  52815. int standardMenuItemHeight,
  52816. int& idealWidth,
  52817. int& idealHeight)
  52818. {
  52819. if (isSeparator)
  52820. {
  52821. idealWidth = 50;
  52822. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52823. }
  52824. else
  52825. {
  52826. Font font (getPopupMenuFont());
  52827. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52828. font.setHeight (standardMenuItemHeight / 1.3f);
  52829. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52830. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52831. }
  52832. }
  52833. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52834. {
  52835. const Colour background (findColour (PopupMenu::backgroundColourId));
  52836. g.fillAll (background);
  52837. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52838. for (int i = 0; i < height; i += 3)
  52839. g.fillRect (0, i, width, 1);
  52840. #if ! JUCE_MAC
  52841. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52842. g.drawRect (0, 0, width, height);
  52843. #endif
  52844. }
  52845. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52846. int width, int height,
  52847. bool isScrollUpArrow)
  52848. {
  52849. const Colour background (findColour (PopupMenu::backgroundColourId));
  52850. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52851. background.withAlpha (0.0f),
  52852. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52853. false));
  52854. g.fillRect (1, 1, width - 2, height - 2);
  52855. const float hw = width * 0.5f;
  52856. const float arrowW = height * 0.3f;
  52857. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52858. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52859. Path p;
  52860. p.addTriangle (hw - arrowW, y1,
  52861. hw + arrowW, y1,
  52862. hw, y2);
  52863. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52864. g.fillPath (p);
  52865. }
  52866. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52867. int width, int height,
  52868. const bool isSeparator,
  52869. const bool isActive,
  52870. const bool isHighlighted,
  52871. const bool isTicked,
  52872. const bool hasSubMenu,
  52873. const String& text,
  52874. const String& shortcutKeyText,
  52875. Image* image,
  52876. const Colour* const textColourToUse)
  52877. {
  52878. const float halfH = height * 0.5f;
  52879. if (isSeparator)
  52880. {
  52881. const float separatorIndent = 5.5f;
  52882. g.setColour (Colour (0x33000000));
  52883. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52884. g.setColour (Colour (0x66ffffff));
  52885. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52886. }
  52887. else
  52888. {
  52889. Colour textColour (findColour (PopupMenu::textColourId));
  52890. if (textColourToUse != 0)
  52891. textColour = *textColourToUse;
  52892. if (isHighlighted)
  52893. {
  52894. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52895. g.fillRect (1, 1, width - 2, height - 2);
  52896. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52897. }
  52898. else
  52899. {
  52900. g.setColour (textColour);
  52901. }
  52902. if (! isActive)
  52903. g.setOpacity (0.3f);
  52904. Font font (getPopupMenuFont());
  52905. if (font.getHeight() > height / 1.3f)
  52906. font.setHeight (height / 1.3f);
  52907. g.setFont (font);
  52908. const int leftBorder = (height * 5) / 4;
  52909. const int rightBorder = 4;
  52910. if (image != 0)
  52911. {
  52912. g.drawImageWithin (*image,
  52913. 2, 1, leftBorder - 4, height - 2,
  52914. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52915. }
  52916. else if (isTicked)
  52917. {
  52918. const Path tick (getTickShape (1.0f));
  52919. const float th = font.getAscent();
  52920. const float ty = halfH - th * 0.5f;
  52921. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52922. th, true));
  52923. }
  52924. g.drawFittedText (text,
  52925. leftBorder, 0,
  52926. width - (leftBorder + rightBorder), height,
  52927. Justification::centredLeft, 1);
  52928. if (shortcutKeyText.isNotEmpty())
  52929. {
  52930. Font f2 (font);
  52931. f2.setHeight (f2.getHeight() * 0.75f);
  52932. f2.setHorizontalScale (0.95f);
  52933. g.setFont (f2);
  52934. g.drawText (shortcutKeyText,
  52935. leftBorder,
  52936. 0,
  52937. width - (leftBorder + rightBorder + 4),
  52938. height,
  52939. Justification::centredRight,
  52940. true);
  52941. }
  52942. if (hasSubMenu)
  52943. {
  52944. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52945. const float x = width - height * 0.6f;
  52946. Path p;
  52947. p.addTriangle (x, halfH - arrowH * 0.5f,
  52948. x, halfH + arrowH * 0.5f,
  52949. x + arrowH * 0.6f, halfH);
  52950. g.fillPath (p);
  52951. }
  52952. }
  52953. }
  52954. int LookAndFeel::getMenuWindowFlags()
  52955. {
  52956. return ComponentPeer::windowHasDropShadow;
  52957. }
  52958. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52959. bool, MenuBarComponent& menuBar)
  52960. {
  52961. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52962. if (menuBar.isEnabled())
  52963. {
  52964. drawShinyButtonShape (g,
  52965. -4.0f, 0.0f,
  52966. width + 8.0f, (float) height,
  52967. 0.0f,
  52968. baseColour,
  52969. 0.4f,
  52970. true, true, true, true);
  52971. }
  52972. else
  52973. {
  52974. g.fillAll (baseColour);
  52975. }
  52976. }
  52977. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52978. {
  52979. return Font (menuBar.getHeight() * 0.7f);
  52980. }
  52981. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52982. {
  52983. return getMenuBarFont (menuBar, itemIndex, itemText)
  52984. .getStringWidth (itemText) + menuBar.getHeight();
  52985. }
  52986. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52987. int width, int height,
  52988. int itemIndex,
  52989. const String& itemText,
  52990. bool isMouseOverItem,
  52991. bool isMenuOpen,
  52992. bool /*isMouseOverBar*/,
  52993. MenuBarComponent& menuBar)
  52994. {
  52995. if (! menuBar.isEnabled())
  52996. {
  52997. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52998. .withMultipliedAlpha (0.5f));
  52999. }
  53000. else if (isMenuOpen || isMouseOverItem)
  53001. {
  53002. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53003. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53004. }
  53005. else
  53006. {
  53007. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53008. }
  53009. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53010. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53011. }
  53012. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53013. TextEditor& textEditor)
  53014. {
  53015. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53016. }
  53017. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53018. {
  53019. if (textEditor.isEnabled())
  53020. {
  53021. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53022. {
  53023. const int border = 2;
  53024. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53025. g.drawRect (0, 0, width, height, border);
  53026. g.setOpacity (1.0f);
  53027. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53028. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53029. }
  53030. else
  53031. {
  53032. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53033. g.drawRect (0, 0, width, height);
  53034. g.setOpacity (1.0f);
  53035. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53036. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53037. }
  53038. }
  53039. }
  53040. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53041. const bool isButtonDown,
  53042. int buttonX, int buttonY,
  53043. int buttonW, int buttonH,
  53044. ComboBox& box)
  53045. {
  53046. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53047. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53048. {
  53049. g.setColour (box.findColour (TextButton::buttonColourId));
  53050. g.drawRect (0, 0, width, height, 2);
  53051. }
  53052. else
  53053. {
  53054. g.setColour (box.findColour (ComboBox::outlineColourId));
  53055. g.drawRect (0, 0, width, height);
  53056. }
  53057. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53058. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53059. box.hasKeyboardFocus (true),
  53060. false, isButtonDown)
  53061. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53062. drawGlassLozenge (g,
  53063. buttonX + outlineThickness, buttonY + outlineThickness,
  53064. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53065. baseColour, outlineThickness, -1.0f,
  53066. true, true, true, true);
  53067. if (box.isEnabled())
  53068. {
  53069. const float arrowX = 0.3f;
  53070. const float arrowH = 0.2f;
  53071. Path p;
  53072. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53073. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53074. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53075. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53076. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53077. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53078. g.setColour (box.findColour (ComboBox::arrowColourId));
  53079. g.fillPath (p);
  53080. }
  53081. }
  53082. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53083. {
  53084. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53085. }
  53086. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53087. {
  53088. return new Label (String::empty, String::empty);
  53089. }
  53090. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53091. {
  53092. label.setBounds (1, 1,
  53093. box.getWidth() + 3 - box.getHeight(),
  53094. box.getHeight() - 2);
  53095. label.setFont (getComboBoxFont (box));
  53096. }
  53097. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53098. {
  53099. g.fillAll (label.findColour (Label::backgroundColourId));
  53100. if (! label.isBeingEdited())
  53101. {
  53102. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53103. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53104. g.setFont (label.getFont());
  53105. g.drawFittedText (label.getText(),
  53106. label.getHorizontalBorderSize(),
  53107. label.getVerticalBorderSize(),
  53108. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53109. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53110. label.getJustificationType(),
  53111. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53112. label.getMinimumHorizontalScale());
  53113. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53114. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53115. }
  53116. else if (label.isEnabled())
  53117. {
  53118. g.setColour (label.findColour (Label::outlineColourId));
  53119. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53120. }
  53121. }
  53122. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53123. int x, int y,
  53124. int width, int height,
  53125. float /*sliderPos*/,
  53126. float /*minSliderPos*/,
  53127. float /*maxSliderPos*/,
  53128. const Slider::SliderStyle /*style*/,
  53129. Slider& slider)
  53130. {
  53131. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53132. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53133. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53134. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53135. Path indent;
  53136. if (slider.isHorizontal())
  53137. {
  53138. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53139. const float ih = sliderRadius;
  53140. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53141. gradCol2, 0.0f, iy + ih, false));
  53142. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53143. width + sliderRadius, ih,
  53144. 5.0f);
  53145. g.fillPath (indent);
  53146. }
  53147. else
  53148. {
  53149. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53150. const float iw = sliderRadius;
  53151. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53152. gradCol2, ix + iw, 0.0f, false));
  53153. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53154. iw, height + sliderRadius,
  53155. 5.0f);
  53156. g.fillPath (indent);
  53157. }
  53158. g.setColour (Colour (0x4c000000));
  53159. g.strokePath (indent, PathStrokeType (0.5f));
  53160. }
  53161. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53162. int x, int y,
  53163. int width, int height,
  53164. float sliderPos,
  53165. float minSliderPos,
  53166. float maxSliderPos,
  53167. const Slider::SliderStyle style,
  53168. Slider& slider)
  53169. {
  53170. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53171. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53172. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53173. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53174. slider.isMouseButtonDown() && slider.isEnabled()));
  53175. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53176. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53177. {
  53178. float kx, ky;
  53179. if (style == Slider::LinearVertical)
  53180. {
  53181. kx = x + width * 0.5f;
  53182. ky = sliderPos;
  53183. }
  53184. else
  53185. {
  53186. kx = sliderPos;
  53187. ky = y + height * 0.5f;
  53188. }
  53189. drawGlassSphere (g,
  53190. kx - sliderRadius,
  53191. ky - sliderRadius,
  53192. sliderRadius * 2.0f,
  53193. knobColour, outlineThickness);
  53194. }
  53195. else
  53196. {
  53197. if (style == Slider::ThreeValueVertical)
  53198. {
  53199. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53200. sliderPos - sliderRadius,
  53201. sliderRadius * 2.0f,
  53202. knobColour, outlineThickness);
  53203. }
  53204. else if (style == Slider::ThreeValueHorizontal)
  53205. {
  53206. drawGlassSphere (g,sliderPos - sliderRadius,
  53207. y + height * 0.5f - sliderRadius,
  53208. sliderRadius * 2.0f,
  53209. knobColour, outlineThickness);
  53210. }
  53211. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53212. {
  53213. const float sr = jmin (sliderRadius, width * 0.4f);
  53214. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53215. minSliderPos - sliderRadius,
  53216. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53217. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53218. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53219. }
  53220. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53221. {
  53222. const float sr = jmin (sliderRadius, height * 0.4f);
  53223. drawGlassPointer (g, minSliderPos - sr,
  53224. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53225. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53226. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53227. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53228. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53229. }
  53230. }
  53231. }
  53232. void LookAndFeel::drawLinearSlider (Graphics& g,
  53233. int x, int y,
  53234. int width, int height,
  53235. float sliderPos,
  53236. float minSliderPos,
  53237. float maxSliderPos,
  53238. const Slider::SliderStyle style,
  53239. Slider& slider)
  53240. {
  53241. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53242. if (style == Slider::LinearBar)
  53243. {
  53244. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53245. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53246. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53247. false, isMouseOver,
  53248. isMouseOver || slider.isMouseButtonDown()));
  53249. drawShinyButtonShape (g,
  53250. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53251. baseColour,
  53252. slider.isEnabled() ? 0.9f : 0.3f,
  53253. true, true, true, true);
  53254. }
  53255. else
  53256. {
  53257. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53258. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53259. }
  53260. }
  53261. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53262. {
  53263. return jmin (7,
  53264. slider.getHeight() / 2,
  53265. slider.getWidth() / 2) + 2;
  53266. }
  53267. void LookAndFeel::drawRotarySlider (Graphics& g,
  53268. int x, int y,
  53269. int width, int height,
  53270. float sliderPos,
  53271. const float rotaryStartAngle,
  53272. const float rotaryEndAngle,
  53273. Slider& slider)
  53274. {
  53275. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53276. const float centreX = x + width * 0.5f;
  53277. const float centreY = y + height * 0.5f;
  53278. const float rx = centreX - radius;
  53279. const float ry = centreY - radius;
  53280. const float rw = radius * 2.0f;
  53281. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53282. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53283. if (radius > 12.0f)
  53284. {
  53285. if (slider.isEnabled())
  53286. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53287. else
  53288. g.setColour (Colour (0x80808080));
  53289. const float thickness = 0.7f;
  53290. {
  53291. Path filledArc;
  53292. filledArc.addPieSegment (rx, ry, rw, rw,
  53293. rotaryStartAngle,
  53294. angle,
  53295. thickness);
  53296. g.fillPath (filledArc);
  53297. }
  53298. if (thickness > 0)
  53299. {
  53300. const float innerRadius = radius * 0.2f;
  53301. Path p;
  53302. p.addTriangle (-innerRadius, 0.0f,
  53303. 0.0f, -radius * thickness * 1.1f,
  53304. innerRadius, 0.0f);
  53305. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53306. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53307. }
  53308. if (slider.isEnabled())
  53309. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53310. else
  53311. g.setColour (Colour (0x80808080));
  53312. Path outlineArc;
  53313. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53314. outlineArc.closeSubPath();
  53315. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53316. }
  53317. else
  53318. {
  53319. if (slider.isEnabled())
  53320. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53321. else
  53322. g.setColour (Colour (0x80808080));
  53323. Path p;
  53324. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53325. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53326. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53327. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53328. }
  53329. }
  53330. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53331. {
  53332. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53333. }
  53334. class SliderLabelComp : public Label
  53335. {
  53336. public:
  53337. SliderLabelComp() : Label (String::empty, String::empty) {}
  53338. ~SliderLabelComp() {}
  53339. void mouseWheelMove (const MouseEvent&, float, float) {}
  53340. };
  53341. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53342. {
  53343. Label* const l = new SliderLabelComp();
  53344. l->setJustificationType (Justification::centred);
  53345. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53346. l->setColour (Label::backgroundColourId,
  53347. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53348. : slider.findColour (Slider::textBoxBackgroundColourId));
  53349. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53350. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53351. l->setColour (TextEditor::backgroundColourId,
  53352. slider.findColour (Slider::textBoxBackgroundColourId)
  53353. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53354. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53355. return l;
  53356. }
  53357. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53358. {
  53359. return 0;
  53360. }
  53361. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53362. {
  53363. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53364. width = tl.getWidth() + 14;
  53365. height = tl.getHeight() + 6;
  53366. }
  53367. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53368. {
  53369. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53370. const Colour textCol (findColour (TooltipWindow::textColourId));
  53371. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53372. g.setColour (findColour (TooltipWindow::outlineColourId));
  53373. g.drawRect (0, 0, width, height, 1);
  53374. #endif
  53375. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53376. g.setColour (findColour (TooltipWindow::textColourId));
  53377. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53378. }
  53379. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53380. {
  53381. return new TextButton (text, TRANS("click to browse for a different file"));
  53382. }
  53383. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53384. ComboBox* filenameBox,
  53385. Button* browseButton)
  53386. {
  53387. browseButton->setSize (80, filenameComp.getHeight());
  53388. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53389. if (tb != 0)
  53390. tb->changeWidthToFitText();
  53391. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53392. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53393. }
  53394. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53395. int imageX, int imageY, int imageW, int imageH,
  53396. const Colour& overlayColour,
  53397. float imageOpacity,
  53398. ImageButton& button)
  53399. {
  53400. if (! button.isEnabled())
  53401. imageOpacity *= 0.3f;
  53402. if (! overlayColour.isOpaque())
  53403. {
  53404. g.setOpacity (imageOpacity);
  53405. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53406. 0, 0, image->getWidth(), image->getHeight(), false);
  53407. }
  53408. if (! overlayColour.isTransparent())
  53409. {
  53410. g.setColour (overlayColour);
  53411. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53412. 0, 0, image->getWidth(), image->getHeight(), true);
  53413. }
  53414. }
  53415. void LookAndFeel::drawCornerResizer (Graphics& g,
  53416. int w, int h,
  53417. bool /*isMouseOver*/,
  53418. bool /*isMouseDragging*/)
  53419. {
  53420. const float lineThickness = jmin (w, h) * 0.075f;
  53421. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53422. {
  53423. g.setColour (Colours::lightgrey);
  53424. g.drawLine (w * i,
  53425. h + 1.0f,
  53426. w + 1.0f,
  53427. h * i,
  53428. lineThickness);
  53429. g.setColour (Colours::darkgrey);
  53430. g.drawLine (w * i + lineThickness,
  53431. h + 1.0f,
  53432. w + 1.0f,
  53433. h * i + lineThickness,
  53434. lineThickness);
  53435. }
  53436. }
  53437. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53438. {
  53439. if (! border.isEmpty())
  53440. {
  53441. const Rectangle<int> fullSize (0, 0, w, h);
  53442. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53443. g.saveState();
  53444. g.excludeClipRegion (centreArea);
  53445. g.setColour (Colour (0x50000000));
  53446. g.drawRect (fullSize);
  53447. g.setColour (Colour (0x19000000));
  53448. g.drawRect (centreArea.expanded (1, 1));
  53449. g.restoreState();
  53450. }
  53451. }
  53452. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53453. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53454. {
  53455. g.fillAll (window.getBackgroundColour());
  53456. }
  53457. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53458. const BorderSize<int>& /*border*/, ResizableWindow&)
  53459. {
  53460. }
  53461. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53462. Graphics& g, int w, int h,
  53463. int titleSpaceX, int titleSpaceW,
  53464. const Image* icon,
  53465. bool drawTitleTextOnLeft)
  53466. {
  53467. const bool isActive = window.isActiveWindow();
  53468. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53469. 0.0f, 0.0f,
  53470. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53471. 0.0f, (float) h, false));
  53472. g.fillAll();
  53473. Font font (h * 0.65f, Font::bold);
  53474. g.setFont (font);
  53475. int textW = font.getStringWidth (window.getName());
  53476. int iconW = 0;
  53477. int iconH = 0;
  53478. if (icon != 0)
  53479. {
  53480. iconH = (int) font.getHeight();
  53481. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53482. }
  53483. textW = jmin (titleSpaceW, textW + iconW);
  53484. int textX = drawTitleTextOnLeft ? titleSpaceX
  53485. : jmax (titleSpaceX, (w - textW) / 2);
  53486. if (textX + textW > titleSpaceX + titleSpaceW)
  53487. textX = titleSpaceX + titleSpaceW - textW;
  53488. if (icon != 0)
  53489. {
  53490. g.setOpacity (isActive ? 1.0f : 0.6f);
  53491. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53492. RectanglePlacement::centred, false);
  53493. textX += iconW;
  53494. textW -= iconW;
  53495. }
  53496. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53497. g.setColour (findColour (DocumentWindow::textColourId));
  53498. else
  53499. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53500. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53501. }
  53502. class GlassWindowButton : public Button
  53503. {
  53504. public:
  53505. GlassWindowButton (const String& name, const Colour& col,
  53506. const Path& normalShape_,
  53507. const Path& toggledShape_) throw()
  53508. : Button (name),
  53509. colour (col),
  53510. normalShape (normalShape_),
  53511. toggledShape (toggledShape_)
  53512. {
  53513. }
  53514. ~GlassWindowButton()
  53515. {
  53516. }
  53517. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53518. {
  53519. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53520. if (! isEnabled())
  53521. alpha *= 0.5f;
  53522. float x = 0, y = 0, diam;
  53523. if (getWidth() < getHeight())
  53524. {
  53525. diam = (float) getWidth();
  53526. y = (getHeight() - getWidth()) * 0.5f;
  53527. }
  53528. else
  53529. {
  53530. diam = (float) getHeight();
  53531. y = (getWidth() - getHeight()) * 0.5f;
  53532. }
  53533. x += diam * 0.05f;
  53534. y += diam * 0.05f;
  53535. diam *= 0.9f;
  53536. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53537. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53538. g.fillEllipse (x, y, diam, diam);
  53539. x += 2.0f;
  53540. y += 2.0f;
  53541. diam -= 4.0f;
  53542. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53543. Path& p = getToggleState() ? toggledShape : normalShape;
  53544. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53545. diam * 0.4f, diam * 0.4f, true));
  53546. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53547. g.fillPath (p, t);
  53548. }
  53549. private:
  53550. Colour colour;
  53551. Path normalShape, toggledShape;
  53552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53553. };
  53554. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53555. {
  53556. Path shape;
  53557. const float crossThickness = 0.25f;
  53558. if (buttonType == DocumentWindow::closeButton)
  53559. {
  53560. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53561. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53562. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53563. }
  53564. else if (buttonType == DocumentWindow::minimiseButton)
  53565. {
  53566. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53567. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53568. }
  53569. else if (buttonType == DocumentWindow::maximiseButton)
  53570. {
  53571. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53572. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53573. Path fullscreenShape;
  53574. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53575. fullscreenShape.lineTo (0.0f, 100.0f);
  53576. fullscreenShape.lineTo (0.0f, 0.0f);
  53577. fullscreenShape.lineTo (100.0f, 0.0f);
  53578. fullscreenShape.lineTo (100.0f, 45.0f);
  53579. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53580. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53581. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53582. }
  53583. jassertfalse;
  53584. return 0;
  53585. }
  53586. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53587. int titleBarX,
  53588. int titleBarY,
  53589. int titleBarW,
  53590. int titleBarH,
  53591. Button* minimiseButton,
  53592. Button* maximiseButton,
  53593. Button* closeButton,
  53594. bool positionTitleBarButtonsOnLeft)
  53595. {
  53596. const int buttonW = titleBarH - titleBarH / 8;
  53597. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53598. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53599. if (closeButton != 0)
  53600. {
  53601. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53602. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53603. }
  53604. if (positionTitleBarButtonsOnLeft)
  53605. swapVariables (minimiseButton, maximiseButton);
  53606. if (maximiseButton != 0)
  53607. {
  53608. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53609. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53610. }
  53611. if (minimiseButton != 0)
  53612. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53613. }
  53614. int LookAndFeel::getDefaultMenuBarHeight()
  53615. {
  53616. return 24;
  53617. }
  53618. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53619. {
  53620. return new DropShadower (0.4f, 1, 5, 10);
  53621. }
  53622. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53623. int w, int h,
  53624. bool /*isVerticalBar*/,
  53625. bool isMouseOver,
  53626. bool isMouseDragging)
  53627. {
  53628. float alpha = 0.5f;
  53629. if (isMouseOver || isMouseDragging)
  53630. {
  53631. g.fillAll (Colour (0x190000ff));
  53632. alpha = 1.0f;
  53633. }
  53634. const float cx = w * 0.5f;
  53635. const float cy = h * 0.5f;
  53636. const float cr = jmin (w, h) * 0.4f;
  53637. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53638. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53639. true));
  53640. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53641. }
  53642. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53643. const String& text,
  53644. const Justification& position,
  53645. GroupComponent& group)
  53646. {
  53647. const float textH = 15.0f;
  53648. const float indent = 3.0f;
  53649. const float textEdgeGap = 4.0f;
  53650. float cs = 5.0f;
  53651. Font f (textH);
  53652. Path p;
  53653. float x = indent;
  53654. float y = f.getAscent() - 3.0f;
  53655. float w = jmax (0.0f, width - x * 2.0f);
  53656. float h = jmax (0.0f, height - y - indent);
  53657. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53658. const float cs2 = 2.0f * cs;
  53659. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53660. float textX = cs + textEdgeGap;
  53661. if (position.testFlags (Justification::horizontallyCentred))
  53662. textX = cs + (w - cs2 - textW) * 0.5f;
  53663. else if (position.testFlags (Justification::right))
  53664. textX = w - cs - textW - textEdgeGap;
  53665. p.startNewSubPath (x + textX + textW, y);
  53666. p.lineTo (x + w - cs, y);
  53667. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53668. p.lineTo (x + w, y + h - cs);
  53669. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53670. p.lineTo (x + cs, y + h);
  53671. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53672. p.lineTo (x, y + cs);
  53673. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53674. p.lineTo (x + textX, y);
  53675. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53676. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53677. .withMultipliedAlpha (alpha));
  53678. g.strokePath (p, PathStrokeType (2.0f));
  53679. g.setColour (group.findColour (GroupComponent::textColourId)
  53680. .withMultipliedAlpha (alpha));
  53681. g.setFont (f);
  53682. g.drawText (text,
  53683. roundToInt (x + textX), 0,
  53684. roundToInt (textW),
  53685. roundToInt (textH),
  53686. Justification::centred, true);
  53687. }
  53688. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53689. {
  53690. return 1 + tabDepth / 3;
  53691. }
  53692. int LookAndFeel::getTabButtonSpaceAroundImage()
  53693. {
  53694. return 4;
  53695. }
  53696. void LookAndFeel::createTabButtonShape (Path& p,
  53697. int width, int height,
  53698. int /*tabIndex*/,
  53699. const String& /*text*/,
  53700. Button& /*button*/,
  53701. TabbedButtonBar::Orientation orientation,
  53702. const bool /*isMouseOver*/,
  53703. const bool /*isMouseDown*/,
  53704. const bool /*isFrontTab*/)
  53705. {
  53706. const float w = (float) width;
  53707. const float h = (float) height;
  53708. float length = w;
  53709. float depth = h;
  53710. if (orientation == TabbedButtonBar::TabsAtLeft
  53711. || orientation == TabbedButtonBar::TabsAtRight)
  53712. {
  53713. swapVariables (length, depth);
  53714. }
  53715. const float indent = (float) getTabButtonOverlap ((int) depth);
  53716. const float overhang = 4.0f;
  53717. if (orientation == TabbedButtonBar::TabsAtLeft)
  53718. {
  53719. p.startNewSubPath (w, 0.0f);
  53720. p.lineTo (0.0f, indent);
  53721. p.lineTo (0.0f, h - indent);
  53722. p.lineTo (w, h);
  53723. p.lineTo (w + overhang, h + overhang);
  53724. p.lineTo (w + overhang, -overhang);
  53725. }
  53726. else if (orientation == TabbedButtonBar::TabsAtRight)
  53727. {
  53728. p.startNewSubPath (0.0f, 0.0f);
  53729. p.lineTo (w, indent);
  53730. p.lineTo (w, h - indent);
  53731. p.lineTo (0.0f, h);
  53732. p.lineTo (-overhang, h + overhang);
  53733. p.lineTo (-overhang, -overhang);
  53734. }
  53735. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53736. {
  53737. p.startNewSubPath (0.0f, 0.0f);
  53738. p.lineTo (indent, h);
  53739. p.lineTo (w - indent, h);
  53740. p.lineTo (w, 0.0f);
  53741. p.lineTo (w + overhang, -overhang);
  53742. p.lineTo (-overhang, -overhang);
  53743. }
  53744. else
  53745. {
  53746. p.startNewSubPath (0.0f, h);
  53747. p.lineTo (indent, 0.0f);
  53748. p.lineTo (w - indent, 0.0f);
  53749. p.lineTo (w, h);
  53750. p.lineTo (w + overhang, h + overhang);
  53751. p.lineTo (-overhang, h + overhang);
  53752. }
  53753. p.closeSubPath();
  53754. p = p.createPathWithRoundedCorners (3.0f);
  53755. }
  53756. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53757. const Path& path,
  53758. const Colour& preferredColour,
  53759. int /*tabIndex*/,
  53760. const String& /*text*/,
  53761. Button& button,
  53762. TabbedButtonBar::Orientation /*orientation*/,
  53763. const bool /*isMouseOver*/,
  53764. const bool /*isMouseDown*/,
  53765. const bool isFrontTab)
  53766. {
  53767. g.setColour (isFrontTab ? preferredColour
  53768. : preferredColour.withMultipliedAlpha (0.9f));
  53769. g.fillPath (path);
  53770. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53771. : TabbedButtonBar::tabOutlineColourId, false)
  53772. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53773. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53774. }
  53775. void LookAndFeel::drawTabButtonText (Graphics& g,
  53776. int x, int y, int w, int h,
  53777. const Colour& preferredBackgroundColour,
  53778. int /*tabIndex*/,
  53779. const String& text,
  53780. Button& button,
  53781. TabbedButtonBar::Orientation orientation,
  53782. const bool isMouseOver,
  53783. const bool isMouseDown,
  53784. const bool isFrontTab)
  53785. {
  53786. int length = w;
  53787. int depth = h;
  53788. if (orientation == TabbedButtonBar::TabsAtLeft
  53789. || orientation == TabbedButtonBar::TabsAtRight)
  53790. {
  53791. swapVariables (length, depth);
  53792. }
  53793. Font font (depth * 0.6f);
  53794. font.setUnderline (button.hasKeyboardFocus (false));
  53795. GlyphArrangement textLayout;
  53796. textLayout.addFittedText (font, text.trim(),
  53797. 0.0f, 0.0f, (float) length, (float) depth,
  53798. Justification::centred,
  53799. jmax (1, depth / 12));
  53800. AffineTransform transform;
  53801. if (orientation == TabbedButtonBar::TabsAtLeft)
  53802. {
  53803. transform = transform.rotated (float_Pi * -0.5f)
  53804. .translated ((float) x, (float) (y + h));
  53805. }
  53806. else if (orientation == TabbedButtonBar::TabsAtRight)
  53807. {
  53808. transform = transform.rotated (float_Pi * 0.5f)
  53809. .translated ((float) (x + w), (float) y);
  53810. }
  53811. else
  53812. {
  53813. transform = transform.translated ((float) x, (float) y);
  53814. }
  53815. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53816. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53817. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53818. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53819. else
  53820. g.setColour (preferredBackgroundColour.contrasting());
  53821. if (! (isMouseOver || isMouseDown))
  53822. g.setOpacity (0.8f);
  53823. if (! button.isEnabled())
  53824. g.setOpacity (0.3f);
  53825. textLayout.draw (g, transform);
  53826. }
  53827. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53828. const String& text,
  53829. int tabDepth,
  53830. Button&)
  53831. {
  53832. Font f (tabDepth * 0.6f);
  53833. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53834. }
  53835. void LookAndFeel::drawTabButton (Graphics& g,
  53836. int w, int h,
  53837. const Colour& preferredColour,
  53838. int tabIndex,
  53839. const String& text,
  53840. Button& button,
  53841. TabbedButtonBar::Orientation orientation,
  53842. const bool isMouseOver,
  53843. const bool isMouseDown,
  53844. const bool isFrontTab)
  53845. {
  53846. int length = w;
  53847. int depth = h;
  53848. if (orientation == TabbedButtonBar::TabsAtLeft
  53849. || orientation == TabbedButtonBar::TabsAtRight)
  53850. {
  53851. swapVariables (length, depth);
  53852. }
  53853. Path tabShape;
  53854. createTabButtonShape (tabShape, w, h,
  53855. tabIndex, text, button, orientation,
  53856. isMouseOver, isMouseDown, isFrontTab);
  53857. fillTabButtonShape (g, tabShape, preferredColour,
  53858. tabIndex, text, button, orientation,
  53859. isMouseOver, isMouseDown, isFrontTab);
  53860. const int indent = getTabButtonOverlap (depth);
  53861. int x = 0, y = 0;
  53862. if (orientation == TabbedButtonBar::TabsAtLeft
  53863. || orientation == TabbedButtonBar::TabsAtRight)
  53864. {
  53865. y += indent;
  53866. h -= indent * 2;
  53867. }
  53868. else
  53869. {
  53870. x += indent;
  53871. w -= indent * 2;
  53872. }
  53873. drawTabButtonText (g, x, y, w, h, preferredColour,
  53874. tabIndex, text, button, orientation,
  53875. isMouseOver, isMouseDown, isFrontTab);
  53876. }
  53877. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53878. int w, int h,
  53879. TabbedButtonBar& tabBar,
  53880. TabbedButtonBar::Orientation orientation)
  53881. {
  53882. const float shadowSize = 0.2f;
  53883. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53884. Rectangle<int> shadowRect;
  53885. if (orientation == TabbedButtonBar::TabsAtLeft)
  53886. {
  53887. x1 = (float) w;
  53888. x2 = w * (1.0f - shadowSize);
  53889. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53890. }
  53891. else if (orientation == TabbedButtonBar::TabsAtRight)
  53892. {
  53893. x2 = w * shadowSize;
  53894. shadowRect.setBounds (0, 0, (int) x2, h);
  53895. }
  53896. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53897. {
  53898. y2 = h * shadowSize;
  53899. shadowRect.setBounds (0, 0, w, (int) y2);
  53900. }
  53901. else
  53902. {
  53903. y1 = (float) h;
  53904. y2 = h * (1.0f - shadowSize);
  53905. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53906. }
  53907. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53908. Colours::transparentBlack, x2, y2, false));
  53909. shadowRect.expand (2, 2);
  53910. g.fillRect (shadowRect);
  53911. g.setColour (Colour (0x80000000));
  53912. if (orientation == TabbedButtonBar::TabsAtLeft)
  53913. {
  53914. g.fillRect (w - 1, 0, 1, h);
  53915. }
  53916. else if (orientation == TabbedButtonBar::TabsAtRight)
  53917. {
  53918. g.fillRect (0, 0, 1, h);
  53919. }
  53920. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53921. {
  53922. g.fillRect (0, 0, w, 1);
  53923. }
  53924. else
  53925. {
  53926. g.fillRect (0, h - 1, w, 1);
  53927. }
  53928. }
  53929. Button* LookAndFeel::createTabBarExtrasButton()
  53930. {
  53931. const float thickness = 7.0f;
  53932. const float indent = 22.0f;
  53933. Path p;
  53934. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53935. DrawablePath ellipse;
  53936. ellipse.setPath (p);
  53937. ellipse.setFill (Colour (0x99ffffff));
  53938. p.clear();
  53939. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53940. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53941. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53942. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53943. p.setUsingNonZeroWinding (false);
  53944. DrawablePath dp;
  53945. dp.setPath (p);
  53946. dp.setFill (Colour (0x59000000));
  53947. DrawableComposite normalImage;
  53948. normalImage.addAndMakeVisible (ellipse.createCopy());
  53949. normalImage.addAndMakeVisible (dp.createCopy());
  53950. dp.setFill (Colour (0xcc000000));
  53951. DrawableComposite overImage;
  53952. overImage.addAndMakeVisible (ellipse.createCopy());
  53953. overImage.addAndMakeVisible (dp.createCopy());
  53954. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53955. db->setImages (&normalImage, &overImage, 0);
  53956. return db;
  53957. }
  53958. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53959. {
  53960. g.fillAll (Colours::white);
  53961. const int w = header.getWidth();
  53962. const int h = header.getHeight();
  53963. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53964. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53965. false));
  53966. g.fillRect (0, h / 2, w, h);
  53967. g.setColour (Colour (0x33000000));
  53968. g.fillRect (0, h - 1, w, 1);
  53969. for (int i = header.getNumColumns (true); --i >= 0;)
  53970. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53971. }
  53972. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53973. int width, int height,
  53974. bool isMouseOver, bool isMouseDown,
  53975. int columnFlags)
  53976. {
  53977. if (isMouseDown)
  53978. g.fillAll (Colour (0x8899aadd));
  53979. else if (isMouseOver)
  53980. g.fillAll (Colour (0x5599aadd));
  53981. int rightOfText = width - 4;
  53982. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53983. {
  53984. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53985. const float bottom = height - top;
  53986. const float w = height * 0.5f;
  53987. const float x = rightOfText - (w * 1.25f);
  53988. rightOfText = (int) x;
  53989. Path sortArrow;
  53990. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53991. g.setColour (Colour (0x99000000));
  53992. g.fillPath (sortArrow);
  53993. }
  53994. g.setColour (Colours::black);
  53995. g.setFont (height * 0.5f, Font::bold);
  53996. const int textX = 4;
  53997. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53998. }
  53999. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54000. {
  54001. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54002. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54003. background.darker (0.1f),
  54004. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54005. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54006. false));
  54007. g.fillAll();
  54008. }
  54009. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54010. {
  54011. return createTabBarExtrasButton();
  54012. }
  54013. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54014. bool isMouseOver, bool isMouseDown,
  54015. ToolbarItemComponent& component)
  54016. {
  54017. if (isMouseDown)
  54018. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54019. else if (isMouseOver)
  54020. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54021. }
  54022. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54023. const String& text, ToolbarItemComponent& component)
  54024. {
  54025. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54026. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54027. const float fontHeight = jmin (14.0f, height * 0.85f);
  54028. g.setFont (fontHeight);
  54029. g.drawFittedText (text,
  54030. x, y, width, height,
  54031. Justification::centred,
  54032. jmax (1, height / (int) fontHeight));
  54033. }
  54034. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54035. bool isOpen, int width, int height)
  54036. {
  54037. const int buttonSize = (height * 3) / 4;
  54038. const int buttonIndent = (height - buttonSize) / 2;
  54039. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54040. const int textX = buttonIndent * 2 + buttonSize + 2;
  54041. g.setColour (Colours::black);
  54042. g.setFont (height * 0.7f, Font::bold);
  54043. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54044. }
  54045. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54046. PropertyComponent&)
  54047. {
  54048. g.setColour (Colour (0x66ffffff));
  54049. g.fillRect (0, 0, width, height - 1);
  54050. }
  54051. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54052. PropertyComponent& component)
  54053. {
  54054. g.setColour (Colours::black);
  54055. if (! component.isEnabled())
  54056. g.setOpacity (0.6f);
  54057. g.setFont (jmin (height, 24) * 0.65f);
  54058. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54059. g.drawFittedText (component.getName(),
  54060. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54061. Justification::centredLeft, 2);
  54062. }
  54063. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54064. {
  54065. return Rectangle<int> (component.getWidth() / 3, 1,
  54066. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54067. }
  54068. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54069. {
  54070. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54071. {
  54072. Graphics g2 (content);
  54073. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54074. g2.fillPath (path);
  54075. g2.setColour (Colours::white.withAlpha (0.8f));
  54076. g2.strokePath (path, PathStrokeType (2.0f));
  54077. }
  54078. DropShadowEffect shadow;
  54079. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54080. shadow.applyEffect (content, g, 1.0f);
  54081. }
  54082. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54083. const String& instructions,
  54084. GlyphArrangement& text,
  54085. int width)
  54086. {
  54087. text.clear();
  54088. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54089. 8.0f, 22.0f, width - 16.0f,
  54090. Justification::centred);
  54091. text.addJustifiedText (Font (14.0f), instructions,
  54092. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54093. Justification::centred);
  54094. }
  54095. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54096. const String& filename, Image* icon,
  54097. const String& fileSizeDescription,
  54098. const String& fileTimeDescription,
  54099. const bool isDirectory,
  54100. const bool isItemSelected,
  54101. const int /*itemIndex*/,
  54102. DirectoryContentsDisplayComponent&)
  54103. {
  54104. if (isItemSelected)
  54105. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54106. const int x = 32;
  54107. g.setColour (Colours::black);
  54108. if (icon != 0 && icon->isValid())
  54109. {
  54110. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54111. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54112. false);
  54113. }
  54114. else
  54115. {
  54116. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54117. : getDefaultDocumentFileImage();
  54118. if (d != 0)
  54119. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54120. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54121. }
  54122. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54123. g.setFont (height * 0.7f);
  54124. if (width > 450 && ! isDirectory)
  54125. {
  54126. const int sizeX = roundToInt (width * 0.7f);
  54127. const int dateX = roundToInt (width * 0.8f);
  54128. g.drawFittedText (filename,
  54129. x, 0, sizeX - x, height,
  54130. Justification::centredLeft, 1);
  54131. g.setFont (height * 0.5f);
  54132. g.setColour (Colours::darkgrey);
  54133. if (! isDirectory)
  54134. {
  54135. g.drawFittedText (fileSizeDescription,
  54136. sizeX, 0, dateX - sizeX - 8, height,
  54137. Justification::centredRight, 1);
  54138. g.drawFittedText (fileTimeDescription,
  54139. dateX, 0, width - 8 - dateX, height,
  54140. Justification::centredRight, 1);
  54141. }
  54142. }
  54143. else
  54144. {
  54145. g.drawFittedText (filename,
  54146. x, 0, width - x, height,
  54147. Justification::centredLeft, 1);
  54148. }
  54149. }
  54150. Button* LookAndFeel::createFileBrowserGoUpButton()
  54151. {
  54152. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54153. Path arrowPath;
  54154. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54155. DrawablePath arrowImage;
  54156. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54157. arrowImage.setPath (arrowPath);
  54158. goUpButton->setImages (&arrowImage);
  54159. return goUpButton;
  54160. }
  54161. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54162. DirectoryContentsDisplayComponent* fileListComponent,
  54163. FilePreviewComponent* previewComp,
  54164. ComboBox* currentPathBox,
  54165. TextEditor* filenameBox,
  54166. Button* goUpButton)
  54167. {
  54168. const int x = 8;
  54169. int w = browserComp.getWidth() - x - x;
  54170. if (previewComp != 0)
  54171. {
  54172. const int previewWidth = w / 3;
  54173. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54174. w -= previewWidth + 4;
  54175. }
  54176. int y = 4;
  54177. const int controlsHeight = 22;
  54178. const int bottomSectionHeight = controlsHeight + 8;
  54179. const int upButtonWidth = 50;
  54180. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54181. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54182. y += controlsHeight + 4;
  54183. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54184. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54185. y = listAsComp->getBottom() + 4;
  54186. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54187. }
  54188. // Pulls a drawable out of compressed valuetree data..
  54189. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54190. {
  54191. MemoryInputStream m (data, numBytes, false);
  54192. GZIPDecompressorInputStream gz (m);
  54193. ValueTree drawable (ValueTree::readFromStream (gz));
  54194. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54195. }
  54196. const Drawable* LookAndFeel::getDefaultFolderImage()
  54197. {
  54198. if (folderImage == 0)
  54199. {
  54200. static const unsigned char drawableData[] =
  54201. { 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,
  54202. 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,
  54203. 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,
  54204. 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,
  54205. 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,
  54206. 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,
  54207. 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,
  54208. 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,
  54209. 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,
  54210. 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,
  54211. 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,
  54212. 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,
  54213. 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,
  54214. 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,
  54215. 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 };
  54216. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54217. }
  54218. return folderImage;
  54219. }
  54220. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54221. {
  54222. if (documentImage == 0)
  54223. {
  54224. static const unsigned char drawableData[] =
  54225. { 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,
  54226. 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,
  54227. 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,
  54228. 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,
  54229. 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,
  54230. 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,
  54231. 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,
  54232. 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,
  54233. 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,
  54234. 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,
  54235. 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,
  54236. 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,
  54237. 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,
  54238. 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,
  54239. 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,
  54240. 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,
  54241. 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,
  54242. 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,
  54243. 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,
  54244. 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,
  54245. 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,
  54246. 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,
  54247. 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 };
  54248. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54249. }
  54250. return documentImage;
  54251. }
  54252. void LookAndFeel::playAlertSound()
  54253. {
  54254. PlatformUtilities::beep();
  54255. }
  54256. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54257. {
  54258. g.setColour (Colours::white.withAlpha (0.7f));
  54259. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54260. g.setColour (Colours::black.withAlpha (0.2f));
  54261. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54262. const int totalBlocks = 7;
  54263. const int numBlocks = roundToInt (totalBlocks * level);
  54264. const float w = (width - 6.0f) / (float) totalBlocks;
  54265. for (int i = 0; i < totalBlocks; ++i)
  54266. {
  54267. if (i >= numBlocks)
  54268. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54269. else
  54270. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54271. : Colours::red);
  54272. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54273. }
  54274. }
  54275. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54276. {
  54277. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54278. if (keyDescription.isNotEmpty())
  54279. {
  54280. if (button.isEnabled())
  54281. {
  54282. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54283. g.fillAll (textColour.withAlpha (alpha));
  54284. g.setOpacity (0.3f);
  54285. g.drawBevel (0, 0, width, height, 2);
  54286. }
  54287. g.setColour (textColour);
  54288. g.setFont (height * 0.6f);
  54289. g.drawFittedText (keyDescription,
  54290. 3, 0, width - 6, height,
  54291. Justification::centred, 1);
  54292. }
  54293. else
  54294. {
  54295. const float thickness = 7.0f;
  54296. const float indent = 22.0f;
  54297. Path p;
  54298. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54299. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54300. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54301. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54302. p.setUsingNonZeroWinding (false);
  54303. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54304. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54305. }
  54306. if (button.hasKeyboardFocus (false))
  54307. {
  54308. g.setColour (textColour.withAlpha (0.4f));
  54309. g.drawRect (0, 0, width, height);
  54310. }
  54311. }
  54312. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54313. float x, float y, float w, float h,
  54314. float maxCornerSize,
  54315. const Colour& baseColour,
  54316. const float strokeWidth,
  54317. const bool flatOnLeft,
  54318. const bool flatOnRight,
  54319. const bool flatOnTop,
  54320. const bool flatOnBottom) throw()
  54321. {
  54322. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54323. return;
  54324. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54325. Path outline;
  54326. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54327. ! (flatOnLeft || flatOnTop),
  54328. ! (flatOnRight || flatOnTop),
  54329. ! (flatOnLeft || flatOnBottom),
  54330. ! (flatOnRight || flatOnBottom));
  54331. ColourGradient cg (baseColour, 0.0f, y,
  54332. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54333. false);
  54334. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54335. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54336. g.setGradientFill (cg);
  54337. g.fillPath (outline);
  54338. g.setColour (Colour (0x80000000));
  54339. g.strokePath (outline, PathStrokeType (strokeWidth));
  54340. }
  54341. void LookAndFeel::drawGlassSphere (Graphics& g,
  54342. const float x, const float y,
  54343. const float diameter,
  54344. const Colour& colour,
  54345. const float outlineThickness) throw()
  54346. {
  54347. if (diameter <= outlineThickness)
  54348. return;
  54349. Path p;
  54350. p.addEllipse (x, y, diameter, diameter);
  54351. {
  54352. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54353. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54354. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54355. g.setGradientFill (cg);
  54356. g.fillPath (p);
  54357. }
  54358. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54359. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54360. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54361. ColourGradient cg (Colours::transparentBlack,
  54362. x + diameter * 0.5f, y + diameter * 0.5f,
  54363. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54364. x, y + diameter * 0.5f, true);
  54365. cg.addColour (0.7, Colours::transparentBlack);
  54366. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54367. g.setGradientFill (cg);
  54368. g.fillPath (p);
  54369. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54370. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54371. }
  54372. void LookAndFeel::drawGlassPointer (Graphics& g,
  54373. const float x, const float y,
  54374. const float diameter,
  54375. const Colour& colour, const float outlineThickness,
  54376. const int direction) throw()
  54377. {
  54378. if (diameter <= outlineThickness)
  54379. return;
  54380. Path p;
  54381. p.startNewSubPath (x + diameter * 0.5f, y);
  54382. p.lineTo (x + diameter, y + diameter * 0.6f);
  54383. p.lineTo (x + diameter, y + diameter);
  54384. p.lineTo (x, y + diameter);
  54385. p.lineTo (x, y + diameter * 0.6f);
  54386. p.closeSubPath();
  54387. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54388. {
  54389. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54390. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54391. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54392. g.setGradientFill (cg);
  54393. g.fillPath (p);
  54394. }
  54395. ColourGradient cg (Colours::transparentBlack,
  54396. x + diameter * 0.5f, y + diameter * 0.5f,
  54397. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54398. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54399. cg.addColour (0.5, Colours::transparentBlack);
  54400. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54401. g.setGradientFill (cg);
  54402. g.fillPath (p);
  54403. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54404. g.strokePath (p, PathStrokeType (outlineThickness));
  54405. }
  54406. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54407. const float x, const float y,
  54408. const float width, const float height,
  54409. const Colour& colour,
  54410. const float outlineThickness,
  54411. const float cornerSize,
  54412. const bool flatOnLeft,
  54413. const bool flatOnRight,
  54414. const bool flatOnTop,
  54415. const bool flatOnBottom) throw()
  54416. {
  54417. if (width <= outlineThickness || height <= outlineThickness)
  54418. return;
  54419. const int intX = (int) x;
  54420. const int intY = (int) y;
  54421. const int intW = (int) width;
  54422. const int intH = (int) height;
  54423. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54424. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54425. const int intEdge = (int) edgeBlurRadius;
  54426. Path outline;
  54427. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54428. ! (flatOnLeft || flatOnTop),
  54429. ! (flatOnRight || flatOnTop),
  54430. ! (flatOnLeft || flatOnBottom),
  54431. ! (flatOnRight || flatOnBottom));
  54432. {
  54433. ColourGradient cg (colour.darker (0.2f), 0, y,
  54434. colour.darker (0.2f), 0, y + height, false);
  54435. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54436. cg.addColour (0.4, colour);
  54437. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54438. g.setGradientFill (cg);
  54439. g.fillPath (outline);
  54440. }
  54441. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54442. colour.darker (0.2f), x, y + height * 0.5f, true);
  54443. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54444. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54445. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54446. {
  54447. g.saveState();
  54448. g.setGradientFill (cg);
  54449. g.reduceClipRegion (intX, intY, intEdge, intH);
  54450. g.fillPath (outline);
  54451. g.restoreState();
  54452. }
  54453. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54454. {
  54455. cg.point1.setX (x + width - edgeBlurRadius);
  54456. cg.point2.setX (x + width);
  54457. g.saveState();
  54458. g.setGradientFill (cg);
  54459. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54460. g.fillPath (outline);
  54461. g.restoreState();
  54462. }
  54463. {
  54464. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54465. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54466. Path highlight;
  54467. LookAndFeelHelpers::createRoundedPath (highlight,
  54468. x + leftIndent,
  54469. y + cs * 0.1f,
  54470. width - (leftIndent + rightIndent),
  54471. height * 0.4f, cs * 0.4f,
  54472. ! (flatOnLeft || flatOnTop),
  54473. ! (flatOnRight || flatOnTop),
  54474. ! (flatOnLeft || flatOnBottom),
  54475. ! (flatOnRight || flatOnBottom));
  54476. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54477. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54478. g.fillPath (highlight);
  54479. }
  54480. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54481. g.strokePath (outline, PathStrokeType (outlineThickness));
  54482. }
  54483. END_JUCE_NAMESPACE
  54484. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54485. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54486. BEGIN_JUCE_NAMESPACE
  54487. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54488. {
  54489. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54490. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54491. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54492. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54493. setColour (Slider::thumbColourId, Colours::white);
  54494. setColour (Slider::trackColourId, Colour (0x7f000000));
  54495. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54496. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54497. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54498. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54499. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54500. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54501. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54502. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54503. }
  54504. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54505. {
  54506. }
  54507. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54508. Button& button,
  54509. const Colour& backgroundColour,
  54510. bool isMouseOverButton,
  54511. bool isButtonDown)
  54512. {
  54513. const int width = button.getWidth();
  54514. const int height = button.getHeight();
  54515. const float indent = 2.0f;
  54516. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54517. roundToInt (height * 0.4f));
  54518. Path p;
  54519. p.addRoundedRectangle (indent, indent,
  54520. width - indent * 2.0f,
  54521. height - indent * 2.0f,
  54522. (float) cornerSize);
  54523. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54524. if (isMouseOverButton)
  54525. {
  54526. if (isButtonDown)
  54527. bc = bc.brighter();
  54528. else if (bc.getBrightness() > 0.5f)
  54529. bc = bc.darker (0.1f);
  54530. else
  54531. bc = bc.brighter (0.1f);
  54532. }
  54533. g.setColour (bc);
  54534. g.fillPath (p);
  54535. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54536. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54537. }
  54538. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54539. Component& /*component*/,
  54540. float x, float y, float w, float h,
  54541. const bool ticked,
  54542. const bool isEnabled,
  54543. const bool /*isMouseOverButton*/,
  54544. const bool isButtonDown)
  54545. {
  54546. Path box;
  54547. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54548. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54549. : Colours::lightgrey.withAlpha (0.1f));
  54550. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54551. g.fillPath (box, trans);
  54552. g.setColour (Colours::black.withAlpha (0.6f));
  54553. g.strokePath (box, PathStrokeType (0.9f), trans);
  54554. if (ticked)
  54555. {
  54556. Path tick;
  54557. tick.startNewSubPath (1.5f, 3.0f);
  54558. tick.lineTo (3.0f, 6.0f);
  54559. tick.lineTo (6.0f, 0.0f);
  54560. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54561. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54562. }
  54563. }
  54564. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54565. ToggleButton& button,
  54566. bool isMouseOverButton,
  54567. bool isButtonDown)
  54568. {
  54569. if (button.hasKeyboardFocus (true))
  54570. {
  54571. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54572. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54573. }
  54574. const int tickWidth = jmin (20, button.getHeight() - 4);
  54575. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54576. (float) tickWidth, (float) tickWidth,
  54577. button.getToggleState(),
  54578. button.isEnabled(),
  54579. isMouseOverButton,
  54580. isButtonDown);
  54581. g.setColour (button.findColour (ToggleButton::textColourId));
  54582. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54583. if (! button.isEnabled())
  54584. g.setOpacity (0.5f);
  54585. const int textX = tickWidth + 5;
  54586. g.drawFittedText (button.getButtonText(),
  54587. textX, 4,
  54588. button.getWidth() - textX - 2, button.getHeight() - 8,
  54589. Justification::centredLeft, 10);
  54590. }
  54591. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54592. int width, int height,
  54593. double progress, const String& textToShow)
  54594. {
  54595. if (progress < 0 || progress >= 1.0)
  54596. {
  54597. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54598. }
  54599. else
  54600. {
  54601. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54602. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54603. g.fillAll (background);
  54604. g.setColour (foreground);
  54605. g.fillRect (1, 1,
  54606. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54607. height - 2);
  54608. if (textToShow.isNotEmpty())
  54609. {
  54610. g.setColour (Colour::contrasting (background, foreground));
  54611. g.setFont (height * 0.6f);
  54612. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54613. }
  54614. }
  54615. }
  54616. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54617. ScrollBar& bar,
  54618. int width, int height,
  54619. int buttonDirection,
  54620. bool isScrollbarVertical,
  54621. bool isMouseOverButton,
  54622. bool isButtonDown)
  54623. {
  54624. if (isScrollbarVertical)
  54625. width -= 2;
  54626. else
  54627. height -= 2;
  54628. Path p;
  54629. if (buttonDirection == 0)
  54630. p.addTriangle (width * 0.5f, height * 0.2f,
  54631. width * 0.1f, height * 0.7f,
  54632. width * 0.9f, height * 0.7f);
  54633. else if (buttonDirection == 1)
  54634. p.addTriangle (width * 0.8f, height * 0.5f,
  54635. width * 0.3f, height * 0.1f,
  54636. width * 0.3f, height * 0.9f);
  54637. else if (buttonDirection == 2)
  54638. p.addTriangle (width * 0.5f, height * 0.8f,
  54639. width * 0.1f, height * 0.3f,
  54640. width * 0.9f, height * 0.3f);
  54641. else if (buttonDirection == 3)
  54642. p.addTriangle (width * 0.2f, height * 0.5f,
  54643. width * 0.7f, height * 0.1f,
  54644. width * 0.7f, height * 0.9f);
  54645. if (isButtonDown)
  54646. g.setColour (Colours::white);
  54647. else if (isMouseOverButton)
  54648. g.setColour (Colours::white.withAlpha (0.7f));
  54649. else
  54650. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54651. g.fillPath (p);
  54652. g.setColour (Colours::black.withAlpha (0.5f));
  54653. g.strokePath (p, PathStrokeType (0.5f));
  54654. }
  54655. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54656. ScrollBar& bar,
  54657. int x, int y,
  54658. int width, int height,
  54659. bool isScrollbarVertical,
  54660. int thumbStartPosition,
  54661. int thumbSize,
  54662. bool isMouseOver,
  54663. bool isMouseDown)
  54664. {
  54665. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54666. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54667. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54668. if (thumbSize > 0.0f)
  54669. {
  54670. Rectangle<int> thumb;
  54671. if (isScrollbarVertical)
  54672. {
  54673. width -= 2;
  54674. g.fillRect (x + roundToInt (width * 0.35f), y,
  54675. roundToInt (width * 0.3f), height);
  54676. thumb.setBounds (x + 1, thumbStartPosition,
  54677. width - 2, thumbSize);
  54678. }
  54679. else
  54680. {
  54681. height -= 2;
  54682. g.fillRect (x, y + roundToInt (height * 0.35f),
  54683. width, roundToInt (height * 0.3f));
  54684. thumb.setBounds (thumbStartPosition, y + 1,
  54685. thumbSize, height - 2);
  54686. }
  54687. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54688. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54689. g.fillRect (thumb);
  54690. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54691. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54692. if (thumbSize > 16)
  54693. {
  54694. for (int i = 3; --i >= 0;)
  54695. {
  54696. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54697. g.setColour (Colours::black.withAlpha (0.15f));
  54698. if (isScrollbarVertical)
  54699. {
  54700. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54701. g.setColour (Colours::white.withAlpha (0.15f));
  54702. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54703. }
  54704. else
  54705. {
  54706. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54707. g.setColour (Colours::white.withAlpha (0.15f));
  54708. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54709. }
  54710. }
  54711. }
  54712. }
  54713. }
  54714. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54715. {
  54716. return &scrollbarShadow;
  54717. }
  54718. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54719. {
  54720. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54721. g.setColour (Colours::black.withAlpha (0.6f));
  54722. g.drawRect (0, 0, width, height);
  54723. }
  54724. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54725. bool, MenuBarComponent& menuBar)
  54726. {
  54727. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54728. }
  54729. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54730. {
  54731. if (textEditor.isEnabled())
  54732. {
  54733. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54734. g.drawRect (0, 0, width, height);
  54735. }
  54736. }
  54737. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54738. const bool isButtonDown,
  54739. int buttonX, int buttonY,
  54740. int buttonW, int buttonH,
  54741. ComboBox& box)
  54742. {
  54743. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54744. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54745. : ComboBox::backgroundColourId));
  54746. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54747. g.setColour (box.findColour (ComboBox::outlineColourId));
  54748. g.drawRect (0, 0, width, height);
  54749. const float arrowX = 0.2f;
  54750. const float arrowH = 0.3f;
  54751. if (box.isEnabled())
  54752. {
  54753. Path p;
  54754. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54755. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54756. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54757. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54758. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54759. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54760. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54761. : ComboBox::buttonColourId));
  54762. g.fillPath (p);
  54763. }
  54764. }
  54765. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54766. {
  54767. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54768. f.setHorizontalScale (0.9f);
  54769. return f;
  54770. }
  54771. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54772. {
  54773. Path p;
  54774. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54775. g.setColour (fill);
  54776. g.fillPath (p);
  54777. g.setColour (outline);
  54778. g.strokePath (p, PathStrokeType (0.3f));
  54779. }
  54780. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54781. int x, int y,
  54782. int w, int h,
  54783. float sliderPos,
  54784. float minSliderPos,
  54785. float maxSliderPos,
  54786. const Slider::SliderStyle style,
  54787. Slider& slider)
  54788. {
  54789. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54790. if (style == Slider::LinearBar)
  54791. {
  54792. g.setColour (slider.findColour (Slider::thumbColourId));
  54793. g.fillRect (x, y, (int) sliderPos - x, h);
  54794. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54795. g.drawRect (x, y, (int) sliderPos - x, h);
  54796. }
  54797. else
  54798. {
  54799. g.setColour (slider.findColour (Slider::trackColourId)
  54800. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54801. if (slider.isHorizontal())
  54802. {
  54803. g.fillRect (x, y + roundToInt (h * 0.6f),
  54804. w, roundToInt (h * 0.2f));
  54805. }
  54806. else
  54807. {
  54808. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54809. jmin (4, roundToInt (w * 0.2f)), h);
  54810. }
  54811. float alpha = 0.35f;
  54812. if (slider.isEnabled())
  54813. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54814. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54815. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54816. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54817. {
  54818. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54819. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54820. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54821. fill, outline);
  54822. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54823. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54824. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54825. fill, outline);
  54826. }
  54827. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54828. {
  54829. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54830. minSliderPos - 7.0f, y + h * 0.9f ,
  54831. minSliderPos, y + h * 0.9f,
  54832. fill, outline);
  54833. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54834. maxSliderPos, y + h * 0.9f,
  54835. maxSliderPos + 7.0f, y + h * 0.9f,
  54836. fill, outline);
  54837. }
  54838. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54839. {
  54840. drawTriangle (g, sliderPos, y + h * 0.9f,
  54841. sliderPos - 7.0f, y + h * 0.2f,
  54842. sliderPos + 7.0f, y + h * 0.2f,
  54843. fill, outline);
  54844. }
  54845. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54846. {
  54847. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54848. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54849. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54850. fill, outline);
  54851. }
  54852. }
  54853. }
  54854. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54855. {
  54856. if (isIncrement)
  54857. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54858. else
  54859. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54860. }
  54861. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54862. {
  54863. return &scrollbarShadow;
  54864. }
  54865. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54866. {
  54867. return 8;
  54868. }
  54869. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54870. int w, int h,
  54871. bool isMouseOver,
  54872. bool isMouseDragging)
  54873. {
  54874. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54875. : Colours::darkgrey);
  54876. const float lineThickness = jmin (w, h) * 0.1f;
  54877. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54878. {
  54879. g.drawLine (w * i,
  54880. h + 1.0f,
  54881. w + 1.0f,
  54882. h * i,
  54883. lineThickness);
  54884. }
  54885. }
  54886. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54887. {
  54888. Path shape;
  54889. if (buttonType == DocumentWindow::closeButton)
  54890. {
  54891. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54892. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54893. ShapeButton* const b = new ShapeButton ("close",
  54894. Colour (0x7fff3333),
  54895. Colour (0xd7ff3333),
  54896. Colour (0xf7ff3333));
  54897. b->setShape (shape, true, true, true);
  54898. return b;
  54899. }
  54900. else if (buttonType == DocumentWindow::minimiseButton)
  54901. {
  54902. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54903. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54904. DrawablePath dp;
  54905. dp.setPath (shape);
  54906. dp.setFill (Colours::black.withAlpha (0.3f));
  54907. b->setImages (&dp);
  54908. return b;
  54909. }
  54910. else if (buttonType == DocumentWindow::maximiseButton)
  54911. {
  54912. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54913. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54914. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54915. DrawablePath dp;
  54916. dp.setPath (shape);
  54917. dp.setFill (Colours::black.withAlpha (0.3f));
  54918. b->setImages (&dp);
  54919. return b;
  54920. }
  54921. jassertfalse;
  54922. return 0;
  54923. }
  54924. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54925. int titleBarX,
  54926. int titleBarY,
  54927. int titleBarW,
  54928. int titleBarH,
  54929. Button* minimiseButton,
  54930. Button* maximiseButton,
  54931. Button* closeButton,
  54932. bool positionTitleBarButtonsOnLeft)
  54933. {
  54934. titleBarY += titleBarH / 8;
  54935. titleBarH -= titleBarH / 4;
  54936. const int buttonW = titleBarH;
  54937. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54938. : titleBarX + titleBarW - buttonW - 4;
  54939. if (closeButton != 0)
  54940. {
  54941. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54942. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54943. : -(buttonW + buttonW / 5);
  54944. }
  54945. if (positionTitleBarButtonsOnLeft)
  54946. swapVariables (minimiseButton, maximiseButton);
  54947. if (maximiseButton != 0)
  54948. {
  54949. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54950. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54951. }
  54952. if (minimiseButton != 0)
  54953. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54954. }
  54955. END_JUCE_NAMESPACE
  54956. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54957. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54958. BEGIN_JUCE_NAMESPACE
  54959. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54960. : model (0),
  54961. itemUnderMouse (-1),
  54962. currentPopupIndex (-1),
  54963. topLevelIndexClicked (0),
  54964. lastMouseX (0),
  54965. lastMouseY (0)
  54966. {
  54967. setRepaintsOnMouseActivity (true);
  54968. setWantsKeyboardFocus (false);
  54969. setMouseClickGrabsKeyboardFocus (false);
  54970. setModel (model_);
  54971. }
  54972. MenuBarComponent::~MenuBarComponent()
  54973. {
  54974. setModel (0);
  54975. Desktop::getInstance().removeGlobalMouseListener (this);
  54976. }
  54977. MenuBarModel* MenuBarComponent::getModel() const throw()
  54978. {
  54979. return model;
  54980. }
  54981. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54982. {
  54983. if (model != newModel)
  54984. {
  54985. if (model != 0)
  54986. model->removeListener (this);
  54987. model = newModel;
  54988. if (model != 0)
  54989. model->addListener (this);
  54990. repaint();
  54991. menuBarItemsChanged (0);
  54992. }
  54993. }
  54994. void MenuBarComponent::paint (Graphics& g)
  54995. {
  54996. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54997. getLookAndFeel().drawMenuBarBackground (g,
  54998. getWidth(),
  54999. getHeight(),
  55000. isMouseOverBar,
  55001. *this);
  55002. if (model != 0)
  55003. {
  55004. for (int i = 0; i < menuNames.size(); ++i)
  55005. {
  55006. Graphics::ScopedSaveState ss (g);
  55007. g.setOrigin (xPositions [i], 0);
  55008. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55009. getLookAndFeel().drawMenuBarItem (g,
  55010. xPositions[i + 1] - xPositions[i],
  55011. getHeight(),
  55012. i,
  55013. menuNames[i],
  55014. i == itemUnderMouse,
  55015. i == currentPopupIndex,
  55016. isMouseOverBar,
  55017. *this);
  55018. }
  55019. }
  55020. }
  55021. void MenuBarComponent::resized()
  55022. {
  55023. xPositions.clear();
  55024. int x = 0;
  55025. xPositions.add (x);
  55026. for (int i = 0; i < menuNames.size(); ++i)
  55027. {
  55028. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55029. xPositions.add (x);
  55030. }
  55031. }
  55032. int MenuBarComponent::getItemAt (const int x, const int y)
  55033. {
  55034. for (int i = 0; i < xPositions.size(); ++i)
  55035. if (x >= xPositions[i] && x < xPositions[i + 1])
  55036. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55037. return -1;
  55038. }
  55039. void MenuBarComponent::repaintMenuItem (int index)
  55040. {
  55041. if (isPositiveAndBelow (index, xPositions.size()))
  55042. {
  55043. const int x1 = xPositions [index];
  55044. const int x2 = xPositions [index + 1];
  55045. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55046. }
  55047. }
  55048. void MenuBarComponent::setItemUnderMouse (const int index)
  55049. {
  55050. if (itemUnderMouse != index)
  55051. {
  55052. repaintMenuItem (itemUnderMouse);
  55053. itemUnderMouse = index;
  55054. repaintMenuItem (itemUnderMouse);
  55055. }
  55056. }
  55057. void MenuBarComponent::setOpenItem (int index)
  55058. {
  55059. if (currentPopupIndex != index)
  55060. {
  55061. repaintMenuItem (currentPopupIndex);
  55062. currentPopupIndex = index;
  55063. repaintMenuItem (currentPopupIndex);
  55064. if (index >= 0)
  55065. Desktop::getInstance().addGlobalMouseListener (this);
  55066. else
  55067. Desktop::getInstance().removeGlobalMouseListener (this);
  55068. }
  55069. }
  55070. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55071. {
  55072. setItemUnderMouse (getItemAt (x, y));
  55073. }
  55074. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55075. {
  55076. public:
  55077. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55078. : bar (bar_), topLevelIndex (topLevelIndex_)
  55079. {
  55080. }
  55081. void modalStateFinished (int returnValue)
  55082. {
  55083. if (bar != 0)
  55084. bar->menuDismissed (topLevelIndex, returnValue);
  55085. }
  55086. private:
  55087. Component::SafePointer<MenuBarComponent> bar;
  55088. const int topLevelIndex;
  55089. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55090. };
  55091. void MenuBarComponent::showMenu (int index)
  55092. {
  55093. if (index != currentPopupIndex)
  55094. {
  55095. PopupMenu::dismissAllActiveMenus();
  55096. menuBarItemsChanged (0);
  55097. setOpenItem (index);
  55098. setItemUnderMouse (index);
  55099. if (index >= 0)
  55100. {
  55101. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55102. menuNames [itemUnderMouse]));
  55103. if (m.lookAndFeel == 0)
  55104. m.setLookAndFeel (&getLookAndFeel());
  55105. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55106. m.showMenu (localAreaToGlobal (itemPos),
  55107. 0, itemPos.getWidth(), 0, 0, this,
  55108. new AsyncCallback (this, index));
  55109. }
  55110. }
  55111. }
  55112. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55113. {
  55114. topLevelIndexClicked = topLevelIndex;
  55115. postCommandMessage (itemId);
  55116. }
  55117. void MenuBarComponent::handleCommandMessage (int commandId)
  55118. {
  55119. const Point<int> mousePos (getMouseXYRelative());
  55120. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55121. if (currentPopupIndex == topLevelIndexClicked)
  55122. setOpenItem (-1);
  55123. if (commandId != 0 && model != 0)
  55124. model->menuItemSelected (commandId, topLevelIndexClicked);
  55125. }
  55126. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55127. {
  55128. if (e.eventComponent == this)
  55129. updateItemUnderMouse (e.x, e.y);
  55130. }
  55131. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55132. {
  55133. if (e.eventComponent == this)
  55134. updateItemUnderMouse (e.x, e.y);
  55135. }
  55136. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55137. {
  55138. if (currentPopupIndex < 0)
  55139. {
  55140. const MouseEvent e2 (e.getEventRelativeTo (this));
  55141. updateItemUnderMouse (e2.x, e2.y);
  55142. currentPopupIndex = -2;
  55143. showMenu (itemUnderMouse);
  55144. }
  55145. }
  55146. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55147. {
  55148. const MouseEvent e2 (e.getEventRelativeTo (this));
  55149. const int item = getItemAt (e2.x, e2.y);
  55150. if (item >= 0)
  55151. showMenu (item);
  55152. }
  55153. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55154. {
  55155. const MouseEvent e2 (e.getEventRelativeTo (this));
  55156. updateItemUnderMouse (e2.x, e2.y);
  55157. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55158. {
  55159. setOpenItem (-1);
  55160. PopupMenu::dismissAllActiveMenus();
  55161. }
  55162. }
  55163. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55164. {
  55165. const MouseEvent e2 (e.getEventRelativeTo (this));
  55166. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55167. {
  55168. if (currentPopupIndex >= 0)
  55169. {
  55170. const int item = getItemAt (e2.x, e2.y);
  55171. if (item >= 0)
  55172. showMenu (item);
  55173. }
  55174. else
  55175. {
  55176. updateItemUnderMouse (e2.x, e2.y);
  55177. }
  55178. lastMouseX = e2.x;
  55179. lastMouseY = e2.y;
  55180. }
  55181. }
  55182. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55183. {
  55184. bool used = false;
  55185. const int numMenus = menuNames.size();
  55186. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55187. if (key.isKeyCode (KeyPress::leftKey))
  55188. {
  55189. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55190. used = true;
  55191. }
  55192. else if (key.isKeyCode (KeyPress::rightKey))
  55193. {
  55194. showMenu ((currentIndex + 1) % numMenus);
  55195. used = true;
  55196. }
  55197. return used;
  55198. }
  55199. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55200. {
  55201. StringArray newNames;
  55202. if (model != 0)
  55203. newNames = model->getMenuBarNames();
  55204. if (newNames != menuNames)
  55205. {
  55206. menuNames = newNames;
  55207. repaint();
  55208. resized();
  55209. }
  55210. }
  55211. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55212. const ApplicationCommandTarget::InvocationInfo& info)
  55213. {
  55214. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55215. return;
  55216. for (int i = 0; i < menuNames.size(); ++i)
  55217. {
  55218. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55219. if (menu.containsCommandItem (info.commandID))
  55220. {
  55221. setItemUnderMouse (i);
  55222. startTimer (200);
  55223. break;
  55224. }
  55225. }
  55226. }
  55227. void MenuBarComponent::timerCallback()
  55228. {
  55229. stopTimer();
  55230. const Point<int> mousePos (getMouseXYRelative());
  55231. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55232. }
  55233. END_JUCE_NAMESPACE
  55234. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55235. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55236. BEGIN_JUCE_NAMESPACE
  55237. MenuBarModel::MenuBarModel() throw()
  55238. : manager (0)
  55239. {
  55240. }
  55241. MenuBarModel::~MenuBarModel()
  55242. {
  55243. setApplicationCommandManagerToWatch (0);
  55244. }
  55245. void MenuBarModel::menuItemsChanged()
  55246. {
  55247. triggerAsyncUpdate();
  55248. }
  55249. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55250. {
  55251. if (manager != newManager)
  55252. {
  55253. if (manager != 0)
  55254. manager->removeListener (this);
  55255. manager = newManager;
  55256. if (manager != 0)
  55257. manager->addListener (this);
  55258. }
  55259. }
  55260. void MenuBarModel::addListener (Listener* const newListener) throw()
  55261. {
  55262. listeners.add (newListener);
  55263. }
  55264. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55265. {
  55266. // Trying to remove a listener that isn't on the list!
  55267. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55268. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55269. jassert (listeners.contains (listenerToRemove));
  55270. listeners.remove (listenerToRemove);
  55271. }
  55272. void MenuBarModel::handleAsyncUpdate()
  55273. {
  55274. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55275. }
  55276. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55277. {
  55278. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55279. }
  55280. void MenuBarModel::applicationCommandListChanged()
  55281. {
  55282. menuItemsChanged();
  55283. }
  55284. END_JUCE_NAMESPACE
  55285. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55286. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55287. BEGIN_JUCE_NAMESPACE
  55288. class PopupMenu::Item
  55289. {
  55290. public:
  55291. Item()
  55292. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55293. usesColour (false), customComp (0), commandManager (0)
  55294. {
  55295. }
  55296. Item (const int itemId_,
  55297. const String& text_,
  55298. const bool active_,
  55299. const bool isTicked_,
  55300. const Image& im,
  55301. const Colour& textColour_,
  55302. const bool usesColour_,
  55303. CustomComponent* const customComp_,
  55304. const PopupMenu* const subMenu_,
  55305. ApplicationCommandManager* const commandManager_)
  55306. : itemId (itemId_), text (text_), textColour (textColour_),
  55307. active (active_), isSeparator (false), isTicked (isTicked_),
  55308. usesColour (usesColour_), image (im), customComp (customComp_),
  55309. commandManager (commandManager_)
  55310. {
  55311. if (subMenu_ != 0)
  55312. subMenu = new PopupMenu (*subMenu_);
  55313. if (commandManager_ != 0 && itemId_ != 0)
  55314. {
  55315. String shortcutKey;
  55316. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55317. ->getKeyPressesAssignedToCommand (itemId_));
  55318. for (int i = 0; i < keyPresses.size(); ++i)
  55319. {
  55320. const String key (keyPresses.getReference(i).getTextDescription());
  55321. if (shortcutKey.isNotEmpty())
  55322. shortcutKey << ", ";
  55323. if (key.length() == 1)
  55324. shortcutKey << "shortcut: '" << key << '\'';
  55325. else
  55326. shortcutKey << key;
  55327. }
  55328. shortcutKey = shortcutKey.trim();
  55329. if (shortcutKey.isNotEmpty())
  55330. text << "<end>" << shortcutKey;
  55331. }
  55332. }
  55333. Item (const Item& other)
  55334. : itemId (other.itemId),
  55335. text (other.text),
  55336. textColour (other.textColour),
  55337. active (other.active),
  55338. isSeparator (other.isSeparator),
  55339. isTicked (other.isTicked),
  55340. usesColour (other.usesColour),
  55341. image (other.image),
  55342. customComp (other.customComp),
  55343. commandManager (other.commandManager)
  55344. {
  55345. if (other.subMenu != 0)
  55346. subMenu = new PopupMenu (*(other.subMenu));
  55347. }
  55348. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55349. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55350. const int itemId;
  55351. String text;
  55352. const Colour textColour;
  55353. const bool active, isSeparator, isTicked, usesColour;
  55354. Image image;
  55355. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55356. ScopedPointer <PopupMenu> subMenu;
  55357. ApplicationCommandManager* const commandManager;
  55358. private:
  55359. Item& operator= (const Item&);
  55360. JUCE_LEAK_DETECTOR (Item);
  55361. };
  55362. class PopupMenu::ItemComponent : public Component
  55363. {
  55364. public:
  55365. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55366. : itemInfo (itemInfo_),
  55367. isHighlighted (false)
  55368. {
  55369. if (itemInfo.customComp != 0)
  55370. addAndMakeVisible (itemInfo.customComp);
  55371. int itemW = 80;
  55372. int itemH = 16;
  55373. getIdealSize (itemW, itemH, standardItemHeight);
  55374. setSize (itemW, jlimit (2, 600, itemH));
  55375. }
  55376. ~ItemComponent()
  55377. {
  55378. if (itemInfo.customComp != 0)
  55379. removeChildComponent (itemInfo.customComp);
  55380. }
  55381. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55382. {
  55383. if (itemInfo.customComp != 0)
  55384. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55385. else
  55386. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55387. itemInfo.isSeparator,
  55388. standardItemHeight,
  55389. idealWidth, idealHeight);
  55390. }
  55391. void paint (Graphics& g)
  55392. {
  55393. if (itemInfo.customComp == 0)
  55394. {
  55395. String mainText (itemInfo.text);
  55396. String endText;
  55397. const int endIndex = mainText.indexOf ("<end>");
  55398. if (endIndex >= 0)
  55399. {
  55400. endText = mainText.substring (endIndex + 5).trim();
  55401. mainText = mainText.substring (0, endIndex);
  55402. }
  55403. getLookAndFeel()
  55404. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55405. itemInfo.isSeparator,
  55406. itemInfo.active,
  55407. isHighlighted,
  55408. itemInfo.isTicked,
  55409. itemInfo.subMenu != 0,
  55410. mainText, endText,
  55411. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55412. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55413. }
  55414. }
  55415. void resized()
  55416. {
  55417. if (getNumChildComponents() > 0)
  55418. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55419. }
  55420. void setHighlighted (bool shouldBeHighlighted)
  55421. {
  55422. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55423. if (isHighlighted != shouldBeHighlighted)
  55424. {
  55425. isHighlighted = shouldBeHighlighted;
  55426. if (itemInfo.customComp != 0)
  55427. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55428. repaint();
  55429. }
  55430. }
  55431. PopupMenu::Item itemInfo;
  55432. private:
  55433. bool isHighlighted;
  55434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55435. };
  55436. namespace PopupMenuSettings
  55437. {
  55438. const int scrollZone = 24;
  55439. const int borderSize = 2;
  55440. const int timerInterval = 50;
  55441. const int dismissCommandId = 0x6287345f;
  55442. }
  55443. class PopupMenu::Window : public Component,
  55444. private Timer
  55445. {
  55446. public:
  55447. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55448. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55449. const int minimumWidth_, const int maximumNumColumns_,
  55450. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55451. ApplicationCommandManager** const managerOfChosenCommand_,
  55452. Component* const componentAttachedTo_)
  55453. : Component ("menu"),
  55454. owner (owner_),
  55455. activeSubMenu (0),
  55456. managerOfChosenCommand (managerOfChosenCommand_),
  55457. componentAttachedTo (componentAttachedTo_),
  55458. componentAttachedToOriginal (componentAttachedTo_),
  55459. minimumWidth (minimumWidth_),
  55460. maximumNumColumns (maximumNumColumns_),
  55461. standardItemHeight (standardItemHeight_),
  55462. isOver (false),
  55463. hasBeenOver (false),
  55464. isDown (false),
  55465. needsToScroll (false),
  55466. dismissOnMouseUp (dismissOnMouseUp_),
  55467. hideOnExit (false),
  55468. disableMouseMoves (false),
  55469. hasAnyJuceCompHadFocus (false),
  55470. numColumns (0),
  55471. contentHeight (0),
  55472. childYOffset (0),
  55473. menuCreationTime (Time::getMillisecondCounter()),
  55474. lastMouseMoveTime (0),
  55475. timeEnteredCurrentChildComp (0),
  55476. scrollAcceleration (1.0)
  55477. {
  55478. lastFocused = lastScroll = menuCreationTime;
  55479. setWantsKeyboardFocus (false);
  55480. setMouseClickGrabsKeyboardFocus (false);
  55481. setAlwaysOnTop (true);
  55482. setLookAndFeel (menu.lookAndFeel);
  55483. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55484. for (int i = 0; i < menu.items.size(); ++i)
  55485. {
  55486. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55487. items.add (itemComp);
  55488. addAndMakeVisible (itemComp);
  55489. itemComp->addMouseListener (this, false);
  55490. }
  55491. calculateWindowPos (target, alignToRectangle);
  55492. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55493. updateYPositions();
  55494. if (itemIdThatMustBeVisible != 0)
  55495. {
  55496. const int y = target.getY() - windowPos.getY();
  55497. ensureItemIsVisible (itemIdThatMustBeVisible,
  55498. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55499. }
  55500. resizeToBestWindowPos();
  55501. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55502. getActiveWindows().add (this);
  55503. Desktop::getInstance().addGlobalMouseListener (this);
  55504. }
  55505. ~Window()
  55506. {
  55507. getActiveWindows().removeValue (this);
  55508. Desktop::getInstance().removeGlobalMouseListener (this);
  55509. activeSubMenu = 0;
  55510. items.clear();
  55511. }
  55512. static Window* create (const PopupMenu& menu,
  55513. bool dismissOnMouseUp,
  55514. Window* const owner_,
  55515. const Rectangle<int>& target,
  55516. int minimumWidth,
  55517. int maximumNumColumns,
  55518. int standardItemHeight,
  55519. bool alignToRectangle,
  55520. int itemIdThatMustBeVisible,
  55521. ApplicationCommandManager** managerOfChosenCommand,
  55522. Component* componentAttachedTo)
  55523. {
  55524. if (menu.items.size() > 0)
  55525. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55526. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55527. managerOfChosenCommand, componentAttachedTo);
  55528. return 0;
  55529. }
  55530. void paint (Graphics& g)
  55531. {
  55532. if (isOpaque())
  55533. g.fillAll (Colours::white);
  55534. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55535. }
  55536. void paintOverChildren (Graphics& g)
  55537. {
  55538. if (isScrolling())
  55539. {
  55540. LookAndFeel& lf = getLookAndFeel();
  55541. if (isScrollZoneActive (false))
  55542. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55543. if (isScrollZoneActive (true))
  55544. {
  55545. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55546. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55547. }
  55548. }
  55549. }
  55550. bool isScrollZoneActive (bool bottomOne) const
  55551. {
  55552. return isScrolling()
  55553. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55554. : childYOffset > 0);
  55555. }
  55556. // hide this and all sub-comps
  55557. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55558. {
  55559. if (isVisible())
  55560. {
  55561. activeSubMenu = 0;
  55562. currentChild = 0;
  55563. exitModalState (item != 0 ? item->itemId : 0);
  55564. if (makeInvisible)
  55565. setVisible (false);
  55566. if (item != 0
  55567. && item->commandManager != 0
  55568. && item->itemId != 0)
  55569. {
  55570. *managerOfChosenCommand = item->commandManager;
  55571. }
  55572. }
  55573. }
  55574. void dismissMenu (const PopupMenu::Item* const item)
  55575. {
  55576. if (owner != 0)
  55577. {
  55578. owner->dismissMenu (item);
  55579. }
  55580. else
  55581. {
  55582. if (item != 0)
  55583. {
  55584. // need a copy of this on the stack as the one passed in will get deleted during this call
  55585. const PopupMenu::Item mi (*item);
  55586. hide (&mi, false);
  55587. }
  55588. else
  55589. {
  55590. hide (0, false);
  55591. }
  55592. }
  55593. }
  55594. void mouseMove (const MouseEvent&) { timerCallback(); }
  55595. void mouseDown (const MouseEvent&) { timerCallback(); }
  55596. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55597. void mouseUp (const MouseEvent&) { timerCallback(); }
  55598. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55599. {
  55600. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55601. lastMouse = Point<int> (-1, -1);
  55602. }
  55603. bool keyPressed (const KeyPress& key)
  55604. {
  55605. if (key.isKeyCode (KeyPress::downKey))
  55606. {
  55607. selectNextItem (1);
  55608. }
  55609. else if (key.isKeyCode (KeyPress::upKey))
  55610. {
  55611. selectNextItem (-1);
  55612. }
  55613. else if (key.isKeyCode (KeyPress::leftKey))
  55614. {
  55615. if (owner != 0)
  55616. {
  55617. Component::SafePointer<Window> parentWindow (owner);
  55618. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55619. hide (0, true);
  55620. if (parentWindow != 0)
  55621. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55622. disableTimerUntilMouseMoves();
  55623. }
  55624. else if (componentAttachedTo != 0)
  55625. {
  55626. componentAttachedTo->keyPressed (key);
  55627. }
  55628. }
  55629. else if (key.isKeyCode (KeyPress::rightKey))
  55630. {
  55631. disableTimerUntilMouseMoves();
  55632. if (showSubMenuFor (currentChild))
  55633. {
  55634. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55635. activeSubMenu->selectNextItem (1);
  55636. }
  55637. else if (componentAttachedTo != 0)
  55638. {
  55639. componentAttachedTo->keyPressed (key);
  55640. }
  55641. }
  55642. else if (key.isKeyCode (KeyPress::returnKey))
  55643. {
  55644. triggerCurrentlyHighlightedItem();
  55645. }
  55646. else if (key.isKeyCode (KeyPress::escapeKey))
  55647. {
  55648. dismissMenu (0);
  55649. }
  55650. else
  55651. {
  55652. return false;
  55653. }
  55654. return true;
  55655. }
  55656. void inputAttemptWhenModal()
  55657. {
  55658. WeakReference<Component> deletionChecker (this);
  55659. timerCallback();
  55660. if (deletionChecker != 0 && ! isOverAnyMenu())
  55661. {
  55662. if (componentAttachedTo != 0)
  55663. {
  55664. // we want to dismiss the menu, but if we do it synchronously, then
  55665. // the mouse-click will be allowed to pass through. That's good, except
  55666. // when the user clicks on the button that orginally popped the menu up,
  55667. // as they'll expect the menu to go away, and in fact it'll just
  55668. // come back. So only dismiss synchronously if they're not on the original
  55669. // comp that we're attached to.
  55670. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55671. if (componentAttachedTo->reallyContains (mousePos, true))
  55672. {
  55673. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55674. return;
  55675. }
  55676. }
  55677. dismissMenu (0);
  55678. }
  55679. }
  55680. void handleCommandMessage (int commandId)
  55681. {
  55682. Component::handleCommandMessage (commandId);
  55683. if (commandId == PopupMenuSettings::dismissCommandId)
  55684. dismissMenu (0);
  55685. }
  55686. void timerCallback()
  55687. {
  55688. if (! isVisible())
  55689. return;
  55690. if (componentAttachedTo != componentAttachedToOriginal)
  55691. {
  55692. dismissMenu (0);
  55693. return;
  55694. }
  55695. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55696. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55697. return;
  55698. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55699. // move rather than a real timer callback
  55700. const Point<int> globalMousePos (Desktop::getMousePosition());
  55701. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55702. const uint32 now = Time::getMillisecondCounter();
  55703. if (now > timeEnteredCurrentChildComp + 100
  55704. && reallyContains (localMousePos, true)
  55705. && currentChild != 0
  55706. && (! disableMouseMoves)
  55707. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55708. {
  55709. showSubMenuFor (currentChild);
  55710. }
  55711. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55712. {
  55713. highlightItemUnderMouse (globalMousePos, localMousePos);
  55714. }
  55715. bool overScrollArea = false;
  55716. if (isScrolling()
  55717. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55718. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55719. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55720. {
  55721. if (now > lastScroll + 20)
  55722. {
  55723. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55724. int amount = 0;
  55725. for (int i = 0; i < items.size() && amount == 0; ++i)
  55726. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55727. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55728. lastScroll = now;
  55729. }
  55730. overScrollArea = true;
  55731. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55732. }
  55733. else
  55734. {
  55735. scrollAcceleration = 1.0;
  55736. }
  55737. const bool wasDown = isDown;
  55738. bool isOverAny = isOverAnyMenu();
  55739. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55740. {
  55741. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55742. isOverAny = isOverAnyMenu();
  55743. }
  55744. if (hideOnExit && hasBeenOver && ! isOverAny)
  55745. {
  55746. hide (0, true);
  55747. }
  55748. else
  55749. {
  55750. isDown = hasBeenOver
  55751. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55752. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55753. bool anyFocused = Process::isForegroundProcess();
  55754. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55755. {
  55756. // because no component at all may have focus, our test here will
  55757. // only be triggered when something has focus and then loses it.
  55758. anyFocused = ! hasAnyJuceCompHadFocus;
  55759. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55760. {
  55761. if (ComponentPeer::getPeer (i)->isFocused())
  55762. {
  55763. anyFocused = true;
  55764. hasAnyJuceCompHadFocus = true;
  55765. break;
  55766. }
  55767. }
  55768. }
  55769. if (! anyFocused)
  55770. {
  55771. if (now > lastFocused + 10)
  55772. {
  55773. wasHiddenBecauseOfAppChange() = true;
  55774. dismissMenu (0);
  55775. return; // may have been deleted by the previous call..
  55776. }
  55777. }
  55778. else if (wasDown && now > menuCreationTime + 250
  55779. && ! (isDown || overScrollArea))
  55780. {
  55781. isOver = reallyContains (localMousePos, true);
  55782. if (isOver)
  55783. {
  55784. triggerCurrentlyHighlightedItem();
  55785. }
  55786. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55787. {
  55788. dismissMenu (0);
  55789. }
  55790. return; // may have been deleted by the previous calls..
  55791. }
  55792. else
  55793. {
  55794. lastFocused = now;
  55795. }
  55796. }
  55797. }
  55798. static Array<Window*>& getActiveWindows()
  55799. {
  55800. static Array<Window*> activeMenuWindows;
  55801. return activeMenuWindows;
  55802. }
  55803. static bool& wasHiddenBecauseOfAppChange() throw()
  55804. {
  55805. static bool b = false;
  55806. return b;
  55807. }
  55808. private:
  55809. Window* owner;
  55810. OwnedArray <PopupMenu::ItemComponent> items;
  55811. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55812. ScopedPointer <Window> activeSubMenu;
  55813. ApplicationCommandManager** managerOfChosenCommand;
  55814. WeakReference<Component> componentAttachedTo;
  55815. Component* componentAttachedToOriginal;
  55816. Rectangle<int> windowPos;
  55817. Point<int> lastMouse;
  55818. int minimumWidth, maximumNumColumns, standardItemHeight;
  55819. bool isOver, hasBeenOver, isDown, needsToScroll;
  55820. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55821. int numColumns, contentHeight, childYOffset;
  55822. Array <int> columnWidths;
  55823. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55824. double scrollAcceleration;
  55825. bool overlaps (const Rectangle<int>& r) const
  55826. {
  55827. return r.intersects (getBounds())
  55828. || (owner != 0 && owner->overlaps (r));
  55829. }
  55830. bool isOverAnyMenu() const
  55831. {
  55832. return (owner != 0) ? owner->isOverAnyMenu()
  55833. : isOverChildren();
  55834. }
  55835. bool isOverChildren() const
  55836. {
  55837. return isVisible()
  55838. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55839. }
  55840. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55841. {
  55842. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55843. isOver = reallyContains (relPos, true);
  55844. if (activeSubMenu != 0)
  55845. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55846. }
  55847. bool treeContains (const Window* const window) const throw()
  55848. {
  55849. const Window* mw = this;
  55850. while (mw->owner != 0)
  55851. mw = mw->owner;
  55852. while (mw != 0)
  55853. {
  55854. if (mw == window)
  55855. return true;
  55856. mw = mw->activeSubMenu;
  55857. }
  55858. return false;
  55859. }
  55860. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55861. {
  55862. const Rectangle<int> mon (Desktop::getInstance()
  55863. .getMonitorAreaContaining (target.getCentre(),
  55864. #if JUCE_MAC
  55865. true));
  55866. #else
  55867. false)); // on windows, don't stop the menu overlapping the taskbar
  55868. #endif
  55869. int x, y, widthToUse, heightToUse;
  55870. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55871. if (alignToRectangle)
  55872. {
  55873. x = target.getX();
  55874. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55875. const int spaceOver = target.getY() - mon.getY();
  55876. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55877. y = target.getBottom();
  55878. else
  55879. y = target.getY() - heightToUse;
  55880. }
  55881. else
  55882. {
  55883. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55884. if (owner != 0)
  55885. {
  55886. if (owner->owner != 0)
  55887. {
  55888. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55889. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55890. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55891. tendTowardsRight = true;
  55892. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55893. tendTowardsRight = false;
  55894. }
  55895. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55896. {
  55897. tendTowardsRight = true;
  55898. }
  55899. }
  55900. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55901. target.getX() - mon.getX()) - 32;
  55902. if (biggestSpace < widthToUse)
  55903. {
  55904. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55905. if (numColumns > 1)
  55906. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55907. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55908. }
  55909. if (tendTowardsRight)
  55910. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55911. else
  55912. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55913. y = target.getY();
  55914. if (target.getCentreY() > mon.getCentreY())
  55915. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55916. }
  55917. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55918. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55919. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55920. // sets this flag if it's big enough to obscure any of its parent menus
  55921. hideOnExit = (owner != 0)
  55922. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55923. }
  55924. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55925. {
  55926. numColumns = 0;
  55927. contentHeight = 0;
  55928. const int maxMenuH = getParentHeight() - 24;
  55929. int totalW;
  55930. do
  55931. {
  55932. ++numColumns;
  55933. totalW = workOutBestSize (maxMenuW);
  55934. if (totalW > maxMenuW)
  55935. {
  55936. numColumns = jmax (1, numColumns - 1);
  55937. totalW = workOutBestSize (maxMenuW); // to update col widths
  55938. break;
  55939. }
  55940. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55941. {
  55942. break;
  55943. }
  55944. } while (numColumns < maximumNumColumns);
  55945. const int actualH = jmin (contentHeight, maxMenuH);
  55946. needsToScroll = contentHeight > actualH;
  55947. width = updateYPositions();
  55948. height = actualH + PopupMenuSettings::borderSize * 2;
  55949. }
  55950. int workOutBestSize (const int maxMenuW)
  55951. {
  55952. int totalW = 0;
  55953. contentHeight = 0;
  55954. int childNum = 0;
  55955. for (int col = 0; col < numColumns; ++col)
  55956. {
  55957. int i, colW = 50, colH = 0;
  55958. const int numChildren = jmin (items.size() - childNum,
  55959. (items.size() + numColumns - 1) / numColumns);
  55960. for (i = numChildren; --i >= 0;)
  55961. {
  55962. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  55963. colH += items.getUnchecked (childNum + i)->getHeight();
  55964. }
  55965. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55966. columnWidths.set (col, colW);
  55967. totalW += colW;
  55968. contentHeight = jmax (contentHeight, colH);
  55969. childNum += numChildren;
  55970. }
  55971. if (totalW < minimumWidth)
  55972. {
  55973. totalW = minimumWidth;
  55974. for (int col = 0; col < numColumns; ++col)
  55975. columnWidths.set (0, totalW / numColumns);
  55976. }
  55977. return totalW;
  55978. }
  55979. void ensureItemIsVisible (const int itemId, int wantedY)
  55980. {
  55981. jassert (itemId != 0)
  55982. for (int i = items.size(); --i >= 0;)
  55983. {
  55984. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  55985. if (m != 0
  55986. && m->itemInfo.itemId == itemId
  55987. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55988. {
  55989. const int currentY = m->getY();
  55990. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55991. {
  55992. if (wantedY < 0)
  55993. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55994. jmax (PopupMenuSettings::scrollZone,
  55995. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55996. currentY);
  55997. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55998. int deltaY = wantedY - currentY;
  55999. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56000. jmin (windowPos.getHeight(), mon.getHeight()));
  56001. const int newY = jlimit (mon.getY(),
  56002. mon.getBottom() - windowPos.getHeight(),
  56003. windowPos.getY() + deltaY);
  56004. deltaY -= newY - windowPos.getY();
  56005. childYOffset -= deltaY;
  56006. windowPos.setPosition (windowPos.getX(), newY);
  56007. updateYPositions();
  56008. }
  56009. break;
  56010. }
  56011. }
  56012. }
  56013. void resizeToBestWindowPos()
  56014. {
  56015. Rectangle<int> r (windowPos);
  56016. if (childYOffset < 0)
  56017. {
  56018. r.setBounds (r.getX(), r.getY() - childYOffset,
  56019. r.getWidth(), r.getHeight() + childYOffset);
  56020. }
  56021. else if (childYOffset > 0)
  56022. {
  56023. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56024. if (spaceAtBottom > 0)
  56025. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56026. }
  56027. setBounds (r);
  56028. updateYPositions();
  56029. }
  56030. void alterChildYPos (const int delta)
  56031. {
  56032. if (isScrolling())
  56033. {
  56034. childYOffset += delta;
  56035. if (delta < 0)
  56036. {
  56037. childYOffset = jmax (childYOffset, 0);
  56038. }
  56039. else if (delta > 0)
  56040. {
  56041. childYOffset = jmin (childYOffset,
  56042. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56043. }
  56044. updateYPositions();
  56045. }
  56046. else
  56047. {
  56048. childYOffset = 0;
  56049. }
  56050. resizeToBestWindowPos();
  56051. repaint();
  56052. }
  56053. int updateYPositions()
  56054. {
  56055. int x = 0;
  56056. int childNum = 0;
  56057. for (int col = 0; col < numColumns; ++col)
  56058. {
  56059. const int numChildren = jmin (items.size() - childNum,
  56060. (items.size() + numColumns - 1) / numColumns);
  56061. const int colW = columnWidths [col];
  56062. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56063. for (int i = 0; i < numChildren; ++i)
  56064. {
  56065. Component* const c = items.getUnchecked (childNum + i);
  56066. c->setBounds (x, y, colW, c->getHeight());
  56067. y += c->getHeight();
  56068. }
  56069. x += colW;
  56070. childNum += numChildren;
  56071. }
  56072. return x;
  56073. }
  56074. bool isScrolling() const throw()
  56075. {
  56076. return childYOffset != 0 || needsToScroll;
  56077. }
  56078. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56079. {
  56080. if (currentChild != 0)
  56081. currentChild->setHighlighted (false);
  56082. currentChild = child;
  56083. if (currentChild != 0)
  56084. {
  56085. currentChild->setHighlighted (true);
  56086. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56087. }
  56088. }
  56089. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56090. {
  56091. activeSubMenu = 0;
  56092. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56093. {
  56094. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56095. dismissOnMouseUp,
  56096. this,
  56097. childComp->getScreenBounds(),
  56098. 0, maximumNumColumns,
  56099. standardItemHeight,
  56100. false, 0, managerOfChosenCommand,
  56101. componentAttachedTo);
  56102. if (activeSubMenu != 0)
  56103. {
  56104. activeSubMenu->setVisible (true);
  56105. activeSubMenu->enterModalState (false);
  56106. activeSubMenu->toFront (false);
  56107. return true;
  56108. }
  56109. }
  56110. return false;
  56111. }
  56112. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56113. {
  56114. isOver = reallyContains (localMousePos, true);
  56115. if (isOver)
  56116. hasBeenOver = true;
  56117. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56118. {
  56119. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56120. if (disableMouseMoves && isOver)
  56121. disableMouseMoves = false;
  56122. }
  56123. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56124. return;
  56125. bool isMovingTowardsMenu = false;
  56126. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56127. {
  56128. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56129. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56130. // extends from the last mouse pos to the submenu's rectangle..
  56131. float subX = (float) activeSubMenu->getScreenX();
  56132. if (activeSubMenu->getX() > getX())
  56133. {
  56134. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56135. }
  56136. else
  56137. {
  56138. lastMouse += Point<int> (2, 0);
  56139. subX += activeSubMenu->getWidth();
  56140. }
  56141. Path areaTowardsSubMenu;
  56142. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56143. subX, (float) activeSubMenu->getScreenY(),
  56144. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56145. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56146. }
  56147. lastMouse = globalMousePos;
  56148. if (! isMovingTowardsMenu)
  56149. {
  56150. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56151. if (c == this)
  56152. c = 0;
  56153. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56154. if (mic == 0 && c != 0)
  56155. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56156. if (mic != currentChild
  56157. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56158. {
  56159. if (isOver && (c != 0) && (activeSubMenu != 0))
  56160. activeSubMenu->hide (0, true);
  56161. if (! isOver)
  56162. mic = 0;
  56163. setCurrentlyHighlightedChild (mic);
  56164. }
  56165. }
  56166. }
  56167. void triggerCurrentlyHighlightedItem()
  56168. {
  56169. if (currentChild != 0
  56170. && currentChild->itemInfo.canBeTriggered()
  56171. && (currentChild->itemInfo.customComp == 0
  56172. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56173. {
  56174. dismissMenu (&currentChild->itemInfo);
  56175. }
  56176. }
  56177. void selectNextItem (const int delta)
  56178. {
  56179. disableTimerUntilMouseMoves();
  56180. PopupMenu::ItemComponent* mic = 0;
  56181. bool wasLastOne = (currentChild == 0);
  56182. const int numItems = items.size();
  56183. for (int i = 0; i < numItems + 1; ++i)
  56184. {
  56185. int index = (delta > 0) ? i : (numItems - 1 - i);
  56186. index = (index + numItems) % numItems;
  56187. mic = items.getUnchecked (index);
  56188. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56189. && wasLastOne)
  56190. break;
  56191. if (mic == currentChild)
  56192. wasLastOne = true;
  56193. }
  56194. setCurrentlyHighlightedChild (mic);
  56195. }
  56196. void disableTimerUntilMouseMoves()
  56197. {
  56198. disableMouseMoves = true;
  56199. if (owner != 0)
  56200. owner->disableTimerUntilMouseMoves();
  56201. }
  56202. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56203. };
  56204. PopupMenu::PopupMenu()
  56205. : lookAndFeel (0),
  56206. separatorPending (false)
  56207. {
  56208. }
  56209. PopupMenu::PopupMenu (const PopupMenu& other)
  56210. : lookAndFeel (other.lookAndFeel),
  56211. separatorPending (false)
  56212. {
  56213. items.addCopiesOf (other.items);
  56214. }
  56215. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56216. {
  56217. if (this != &other)
  56218. {
  56219. lookAndFeel = other.lookAndFeel;
  56220. clear();
  56221. items.addCopiesOf (other.items);
  56222. }
  56223. return *this;
  56224. }
  56225. PopupMenu::~PopupMenu()
  56226. {
  56227. clear();
  56228. }
  56229. void PopupMenu::clear()
  56230. {
  56231. items.clear();
  56232. separatorPending = false;
  56233. }
  56234. void PopupMenu::addSeparatorIfPending()
  56235. {
  56236. if (separatorPending)
  56237. {
  56238. separatorPending = false;
  56239. if (items.size() > 0)
  56240. items.add (new Item());
  56241. }
  56242. }
  56243. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56244. const bool isActive, const bool isTicked, const Image& iconToUse)
  56245. {
  56246. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56247. // didn't pick anything, so you shouldn't use it as the id
  56248. // for an item..
  56249. addSeparatorIfPending();
  56250. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56251. Colours::black, false, 0, 0, 0));
  56252. }
  56253. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56254. const int commandID,
  56255. const String& displayName)
  56256. {
  56257. jassert (commandManager != 0 && commandID != 0);
  56258. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56259. if (registeredInfo != 0)
  56260. {
  56261. ApplicationCommandInfo info (*registeredInfo);
  56262. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56263. addSeparatorIfPending();
  56264. items.add (new Item (commandID,
  56265. displayName.isNotEmpty() ? displayName
  56266. : info.shortName,
  56267. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56268. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56269. Image::null,
  56270. Colours::black,
  56271. false,
  56272. 0, 0,
  56273. commandManager));
  56274. }
  56275. }
  56276. void PopupMenu::addColouredItem (const int itemResultId,
  56277. const String& itemText,
  56278. const Colour& itemTextColour,
  56279. const bool isActive,
  56280. const bool isTicked,
  56281. const Image& iconToUse)
  56282. {
  56283. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56284. // didn't pick anything, so you shouldn't use it as the id
  56285. // for an item..
  56286. addSeparatorIfPending();
  56287. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56288. itemTextColour, true, 0, 0, 0));
  56289. }
  56290. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56291. {
  56292. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56293. // didn't pick anything, so you shouldn't use it as the id
  56294. // for an item..
  56295. addSeparatorIfPending();
  56296. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56297. Colours::black, false, customComponent, 0, 0));
  56298. }
  56299. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56300. {
  56301. public:
  56302. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56303. const bool triggerMenuItemAutomaticallyWhenClicked)
  56304. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56305. width (w), height (h)
  56306. {
  56307. addAndMakeVisible (comp);
  56308. }
  56309. void getIdealSize (int& idealWidth, int& idealHeight)
  56310. {
  56311. idealWidth = width;
  56312. idealHeight = height;
  56313. }
  56314. void resized()
  56315. {
  56316. if (getChildComponent(0) != 0)
  56317. getChildComponent(0)->setBounds (getLocalBounds());
  56318. }
  56319. private:
  56320. const int width, height;
  56321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56322. };
  56323. void PopupMenu::addCustomItem (const int itemResultId,
  56324. Component* customComponent,
  56325. int idealWidth, int idealHeight,
  56326. const bool triggerMenuItemAutomaticallyWhenClicked)
  56327. {
  56328. addCustomItem (itemResultId,
  56329. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56330. triggerMenuItemAutomaticallyWhenClicked));
  56331. }
  56332. void PopupMenu::addSubMenu (const String& subMenuName,
  56333. const PopupMenu& subMenu,
  56334. const bool isActive,
  56335. const Image& iconToUse,
  56336. const bool isTicked)
  56337. {
  56338. addSeparatorIfPending();
  56339. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56340. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56341. }
  56342. void PopupMenu::addSeparator()
  56343. {
  56344. separatorPending = true;
  56345. }
  56346. class HeaderItemComponent : public PopupMenu::CustomComponent
  56347. {
  56348. public:
  56349. HeaderItemComponent (const String& name)
  56350. : PopupMenu::CustomComponent (false)
  56351. {
  56352. setName (name);
  56353. }
  56354. void paint (Graphics& g)
  56355. {
  56356. Font f (getLookAndFeel().getPopupMenuFont());
  56357. f.setBold (true);
  56358. g.setFont (f);
  56359. g.setColour (findColour (PopupMenu::headerTextColourId));
  56360. g.drawFittedText (getName(),
  56361. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56362. Justification::bottomLeft, 1);
  56363. }
  56364. void getIdealSize (int& idealWidth, int& idealHeight)
  56365. {
  56366. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56367. idealHeight += idealHeight / 2;
  56368. idealWidth += idealWidth / 4;
  56369. }
  56370. private:
  56371. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56372. };
  56373. void PopupMenu::addSectionHeader (const String& title)
  56374. {
  56375. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56376. }
  56377. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56378. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56379. {
  56380. public:
  56381. PopupMenuCompletionCallback()
  56382. : managerOfChosenCommand (0)
  56383. {
  56384. }
  56385. void modalStateFinished (int result)
  56386. {
  56387. if (managerOfChosenCommand != 0 && result != 0)
  56388. {
  56389. ApplicationCommandTarget::InvocationInfo info (result);
  56390. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56391. managerOfChosenCommand->invoke (info, true);
  56392. }
  56393. // (this would be the place to fade out the component, if that's what's required)
  56394. component = 0;
  56395. }
  56396. ApplicationCommandManager* managerOfChosenCommand;
  56397. ScopedPointer<Component> component;
  56398. private:
  56399. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56400. };
  56401. int PopupMenu::showMenu (const Rectangle<int>& target,
  56402. const int itemIdThatMustBeVisible,
  56403. const int minimumWidth,
  56404. const int maximumNumColumns,
  56405. const int standardItemHeight,
  56406. Component* const componentAttachedTo,
  56407. ModalComponentManager::Callback* userCallback)
  56408. {
  56409. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56410. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56411. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56412. Window::wasHiddenBecauseOfAppChange() = false;
  56413. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56414. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56415. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56416. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56417. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56418. &callback->managerOfChosenCommand, componentAttachedTo);
  56419. if (callback->component == 0)
  56420. return 0;
  56421. callback->component->enterModalState (false, userCallbackDeleter.release());
  56422. callback->component->toFront (false); // need to do this after making it modal, or it could
  56423. // be stuck behind other comps that are already modal..
  56424. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56425. callbackDeleter.release();
  56426. if (userCallback != 0)
  56427. return 0;
  56428. const int result = callback->component->runModalLoop();
  56429. if (! Window::wasHiddenBecauseOfAppChange())
  56430. {
  56431. if (prevTopLevel != 0)
  56432. prevTopLevel->toFront (true);
  56433. if (prevFocused != 0)
  56434. prevFocused->grabKeyboardFocus();
  56435. }
  56436. return result;
  56437. }
  56438. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56439. const int minimumWidth, const int maximumNumColumns,
  56440. const int standardItemHeight,
  56441. ModalComponentManager::Callback* callback)
  56442. {
  56443. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56444. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56445. standardItemHeight, 0, callback);
  56446. }
  56447. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56448. const int itemIdThatMustBeVisible,
  56449. const int minimumWidth, const int maximumNumColumns,
  56450. const int standardItemHeight,
  56451. ModalComponentManager::Callback* callback)
  56452. {
  56453. return showMenu (screenAreaToAttachTo,
  56454. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56455. standardItemHeight, 0, callback);
  56456. }
  56457. int PopupMenu::showAt (Component* componentToAttachTo,
  56458. const int itemIdThatMustBeVisible,
  56459. const int minimumWidth, const int maximumNumColumns,
  56460. const int standardItemHeight,
  56461. ModalComponentManager::Callback* callback)
  56462. {
  56463. if (componentToAttachTo != 0)
  56464. {
  56465. return showMenu (componentToAttachTo->getScreenBounds(),
  56466. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56467. standardItemHeight, componentToAttachTo, callback);
  56468. }
  56469. else
  56470. {
  56471. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56472. standardItemHeight, callback);
  56473. }
  56474. }
  56475. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56476. {
  56477. const int numWindows = Window::getActiveWindows().size();
  56478. for (int i = numWindows; --i >= 0;)
  56479. {
  56480. Window* const pmw = Window::getActiveWindows()[i];
  56481. if (pmw != 0)
  56482. pmw->dismissMenu (0);
  56483. }
  56484. return numWindows > 0;
  56485. }
  56486. int PopupMenu::getNumItems() const throw()
  56487. {
  56488. int num = 0;
  56489. for (int i = items.size(); --i >= 0;)
  56490. if (! (items.getUnchecked(i))->isSeparator)
  56491. ++num;
  56492. return num;
  56493. }
  56494. bool PopupMenu::containsCommandItem (const int commandID) const
  56495. {
  56496. for (int i = items.size(); --i >= 0;)
  56497. {
  56498. const Item* mi = items.getUnchecked (i);
  56499. if ((mi->itemId == commandID && mi->commandManager != 0)
  56500. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56501. {
  56502. return true;
  56503. }
  56504. }
  56505. return false;
  56506. }
  56507. bool PopupMenu::containsAnyActiveItems() const throw()
  56508. {
  56509. for (int i = items.size(); --i >= 0;)
  56510. {
  56511. const Item* const mi = items.getUnchecked (i);
  56512. if (mi->subMenu != 0)
  56513. {
  56514. if (mi->subMenu->containsAnyActiveItems())
  56515. return true;
  56516. }
  56517. else if (mi->active)
  56518. {
  56519. return true;
  56520. }
  56521. }
  56522. return false;
  56523. }
  56524. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56525. {
  56526. lookAndFeel = newLookAndFeel;
  56527. }
  56528. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56529. : isHighlighted (false),
  56530. triggeredAutomatically (isTriggeredAutomatically_)
  56531. {
  56532. }
  56533. PopupMenu::CustomComponent::~CustomComponent()
  56534. {
  56535. }
  56536. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56537. {
  56538. isHighlighted = shouldBeHighlighted;
  56539. repaint();
  56540. }
  56541. void PopupMenu::CustomComponent::triggerMenuItem()
  56542. {
  56543. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56544. if (mic != 0)
  56545. {
  56546. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56547. if (pmw != 0)
  56548. {
  56549. pmw->dismissMenu (&mic->itemInfo);
  56550. }
  56551. else
  56552. {
  56553. // something must have gone wrong with the component hierarchy if this happens..
  56554. jassertfalse;
  56555. }
  56556. }
  56557. else
  56558. {
  56559. // why isn't this component inside a menu? Not much point triggering the item if
  56560. // there's no menu.
  56561. jassertfalse;
  56562. }
  56563. }
  56564. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56565. : subMenu (0),
  56566. itemId (0),
  56567. isSeparator (false),
  56568. isTicked (false),
  56569. isEnabled (false),
  56570. isCustomComponent (false),
  56571. isSectionHeader (false),
  56572. customColour (0),
  56573. customImage (0),
  56574. menu (menu_),
  56575. index (0)
  56576. {
  56577. }
  56578. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56579. {
  56580. }
  56581. bool PopupMenu::MenuItemIterator::next()
  56582. {
  56583. if (index >= menu.items.size())
  56584. return false;
  56585. const Item* const item = menu.items.getUnchecked (index);
  56586. ++index;
  56587. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56588. subMenu = item->subMenu;
  56589. itemId = item->itemId;
  56590. isSeparator = item->isSeparator;
  56591. isTicked = item->isTicked;
  56592. isEnabled = item->active;
  56593. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56594. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56595. customColour = item->usesColour ? &(item->textColour) : 0;
  56596. customImage = item->image;
  56597. commandManager = item->commandManager;
  56598. return true;
  56599. }
  56600. END_JUCE_NAMESPACE
  56601. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56602. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56603. BEGIN_JUCE_NAMESPACE
  56604. ComponentDragger::ComponentDragger()
  56605. {
  56606. }
  56607. ComponentDragger::~ComponentDragger()
  56608. {
  56609. }
  56610. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56611. {
  56612. jassert (componentToDrag != 0);
  56613. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56614. if (componentToDrag != 0)
  56615. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56616. }
  56617. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56618. ComponentBoundsConstrainer* const constrainer)
  56619. {
  56620. jassert (componentToDrag != 0);
  56621. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56622. if (componentToDrag != 0)
  56623. {
  56624. Rectangle<int> bounds (componentToDrag->getBounds());
  56625. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56626. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56627. // the current mouse position instead of the one that the event contains...
  56628. if (componentToDrag->isOnDesktop())
  56629. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56630. else
  56631. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56632. if (constrainer != 0)
  56633. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56634. else
  56635. componentToDrag->setBounds (bounds);
  56636. }
  56637. }
  56638. END_JUCE_NAMESPACE
  56639. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56640. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56641. BEGIN_JUCE_NAMESPACE
  56642. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56643. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56644. class DragImageComponent : public Component,
  56645. public Timer
  56646. {
  56647. public:
  56648. DragImageComponent (const Image& im,
  56649. const String& desc,
  56650. Component* const sourceComponent,
  56651. Component* const mouseDragSource_,
  56652. DragAndDropContainer* const o,
  56653. const Point<int>& imageOffset_)
  56654. : image (im),
  56655. source (sourceComponent),
  56656. mouseDragSource (mouseDragSource_),
  56657. owner (o),
  56658. dragDesc (desc),
  56659. imageOffset (imageOffset_),
  56660. hasCheckedForExternalDrag (false),
  56661. drawImage (true)
  56662. {
  56663. setSize (im.getWidth(), im.getHeight());
  56664. if (mouseDragSource == 0)
  56665. mouseDragSource = source;
  56666. mouseDragSource->addMouseListener (this, false);
  56667. startTimer (200);
  56668. setInterceptsMouseClicks (false, false);
  56669. setAlwaysOnTop (true);
  56670. }
  56671. ~DragImageComponent()
  56672. {
  56673. if (owner->dragImageComponent == this)
  56674. owner->dragImageComponent.release();
  56675. if (mouseDragSource != 0)
  56676. {
  56677. mouseDragSource->removeMouseListener (this);
  56678. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56679. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56680. }
  56681. }
  56682. void paint (Graphics& g)
  56683. {
  56684. if (isOpaque())
  56685. g.fillAll (Colours::white);
  56686. if (drawImage)
  56687. {
  56688. g.setOpacity (1.0f);
  56689. g.drawImageAt (image, 0, 0);
  56690. }
  56691. }
  56692. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56693. {
  56694. Component* hit = getParentComponent();
  56695. if (hit == 0)
  56696. {
  56697. hit = Desktop::getInstance().findComponentAt (screenPos);
  56698. }
  56699. else
  56700. {
  56701. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56702. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56703. }
  56704. // (note: use a local copy of the dragDesc member in case the callback runs
  56705. // a modal loop and deletes this object before the method completes)
  56706. const String dragDescLocal (dragDesc);
  56707. while (hit != 0)
  56708. {
  56709. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56710. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56711. {
  56712. relativePos = hit->getLocalPoint (0, screenPos);
  56713. return ddt;
  56714. }
  56715. hit = hit->getParentComponent();
  56716. }
  56717. return 0;
  56718. }
  56719. void mouseUp (const MouseEvent& e)
  56720. {
  56721. if (e.originalComponent != this)
  56722. {
  56723. if (mouseDragSource != 0)
  56724. mouseDragSource->removeMouseListener (this);
  56725. bool dropAccepted = false;
  56726. DragAndDropTarget* ddt = 0;
  56727. Point<int> relPos;
  56728. if (isVisible())
  56729. {
  56730. setVisible (false);
  56731. ddt = findTarget (e.getScreenPosition(), relPos);
  56732. // fade this component and remove it - it'll be deleted later by the timer callback
  56733. dropAccepted = ddt != 0;
  56734. setVisible (true);
  56735. if (dropAccepted || source == 0)
  56736. {
  56737. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56738. }
  56739. else
  56740. {
  56741. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56742. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56743. Desktop::getInstance().getAnimator().animateComponent (this,
  56744. getBounds() + (target - ourCentre),
  56745. 0.0f, 120,
  56746. true, 1.0, 1.0);
  56747. }
  56748. }
  56749. if (getParentComponent() != 0)
  56750. getParentComponent()->removeChildComponent (this);
  56751. if (dropAccepted && ddt != 0)
  56752. {
  56753. // (note: use a local copy of the dragDesc member in case the callback runs
  56754. // a modal loop and deletes this object before the method completes)
  56755. const String dragDescLocal (dragDesc);
  56756. currentlyOverComp = 0;
  56757. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56758. }
  56759. // careful - this object could now be deleted..
  56760. }
  56761. }
  56762. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56763. {
  56764. // (note: use a local copy of the dragDesc member in case the callback runs
  56765. // a modal loop and deletes this object before it returns)
  56766. const String dragDescLocal (dragDesc);
  56767. Point<int> newPos (screenPos + imageOffset);
  56768. if (getParentComponent() != 0)
  56769. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56770. //if (newX != getX() || newY != getY())
  56771. {
  56772. setTopLeftPosition (newPos.getX(), newPos.getY());
  56773. Point<int> relPos;
  56774. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56775. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56776. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56777. if (ddtComp != currentlyOverComp)
  56778. {
  56779. if (currentlyOverComp != 0 && source != 0
  56780. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56781. {
  56782. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56783. }
  56784. currentlyOverComp = ddtComp;
  56785. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56786. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56787. }
  56788. DragAndDropTarget* target = getCurrentlyOver();
  56789. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56790. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56791. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56792. {
  56793. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56794. {
  56795. hasCheckedForExternalDrag = true;
  56796. StringArray files;
  56797. bool canMoveFiles = false;
  56798. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56799. && files.size() > 0)
  56800. {
  56801. WeakReference<Component> cdw (this);
  56802. setVisible (false);
  56803. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56804. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56805. if (cdw != 0)
  56806. delete this;
  56807. return;
  56808. }
  56809. }
  56810. }
  56811. }
  56812. }
  56813. void mouseDrag (const MouseEvent& e)
  56814. {
  56815. if (e.originalComponent != this)
  56816. updateLocation (true, e.getScreenPosition());
  56817. }
  56818. void timerCallback()
  56819. {
  56820. if (source == 0)
  56821. {
  56822. delete this;
  56823. }
  56824. else if (! isMouseButtonDownAnywhere())
  56825. {
  56826. if (mouseDragSource != 0)
  56827. mouseDragSource->removeMouseListener (this);
  56828. delete this;
  56829. }
  56830. }
  56831. private:
  56832. Image image;
  56833. WeakReference<Component> source;
  56834. WeakReference<Component> mouseDragSource;
  56835. DragAndDropContainer* const owner;
  56836. WeakReference<Component> currentlyOverComp;
  56837. DragAndDropTarget* getCurrentlyOver()
  56838. {
  56839. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  56840. }
  56841. String dragDesc;
  56842. const Point<int> imageOffset;
  56843. bool hasCheckedForExternalDrag, drawImage;
  56844. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56845. };
  56846. DragAndDropContainer::DragAndDropContainer()
  56847. {
  56848. }
  56849. DragAndDropContainer::~DragAndDropContainer()
  56850. {
  56851. dragImageComponent = 0;
  56852. }
  56853. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56854. Component* sourceComponent,
  56855. const Image& dragImage_,
  56856. const bool allowDraggingToExternalWindows,
  56857. const Point<int>* imageOffsetFromMouse)
  56858. {
  56859. Image dragImage (dragImage_);
  56860. if (dragImageComponent == 0)
  56861. {
  56862. Component* const thisComp = dynamic_cast <Component*> (this);
  56863. if (thisComp == 0)
  56864. {
  56865. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56866. return;
  56867. }
  56868. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56869. if (draggingSource == 0 || ! draggingSource->isDragging())
  56870. {
  56871. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56872. return;
  56873. }
  56874. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56875. Point<int> imageOffset;
  56876. if (dragImage.isNull())
  56877. {
  56878. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56879. .convertedToFormat (Image::ARGB);
  56880. dragImage.multiplyAllAlphas (0.6f);
  56881. const int lo = 150;
  56882. const int hi = 400;
  56883. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  56884. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56885. for (int y = dragImage.getHeight(); --y >= 0;)
  56886. {
  56887. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56888. for (int x = dragImage.getWidth(); --x >= 0;)
  56889. {
  56890. const int dx = x - clipped.getX();
  56891. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56892. if (distance > lo)
  56893. {
  56894. const float alpha = (distance > hi) ? 0
  56895. : (hi - distance) / (float) (hi - lo)
  56896. + Random::getSystemRandom().nextFloat() * 0.008f;
  56897. dragImage.multiplyAlphaAt (x, y, alpha);
  56898. }
  56899. }
  56900. }
  56901. imageOffset = -clipped;
  56902. }
  56903. else
  56904. {
  56905. if (imageOffsetFromMouse == 0)
  56906. imageOffset = -dragImage.getBounds().getCentre();
  56907. else
  56908. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56909. }
  56910. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56911. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56912. currentDragDesc = sourceDescription;
  56913. if (allowDraggingToExternalWindows)
  56914. {
  56915. if (! Desktop::canUseSemiTransparentWindows())
  56916. dragImageComponent->setOpaque (true);
  56917. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56918. | ComponentPeer::windowIsTemporary
  56919. | ComponentPeer::windowIgnoresKeyPresses);
  56920. }
  56921. else
  56922. thisComp->addChildComponent (dragImageComponent);
  56923. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56924. dragImageComponent->setVisible (true);
  56925. }
  56926. }
  56927. bool DragAndDropContainer::isDragAndDropActive() const
  56928. {
  56929. return dragImageComponent != 0;
  56930. }
  56931. const String DragAndDropContainer::getCurrentDragDescription() const
  56932. {
  56933. return (dragImageComponent != 0) ? currentDragDesc
  56934. : String::empty;
  56935. }
  56936. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56937. {
  56938. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56939. }
  56940. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56941. {
  56942. return false;
  56943. }
  56944. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56945. {
  56946. }
  56947. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56948. {
  56949. }
  56950. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56951. {
  56952. }
  56953. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56954. {
  56955. return true;
  56956. }
  56957. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56958. {
  56959. }
  56960. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56961. {
  56962. }
  56963. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56964. {
  56965. }
  56966. END_JUCE_NAMESPACE
  56967. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56968. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56969. BEGIN_JUCE_NAMESPACE
  56970. class MouseCursor::SharedCursorHandle
  56971. {
  56972. public:
  56973. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56974. : handle (createStandardMouseCursor (type)),
  56975. refCount (1),
  56976. standardType (type),
  56977. isStandard (true)
  56978. {
  56979. }
  56980. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56981. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56982. refCount (1),
  56983. standardType (MouseCursor::NormalCursor),
  56984. isStandard (false)
  56985. {
  56986. }
  56987. ~SharedCursorHandle()
  56988. {
  56989. deleteMouseCursor (handle, isStandard);
  56990. }
  56991. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56992. {
  56993. const ScopedLock sl (getLock());
  56994. for (int i = 0; i < getCursors().size(); ++i)
  56995. {
  56996. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56997. if (sc->standardType == type)
  56998. return sc->retain();
  56999. }
  57000. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57001. getCursors().add (sc);
  57002. return sc;
  57003. }
  57004. SharedCursorHandle* retain() throw()
  57005. {
  57006. ++refCount;
  57007. return this;
  57008. }
  57009. void release()
  57010. {
  57011. if (--refCount == 0)
  57012. {
  57013. if (isStandard)
  57014. {
  57015. const ScopedLock sl (getLock());
  57016. getCursors().removeValue (this);
  57017. }
  57018. delete this;
  57019. }
  57020. }
  57021. void* getHandle() const throw() { return handle; }
  57022. private:
  57023. void* const handle;
  57024. Atomic <int> refCount;
  57025. const MouseCursor::StandardCursorType standardType;
  57026. const bool isStandard;
  57027. static CriticalSection& getLock()
  57028. {
  57029. static CriticalSection lock;
  57030. return lock;
  57031. }
  57032. static Array <SharedCursorHandle*>& getCursors()
  57033. {
  57034. static Array <SharedCursorHandle*> cursors;
  57035. return cursors;
  57036. }
  57037. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57038. };
  57039. MouseCursor::MouseCursor()
  57040. : cursorHandle (0)
  57041. {
  57042. }
  57043. MouseCursor::MouseCursor (const StandardCursorType type)
  57044. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57045. {
  57046. }
  57047. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57048. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57049. {
  57050. }
  57051. MouseCursor::MouseCursor (const MouseCursor& other)
  57052. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57053. {
  57054. }
  57055. MouseCursor::~MouseCursor()
  57056. {
  57057. if (cursorHandle != 0)
  57058. cursorHandle->release();
  57059. }
  57060. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57061. {
  57062. if (other.cursorHandle != 0)
  57063. other.cursorHandle->retain();
  57064. if (cursorHandle != 0)
  57065. cursorHandle->release();
  57066. cursorHandle = other.cursorHandle;
  57067. return *this;
  57068. }
  57069. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57070. {
  57071. return getHandle() == other.getHandle();
  57072. }
  57073. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57074. {
  57075. return getHandle() != other.getHandle();
  57076. }
  57077. void* MouseCursor::getHandle() const throw()
  57078. {
  57079. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57080. }
  57081. void MouseCursor::showWaitCursor()
  57082. {
  57083. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57084. }
  57085. void MouseCursor::hideWaitCursor()
  57086. {
  57087. Desktop::getInstance().getMainMouseSource().revealCursor();
  57088. }
  57089. END_JUCE_NAMESPACE
  57090. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57091. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57092. BEGIN_JUCE_NAMESPACE
  57093. MouseEvent::MouseEvent (MouseInputSource& source_,
  57094. const Point<int>& position,
  57095. const ModifierKeys& mods_,
  57096. Component* const eventComponent_,
  57097. Component* const originator,
  57098. const Time& eventTime_,
  57099. const Point<int> mouseDownPos_,
  57100. const Time& mouseDownTime_,
  57101. const int numberOfClicks_,
  57102. const bool mouseWasDragged) throw()
  57103. : x (position.getX()),
  57104. y (position.getY()),
  57105. mods (mods_),
  57106. eventComponent (eventComponent_),
  57107. originalComponent (originator),
  57108. eventTime (eventTime_),
  57109. source (source_),
  57110. mouseDownPos (mouseDownPos_),
  57111. mouseDownTime (mouseDownTime_),
  57112. numberOfClicks (numberOfClicks_),
  57113. wasMovedSinceMouseDown (mouseWasDragged)
  57114. {
  57115. }
  57116. MouseEvent::~MouseEvent() throw()
  57117. {
  57118. }
  57119. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57120. {
  57121. if (otherComponent == 0)
  57122. {
  57123. jassertfalse;
  57124. return *this;
  57125. }
  57126. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57127. mods, otherComponent, originalComponent, eventTime,
  57128. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57129. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57130. }
  57131. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57132. {
  57133. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57134. eventTime, mouseDownPos, mouseDownTime,
  57135. numberOfClicks, wasMovedSinceMouseDown);
  57136. }
  57137. bool MouseEvent::mouseWasClicked() const throw()
  57138. {
  57139. return ! wasMovedSinceMouseDown;
  57140. }
  57141. int MouseEvent::getMouseDownX() const throw()
  57142. {
  57143. return mouseDownPos.getX();
  57144. }
  57145. int MouseEvent::getMouseDownY() const throw()
  57146. {
  57147. return mouseDownPos.getY();
  57148. }
  57149. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57150. {
  57151. return mouseDownPos;
  57152. }
  57153. int MouseEvent::getDistanceFromDragStartX() const throw()
  57154. {
  57155. return x - mouseDownPos.getX();
  57156. }
  57157. int MouseEvent::getDistanceFromDragStartY() const throw()
  57158. {
  57159. return y - mouseDownPos.getY();
  57160. }
  57161. int MouseEvent::getDistanceFromDragStart() const throw()
  57162. {
  57163. return mouseDownPos.getDistanceFrom (getPosition());
  57164. }
  57165. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57166. {
  57167. return getPosition() - mouseDownPos;
  57168. }
  57169. int MouseEvent::getLengthOfMousePress() const throw()
  57170. {
  57171. if (mouseDownTime.toMilliseconds() > 0)
  57172. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57173. return 0;
  57174. }
  57175. const Point<int> MouseEvent::getPosition() const throw()
  57176. {
  57177. return Point<int> (x, y);
  57178. }
  57179. int MouseEvent::getScreenX() const
  57180. {
  57181. return getScreenPosition().getX();
  57182. }
  57183. int MouseEvent::getScreenY() const
  57184. {
  57185. return getScreenPosition().getY();
  57186. }
  57187. const Point<int> MouseEvent::getScreenPosition() const
  57188. {
  57189. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57190. }
  57191. int MouseEvent::getMouseDownScreenX() const
  57192. {
  57193. return getMouseDownScreenPosition().getX();
  57194. }
  57195. int MouseEvent::getMouseDownScreenY() const
  57196. {
  57197. return getMouseDownScreenPosition().getY();
  57198. }
  57199. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57200. {
  57201. return eventComponent->localPointToGlobal (mouseDownPos);
  57202. }
  57203. int MouseEvent::doubleClickTimeOutMs = 400;
  57204. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57205. {
  57206. doubleClickTimeOutMs = newTime;
  57207. }
  57208. int MouseEvent::getDoubleClickTimeout() throw()
  57209. {
  57210. return doubleClickTimeOutMs;
  57211. }
  57212. END_JUCE_NAMESPACE
  57213. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57214. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57215. BEGIN_JUCE_NAMESPACE
  57216. class MouseInputSourceInternal : public AsyncUpdater
  57217. {
  57218. public:
  57219. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57220. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57221. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57222. mouseEventCounter (0)
  57223. {
  57224. }
  57225. bool isDragging() const throw()
  57226. {
  57227. return buttonState.isAnyMouseButtonDown();
  57228. }
  57229. Component* getComponentUnderMouse() const
  57230. {
  57231. return static_cast <Component*> (componentUnderMouse);
  57232. }
  57233. const ModifierKeys getCurrentModifiers() const
  57234. {
  57235. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57236. }
  57237. ComponentPeer* getPeer()
  57238. {
  57239. if (! ComponentPeer::isValidPeer (lastPeer))
  57240. lastPeer = 0;
  57241. return lastPeer;
  57242. }
  57243. Component* findComponentAt (const Point<int>& screenPos)
  57244. {
  57245. ComponentPeer* const peer = getPeer();
  57246. if (peer != 0)
  57247. {
  57248. Component* const comp = peer->getComponent();
  57249. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57250. // (the contains() call is needed to test for overlapping desktop windows)
  57251. if (comp->contains (relativePos))
  57252. return comp->getComponentAt (relativePos);
  57253. }
  57254. return 0;
  57255. }
  57256. const Point<int> getScreenPosition() const
  57257. {
  57258. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57259. // value, because that can cause continuity problems.
  57260. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57261. : lastScreenPos);
  57262. }
  57263. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57264. {
  57265. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57266. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57267. }
  57268. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57269. {
  57270. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57271. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57272. }
  57273. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57274. {
  57275. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57276. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57277. }
  57278. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57279. {
  57280. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57281. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57282. }
  57283. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57284. {
  57285. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57286. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57287. }
  57288. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57289. {
  57290. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57291. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57292. }
  57293. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57294. {
  57295. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57296. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57297. }
  57298. // (returns true if the button change caused a modal event loop)
  57299. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57300. {
  57301. if (buttonState == newButtonState)
  57302. return false;
  57303. setScreenPos (screenPos, time, false);
  57304. // (ignore secondary clicks when there's already a button down)
  57305. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57306. {
  57307. buttonState = newButtonState;
  57308. return false;
  57309. }
  57310. const int lastCounter = mouseEventCounter;
  57311. if (buttonState.isAnyMouseButtonDown())
  57312. {
  57313. Component* const current = getComponentUnderMouse();
  57314. if (current != 0)
  57315. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57316. enableUnboundedMouseMovement (false, false);
  57317. }
  57318. buttonState = newButtonState;
  57319. if (buttonState.isAnyMouseButtonDown())
  57320. {
  57321. Desktop::getInstance().incrementMouseClickCounter();
  57322. Component* const current = getComponentUnderMouse();
  57323. if (current != 0)
  57324. {
  57325. registerMouseDown (screenPos, time, current, buttonState);
  57326. sendMouseDown (current, screenPos, time);
  57327. }
  57328. }
  57329. return lastCounter != mouseEventCounter;
  57330. }
  57331. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57332. {
  57333. Component* current = getComponentUnderMouse();
  57334. if (newComponent != current)
  57335. {
  57336. WeakReference<Component> safeNewComp (newComponent);
  57337. const ModifierKeys originalButtonState (buttonState);
  57338. if (current != 0)
  57339. {
  57340. setButtons (screenPos, time, ModifierKeys());
  57341. sendMouseExit (current, screenPos, time);
  57342. buttonState = originalButtonState;
  57343. }
  57344. componentUnderMouse = safeNewComp;
  57345. current = getComponentUnderMouse();
  57346. if (current != 0)
  57347. sendMouseEnter (current, screenPos, time);
  57348. revealCursor (false);
  57349. setButtons (screenPos, time, originalButtonState);
  57350. }
  57351. }
  57352. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57353. {
  57354. ModifierKeys::updateCurrentModifiers();
  57355. if (newPeer != lastPeer)
  57356. {
  57357. setComponentUnderMouse (0, screenPos, time);
  57358. lastPeer = newPeer;
  57359. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57360. }
  57361. }
  57362. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57363. {
  57364. if (! isDragging())
  57365. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57366. if (newScreenPos != lastScreenPos || forceUpdate)
  57367. {
  57368. cancelPendingUpdate();
  57369. lastScreenPos = newScreenPos;
  57370. Component* const current = getComponentUnderMouse();
  57371. if (current != 0)
  57372. {
  57373. if (isDragging())
  57374. {
  57375. registerMouseDrag (newScreenPos);
  57376. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57377. if (isUnboundedMouseModeOn)
  57378. handleUnboundedDrag (current);
  57379. }
  57380. else
  57381. {
  57382. sendMouseMove (current, newScreenPos, time);
  57383. }
  57384. }
  57385. revealCursor (false);
  57386. }
  57387. }
  57388. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57389. {
  57390. jassert (newPeer != 0);
  57391. lastTime = time;
  57392. ++mouseEventCounter;
  57393. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57394. if (isDragging() && newMods.isAnyMouseButtonDown())
  57395. {
  57396. setScreenPos (screenPos, time, false);
  57397. }
  57398. else
  57399. {
  57400. setPeer (newPeer, screenPos, time);
  57401. ComponentPeer* peer = getPeer();
  57402. if (peer != 0)
  57403. {
  57404. if (setButtons (screenPos, time, newMods))
  57405. return; // some modal events have been dispatched, so the current event is now out-of-date
  57406. peer = getPeer();
  57407. if (peer != 0)
  57408. setScreenPos (screenPos, time, false);
  57409. }
  57410. }
  57411. }
  57412. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57413. {
  57414. jassert (peer != 0);
  57415. lastTime = time;
  57416. ++mouseEventCounter;
  57417. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57418. setPeer (peer, screenPos, time);
  57419. setScreenPos (screenPos, time, false);
  57420. triggerFakeMove();
  57421. if (! isDragging())
  57422. {
  57423. Component* current = getComponentUnderMouse();
  57424. if (current != 0)
  57425. sendMouseWheel (current, screenPos, time, x, y);
  57426. }
  57427. }
  57428. const Time getLastMouseDownTime() const throw()
  57429. {
  57430. return Time (mouseDowns[0].time);
  57431. }
  57432. const Point<int> getLastMouseDownPosition() const throw()
  57433. {
  57434. return mouseDowns[0].position;
  57435. }
  57436. int getNumberOfMultipleClicks() const throw()
  57437. {
  57438. int numClicks = 0;
  57439. if (mouseDowns[0].time != Time())
  57440. {
  57441. if (! mouseMovedSignificantlySincePressed)
  57442. ++numClicks;
  57443. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57444. {
  57445. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57446. ++numClicks;
  57447. else
  57448. break;
  57449. }
  57450. }
  57451. return numClicks;
  57452. }
  57453. bool hasMouseMovedSignificantlySincePressed() const throw()
  57454. {
  57455. return mouseMovedSignificantlySincePressed
  57456. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57457. }
  57458. void triggerFakeMove()
  57459. {
  57460. triggerAsyncUpdate();
  57461. }
  57462. void handleAsyncUpdate()
  57463. {
  57464. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57465. }
  57466. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57467. {
  57468. enable = enable && isDragging();
  57469. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57470. if (enable != isUnboundedMouseModeOn)
  57471. {
  57472. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57473. {
  57474. // when released, return the mouse to within the component's bounds
  57475. Component* current = getComponentUnderMouse();
  57476. if (current != 0)
  57477. Desktop::setMousePosition (current->getScreenBounds()
  57478. .getConstrainedPoint (lastScreenPos));
  57479. }
  57480. isUnboundedMouseModeOn = enable;
  57481. unboundedMouseOffset = Point<int>();
  57482. revealCursor (true);
  57483. }
  57484. }
  57485. void handleUnboundedDrag (Component* current)
  57486. {
  57487. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57488. if (! screenArea.contains (lastScreenPos))
  57489. {
  57490. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57491. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57492. Desktop::setMousePosition (componentCentre);
  57493. }
  57494. else if (isCursorVisibleUntilOffscreen
  57495. && (! unboundedMouseOffset.isOrigin())
  57496. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57497. {
  57498. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57499. unboundedMouseOffset = Point<int>();
  57500. }
  57501. }
  57502. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57503. {
  57504. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57505. {
  57506. cursor = MouseCursor::NoCursor;
  57507. forcedUpdate = true;
  57508. }
  57509. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57510. {
  57511. currentCursorHandle = cursor.getHandle();
  57512. cursor.showInWindow (getPeer());
  57513. }
  57514. }
  57515. void hideCursor()
  57516. {
  57517. showMouseCursor (MouseCursor::NoCursor, true);
  57518. }
  57519. void revealCursor (bool forcedUpdate)
  57520. {
  57521. MouseCursor mc (MouseCursor::NormalCursor);
  57522. Component* current = getComponentUnderMouse();
  57523. if (current != 0)
  57524. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57525. showMouseCursor (mc, forcedUpdate);
  57526. }
  57527. const int index;
  57528. const bool isMouseDevice;
  57529. Point<int> lastScreenPos;
  57530. ModifierKeys buttonState;
  57531. private:
  57532. MouseInputSource& source;
  57533. WeakReference<Component> componentUnderMouse;
  57534. ComponentPeer* lastPeer;
  57535. Point<int> unboundedMouseOffset;
  57536. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57537. void* currentCursorHandle;
  57538. int mouseEventCounter;
  57539. struct RecentMouseDown
  57540. {
  57541. RecentMouseDown() : component (0)
  57542. {
  57543. }
  57544. Point<int> position;
  57545. Time time;
  57546. Component* component;
  57547. ModifierKeys buttons;
  57548. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57549. {
  57550. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57551. && abs (position.getX() - other.position.getX()) < 8
  57552. && abs (position.getY() - other.position.getY()) < 8
  57553. && buttons == other.buttons;;
  57554. }
  57555. };
  57556. RecentMouseDown mouseDowns[4];
  57557. bool mouseMovedSignificantlySincePressed;
  57558. Time lastTime;
  57559. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57560. Component* const component, const ModifierKeys& modifiers) throw()
  57561. {
  57562. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57563. mouseDowns[i] = mouseDowns[i - 1];
  57564. mouseDowns[0].position = screenPos;
  57565. mouseDowns[0].time = time;
  57566. mouseDowns[0].component = component;
  57567. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57568. mouseMovedSignificantlySincePressed = false;
  57569. }
  57570. void registerMouseDrag (const Point<int>& screenPos) throw()
  57571. {
  57572. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57573. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57574. }
  57575. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57576. };
  57577. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57578. {
  57579. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57580. }
  57581. MouseInputSource::~MouseInputSource()
  57582. {
  57583. }
  57584. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57585. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57586. bool MouseInputSource::canHover() const { return isMouse(); }
  57587. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57588. int MouseInputSource::getIndex() const { return pimpl->index; }
  57589. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57590. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57591. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57592. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57593. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57594. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57595. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57596. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57597. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57598. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57599. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57600. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57601. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57602. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57603. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57604. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57605. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57606. {
  57607. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57608. }
  57609. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57610. {
  57611. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57612. }
  57613. END_JUCE_NAMESPACE
  57614. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57615. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57616. BEGIN_JUCE_NAMESPACE
  57617. void MouseListener::mouseEnter (const MouseEvent&)
  57618. {
  57619. }
  57620. void MouseListener::mouseExit (const MouseEvent&)
  57621. {
  57622. }
  57623. void MouseListener::mouseDown (const MouseEvent&)
  57624. {
  57625. }
  57626. void MouseListener::mouseUp (const MouseEvent&)
  57627. {
  57628. }
  57629. void MouseListener::mouseDrag (const MouseEvent&)
  57630. {
  57631. }
  57632. void MouseListener::mouseMove (const MouseEvent&)
  57633. {
  57634. }
  57635. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57636. {
  57637. }
  57638. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57639. {
  57640. }
  57641. END_JUCE_NAMESPACE
  57642. /*** End of inlined file: juce_MouseListener.cpp ***/
  57643. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57644. BEGIN_JUCE_NAMESPACE
  57645. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57646. const String& buttonTextWhenTrue,
  57647. const String& buttonTextWhenFalse)
  57648. : PropertyComponent (name),
  57649. onText (buttonTextWhenTrue),
  57650. offText (buttonTextWhenFalse)
  57651. {
  57652. addAndMakeVisible (&button);
  57653. button.setClickingTogglesState (false);
  57654. button.addListener (this);
  57655. }
  57656. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57657. const String& name,
  57658. const String& buttonText)
  57659. : PropertyComponent (name),
  57660. onText (buttonText),
  57661. offText (buttonText)
  57662. {
  57663. addAndMakeVisible (&button);
  57664. button.setClickingTogglesState (false);
  57665. button.setButtonText (buttonText);
  57666. button.getToggleStateValue().referTo (valueToControl);
  57667. button.setClickingTogglesState (true);
  57668. }
  57669. BooleanPropertyComponent::~BooleanPropertyComponent()
  57670. {
  57671. }
  57672. void BooleanPropertyComponent::setState (const bool newState)
  57673. {
  57674. button.setToggleState (newState, true);
  57675. }
  57676. bool BooleanPropertyComponent::getState() const
  57677. {
  57678. return button.getToggleState();
  57679. }
  57680. void BooleanPropertyComponent::paint (Graphics& g)
  57681. {
  57682. PropertyComponent::paint (g);
  57683. g.setColour (Colours::white);
  57684. g.fillRect (button.getBounds());
  57685. g.setColour (findColour (ComboBox::outlineColourId));
  57686. g.drawRect (button.getBounds());
  57687. }
  57688. void BooleanPropertyComponent::refresh()
  57689. {
  57690. button.setToggleState (getState(), false);
  57691. button.setButtonText (button.getToggleState() ? onText : offText);
  57692. }
  57693. void BooleanPropertyComponent::buttonClicked (Button*)
  57694. {
  57695. setState (! getState());
  57696. }
  57697. END_JUCE_NAMESPACE
  57698. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57699. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57700. BEGIN_JUCE_NAMESPACE
  57701. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57702. const bool triggerOnMouseDown)
  57703. : PropertyComponent (name)
  57704. {
  57705. addAndMakeVisible (&button);
  57706. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57707. button.addListener (this);
  57708. }
  57709. ButtonPropertyComponent::~ButtonPropertyComponent()
  57710. {
  57711. }
  57712. void ButtonPropertyComponent::refresh()
  57713. {
  57714. button.setButtonText (getButtonText());
  57715. }
  57716. void ButtonPropertyComponent::buttonClicked (Button*)
  57717. {
  57718. buttonClicked();
  57719. }
  57720. END_JUCE_NAMESPACE
  57721. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57722. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57723. BEGIN_JUCE_NAMESPACE
  57724. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57725. public ValueListener
  57726. {
  57727. public:
  57728. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57729. : sourceValue (sourceValue_),
  57730. mappings (mappings_)
  57731. {
  57732. sourceValue.addListener (this);
  57733. }
  57734. ~RemapperValueSource() {}
  57735. const var getValue() const
  57736. {
  57737. return mappings.indexOf (sourceValue.getValue()) + 1;
  57738. }
  57739. void setValue (const var& newValue)
  57740. {
  57741. const var remappedVal (mappings [(int) newValue - 1]);
  57742. if (remappedVal != sourceValue)
  57743. sourceValue = remappedVal;
  57744. }
  57745. void valueChanged (Value&)
  57746. {
  57747. sendChangeMessage (true);
  57748. }
  57749. protected:
  57750. Value sourceValue;
  57751. Array<var> mappings;
  57752. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57753. };
  57754. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57755. : PropertyComponent (name),
  57756. isCustomClass (true)
  57757. {
  57758. }
  57759. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57760. const String& name,
  57761. const StringArray& choices_,
  57762. const Array <var>& correspondingValues)
  57763. : PropertyComponent (name),
  57764. choices (choices_),
  57765. isCustomClass (false)
  57766. {
  57767. // The array of corresponding values must contain one value for each of the items in
  57768. // the choices array!
  57769. jassert (correspondingValues.size() == choices.size());
  57770. createComboBox();
  57771. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57772. }
  57773. ChoicePropertyComponent::~ChoicePropertyComponent()
  57774. {
  57775. }
  57776. void ChoicePropertyComponent::createComboBox()
  57777. {
  57778. addAndMakeVisible (&comboBox);
  57779. for (int i = 0; i < choices.size(); ++i)
  57780. {
  57781. if (choices[i].isNotEmpty())
  57782. comboBox.addItem (choices[i], i + 1);
  57783. else
  57784. comboBox.addSeparator();
  57785. }
  57786. comboBox.setEditableText (false);
  57787. }
  57788. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57789. {
  57790. jassertfalse; // you need to override this method in your subclass!
  57791. }
  57792. int ChoicePropertyComponent::getIndex() const
  57793. {
  57794. jassertfalse; // you need to override this method in your subclass!
  57795. return -1;
  57796. }
  57797. const StringArray& ChoicePropertyComponent::getChoices() const
  57798. {
  57799. return choices;
  57800. }
  57801. void ChoicePropertyComponent::refresh()
  57802. {
  57803. if (isCustomClass)
  57804. {
  57805. if (! comboBox.isVisible())
  57806. {
  57807. createComboBox();
  57808. comboBox.addListener (this);
  57809. }
  57810. comboBox.setSelectedId (getIndex() + 1, true);
  57811. }
  57812. }
  57813. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57814. {
  57815. if (isCustomClass)
  57816. {
  57817. const int newIndex = comboBox.getSelectedId() - 1;
  57818. if (newIndex != getIndex())
  57819. setIndex (newIndex);
  57820. }
  57821. }
  57822. END_JUCE_NAMESPACE
  57823. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57824. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57825. BEGIN_JUCE_NAMESPACE
  57826. PropertyComponent::PropertyComponent (const String& name,
  57827. const int preferredHeight_)
  57828. : Component (name),
  57829. preferredHeight (preferredHeight_)
  57830. {
  57831. jassert (name.isNotEmpty());
  57832. }
  57833. PropertyComponent::~PropertyComponent()
  57834. {
  57835. }
  57836. void PropertyComponent::paint (Graphics& g)
  57837. {
  57838. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57839. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57840. }
  57841. void PropertyComponent::resized()
  57842. {
  57843. if (getNumChildComponents() > 0)
  57844. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57845. }
  57846. void PropertyComponent::enablementChanged()
  57847. {
  57848. repaint();
  57849. }
  57850. END_JUCE_NAMESPACE
  57851. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57852. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57853. BEGIN_JUCE_NAMESPACE
  57854. class PropertySectionComponent : public Component
  57855. {
  57856. public:
  57857. PropertySectionComponent (const String& sectionTitle,
  57858. const Array <PropertyComponent*>& newProperties,
  57859. const bool sectionIsOpen_)
  57860. : Component (sectionTitle),
  57861. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57862. sectionIsOpen (sectionIsOpen_)
  57863. {
  57864. propertyComps.addArray (newProperties);
  57865. for (int i = propertyComps.size(); --i >= 0;)
  57866. {
  57867. addAndMakeVisible (propertyComps.getUnchecked(i));
  57868. propertyComps.getUnchecked(i)->refresh();
  57869. }
  57870. }
  57871. ~PropertySectionComponent()
  57872. {
  57873. propertyComps.clear();
  57874. }
  57875. void paint (Graphics& g)
  57876. {
  57877. if (titleHeight > 0)
  57878. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57879. }
  57880. void resized()
  57881. {
  57882. int y = titleHeight;
  57883. for (int i = 0; i < propertyComps.size(); ++i)
  57884. {
  57885. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  57886. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  57887. y = pec->getBottom();
  57888. }
  57889. }
  57890. int getPreferredHeight() const
  57891. {
  57892. int y = titleHeight;
  57893. if (isOpen())
  57894. {
  57895. for (int i = propertyComps.size(); --i >= 0;)
  57896. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  57897. }
  57898. return y;
  57899. }
  57900. void setOpen (const bool open)
  57901. {
  57902. if (sectionIsOpen != open)
  57903. {
  57904. sectionIsOpen = open;
  57905. for (int i = propertyComps.size(); --i >= 0;)
  57906. propertyComps.getUnchecked(i)->setVisible (open);
  57907. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57908. if (pp != 0)
  57909. pp->resized();
  57910. }
  57911. }
  57912. bool isOpen() const
  57913. {
  57914. return sectionIsOpen;
  57915. }
  57916. void refreshAll() const
  57917. {
  57918. for (int i = propertyComps.size(); --i >= 0;)
  57919. propertyComps.getUnchecked (i)->refresh();
  57920. }
  57921. void mouseUp (const MouseEvent& e)
  57922. {
  57923. if (e.getMouseDownX() < titleHeight
  57924. && e.x < titleHeight
  57925. && e.y < titleHeight
  57926. && e.getNumberOfClicks() != 2)
  57927. {
  57928. setOpen (! isOpen());
  57929. }
  57930. }
  57931. void mouseDoubleClick (const MouseEvent& e)
  57932. {
  57933. if (e.y < titleHeight)
  57934. setOpen (! isOpen());
  57935. }
  57936. private:
  57937. OwnedArray <PropertyComponent> propertyComps;
  57938. int titleHeight;
  57939. bool sectionIsOpen;
  57940. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  57941. };
  57942. class PropertyPanel::PropertyHolderComponent : public Component
  57943. {
  57944. public:
  57945. PropertyHolderComponent() {}
  57946. void paint (Graphics&) {}
  57947. void updateLayout (int width)
  57948. {
  57949. int y = 0;
  57950. for (int i = 0; i < sections.size(); ++i)
  57951. {
  57952. PropertySectionComponent* const section = sections.getUnchecked(i);
  57953. section->setBounds (0, y, width, section->getPreferredHeight());
  57954. y = section->getBottom();
  57955. }
  57956. setSize (width, y);
  57957. repaint();
  57958. }
  57959. void refreshAll() const
  57960. {
  57961. for (int i = 0; i < sections.size(); ++i)
  57962. sections.getUnchecked(i)->refreshAll();
  57963. }
  57964. void clear()
  57965. {
  57966. sections.clear();
  57967. }
  57968. void addSection (PropertySectionComponent* newSection)
  57969. {
  57970. sections.add (newSection);
  57971. addAndMakeVisible (newSection, 0);
  57972. }
  57973. int getNumSections() const throw() { return sections.size(); }
  57974. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  57975. private:
  57976. OwnedArray<PropertySectionComponent> sections;
  57977. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  57978. };
  57979. PropertyPanel::PropertyPanel()
  57980. {
  57981. messageWhenEmpty = TRANS("(nothing selected)");
  57982. addAndMakeVisible (&viewport);
  57983. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57984. viewport.setFocusContainer (true);
  57985. }
  57986. PropertyPanel::~PropertyPanel()
  57987. {
  57988. clear();
  57989. }
  57990. void PropertyPanel::paint (Graphics& g)
  57991. {
  57992. if (propertyHolderComponent->getNumSections() == 0)
  57993. {
  57994. g.setColour (Colours::black.withAlpha (0.5f));
  57995. g.setFont (14.0f);
  57996. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57997. Justification::centred, true);
  57998. }
  57999. }
  58000. void PropertyPanel::resized()
  58001. {
  58002. viewport.setBounds (getLocalBounds());
  58003. updatePropHolderLayout();
  58004. }
  58005. void PropertyPanel::clear()
  58006. {
  58007. if (propertyHolderComponent->getNumSections() > 0)
  58008. {
  58009. propertyHolderComponent->clear();
  58010. repaint();
  58011. }
  58012. }
  58013. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58014. {
  58015. if (propertyHolderComponent->getNumSections() == 0)
  58016. repaint();
  58017. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58018. updatePropHolderLayout();
  58019. }
  58020. void PropertyPanel::addSection (const String& sectionTitle,
  58021. const Array <PropertyComponent*>& newProperties,
  58022. const bool shouldBeOpen)
  58023. {
  58024. jassert (sectionTitle.isNotEmpty());
  58025. if (propertyHolderComponent->getNumSections() == 0)
  58026. repaint();
  58027. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58028. updatePropHolderLayout();
  58029. }
  58030. void PropertyPanel::updatePropHolderLayout() const
  58031. {
  58032. const int maxWidth = viewport.getMaximumVisibleWidth();
  58033. propertyHolderComponent->updateLayout (maxWidth);
  58034. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58035. if (maxWidth != newMaxWidth)
  58036. {
  58037. // need to do this twice because of scrollbars changing the size, etc.
  58038. propertyHolderComponent->updateLayout (newMaxWidth);
  58039. }
  58040. }
  58041. void PropertyPanel::refreshAll() const
  58042. {
  58043. propertyHolderComponent->refreshAll();
  58044. }
  58045. const StringArray PropertyPanel::getSectionNames() const
  58046. {
  58047. StringArray s;
  58048. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58049. {
  58050. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58051. if (section->getName().isNotEmpty())
  58052. s.add (section->getName());
  58053. }
  58054. return s;
  58055. }
  58056. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58057. {
  58058. int index = 0;
  58059. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58060. {
  58061. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58062. if (section->getName().isNotEmpty())
  58063. {
  58064. if (index == sectionIndex)
  58065. return section->isOpen();
  58066. ++index;
  58067. }
  58068. }
  58069. return false;
  58070. }
  58071. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58072. {
  58073. int index = 0;
  58074. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58075. {
  58076. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58077. if (section->getName().isNotEmpty())
  58078. {
  58079. if (index == sectionIndex)
  58080. {
  58081. section->setOpen (shouldBeOpen);
  58082. break;
  58083. }
  58084. ++index;
  58085. }
  58086. }
  58087. }
  58088. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58089. {
  58090. int index = 0;
  58091. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58092. {
  58093. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58094. if (section->getName().isNotEmpty())
  58095. {
  58096. if (index == sectionIndex)
  58097. {
  58098. section->setEnabled (shouldBeEnabled);
  58099. break;
  58100. }
  58101. ++index;
  58102. }
  58103. }
  58104. }
  58105. XmlElement* PropertyPanel::getOpennessState() const
  58106. {
  58107. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58108. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58109. const StringArray sections (getSectionNames());
  58110. for (int i = 0; i < sections.size(); ++i)
  58111. {
  58112. if (sections[i].isNotEmpty())
  58113. {
  58114. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58115. e->setAttribute ("name", sections[i]);
  58116. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58117. }
  58118. }
  58119. return xml;
  58120. }
  58121. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58122. {
  58123. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58124. {
  58125. const StringArray sections (getSectionNames());
  58126. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58127. {
  58128. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58129. e->getBoolAttribute ("open"));
  58130. }
  58131. viewport.setViewPosition (viewport.getViewPositionX(),
  58132. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58133. }
  58134. }
  58135. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58136. {
  58137. if (messageWhenEmpty != newMessage)
  58138. {
  58139. messageWhenEmpty = newMessage;
  58140. repaint();
  58141. }
  58142. }
  58143. const String& PropertyPanel::getMessageWhenEmpty() const
  58144. {
  58145. return messageWhenEmpty;
  58146. }
  58147. END_JUCE_NAMESPACE
  58148. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58149. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58150. BEGIN_JUCE_NAMESPACE
  58151. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58152. const double rangeMin,
  58153. const double rangeMax,
  58154. const double interval,
  58155. const double skewFactor)
  58156. : PropertyComponent (name)
  58157. {
  58158. addAndMakeVisible (&slider);
  58159. slider.setRange (rangeMin, rangeMax, interval);
  58160. slider.setSkewFactor (skewFactor);
  58161. slider.setSliderStyle (Slider::LinearBar);
  58162. slider.addListener (this);
  58163. }
  58164. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58165. const String& name,
  58166. const double rangeMin,
  58167. const double rangeMax,
  58168. const double interval,
  58169. const double skewFactor)
  58170. : PropertyComponent (name)
  58171. {
  58172. addAndMakeVisible (&slider);
  58173. slider.setRange (rangeMin, rangeMax, interval);
  58174. slider.setSkewFactor (skewFactor);
  58175. slider.setSliderStyle (Slider::LinearBar);
  58176. slider.getValueObject().referTo (valueToControl);
  58177. }
  58178. SliderPropertyComponent::~SliderPropertyComponent()
  58179. {
  58180. }
  58181. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58182. {
  58183. }
  58184. double SliderPropertyComponent::getValue() const
  58185. {
  58186. return slider.getValue();
  58187. }
  58188. void SliderPropertyComponent::refresh()
  58189. {
  58190. slider.setValue (getValue(), false);
  58191. }
  58192. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58193. {
  58194. if (getValue() != slider.getValue())
  58195. setValue (slider.getValue());
  58196. }
  58197. END_JUCE_NAMESPACE
  58198. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58199. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58200. BEGIN_JUCE_NAMESPACE
  58201. class TextPropLabel : public Label
  58202. {
  58203. public:
  58204. TextPropLabel (TextPropertyComponent& owner_,
  58205. const int maxChars_, const bool isMultiline_)
  58206. : Label (String::empty, String::empty),
  58207. owner (owner_),
  58208. maxChars (maxChars_),
  58209. isMultiline (isMultiline_)
  58210. {
  58211. setEditable (true, true, false);
  58212. setColour (backgroundColourId, Colours::white);
  58213. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58214. }
  58215. TextEditor* createEditorComponent()
  58216. {
  58217. TextEditor* const textEditor = Label::createEditorComponent();
  58218. textEditor->setInputRestrictions (maxChars);
  58219. if (isMultiline)
  58220. {
  58221. textEditor->setMultiLine (true, true);
  58222. textEditor->setReturnKeyStartsNewLine (true);
  58223. }
  58224. return textEditor;
  58225. }
  58226. void textWasEdited()
  58227. {
  58228. owner.textWasEdited();
  58229. }
  58230. private:
  58231. TextPropertyComponent& owner;
  58232. int maxChars;
  58233. bool isMultiline;
  58234. };
  58235. TextPropertyComponent::TextPropertyComponent (const String& name,
  58236. const int maxNumChars,
  58237. const bool isMultiLine)
  58238. : PropertyComponent (name)
  58239. {
  58240. createEditor (maxNumChars, isMultiLine);
  58241. }
  58242. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58243. const String& name,
  58244. const int maxNumChars,
  58245. const bool isMultiLine)
  58246. : PropertyComponent (name)
  58247. {
  58248. createEditor (maxNumChars, isMultiLine);
  58249. textEditor->getTextValue().referTo (valueToControl);
  58250. }
  58251. TextPropertyComponent::~TextPropertyComponent()
  58252. {
  58253. }
  58254. void TextPropertyComponent::setText (const String& newText)
  58255. {
  58256. textEditor->setText (newText, true);
  58257. }
  58258. const String TextPropertyComponent::getText() const
  58259. {
  58260. return textEditor->getText();
  58261. }
  58262. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58263. {
  58264. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58265. if (isMultiLine)
  58266. {
  58267. textEditor->setJustificationType (Justification::topLeft);
  58268. preferredHeight = 120;
  58269. }
  58270. }
  58271. void TextPropertyComponent::refresh()
  58272. {
  58273. textEditor->setText (getText(), false);
  58274. }
  58275. void TextPropertyComponent::textWasEdited()
  58276. {
  58277. const String newText (textEditor->getText());
  58278. if (getText() != newText)
  58279. setText (newText);
  58280. }
  58281. END_JUCE_NAMESPACE
  58282. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58283. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58284. BEGIN_JUCE_NAMESPACE
  58285. class SimpleDeviceManagerInputLevelMeter : public Component,
  58286. public Timer
  58287. {
  58288. public:
  58289. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58290. : manager (manager_),
  58291. level (0)
  58292. {
  58293. startTimer (50);
  58294. manager->enableInputLevelMeasurement (true);
  58295. }
  58296. ~SimpleDeviceManagerInputLevelMeter()
  58297. {
  58298. manager->enableInputLevelMeasurement (false);
  58299. }
  58300. void timerCallback()
  58301. {
  58302. const float newLevel = (float) manager->getCurrentInputLevel();
  58303. if (std::abs (level - newLevel) > 0.005f)
  58304. {
  58305. level = newLevel;
  58306. repaint();
  58307. }
  58308. }
  58309. void paint (Graphics& g)
  58310. {
  58311. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58312. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58313. }
  58314. private:
  58315. AudioDeviceManager* const manager;
  58316. float level;
  58317. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58318. };
  58319. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58320. public ListBoxModel
  58321. {
  58322. public:
  58323. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58324. const String& noItemsMessage_,
  58325. const int minNumber_,
  58326. const int maxNumber_)
  58327. : ListBox (String::empty, 0),
  58328. deviceManager (deviceManager_),
  58329. noItemsMessage (noItemsMessage_),
  58330. minNumber (minNumber_),
  58331. maxNumber (maxNumber_)
  58332. {
  58333. items = MidiInput::getDevices();
  58334. setModel (this);
  58335. setOutlineThickness (1);
  58336. }
  58337. ~MidiInputSelectorComponentListBox()
  58338. {
  58339. }
  58340. int getNumRows()
  58341. {
  58342. return items.size();
  58343. }
  58344. void paintListBoxItem (int row,
  58345. Graphics& g,
  58346. int width, int height,
  58347. bool rowIsSelected)
  58348. {
  58349. if (isPositiveAndBelow (row, items.size()))
  58350. {
  58351. if (rowIsSelected)
  58352. g.fillAll (findColour (TextEditor::highlightColourId)
  58353. .withMultipliedAlpha (0.3f));
  58354. const String item (items [row]);
  58355. bool enabled = deviceManager.isMidiInputEnabled (item);
  58356. const int x = getTickX();
  58357. const float tickW = height * 0.75f;
  58358. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58359. enabled, true, true, false);
  58360. g.setFont (height * 0.6f);
  58361. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58362. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58363. }
  58364. }
  58365. void listBoxItemClicked (int row, const MouseEvent& e)
  58366. {
  58367. selectRow (row);
  58368. if (e.x < getTickX())
  58369. flipEnablement (row);
  58370. }
  58371. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58372. {
  58373. flipEnablement (row);
  58374. }
  58375. void returnKeyPressed (int row)
  58376. {
  58377. flipEnablement (row);
  58378. }
  58379. void paint (Graphics& g)
  58380. {
  58381. ListBox::paint (g);
  58382. if (items.size() == 0)
  58383. {
  58384. g.setColour (Colours::grey);
  58385. g.setFont (13.0f);
  58386. g.drawText (noItemsMessage,
  58387. 0, 0, getWidth(), getHeight() / 2,
  58388. Justification::centred, true);
  58389. }
  58390. }
  58391. int getBestHeight (const int preferredHeight)
  58392. {
  58393. const int extra = getOutlineThickness() * 2;
  58394. return jmax (getRowHeight() * 2 + extra,
  58395. jmin (getRowHeight() * getNumRows() + extra,
  58396. preferredHeight));
  58397. }
  58398. private:
  58399. AudioDeviceManager& deviceManager;
  58400. const String noItemsMessage;
  58401. StringArray items;
  58402. int minNumber, maxNumber;
  58403. void flipEnablement (const int row)
  58404. {
  58405. if (isPositiveAndBelow (row, items.size()))
  58406. {
  58407. const String item (items [row]);
  58408. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58409. }
  58410. }
  58411. int getTickX() const
  58412. {
  58413. return getRowHeight() + 5;
  58414. }
  58415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58416. };
  58417. class AudioDeviceSettingsPanel : public Component,
  58418. public ChangeListener,
  58419. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58420. public ButtonListener
  58421. {
  58422. public:
  58423. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58424. AudioIODeviceType::DeviceSetupDetails& setup_,
  58425. const bool hideAdvancedOptionsWithButton)
  58426. : type (type_),
  58427. setup (setup_)
  58428. {
  58429. if (hideAdvancedOptionsWithButton)
  58430. {
  58431. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58432. showAdvancedSettingsButton->addListener (this);
  58433. }
  58434. type->scanForDevices();
  58435. setup.manager->addChangeListener (this);
  58436. changeListenerCallback (0);
  58437. }
  58438. ~AudioDeviceSettingsPanel()
  58439. {
  58440. setup.manager->removeChangeListener (this);
  58441. }
  58442. void resized()
  58443. {
  58444. const int lx = proportionOfWidth (0.35f);
  58445. const int w = proportionOfWidth (0.4f);
  58446. const int h = 24;
  58447. const int space = 6;
  58448. const int dh = h + space;
  58449. int y = 0;
  58450. if (outputDeviceDropDown != 0)
  58451. {
  58452. outputDeviceDropDown->setBounds (lx, y, w, h);
  58453. if (testButton != 0)
  58454. testButton->setBounds (proportionOfWidth (0.77f),
  58455. outputDeviceDropDown->getY(),
  58456. proportionOfWidth (0.18f),
  58457. h);
  58458. y += dh;
  58459. }
  58460. if (inputDeviceDropDown != 0)
  58461. {
  58462. inputDeviceDropDown->setBounds (lx, y, w, h);
  58463. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58464. inputDeviceDropDown->getY(),
  58465. proportionOfWidth (0.18f),
  58466. h);
  58467. y += dh;
  58468. }
  58469. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58470. if (outputChanList != 0)
  58471. {
  58472. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58473. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58474. y += bh + space;
  58475. }
  58476. if (inputChanList != 0)
  58477. {
  58478. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58479. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58480. y += bh + space;
  58481. }
  58482. y += space * 2;
  58483. if (showAdvancedSettingsButton != 0)
  58484. {
  58485. showAdvancedSettingsButton->changeWidthToFitText (h);
  58486. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58487. }
  58488. if (sampleRateDropDown != 0)
  58489. {
  58490. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58491. || ! showAdvancedSettingsButton->isVisible());
  58492. sampleRateDropDown->setBounds (lx, y, w, h);
  58493. y += dh;
  58494. }
  58495. if (bufferSizeDropDown != 0)
  58496. {
  58497. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58498. || ! showAdvancedSettingsButton->isVisible());
  58499. bufferSizeDropDown->setBounds (lx, y, w, h);
  58500. y += dh;
  58501. }
  58502. if (showUIButton != 0)
  58503. {
  58504. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58505. || ! showAdvancedSettingsButton->isVisible());
  58506. showUIButton->changeWidthToFitText (h);
  58507. showUIButton->setTopLeftPosition (lx, y);
  58508. }
  58509. }
  58510. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58511. {
  58512. if (comboBoxThatHasChanged == 0)
  58513. return;
  58514. AudioDeviceManager::AudioDeviceSetup config;
  58515. setup.manager->getAudioDeviceSetup (config);
  58516. String error;
  58517. if (comboBoxThatHasChanged == outputDeviceDropDown
  58518. || comboBoxThatHasChanged == inputDeviceDropDown)
  58519. {
  58520. if (outputDeviceDropDown != 0)
  58521. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58522. : outputDeviceDropDown->getText();
  58523. if (inputDeviceDropDown != 0)
  58524. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58525. : inputDeviceDropDown->getText();
  58526. if (! type->hasSeparateInputsAndOutputs())
  58527. config.inputDeviceName = config.outputDeviceName;
  58528. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58529. config.useDefaultInputChannels = true;
  58530. else
  58531. config.useDefaultOutputChannels = true;
  58532. error = setup.manager->setAudioDeviceSetup (config, true);
  58533. showCorrectDeviceName (inputDeviceDropDown, true);
  58534. showCorrectDeviceName (outputDeviceDropDown, false);
  58535. updateControlPanelButton();
  58536. resized();
  58537. }
  58538. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58539. {
  58540. if (sampleRateDropDown->getSelectedId() > 0)
  58541. {
  58542. config.sampleRate = sampleRateDropDown->getSelectedId();
  58543. error = setup.manager->setAudioDeviceSetup (config, true);
  58544. }
  58545. }
  58546. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58547. {
  58548. if (bufferSizeDropDown->getSelectedId() > 0)
  58549. {
  58550. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58551. error = setup.manager->setAudioDeviceSetup (config, true);
  58552. }
  58553. }
  58554. if (error.isNotEmpty())
  58555. {
  58556. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58557. "Error when trying to open audio device!",
  58558. error);
  58559. }
  58560. }
  58561. void buttonClicked (Button* button)
  58562. {
  58563. if (button == showAdvancedSettingsButton)
  58564. {
  58565. showAdvancedSettingsButton->setVisible (false);
  58566. resized();
  58567. }
  58568. else if (button == showUIButton)
  58569. {
  58570. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58571. if (device != 0 && device->showControlPanel())
  58572. {
  58573. setup.manager->closeAudioDevice();
  58574. setup.manager->restartLastAudioDevice();
  58575. getTopLevelComponent()->toFront (true);
  58576. }
  58577. }
  58578. else if (button == testButton && testButton != 0)
  58579. {
  58580. setup.manager->playTestSound();
  58581. }
  58582. }
  58583. void updateControlPanelButton()
  58584. {
  58585. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58586. showUIButton = 0;
  58587. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58588. {
  58589. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58590. TRANS ("opens the device's own control panel")));
  58591. showUIButton->addListener (this);
  58592. }
  58593. resized();
  58594. }
  58595. void changeListenerCallback (ChangeBroadcaster*)
  58596. {
  58597. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58598. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58599. {
  58600. if (outputDeviceDropDown == 0)
  58601. {
  58602. outputDeviceDropDown = new ComboBox (String::empty);
  58603. outputDeviceDropDown->addListener (this);
  58604. addAndMakeVisible (outputDeviceDropDown);
  58605. outputDeviceLabel = new Label (String::empty,
  58606. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58607. : TRANS ("device:"));
  58608. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58609. if (setup.maxNumOutputChannels > 0)
  58610. {
  58611. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58612. testButton->addListener (this);
  58613. }
  58614. }
  58615. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58616. }
  58617. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58618. {
  58619. if (inputDeviceDropDown == 0)
  58620. {
  58621. inputDeviceDropDown = new ComboBox (String::empty);
  58622. inputDeviceDropDown->addListener (this);
  58623. addAndMakeVisible (inputDeviceDropDown);
  58624. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58625. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58626. addAndMakeVisible (inputLevelMeter
  58627. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58628. }
  58629. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58630. }
  58631. updateControlPanelButton();
  58632. showCorrectDeviceName (inputDeviceDropDown, true);
  58633. showCorrectDeviceName (outputDeviceDropDown, false);
  58634. if (currentDevice != 0)
  58635. {
  58636. if (setup.maxNumOutputChannels > 0
  58637. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58638. {
  58639. if (outputChanList == 0)
  58640. {
  58641. addAndMakeVisible (outputChanList
  58642. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58643. TRANS ("(no audio output channels found)")));
  58644. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58645. outputChanLabel->attachToComponent (outputChanList, true);
  58646. }
  58647. outputChanList->refresh();
  58648. }
  58649. else
  58650. {
  58651. outputChanLabel = 0;
  58652. outputChanList = 0;
  58653. }
  58654. if (setup.maxNumInputChannels > 0
  58655. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58656. {
  58657. if (inputChanList == 0)
  58658. {
  58659. addAndMakeVisible (inputChanList
  58660. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58661. TRANS ("(no audio input channels found)")));
  58662. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58663. inputChanLabel->attachToComponent (inputChanList, true);
  58664. }
  58665. inputChanList->refresh();
  58666. }
  58667. else
  58668. {
  58669. inputChanLabel = 0;
  58670. inputChanList = 0;
  58671. }
  58672. // sample rate..
  58673. {
  58674. if (sampleRateDropDown == 0)
  58675. {
  58676. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58677. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58678. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58679. }
  58680. else
  58681. {
  58682. sampleRateDropDown->clear();
  58683. sampleRateDropDown->removeListener (this);
  58684. }
  58685. const int numRates = currentDevice->getNumSampleRates();
  58686. for (int i = 0; i < numRates; ++i)
  58687. {
  58688. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58689. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58690. }
  58691. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58692. sampleRateDropDown->addListener (this);
  58693. }
  58694. // buffer size
  58695. {
  58696. if (bufferSizeDropDown == 0)
  58697. {
  58698. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58699. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58700. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58701. }
  58702. else
  58703. {
  58704. bufferSizeDropDown->clear();
  58705. bufferSizeDropDown->removeListener (this);
  58706. }
  58707. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58708. double currentRate = currentDevice->getCurrentSampleRate();
  58709. if (currentRate == 0)
  58710. currentRate = 48000.0;
  58711. for (int i = 0; i < numBufferSizes; ++i)
  58712. {
  58713. const int bs = currentDevice->getBufferSizeSamples (i);
  58714. bufferSizeDropDown->addItem (String (bs)
  58715. + " samples ("
  58716. + String (bs * 1000.0 / currentRate, 1)
  58717. + " ms)",
  58718. bs);
  58719. }
  58720. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58721. bufferSizeDropDown->addListener (this);
  58722. }
  58723. }
  58724. else
  58725. {
  58726. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58727. sampleRateLabel = 0;
  58728. bufferSizeLabel = 0;
  58729. sampleRateDropDown = 0;
  58730. bufferSizeDropDown = 0;
  58731. if (outputDeviceDropDown != 0)
  58732. outputDeviceDropDown->setSelectedId (-1, true);
  58733. if (inputDeviceDropDown != 0)
  58734. inputDeviceDropDown->setSelectedId (-1, true);
  58735. }
  58736. resized();
  58737. setSize (getWidth(), getLowestY() + 4);
  58738. }
  58739. private:
  58740. AudioIODeviceType* const type;
  58741. const AudioIODeviceType::DeviceSetupDetails setup;
  58742. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58743. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58744. ScopedPointer<TextButton> testButton;
  58745. ScopedPointer<Component> inputLevelMeter;
  58746. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58747. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58748. {
  58749. if (box != 0)
  58750. {
  58751. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58752. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58753. box->setSelectedId (index + 1, true);
  58754. if (testButton != 0 && ! isInput)
  58755. testButton->setEnabled (index >= 0);
  58756. }
  58757. }
  58758. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58759. {
  58760. const StringArray devs (type->getDeviceNames (isInputs));
  58761. combo.clear (true);
  58762. for (int i = 0; i < devs.size(); ++i)
  58763. combo.addItem (devs[i], i + 1);
  58764. combo.addItem (TRANS("<< none >>"), -1);
  58765. combo.setSelectedId (-1, true);
  58766. }
  58767. int getLowestY() const
  58768. {
  58769. int y = 0;
  58770. for (int i = getNumChildComponents(); --i >= 0;)
  58771. y = jmax (y, getChildComponent (i)->getBottom());
  58772. return y;
  58773. }
  58774. public:
  58775. class ChannelSelectorListBox : public ListBox,
  58776. public ListBoxModel
  58777. {
  58778. public:
  58779. enum BoxType
  58780. {
  58781. audioInputType,
  58782. audioOutputType
  58783. };
  58784. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58785. const BoxType type_,
  58786. const String& noItemsMessage_)
  58787. : ListBox (String::empty, 0),
  58788. setup (setup_),
  58789. type (type_),
  58790. noItemsMessage (noItemsMessage_)
  58791. {
  58792. refresh();
  58793. setModel (this);
  58794. setOutlineThickness (1);
  58795. }
  58796. ~ChannelSelectorListBox()
  58797. {
  58798. }
  58799. void refresh()
  58800. {
  58801. items.clear();
  58802. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58803. if (currentDevice != 0)
  58804. {
  58805. if (type == audioInputType)
  58806. items = currentDevice->getInputChannelNames();
  58807. else if (type == audioOutputType)
  58808. items = currentDevice->getOutputChannelNames();
  58809. if (setup.useStereoPairs)
  58810. {
  58811. StringArray pairs;
  58812. for (int i = 0; i < items.size(); i += 2)
  58813. {
  58814. const String name (items[i]);
  58815. const String name2 (items[i + 1]);
  58816. String commonBit;
  58817. for (int j = 0; j < name.length(); ++j)
  58818. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58819. commonBit = name.substring (0, j);
  58820. // Make sure we only split the name at a space, because otherwise, things
  58821. // like "input 11" + "input 12" would become "input 11 + 2"
  58822. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58823. commonBit = commonBit.dropLastCharacters (1);
  58824. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58825. }
  58826. items = pairs;
  58827. }
  58828. }
  58829. updateContent();
  58830. repaint();
  58831. }
  58832. int getNumRows()
  58833. {
  58834. return items.size();
  58835. }
  58836. void paintListBoxItem (int row,
  58837. Graphics& g,
  58838. int width, int height,
  58839. bool rowIsSelected)
  58840. {
  58841. if (isPositiveAndBelow (row, items.size()))
  58842. {
  58843. if (rowIsSelected)
  58844. g.fillAll (findColour (TextEditor::highlightColourId)
  58845. .withMultipliedAlpha (0.3f));
  58846. const String item (items [row]);
  58847. bool enabled = false;
  58848. AudioDeviceManager::AudioDeviceSetup config;
  58849. setup.manager->getAudioDeviceSetup (config);
  58850. if (setup.useStereoPairs)
  58851. {
  58852. if (type == audioInputType)
  58853. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58854. else if (type == audioOutputType)
  58855. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58856. }
  58857. else
  58858. {
  58859. if (type == audioInputType)
  58860. enabled = config.inputChannels [row];
  58861. else if (type == audioOutputType)
  58862. enabled = config.outputChannels [row];
  58863. }
  58864. const int x = getTickX();
  58865. const float tickW = height * 0.75f;
  58866. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58867. enabled, true, true, false);
  58868. g.setFont (height * 0.6f);
  58869. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58870. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58871. }
  58872. }
  58873. void listBoxItemClicked (int row, const MouseEvent& e)
  58874. {
  58875. selectRow (row);
  58876. if (e.x < getTickX())
  58877. flipEnablement (row);
  58878. }
  58879. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58880. {
  58881. flipEnablement (row);
  58882. }
  58883. void returnKeyPressed (int row)
  58884. {
  58885. flipEnablement (row);
  58886. }
  58887. void paint (Graphics& g)
  58888. {
  58889. ListBox::paint (g);
  58890. if (items.size() == 0)
  58891. {
  58892. g.setColour (Colours::grey);
  58893. g.setFont (13.0f);
  58894. g.drawText (noItemsMessage,
  58895. 0, 0, getWidth(), getHeight() / 2,
  58896. Justification::centred, true);
  58897. }
  58898. }
  58899. int getBestHeight (int maxHeight)
  58900. {
  58901. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58902. getNumRows())
  58903. + getOutlineThickness() * 2;
  58904. }
  58905. private:
  58906. const AudioIODeviceType::DeviceSetupDetails setup;
  58907. const BoxType type;
  58908. const String noItemsMessage;
  58909. StringArray items;
  58910. void flipEnablement (const int row)
  58911. {
  58912. jassert (type == audioInputType || type == audioOutputType);
  58913. if (isPositiveAndBelow (row, items.size()))
  58914. {
  58915. AudioDeviceManager::AudioDeviceSetup config;
  58916. setup.manager->getAudioDeviceSetup (config);
  58917. if (setup.useStereoPairs)
  58918. {
  58919. BigInteger bits;
  58920. BigInteger& original = (type == audioInputType ? config.inputChannels
  58921. : config.outputChannels);
  58922. int i;
  58923. for (i = 0; i < 256; i += 2)
  58924. bits.setBit (i / 2, original [i] || original [i + 1]);
  58925. if (type == audioInputType)
  58926. {
  58927. config.useDefaultInputChannels = false;
  58928. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58929. }
  58930. else
  58931. {
  58932. config.useDefaultOutputChannels = false;
  58933. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58934. }
  58935. for (i = 0; i < 256; ++i)
  58936. original.setBit (i, bits [i / 2]);
  58937. }
  58938. else
  58939. {
  58940. if (type == audioInputType)
  58941. {
  58942. config.useDefaultInputChannels = false;
  58943. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58944. }
  58945. else
  58946. {
  58947. config.useDefaultOutputChannels = false;
  58948. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58949. }
  58950. }
  58951. String error (setup.manager->setAudioDeviceSetup (config, true));
  58952. if (! error.isEmpty())
  58953. {
  58954. //xxx
  58955. }
  58956. }
  58957. }
  58958. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58959. {
  58960. const int numActive = chans.countNumberOfSetBits();
  58961. if (chans [index])
  58962. {
  58963. if (numActive > minNumber)
  58964. chans.setBit (index, false);
  58965. }
  58966. else
  58967. {
  58968. if (numActive >= maxNumber)
  58969. {
  58970. const int firstActiveChan = chans.findNextSetBit();
  58971. chans.setBit (index > firstActiveChan
  58972. ? firstActiveChan : chans.getHighestBit(),
  58973. false);
  58974. }
  58975. chans.setBit (index, true);
  58976. }
  58977. }
  58978. int getTickX() const
  58979. {
  58980. return getRowHeight() + 5;
  58981. }
  58982. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  58983. };
  58984. private:
  58985. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58986. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  58987. };
  58988. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58989. const int minInputChannels_,
  58990. const int maxInputChannels_,
  58991. const int minOutputChannels_,
  58992. const int maxOutputChannels_,
  58993. const bool showMidiInputOptions,
  58994. const bool showMidiOutputSelector,
  58995. const bool showChannelsAsStereoPairs_,
  58996. const bool hideAdvancedOptionsWithButton_)
  58997. : deviceManager (deviceManager_),
  58998. deviceTypeDropDown (0),
  58999. deviceTypeDropDownLabel (0),
  59000. minOutputChannels (minOutputChannels_),
  59001. maxOutputChannels (maxOutputChannels_),
  59002. minInputChannels (minInputChannels_),
  59003. maxInputChannels (maxInputChannels_),
  59004. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59005. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59006. {
  59007. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59008. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59009. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59010. {
  59011. deviceTypeDropDown = new ComboBox (String::empty);
  59012. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59013. {
  59014. deviceTypeDropDown
  59015. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59016. i + 1);
  59017. }
  59018. addAndMakeVisible (deviceTypeDropDown);
  59019. deviceTypeDropDown->addListener (this);
  59020. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59021. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59022. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59023. }
  59024. if (showMidiInputOptions)
  59025. {
  59026. addAndMakeVisible (midiInputsList
  59027. = new MidiInputSelectorComponentListBox (deviceManager,
  59028. TRANS("(no midi inputs available)"),
  59029. 0, 0));
  59030. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59031. midiInputsLabel->setJustificationType (Justification::topRight);
  59032. midiInputsLabel->attachToComponent (midiInputsList, true);
  59033. }
  59034. else
  59035. {
  59036. midiInputsList = 0;
  59037. midiInputsLabel = 0;
  59038. }
  59039. if (showMidiOutputSelector)
  59040. {
  59041. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59042. midiOutputSelector->addListener (this);
  59043. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59044. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59045. }
  59046. else
  59047. {
  59048. midiOutputSelector = 0;
  59049. midiOutputLabel = 0;
  59050. }
  59051. deviceManager_.addChangeListener (this);
  59052. changeListenerCallback (0);
  59053. }
  59054. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59055. {
  59056. deviceManager.removeChangeListener (this);
  59057. }
  59058. void AudioDeviceSelectorComponent::resized()
  59059. {
  59060. const int lx = proportionOfWidth (0.35f);
  59061. const int w = proportionOfWidth (0.4f);
  59062. const int h = 24;
  59063. const int space = 6;
  59064. const int dh = h + space;
  59065. int y = 15;
  59066. if (deviceTypeDropDown != 0)
  59067. {
  59068. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59069. y += dh + space * 2;
  59070. }
  59071. if (audioDeviceSettingsComp != 0)
  59072. {
  59073. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59074. y += audioDeviceSettingsComp->getHeight() + space;
  59075. }
  59076. if (midiInputsList != 0)
  59077. {
  59078. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59079. midiInputsList->setBounds (lx, y, w, bh);
  59080. y += bh + space;
  59081. }
  59082. if (midiOutputSelector != 0)
  59083. midiOutputSelector->setBounds (lx, y, w, h);
  59084. }
  59085. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59086. {
  59087. if (child == audioDeviceSettingsComp)
  59088. resized();
  59089. }
  59090. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59091. {
  59092. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59093. if (device != 0 && device->hasControlPanel())
  59094. {
  59095. if (device->showControlPanel())
  59096. deviceManager.restartLastAudioDevice();
  59097. getTopLevelComponent()->toFront (true);
  59098. }
  59099. }
  59100. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59101. {
  59102. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59103. {
  59104. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59105. if (type != 0)
  59106. {
  59107. audioDeviceSettingsComp = 0;
  59108. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59109. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59110. }
  59111. }
  59112. else if (comboBoxThatHasChanged == midiOutputSelector)
  59113. {
  59114. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59115. }
  59116. }
  59117. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59118. {
  59119. if (deviceTypeDropDown != 0)
  59120. {
  59121. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59122. }
  59123. if (audioDeviceSettingsComp == 0
  59124. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59125. {
  59126. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59127. audioDeviceSettingsComp = 0;
  59128. AudioIODeviceType* const type
  59129. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59130. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59131. if (type != 0)
  59132. {
  59133. AudioIODeviceType::DeviceSetupDetails details;
  59134. details.manager = &deviceManager;
  59135. details.minNumInputChannels = minInputChannels;
  59136. details.maxNumInputChannels = maxInputChannels;
  59137. details.minNumOutputChannels = minOutputChannels;
  59138. details.maxNumOutputChannels = maxOutputChannels;
  59139. details.useStereoPairs = showChannelsAsStereoPairs;
  59140. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59141. if (audioDeviceSettingsComp != 0)
  59142. {
  59143. addAndMakeVisible (audioDeviceSettingsComp);
  59144. audioDeviceSettingsComp->resized();
  59145. }
  59146. }
  59147. }
  59148. if (midiInputsList != 0)
  59149. {
  59150. midiInputsList->updateContent();
  59151. midiInputsList->repaint();
  59152. }
  59153. if (midiOutputSelector != 0)
  59154. {
  59155. midiOutputSelector->clear();
  59156. const StringArray midiOuts (MidiOutput::getDevices());
  59157. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59158. midiOutputSelector->addSeparator();
  59159. for (int i = 0; i < midiOuts.size(); ++i)
  59160. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59161. int current = -1;
  59162. if (deviceManager.getDefaultMidiOutput() != 0)
  59163. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59164. midiOutputSelector->setSelectedId (current, true);
  59165. }
  59166. resized();
  59167. }
  59168. END_JUCE_NAMESPACE
  59169. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59170. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59171. BEGIN_JUCE_NAMESPACE
  59172. BubbleComponent::BubbleComponent()
  59173. : side (0),
  59174. allowablePlacements (above | below | left | right),
  59175. arrowTipX (0.0f),
  59176. arrowTipY (0.0f)
  59177. {
  59178. setInterceptsMouseClicks (false, false);
  59179. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59180. setComponentEffect (&shadow);
  59181. }
  59182. BubbleComponent::~BubbleComponent()
  59183. {
  59184. }
  59185. void BubbleComponent::paint (Graphics& g)
  59186. {
  59187. int x = content.getX();
  59188. int y = content.getY();
  59189. int w = content.getWidth();
  59190. int h = content.getHeight();
  59191. int cw, ch;
  59192. getContentSize (cw, ch);
  59193. if (side == 3)
  59194. x += w - cw;
  59195. else if (side != 1)
  59196. x += (w - cw) / 2;
  59197. w = cw;
  59198. if (side == 2)
  59199. y += h - ch;
  59200. else if (side != 0)
  59201. y += (h - ch) / 2;
  59202. h = ch;
  59203. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59204. (float) x, (float) y,
  59205. (float) w, (float) h);
  59206. const int cx = x + (w - cw) / 2;
  59207. const int cy = y + (h - ch) / 2;
  59208. const int indent = 3;
  59209. g.setOrigin (cx + indent, cy + indent);
  59210. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59211. paintContent (g, cw - indent * 2, ch - indent * 2);
  59212. }
  59213. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59214. {
  59215. allowablePlacements = newPlacement;
  59216. }
  59217. void BubbleComponent::setPosition (Component* componentToPointTo)
  59218. {
  59219. jassert (componentToPointTo != 0);
  59220. Point<int> pos;
  59221. if (getParentComponent() != 0)
  59222. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59223. else
  59224. pos = componentToPointTo->localPointToGlobal (pos);
  59225. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59226. }
  59227. void BubbleComponent::setPosition (const int arrowTipX_,
  59228. const int arrowTipY_)
  59229. {
  59230. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59231. }
  59232. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59233. {
  59234. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59235. : getParentMonitorArea());
  59236. int x = 0;
  59237. int y = 0;
  59238. int w = 150;
  59239. int h = 30;
  59240. getContentSize (w, h);
  59241. w += 30;
  59242. h += 30;
  59243. const float edgeIndent = 2.0f;
  59244. const int arrowLength = jmin (10, h / 3, w / 3);
  59245. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59246. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59247. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59248. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59249. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59250. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59251. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59252. {
  59253. spaceLeft = spaceRight = 0;
  59254. }
  59255. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59256. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59257. {
  59258. spaceAbove = spaceBelow = 0;
  59259. }
  59260. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59261. {
  59262. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59263. arrowTipX = w * 0.5f;
  59264. content.setSize (w, h - arrowLength);
  59265. if (spaceAbove >= spaceBelow)
  59266. {
  59267. // above
  59268. y = rectangleToPointTo.getY() - h;
  59269. content.setPosition (0, 0);
  59270. arrowTipY = h - edgeIndent;
  59271. side = 2;
  59272. }
  59273. else
  59274. {
  59275. // below
  59276. y = rectangleToPointTo.getBottom();
  59277. content.setPosition (0, arrowLength);
  59278. arrowTipY = edgeIndent;
  59279. side = 0;
  59280. }
  59281. }
  59282. else
  59283. {
  59284. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59285. arrowTipY = h * 0.5f;
  59286. content.setSize (w - arrowLength, h);
  59287. if (spaceLeft > spaceRight)
  59288. {
  59289. // on the left
  59290. x = rectangleToPointTo.getX() - w;
  59291. content.setPosition (0, 0);
  59292. arrowTipX = w - edgeIndent;
  59293. side = 3;
  59294. }
  59295. else
  59296. {
  59297. // on the right
  59298. x = rectangleToPointTo.getRight();
  59299. content.setPosition (arrowLength, 0);
  59300. arrowTipX = edgeIndent;
  59301. side = 1;
  59302. }
  59303. }
  59304. setBounds (x, y, w, h);
  59305. }
  59306. END_JUCE_NAMESPACE
  59307. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59308. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59309. BEGIN_JUCE_NAMESPACE
  59310. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59311. : fadeOutLength (fadeOutLengthMs),
  59312. deleteAfterUse (false)
  59313. {
  59314. }
  59315. BubbleMessageComponent::~BubbleMessageComponent()
  59316. {
  59317. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59318. }
  59319. void BubbleMessageComponent::showAt (int x, int y,
  59320. const String& text,
  59321. const int numMillisecondsBeforeRemoving,
  59322. const bool removeWhenMouseClicked,
  59323. const bool deleteSelfAfterUse)
  59324. {
  59325. textLayout.clear();
  59326. textLayout.setText (text, Font (14.0f));
  59327. textLayout.layout (256, Justification::centredLeft, true);
  59328. setPosition (x, y);
  59329. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59330. }
  59331. void BubbleMessageComponent::showAt (Component* const component,
  59332. const String& text,
  59333. const int numMillisecondsBeforeRemoving,
  59334. const bool removeWhenMouseClicked,
  59335. const bool deleteSelfAfterUse)
  59336. {
  59337. textLayout.clear();
  59338. textLayout.setText (text, Font (14.0f));
  59339. textLayout.layout (256, Justification::centredLeft, true);
  59340. setPosition (component);
  59341. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59342. }
  59343. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59344. const bool removeWhenMouseClicked,
  59345. const bool deleteSelfAfterUse)
  59346. {
  59347. setVisible (true);
  59348. deleteAfterUse = deleteSelfAfterUse;
  59349. if (numMillisecondsBeforeRemoving > 0)
  59350. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59351. else
  59352. expiryTime = 0;
  59353. startTimer (77);
  59354. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59355. if (! (removeWhenMouseClicked && isShowing()))
  59356. mouseClickCounter += 0xfffff;
  59357. repaint();
  59358. }
  59359. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59360. {
  59361. w = textLayout.getWidth() + 16;
  59362. h = textLayout.getHeight() + 16;
  59363. }
  59364. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59365. {
  59366. g.setColour (findColour (TooltipWindow::textColourId));
  59367. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59368. }
  59369. void BubbleMessageComponent::timerCallback()
  59370. {
  59371. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59372. {
  59373. stopTimer();
  59374. setVisible (false);
  59375. if (deleteAfterUse)
  59376. delete this;
  59377. }
  59378. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59379. {
  59380. stopTimer();
  59381. if (deleteAfterUse)
  59382. delete this;
  59383. else
  59384. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59385. }
  59386. }
  59387. END_JUCE_NAMESPACE
  59388. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59389. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59390. BEGIN_JUCE_NAMESPACE
  59391. class ColourComponentSlider : public Slider
  59392. {
  59393. public:
  59394. ColourComponentSlider (const String& name)
  59395. : Slider (name)
  59396. {
  59397. setRange (0.0, 255.0, 1.0);
  59398. }
  59399. const String getTextFromValue (double value)
  59400. {
  59401. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59402. }
  59403. double getValueFromText (const String& text)
  59404. {
  59405. return (double) text.getHexValue32();
  59406. }
  59407. private:
  59408. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59409. };
  59410. class ColourSpaceMarker : public Component
  59411. {
  59412. public:
  59413. ColourSpaceMarker()
  59414. {
  59415. setInterceptsMouseClicks (false, false);
  59416. }
  59417. void paint (Graphics& g)
  59418. {
  59419. g.setColour (Colour::greyLevel (0.1f));
  59420. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59421. g.setColour (Colour::greyLevel (0.9f));
  59422. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59423. }
  59424. private:
  59425. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59426. };
  59427. class ColourSelector::ColourSpaceView : public Component
  59428. {
  59429. public:
  59430. ColourSpaceView (ColourSelector& owner_,
  59431. float& h_, float& s_, float& v_,
  59432. const int edgeSize)
  59433. : owner (owner_),
  59434. h (h_), s (s_), v (v_),
  59435. lastHue (0.0f),
  59436. edge (edgeSize)
  59437. {
  59438. addAndMakeVisible (&marker);
  59439. setMouseCursor (MouseCursor::CrosshairCursor);
  59440. }
  59441. void paint (Graphics& g)
  59442. {
  59443. if (colours.isNull())
  59444. {
  59445. const int width = getWidth() / 2;
  59446. const int height = getHeight() / 2;
  59447. colours = Image (Image::RGB, width, height, false);
  59448. Image::BitmapData pixels (colours, true);
  59449. for (int y = 0; y < height; ++y)
  59450. {
  59451. const float val = 1.0f - y / (float) height;
  59452. for (int x = 0; x < width; ++x)
  59453. {
  59454. const float sat = x / (float) width;
  59455. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59456. }
  59457. }
  59458. }
  59459. g.setOpacity (1.0f);
  59460. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59461. 0, 0, colours.getWidth(), colours.getHeight());
  59462. }
  59463. void mouseDown (const MouseEvent& e)
  59464. {
  59465. mouseDrag (e);
  59466. }
  59467. void mouseDrag (const MouseEvent& e)
  59468. {
  59469. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59470. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59471. owner.setSV (sat, val);
  59472. }
  59473. void updateIfNeeded()
  59474. {
  59475. if (lastHue != h)
  59476. {
  59477. lastHue = h;
  59478. colours = Image::null;
  59479. repaint();
  59480. }
  59481. updateMarker();
  59482. }
  59483. void resized()
  59484. {
  59485. colours = Image::null;
  59486. updateMarker();
  59487. }
  59488. private:
  59489. ColourSelector& owner;
  59490. float& h;
  59491. float& s;
  59492. float& v;
  59493. float lastHue;
  59494. ColourSpaceMarker marker;
  59495. const int edge;
  59496. Image colours;
  59497. void updateMarker()
  59498. {
  59499. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59500. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59501. edge * 2, edge * 2);
  59502. }
  59503. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59504. };
  59505. class HueSelectorMarker : public Component
  59506. {
  59507. public:
  59508. HueSelectorMarker()
  59509. {
  59510. setInterceptsMouseClicks (false, false);
  59511. }
  59512. void paint (Graphics& g)
  59513. {
  59514. Path p;
  59515. p.addTriangle (1.0f, 1.0f,
  59516. getWidth() * 0.3f, getHeight() * 0.5f,
  59517. 1.0f, getHeight() - 1.0f);
  59518. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59519. getWidth() * 0.7f, getHeight() * 0.5f,
  59520. getWidth() - 1.0f, getHeight() - 1.0f);
  59521. g.setColour (Colours::white.withAlpha (0.75f));
  59522. g.fillPath (p);
  59523. g.setColour (Colours::black.withAlpha (0.75f));
  59524. g.strokePath (p, PathStrokeType (1.2f));
  59525. }
  59526. private:
  59527. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59528. };
  59529. class ColourSelector::HueSelectorComp : public Component
  59530. {
  59531. public:
  59532. HueSelectorComp (ColourSelector& owner_,
  59533. float& h_, float& s_, float& v_,
  59534. const int edgeSize)
  59535. : owner (owner_),
  59536. h (h_), s (s_), v (v_),
  59537. lastHue (0.0f),
  59538. edge (edgeSize)
  59539. {
  59540. addAndMakeVisible (&marker);
  59541. }
  59542. void paint (Graphics& g)
  59543. {
  59544. const float yScale = 1.0f / (getHeight() - edge * 2);
  59545. const Rectangle<int> clip (g.getClipBounds());
  59546. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59547. {
  59548. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59549. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59550. }
  59551. }
  59552. void resized()
  59553. {
  59554. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59555. getWidth(), edge * 2);
  59556. }
  59557. void mouseDown (const MouseEvent& e)
  59558. {
  59559. mouseDrag (e);
  59560. }
  59561. void mouseDrag (const MouseEvent& e)
  59562. {
  59563. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59564. }
  59565. void updateIfNeeded()
  59566. {
  59567. resized();
  59568. }
  59569. private:
  59570. ColourSelector& owner;
  59571. float& h;
  59572. float& s;
  59573. float& v;
  59574. float lastHue;
  59575. HueSelectorMarker marker;
  59576. const int edge;
  59577. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59578. };
  59579. class ColourSelector::SwatchComponent : public Component
  59580. {
  59581. public:
  59582. SwatchComponent (ColourSelector& owner_, int index_)
  59583. : owner (owner_), index (index_)
  59584. {
  59585. }
  59586. void paint (Graphics& g)
  59587. {
  59588. const Colour colour (owner.getSwatchColour (index));
  59589. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59590. Colour (0xffdddddd).overlaidWith (colour),
  59591. Colour (0xffffffff).overlaidWith (colour));
  59592. }
  59593. void mouseDown (const MouseEvent&)
  59594. {
  59595. PopupMenu m;
  59596. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59597. m.addSeparator();
  59598. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59599. const int r = m.showAt (this);
  59600. if (r == 1)
  59601. {
  59602. owner.setCurrentColour (owner.getSwatchColour (index));
  59603. }
  59604. else if (r == 2)
  59605. {
  59606. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59607. {
  59608. owner.setSwatchColour (index, owner.getCurrentColour());
  59609. repaint();
  59610. }
  59611. }
  59612. }
  59613. private:
  59614. ColourSelector& owner;
  59615. const int index;
  59616. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59617. };
  59618. ColourSelector::ColourSelector (const int flags_,
  59619. const int edgeGap_,
  59620. const int gapAroundColourSpaceComponent)
  59621. : colour (Colours::white),
  59622. flags (flags_),
  59623. edgeGap (edgeGap_)
  59624. {
  59625. // not much point having a selector with no components in it!
  59626. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59627. updateHSV();
  59628. if ((flags & showSliders) != 0)
  59629. {
  59630. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59631. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59632. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59633. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59634. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59635. for (int i = 4; --i >= 0;)
  59636. sliders[i]->addListener (this);
  59637. }
  59638. if ((flags & showColourspace) != 0)
  59639. {
  59640. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59641. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59642. }
  59643. update();
  59644. }
  59645. ColourSelector::~ColourSelector()
  59646. {
  59647. dispatchPendingMessages();
  59648. swatchComponents.clear();
  59649. }
  59650. const Colour ColourSelector::getCurrentColour() const
  59651. {
  59652. return ((flags & showAlphaChannel) != 0) ? colour
  59653. : colour.withAlpha ((uint8) 0xff);
  59654. }
  59655. void ColourSelector::setCurrentColour (const Colour& c)
  59656. {
  59657. if (c != colour)
  59658. {
  59659. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59660. updateHSV();
  59661. update();
  59662. }
  59663. }
  59664. void ColourSelector::setHue (float newH)
  59665. {
  59666. newH = jlimit (0.0f, 1.0f, newH);
  59667. if (h != newH)
  59668. {
  59669. h = newH;
  59670. colour = Colour (h, s, v, colour.getFloatAlpha());
  59671. update();
  59672. }
  59673. }
  59674. void ColourSelector::setSV (float newS, float newV)
  59675. {
  59676. newS = jlimit (0.0f, 1.0f, newS);
  59677. newV = jlimit (0.0f, 1.0f, newV);
  59678. if (s != newS || v != newV)
  59679. {
  59680. s = newS;
  59681. v = newV;
  59682. colour = Colour (h, s, v, colour.getFloatAlpha());
  59683. update();
  59684. }
  59685. }
  59686. void ColourSelector::updateHSV()
  59687. {
  59688. colour.getHSB (h, s, v);
  59689. }
  59690. void ColourSelector::update()
  59691. {
  59692. if (sliders[0] != 0)
  59693. {
  59694. sliders[0]->setValue ((int) colour.getRed());
  59695. sliders[1]->setValue ((int) colour.getGreen());
  59696. sliders[2]->setValue ((int) colour.getBlue());
  59697. sliders[3]->setValue ((int) colour.getAlpha());
  59698. }
  59699. if (colourSpace != 0)
  59700. {
  59701. colourSpace->updateIfNeeded();
  59702. hueSelector->updateIfNeeded();
  59703. }
  59704. if ((flags & showColourAtTop) != 0)
  59705. repaint (previewArea);
  59706. sendChangeMessage();
  59707. }
  59708. void ColourSelector::paint (Graphics& g)
  59709. {
  59710. g.fillAll (findColour (backgroundColourId));
  59711. if ((flags & showColourAtTop) != 0)
  59712. {
  59713. const Colour currentColour (getCurrentColour());
  59714. g.fillCheckerBoard (previewArea, 10, 10,
  59715. Colour (0xffdddddd).overlaidWith (currentColour),
  59716. Colour (0xffffffff).overlaidWith (currentColour));
  59717. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59718. g.setFont (14.0f, true);
  59719. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59720. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59721. Justification::centred, false);
  59722. }
  59723. if ((flags & showSliders) != 0)
  59724. {
  59725. g.setColour (findColour (labelTextColourId));
  59726. g.setFont (11.0f);
  59727. for (int i = 4; --i >= 0;)
  59728. {
  59729. if (sliders[i]->isVisible())
  59730. g.drawText (sliders[i]->getName() + ":",
  59731. 0, sliders[i]->getY(),
  59732. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59733. Justification::centredRight, false);
  59734. }
  59735. }
  59736. }
  59737. void ColourSelector::resized()
  59738. {
  59739. const int swatchesPerRow = 8;
  59740. const int swatchHeight = 22;
  59741. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59742. const int numSwatches = getNumSwatches();
  59743. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59744. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59745. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59746. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59747. int y = topSpace;
  59748. if ((flags & showColourspace) != 0)
  59749. {
  59750. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59751. colourSpace->setBounds (edgeGap, y,
  59752. getWidth() - hueWidth - edgeGap - 4,
  59753. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59754. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59755. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59756. colourSpace->getHeight());
  59757. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59758. }
  59759. if ((flags & showSliders) != 0)
  59760. {
  59761. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59762. for (int i = 0; i < numSliders; ++i)
  59763. {
  59764. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59765. proportionOfWidth (0.72f), sliderHeight - 2);
  59766. y += sliderHeight;
  59767. }
  59768. }
  59769. if (numSwatches > 0)
  59770. {
  59771. const int startX = 8;
  59772. const int xGap = 4;
  59773. const int yGap = 4;
  59774. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59775. y += edgeGap;
  59776. if (swatchComponents.size() != numSwatches)
  59777. {
  59778. swatchComponents.clear();
  59779. for (int i = 0; i < numSwatches; ++i)
  59780. {
  59781. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59782. swatchComponents.add (sc);
  59783. addAndMakeVisible (sc);
  59784. }
  59785. }
  59786. int x = startX;
  59787. for (int i = 0; i < swatchComponents.size(); ++i)
  59788. {
  59789. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59790. sc->setBounds (x + xGap / 2,
  59791. y + yGap / 2,
  59792. swatchWidth - xGap,
  59793. swatchHeight - yGap);
  59794. if (((i + 1) % swatchesPerRow) == 0)
  59795. {
  59796. x = startX;
  59797. y += swatchHeight;
  59798. }
  59799. else
  59800. {
  59801. x += swatchWidth;
  59802. }
  59803. }
  59804. }
  59805. }
  59806. void ColourSelector::sliderValueChanged (Slider*)
  59807. {
  59808. if (sliders[0] != 0)
  59809. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59810. (uint8) sliders[1]->getValue(),
  59811. (uint8) sliders[2]->getValue(),
  59812. (uint8) sliders[3]->getValue()));
  59813. }
  59814. int ColourSelector::getNumSwatches() const
  59815. {
  59816. return 0;
  59817. }
  59818. const Colour ColourSelector::getSwatchColour (const int) const
  59819. {
  59820. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59821. return Colours::black;
  59822. }
  59823. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59824. {
  59825. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59826. }
  59827. END_JUCE_NAMESPACE
  59828. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59829. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59830. BEGIN_JUCE_NAMESPACE
  59831. class ShadowWindow : public Component
  59832. {
  59833. public:
  59834. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  59835. : topLeft (shadowImageSections [type_ * 3]),
  59836. bottomRight (shadowImageSections [type_ * 3 + 1]),
  59837. filler (shadowImageSections [type_ * 3 + 2]),
  59838. type (type_)
  59839. {
  59840. setInterceptsMouseClicks (false, false);
  59841. if (owner.isOnDesktop())
  59842. {
  59843. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59844. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59845. | ComponentPeer::windowIsTemporary
  59846. | ComponentPeer::windowIgnoresKeyPresses);
  59847. }
  59848. else if (owner.getParentComponent() != 0)
  59849. {
  59850. owner.getParentComponent()->addChildComponent (this);
  59851. }
  59852. }
  59853. void paint (Graphics& g)
  59854. {
  59855. g.setOpacity (1.0f);
  59856. if (type < 2)
  59857. {
  59858. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59859. g.drawImage (topLeft,
  59860. 0, 0, topLeft.getWidth(), imH,
  59861. 0, 0, topLeft.getWidth(), imH);
  59862. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59863. g.drawImage (bottomRight,
  59864. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59865. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59866. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59867. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59868. }
  59869. else
  59870. {
  59871. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59872. g.drawImage (topLeft,
  59873. 0, 0, imW, topLeft.getHeight(),
  59874. 0, 0, imW, topLeft.getHeight());
  59875. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59876. g.drawImage (bottomRight,
  59877. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59878. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59879. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59880. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59881. }
  59882. }
  59883. void resized()
  59884. {
  59885. repaint(); // (needed for correct repainting)
  59886. }
  59887. private:
  59888. const Image topLeft, bottomRight, filler;
  59889. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59890. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  59891. };
  59892. DropShadower::DropShadower (const float alpha_,
  59893. const int xOffset_,
  59894. const int yOffset_,
  59895. const float blurRadius_)
  59896. : owner (0),
  59897. xOffset (xOffset_),
  59898. yOffset (yOffset_),
  59899. alpha (alpha_),
  59900. blurRadius (blurRadius_),
  59901. reentrant (false)
  59902. {
  59903. }
  59904. DropShadower::~DropShadower()
  59905. {
  59906. if (owner != 0)
  59907. owner->removeComponentListener (this);
  59908. reentrant = true;
  59909. shadowWindows.clear();
  59910. }
  59911. void DropShadower::setOwner (Component* componentToFollow)
  59912. {
  59913. if (componentToFollow != owner)
  59914. {
  59915. if (owner != 0)
  59916. owner->removeComponentListener (this);
  59917. // (the component can't be null)
  59918. jassert (componentToFollow != 0);
  59919. owner = componentToFollow;
  59920. jassert (owner != 0);
  59921. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59922. owner->addComponentListener (this);
  59923. updateShadows();
  59924. }
  59925. }
  59926. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59927. {
  59928. updateShadows();
  59929. }
  59930. void DropShadower::componentBroughtToFront (Component&)
  59931. {
  59932. bringShadowWindowsToFront();
  59933. }
  59934. void DropShadower::componentParentHierarchyChanged (Component&)
  59935. {
  59936. shadowWindows.clear();
  59937. updateShadows();
  59938. }
  59939. void DropShadower::componentVisibilityChanged (Component&)
  59940. {
  59941. updateShadows();
  59942. }
  59943. void DropShadower::updateShadows()
  59944. {
  59945. if (reentrant || owner == 0)
  59946. return;
  59947. ComponentPeer* const peer = owner->getPeer();
  59948. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  59949. const bool createShadowWindows = shadowWindows.size() == 0
  59950. && owner->getWidth() > 0
  59951. && owner->getHeight() > 0
  59952. && isOwnerVisible
  59953. && (Desktop::canUseSemiTransparentWindows()
  59954. || owner->getParentComponent() != 0);
  59955. {
  59956. const ScopedValueSetter<bool> setter (reentrant, true, false);
  59957. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  59958. if (createShadowWindows)
  59959. {
  59960. // keep a cached version of the image to save doing the gaussian too often
  59961. String imageId;
  59962. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59963. const int hash = imageId.hashCode();
  59964. Image bigIm (ImageCache::getFromHashCode (hash));
  59965. if (bigIm.isNull())
  59966. {
  59967. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59968. Graphics bigG (bigIm);
  59969. bigG.setColour (Colours::black.withAlpha (alpha));
  59970. bigG.fillRect (shadowEdge + xOffset,
  59971. shadowEdge + yOffset,
  59972. bigIm.getWidth() - (shadowEdge * 2),
  59973. bigIm.getHeight() - (shadowEdge * 2));
  59974. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59975. blurKernel.createGaussianBlur (blurRadius);
  59976. blurKernel.applyToImage (bigIm, bigIm,
  59977. Rectangle<int> (xOffset, yOffset,
  59978. bigIm.getWidth(), bigIm.getHeight()));
  59979. ImageCache::addImageToCache (bigIm, hash);
  59980. }
  59981. const int iw = bigIm.getWidth();
  59982. const int ih = bigIm.getHeight();
  59983. const int shadowEdge2 = shadowEdge * 2;
  59984. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59985. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59986. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59987. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59988. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59989. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59990. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59991. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59992. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59993. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59994. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59995. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59996. for (int i = 0; i < 4; ++i)
  59997. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  59998. }
  59999. if (shadowWindows.size() >= 4)
  60000. {
  60001. for (int i = shadowWindows.size(); --i >= 0;)
  60002. {
  60003. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60004. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60005. }
  60006. const int x = owner->getX();
  60007. const int y = owner->getY() - shadowEdge;
  60008. const int w = owner->getWidth();
  60009. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60010. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60011. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60012. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60013. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60014. }
  60015. }
  60016. if (createShadowWindows)
  60017. bringShadowWindowsToFront();
  60018. }
  60019. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60020. const int sx, const int sy)
  60021. {
  60022. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60023. Graphics g (shadowImageSections[num]);
  60024. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60025. }
  60026. void DropShadower::bringShadowWindowsToFront()
  60027. {
  60028. if (! reentrant)
  60029. {
  60030. updateShadows();
  60031. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60032. for (int i = shadowWindows.size(); --i >= 0;)
  60033. shadowWindows.getUnchecked(i)->toBehind (owner);
  60034. }
  60035. }
  60036. END_JUCE_NAMESPACE
  60037. /*** End of inlined file: juce_DropShadower.cpp ***/
  60038. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60039. BEGIN_JUCE_NAMESPACE
  60040. class MidiKeyboardUpDownButton : public Button
  60041. {
  60042. public:
  60043. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60044. : Button (String::empty),
  60045. owner (owner_),
  60046. delta (delta_)
  60047. {
  60048. setOpaque (true);
  60049. }
  60050. void clicked()
  60051. {
  60052. int note = owner.getLowestVisibleKey();
  60053. if (delta < 0)
  60054. note = (note - 1) / 12;
  60055. else
  60056. note = note / 12 + 1;
  60057. owner.setLowestVisibleKey (note * 12);
  60058. }
  60059. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60060. {
  60061. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60062. isMouseOverButton, isButtonDown,
  60063. delta > 0);
  60064. }
  60065. private:
  60066. MidiKeyboardComponent& owner;
  60067. const int delta;
  60068. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60069. };
  60070. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60071. const Orientation orientation_)
  60072. : state (state_),
  60073. xOffset (0),
  60074. blackNoteLength (1),
  60075. keyWidth (16.0f),
  60076. orientation (orientation_),
  60077. midiChannel (1),
  60078. midiInChannelMask (0xffff),
  60079. velocity (1.0f),
  60080. noteUnderMouse (-1),
  60081. mouseDownNote (-1),
  60082. rangeStart (0),
  60083. rangeEnd (127),
  60084. firstKey (12 * 4),
  60085. canScroll (true),
  60086. mouseDragging (false),
  60087. useMousePositionForVelocity (true),
  60088. keyMappingOctave (6),
  60089. octaveNumForMiddleC (3)
  60090. {
  60091. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60092. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60093. // initialise with a default set of querty key-mappings..
  60094. const char* const keymap = "awsedftgyhujkolp;";
  60095. for (int i = String (keymap).length(); --i >= 0;)
  60096. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60097. setOpaque (true);
  60098. setWantsKeyboardFocus (true);
  60099. state.addListener (this);
  60100. }
  60101. MidiKeyboardComponent::~MidiKeyboardComponent()
  60102. {
  60103. state.removeListener (this);
  60104. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60105. }
  60106. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60107. {
  60108. keyWidth = widthInPixels;
  60109. resized();
  60110. }
  60111. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60112. {
  60113. if (orientation != newOrientation)
  60114. {
  60115. orientation = newOrientation;
  60116. resized();
  60117. }
  60118. }
  60119. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60120. const int highestNote)
  60121. {
  60122. jassert (lowestNote >= 0 && lowestNote <= 127);
  60123. jassert (highestNote >= 0 && highestNote <= 127);
  60124. jassert (lowestNote <= highestNote);
  60125. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60126. {
  60127. rangeStart = jlimit (0, 127, lowestNote);
  60128. rangeEnd = jlimit (0, 127, highestNote);
  60129. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60130. resized();
  60131. }
  60132. }
  60133. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60134. {
  60135. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60136. if (noteNumber != firstKey)
  60137. {
  60138. firstKey = noteNumber;
  60139. sendChangeMessage();
  60140. resized();
  60141. }
  60142. }
  60143. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60144. {
  60145. if (canScroll != canScroll_)
  60146. {
  60147. canScroll = canScroll_;
  60148. resized();
  60149. }
  60150. }
  60151. void MidiKeyboardComponent::colourChanged()
  60152. {
  60153. repaint();
  60154. }
  60155. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60156. {
  60157. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60158. if (midiChannel != midiChannelNumber)
  60159. {
  60160. resetAnyKeysInUse();
  60161. midiChannel = jlimit (1, 16, midiChannelNumber);
  60162. }
  60163. }
  60164. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60165. {
  60166. midiInChannelMask = midiChannelMask;
  60167. triggerAsyncUpdate();
  60168. }
  60169. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60170. {
  60171. velocity = jlimit (0.0f, 1.0f, velocity_);
  60172. useMousePositionForVelocity = useMousePositionForVelocity_;
  60173. }
  60174. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60175. {
  60176. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60177. static const float blackNoteWidth = 0.7f;
  60178. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60179. 1.0f, 2 - blackNoteWidth * 0.4f,
  60180. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60181. 4.0f, 5 - blackNoteWidth * 0.5f,
  60182. 5.0f, 6 - blackNoteWidth * 0.3f,
  60183. 6.0f };
  60184. static const float widths[] = { 1.0f, blackNoteWidth,
  60185. 1.0f, blackNoteWidth,
  60186. 1.0f, 1.0f, blackNoteWidth,
  60187. 1.0f, blackNoteWidth,
  60188. 1.0f, blackNoteWidth,
  60189. 1.0f };
  60190. const int octave = midiNoteNumber / 12;
  60191. const int note = midiNoteNumber % 12;
  60192. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60193. w = roundToInt (widths [note] * keyWidth_);
  60194. }
  60195. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60196. {
  60197. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60198. int rx, rw;
  60199. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60200. x -= xOffset + rx;
  60201. }
  60202. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60203. {
  60204. int x, y;
  60205. getKeyPos (midiNoteNumber, x, y);
  60206. return x;
  60207. }
  60208. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60209. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60210. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60211. {
  60212. if (! reallyContains (pos, false))
  60213. return -1;
  60214. Point<int> p (pos);
  60215. if (orientation != horizontalKeyboard)
  60216. {
  60217. p = Point<int> (p.getY(), p.getX());
  60218. if (orientation == verticalKeyboardFacingLeft)
  60219. p = Point<int> (p.getX(), getWidth() - p.getY());
  60220. else
  60221. p = Point<int> (getHeight() - p.getX(), p.getY());
  60222. }
  60223. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60224. }
  60225. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60226. {
  60227. if (pos.getY() < blackNoteLength)
  60228. {
  60229. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60230. {
  60231. for (int i = 0; i < 5; ++i)
  60232. {
  60233. const int note = octaveStart + blackNotes [i];
  60234. if (note >= rangeStart && note <= rangeEnd)
  60235. {
  60236. int kx, kw;
  60237. getKeyPos (note, kx, kw);
  60238. kx += xOffset;
  60239. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60240. {
  60241. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60242. return note;
  60243. }
  60244. }
  60245. }
  60246. }
  60247. }
  60248. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60249. {
  60250. for (int i = 0; i < 7; ++i)
  60251. {
  60252. const int note = octaveStart + whiteNotes [i];
  60253. if (note >= rangeStart && note <= rangeEnd)
  60254. {
  60255. int kx, kw;
  60256. getKeyPos (note, kx, kw);
  60257. kx += xOffset;
  60258. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60259. {
  60260. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60261. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60262. return note;
  60263. }
  60264. }
  60265. }
  60266. }
  60267. mousePositionVelocity = 0;
  60268. return -1;
  60269. }
  60270. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60271. {
  60272. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60273. {
  60274. int x, w;
  60275. getKeyPos (noteNum, x, w);
  60276. if (orientation == horizontalKeyboard)
  60277. repaint (x, 0, w, getHeight());
  60278. else if (orientation == verticalKeyboardFacingLeft)
  60279. repaint (0, x, getWidth(), w);
  60280. else if (orientation == verticalKeyboardFacingRight)
  60281. repaint (0, getHeight() - x - w, getWidth(), w);
  60282. }
  60283. }
  60284. void MidiKeyboardComponent::paint (Graphics& g)
  60285. {
  60286. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60287. const Colour lineColour (findColour (keySeparatorLineColourId));
  60288. const Colour textColour (findColour (textLabelColourId));
  60289. int x, w, octave;
  60290. for (octave = 0; octave < 128; octave += 12)
  60291. {
  60292. for (int white = 0; white < 7; ++white)
  60293. {
  60294. const int noteNum = octave + whiteNotes [white];
  60295. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60296. {
  60297. getKeyPos (noteNum, x, w);
  60298. if (orientation == horizontalKeyboard)
  60299. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60300. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60301. noteUnderMouse == noteNum,
  60302. lineColour, textColour);
  60303. else if (orientation == verticalKeyboardFacingLeft)
  60304. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60305. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60306. noteUnderMouse == noteNum,
  60307. lineColour, textColour);
  60308. else if (orientation == verticalKeyboardFacingRight)
  60309. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60310. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60311. noteUnderMouse == noteNum,
  60312. lineColour, textColour);
  60313. }
  60314. }
  60315. }
  60316. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60317. if (orientation == verticalKeyboardFacingLeft)
  60318. {
  60319. x1 = getWidth() - 1.0f;
  60320. x2 = getWidth() - 5.0f;
  60321. }
  60322. else if (orientation == verticalKeyboardFacingRight)
  60323. x2 = 5.0f;
  60324. else
  60325. y2 = 5.0f;
  60326. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60327. Colours::transparentBlack, x2, y2, false));
  60328. getKeyPos (rangeEnd, x, w);
  60329. x += w;
  60330. if (orientation == verticalKeyboardFacingLeft)
  60331. g.fillRect (getWidth() - 5, 0, 5, x);
  60332. else if (orientation == verticalKeyboardFacingRight)
  60333. g.fillRect (0, 0, 5, x);
  60334. else
  60335. g.fillRect (0, 0, x, 5);
  60336. g.setColour (lineColour);
  60337. if (orientation == verticalKeyboardFacingLeft)
  60338. g.fillRect (0, 0, 1, x);
  60339. else if (orientation == verticalKeyboardFacingRight)
  60340. g.fillRect (getWidth() - 1, 0, 1, x);
  60341. else
  60342. g.fillRect (0, getHeight() - 1, x, 1);
  60343. const Colour blackNoteColour (findColour (blackNoteColourId));
  60344. for (octave = 0; octave < 128; octave += 12)
  60345. {
  60346. for (int black = 0; black < 5; ++black)
  60347. {
  60348. const int noteNum = octave + blackNotes [black];
  60349. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60350. {
  60351. getKeyPos (noteNum, x, w);
  60352. if (orientation == horizontalKeyboard)
  60353. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60354. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60355. noteUnderMouse == noteNum,
  60356. blackNoteColour);
  60357. else if (orientation == verticalKeyboardFacingLeft)
  60358. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60359. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60360. noteUnderMouse == noteNum,
  60361. blackNoteColour);
  60362. else if (orientation == verticalKeyboardFacingRight)
  60363. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60364. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60365. noteUnderMouse == noteNum,
  60366. blackNoteColour);
  60367. }
  60368. }
  60369. }
  60370. }
  60371. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60372. Graphics& g, int x, int y, int w, int h,
  60373. bool isDown, bool isOver,
  60374. const Colour& lineColour,
  60375. const Colour& textColour)
  60376. {
  60377. Colour c (Colours::transparentWhite);
  60378. if (isDown)
  60379. c = findColour (keyDownOverlayColourId);
  60380. if (isOver)
  60381. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60382. g.setColour (c);
  60383. g.fillRect (x, y, w, h);
  60384. const String text (getWhiteNoteText (midiNoteNumber));
  60385. if (! text.isEmpty())
  60386. {
  60387. g.setColour (textColour);
  60388. Font f (jmin (12.0f, keyWidth * 0.9f));
  60389. f.setHorizontalScale (0.8f);
  60390. g.setFont (f);
  60391. Justification justification (Justification::centredBottom);
  60392. if (orientation == verticalKeyboardFacingLeft)
  60393. justification = Justification::centredLeft;
  60394. else if (orientation == verticalKeyboardFacingRight)
  60395. justification = Justification::centredRight;
  60396. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60397. }
  60398. g.setColour (lineColour);
  60399. if (orientation == horizontalKeyboard)
  60400. g.fillRect (x, y, 1, h);
  60401. else if (orientation == verticalKeyboardFacingLeft)
  60402. g.fillRect (x, y, w, 1);
  60403. else if (orientation == verticalKeyboardFacingRight)
  60404. g.fillRect (x, y + h - 1, w, 1);
  60405. if (midiNoteNumber == rangeEnd)
  60406. {
  60407. if (orientation == horizontalKeyboard)
  60408. g.fillRect (x + w, y, 1, h);
  60409. else if (orientation == verticalKeyboardFacingLeft)
  60410. g.fillRect (x, y + h, w, 1);
  60411. else if (orientation == verticalKeyboardFacingRight)
  60412. g.fillRect (x, y - 1, w, 1);
  60413. }
  60414. }
  60415. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60416. Graphics& g, int x, int y, int w, int h,
  60417. bool isDown, bool isOver,
  60418. const Colour& noteFillColour)
  60419. {
  60420. Colour c (noteFillColour);
  60421. if (isDown)
  60422. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60423. if (isOver)
  60424. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60425. g.setColour (c);
  60426. g.fillRect (x, y, w, h);
  60427. if (isDown)
  60428. {
  60429. g.setColour (noteFillColour);
  60430. g.drawRect (x, y, w, h);
  60431. }
  60432. else
  60433. {
  60434. const int xIndent = jmax (1, jmin (w, h) / 8);
  60435. g.setColour (c.brighter());
  60436. if (orientation == horizontalKeyboard)
  60437. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60438. else if (orientation == verticalKeyboardFacingLeft)
  60439. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60440. else if (orientation == verticalKeyboardFacingRight)
  60441. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60442. }
  60443. }
  60444. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60445. {
  60446. octaveNumForMiddleC = octaveNumForMiddleC_;
  60447. repaint();
  60448. }
  60449. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60450. {
  60451. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60452. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60453. return String::empty;
  60454. }
  60455. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60456. const bool isMouseOver_,
  60457. const bool isButtonDown,
  60458. const bool movesOctavesUp)
  60459. {
  60460. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60461. float angle;
  60462. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60463. angle = movesOctavesUp ? 0.0f : 0.5f;
  60464. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60465. angle = movesOctavesUp ? 0.25f : 0.75f;
  60466. else
  60467. angle = movesOctavesUp ? 0.75f : 0.25f;
  60468. Path path;
  60469. path.lineTo (0.0f, 1.0f);
  60470. path.lineTo (1.0f, 0.5f);
  60471. path.closeSubPath();
  60472. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60473. g.setColour (findColour (upDownButtonArrowColourId)
  60474. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60475. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60476. w - 2.0f,
  60477. h - 2.0f,
  60478. true));
  60479. }
  60480. void MidiKeyboardComponent::resized()
  60481. {
  60482. int w = getWidth();
  60483. int h = getHeight();
  60484. if (w > 0 && h > 0)
  60485. {
  60486. if (orientation != horizontalKeyboard)
  60487. swapVariables (w, h);
  60488. blackNoteLength = roundToInt (h * 0.7f);
  60489. int kx2, kw2;
  60490. getKeyPos (rangeEnd, kx2, kw2);
  60491. kx2 += kw2;
  60492. if (firstKey != rangeStart)
  60493. {
  60494. int kx1, kw1;
  60495. getKeyPos (rangeStart, kx1, kw1);
  60496. if (kx2 - kx1 <= w)
  60497. {
  60498. firstKey = rangeStart;
  60499. sendChangeMessage();
  60500. repaint();
  60501. }
  60502. }
  60503. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60504. scrollDown->setVisible (showScrollButtons);
  60505. scrollUp->setVisible (showScrollButtons);
  60506. xOffset = 0;
  60507. if (showScrollButtons)
  60508. {
  60509. const int scrollButtonW = jmin (12, w / 2);
  60510. if (orientation == horizontalKeyboard)
  60511. {
  60512. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60513. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60514. }
  60515. else if (orientation == verticalKeyboardFacingLeft)
  60516. {
  60517. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60518. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60519. }
  60520. else if (orientation == verticalKeyboardFacingRight)
  60521. {
  60522. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60523. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60524. }
  60525. int endOfLastKey, kw;
  60526. getKeyPos (rangeEnd, endOfLastKey, kw);
  60527. endOfLastKey += kw;
  60528. float mousePositionVelocity;
  60529. const int spaceAvailable = w - scrollButtonW * 2;
  60530. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60531. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60532. {
  60533. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60534. sendChangeMessage();
  60535. }
  60536. int newOffset = 0;
  60537. getKeyPos (firstKey, newOffset, kw);
  60538. xOffset = newOffset - scrollButtonW;
  60539. }
  60540. else
  60541. {
  60542. firstKey = rangeStart;
  60543. }
  60544. timerCallback();
  60545. repaint();
  60546. }
  60547. }
  60548. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60549. {
  60550. triggerAsyncUpdate();
  60551. }
  60552. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60553. {
  60554. triggerAsyncUpdate();
  60555. }
  60556. void MidiKeyboardComponent::handleAsyncUpdate()
  60557. {
  60558. for (int i = rangeStart; i <= rangeEnd; ++i)
  60559. {
  60560. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60561. {
  60562. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60563. repaintNote (i);
  60564. }
  60565. }
  60566. }
  60567. void MidiKeyboardComponent::resetAnyKeysInUse()
  60568. {
  60569. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60570. {
  60571. state.allNotesOff (midiChannel);
  60572. keysPressed.clear();
  60573. mouseDownNote = -1;
  60574. }
  60575. }
  60576. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60577. {
  60578. float mousePositionVelocity = 0.0f;
  60579. const int newNote = (mouseDragging || isMouseOver())
  60580. ? xyToNote (pos, mousePositionVelocity) : -1;
  60581. if (noteUnderMouse != newNote)
  60582. {
  60583. if (mouseDownNote >= 0)
  60584. {
  60585. state.noteOff (midiChannel, mouseDownNote);
  60586. mouseDownNote = -1;
  60587. }
  60588. if (mouseDragging && newNote >= 0)
  60589. {
  60590. if (! useMousePositionForVelocity)
  60591. mousePositionVelocity = 1.0f;
  60592. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60593. mouseDownNote = newNote;
  60594. }
  60595. repaintNote (noteUnderMouse);
  60596. noteUnderMouse = newNote;
  60597. repaintNote (noteUnderMouse);
  60598. }
  60599. else if (mouseDownNote >= 0 && ! mouseDragging)
  60600. {
  60601. state.noteOff (midiChannel, mouseDownNote);
  60602. mouseDownNote = -1;
  60603. }
  60604. }
  60605. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60606. {
  60607. updateNoteUnderMouse (e.getPosition());
  60608. stopTimer();
  60609. }
  60610. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60611. {
  60612. float mousePositionVelocity;
  60613. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60614. if (newNote >= 0)
  60615. mouseDraggedToKey (newNote, e);
  60616. updateNoteUnderMouse (e.getPosition());
  60617. }
  60618. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60619. {
  60620. return true;
  60621. }
  60622. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60623. {
  60624. }
  60625. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60626. {
  60627. float mousePositionVelocity;
  60628. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60629. mouseDragging = false;
  60630. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60631. {
  60632. repaintNote (noteUnderMouse);
  60633. noteUnderMouse = -1;
  60634. mouseDragging = true;
  60635. updateNoteUnderMouse (e.getPosition());
  60636. startTimer (500);
  60637. }
  60638. }
  60639. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60640. {
  60641. mouseDragging = false;
  60642. updateNoteUnderMouse (e.getPosition());
  60643. stopTimer();
  60644. }
  60645. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60646. {
  60647. updateNoteUnderMouse (e.getPosition());
  60648. }
  60649. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60650. {
  60651. updateNoteUnderMouse (e.getPosition());
  60652. }
  60653. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60654. {
  60655. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60656. }
  60657. void MidiKeyboardComponent::timerCallback()
  60658. {
  60659. updateNoteUnderMouse (getMouseXYRelative());
  60660. }
  60661. void MidiKeyboardComponent::clearKeyMappings()
  60662. {
  60663. resetAnyKeysInUse();
  60664. keyPressNotes.clear();
  60665. keyPresses.clear();
  60666. }
  60667. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60668. const int midiNoteOffsetFromC)
  60669. {
  60670. removeKeyPressForNote (midiNoteOffsetFromC);
  60671. keyPressNotes.add (midiNoteOffsetFromC);
  60672. keyPresses.add (key);
  60673. }
  60674. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60675. {
  60676. for (int i = keyPressNotes.size(); --i >= 0;)
  60677. {
  60678. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60679. {
  60680. keyPressNotes.remove (i);
  60681. keyPresses.remove (i);
  60682. }
  60683. }
  60684. }
  60685. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60686. {
  60687. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60688. keyMappingOctave = newOctaveNumber;
  60689. }
  60690. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60691. {
  60692. bool keyPressUsed = false;
  60693. for (int i = keyPresses.size(); --i >= 0;)
  60694. {
  60695. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60696. if (keyPresses.getReference(i).isCurrentlyDown())
  60697. {
  60698. if (! keysPressed [note])
  60699. {
  60700. keysPressed.setBit (note);
  60701. state.noteOn (midiChannel, note, velocity);
  60702. keyPressUsed = true;
  60703. }
  60704. }
  60705. else
  60706. {
  60707. if (keysPressed [note])
  60708. {
  60709. keysPressed.clearBit (note);
  60710. state.noteOff (midiChannel, note);
  60711. keyPressUsed = true;
  60712. }
  60713. }
  60714. }
  60715. return keyPressUsed;
  60716. }
  60717. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60718. {
  60719. resetAnyKeysInUse();
  60720. }
  60721. END_JUCE_NAMESPACE
  60722. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60723. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60724. #if JUCE_OPENGL
  60725. BEGIN_JUCE_NAMESPACE
  60726. extern void juce_glViewport (const int w, const int h);
  60727. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60728. const int alphaBits_,
  60729. const int depthBufferBits_,
  60730. const int stencilBufferBits_)
  60731. : redBits (bitsPerRGBComponent),
  60732. greenBits (bitsPerRGBComponent),
  60733. blueBits (bitsPerRGBComponent),
  60734. alphaBits (alphaBits_),
  60735. depthBufferBits (depthBufferBits_),
  60736. stencilBufferBits (stencilBufferBits_),
  60737. accumulationBufferRedBits (0),
  60738. accumulationBufferGreenBits (0),
  60739. accumulationBufferBlueBits (0),
  60740. accumulationBufferAlphaBits (0),
  60741. fullSceneAntiAliasingNumSamples (0)
  60742. {
  60743. }
  60744. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60745. : redBits (other.redBits),
  60746. greenBits (other.greenBits),
  60747. blueBits (other.blueBits),
  60748. alphaBits (other.alphaBits),
  60749. depthBufferBits (other.depthBufferBits),
  60750. stencilBufferBits (other.stencilBufferBits),
  60751. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60752. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60753. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60754. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60755. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60756. {
  60757. }
  60758. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60759. {
  60760. redBits = other.redBits;
  60761. greenBits = other.greenBits;
  60762. blueBits = other.blueBits;
  60763. alphaBits = other.alphaBits;
  60764. depthBufferBits = other.depthBufferBits;
  60765. stencilBufferBits = other.stencilBufferBits;
  60766. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60767. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60768. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60769. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60770. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60771. return *this;
  60772. }
  60773. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60774. {
  60775. return redBits == other.redBits
  60776. && greenBits == other.greenBits
  60777. && blueBits == other.blueBits
  60778. && alphaBits == other.alphaBits
  60779. && depthBufferBits == other.depthBufferBits
  60780. && stencilBufferBits == other.stencilBufferBits
  60781. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60782. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60783. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60784. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60785. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60786. }
  60787. static Array<OpenGLContext*> knownContexts;
  60788. OpenGLContext::OpenGLContext() throw()
  60789. {
  60790. knownContexts.add (this);
  60791. }
  60792. OpenGLContext::~OpenGLContext()
  60793. {
  60794. knownContexts.removeValue (this);
  60795. }
  60796. OpenGLContext* OpenGLContext::getCurrentContext()
  60797. {
  60798. for (int i = knownContexts.size(); --i >= 0;)
  60799. {
  60800. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60801. if (oglc->isActive())
  60802. return oglc;
  60803. }
  60804. return 0;
  60805. }
  60806. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60807. {
  60808. public:
  60809. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60810. : ComponentMovementWatcher (owner_),
  60811. owner (owner_)
  60812. {
  60813. }
  60814. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60815. {
  60816. owner->updateContextPosition();
  60817. }
  60818. void componentPeerChanged()
  60819. {
  60820. const ScopedLock sl (owner->getContextLock());
  60821. owner->deleteContext();
  60822. }
  60823. void componentVisibilityChanged()
  60824. {
  60825. if (! owner->isShowing())
  60826. {
  60827. const ScopedLock sl (owner->getContextLock());
  60828. owner->deleteContext();
  60829. }
  60830. }
  60831. private:
  60832. OpenGLComponent* const owner;
  60833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  60834. };
  60835. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60836. : type (type_),
  60837. contextToShareListsWith (0),
  60838. needToUpdateViewport (true)
  60839. {
  60840. setOpaque (true);
  60841. componentWatcher = new OpenGLComponentWatcher (this);
  60842. }
  60843. OpenGLComponent::~OpenGLComponent()
  60844. {
  60845. deleteContext();
  60846. componentWatcher = 0;
  60847. }
  60848. void OpenGLComponent::deleteContext()
  60849. {
  60850. const ScopedLock sl (contextLock);
  60851. context = 0;
  60852. }
  60853. void OpenGLComponent::updateContextPosition()
  60854. {
  60855. needToUpdateViewport = true;
  60856. if (getWidth() > 0 && getHeight() > 0)
  60857. {
  60858. Component* const topComp = getTopLevelComponent();
  60859. if (topComp->getPeer() != 0)
  60860. {
  60861. const ScopedLock sl (contextLock);
  60862. if (context != 0)
  60863. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60864. getScreenY() - topComp->getScreenY(),
  60865. getWidth(),
  60866. getHeight(),
  60867. topComp->getHeight());
  60868. }
  60869. }
  60870. }
  60871. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60872. {
  60873. OpenGLPixelFormat pf;
  60874. const ScopedLock sl (contextLock);
  60875. if (context != 0)
  60876. pf = context->getPixelFormat();
  60877. return pf;
  60878. }
  60879. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60880. {
  60881. if (! (preferredPixelFormat == formatToUse))
  60882. {
  60883. const ScopedLock sl (contextLock);
  60884. deleteContext();
  60885. preferredPixelFormat = formatToUse;
  60886. }
  60887. }
  60888. void OpenGLComponent::shareWith (OpenGLContext* c)
  60889. {
  60890. if (contextToShareListsWith != c)
  60891. {
  60892. const ScopedLock sl (contextLock);
  60893. deleteContext();
  60894. contextToShareListsWith = c;
  60895. }
  60896. }
  60897. bool OpenGLComponent::makeCurrentContextActive()
  60898. {
  60899. if (context == 0)
  60900. {
  60901. const ScopedLock sl (contextLock);
  60902. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60903. {
  60904. context = createContext();
  60905. if (context != 0)
  60906. {
  60907. updateContextPosition();
  60908. if (context->makeActive())
  60909. newOpenGLContextCreated();
  60910. }
  60911. }
  60912. }
  60913. return context != 0 && context->makeActive();
  60914. }
  60915. void OpenGLComponent::makeCurrentContextInactive()
  60916. {
  60917. if (context != 0)
  60918. context->makeInactive();
  60919. }
  60920. bool OpenGLComponent::isActiveContext() const throw()
  60921. {
  60922. return context != 0 && context->isActive();
  60923. }
  60924. void OpenGLComponent::swapBuffers()
  60925. {
  60926. if (context != 0)
  60927. context->swapBuffers();
  60928. }
  60929. void OpenGLComponent::paint (Graphics&)
  60930. {
  60931. if (renderAndSwapBuffers())
  60932. {
  60933. ComponentPeer* const peer = getPeer();
  60934. if (peer != 0)
  60935. {
  60936. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60937. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60938. }
  60939. }
  60940. }
  60941. bool OpenGLComponent::renderAndSwapBuffers()
  60942. {
  60943. const ScopedLock sl (contextLock);
  60944. if (! makeCurrentContextActive())
  60945. return false;
  60946. if (needToUpdateViewport)
  60947. {
  60948. needToUpdateViewport = false;
  60949. juce_glViewport (getWidth(), getHeight());
  60950. }
  60951. renderOpenGL();
  60952. swapBuffers();
  60953. return true;
  60954. }
  60955. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60956. {
  60957. Component::internalRepaint (x, y, w, h);
  60958. if (context != 0)
  60959. context->repaint();
  60960. }
  60961. END_JUCE_NAMESPACE
  60962. #endif
  60963. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60964. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60965. BEGIN_JUCE_NAMESPACE
  60966. PreferencesPanel::PreferencesPanel()
  60967. : buttonSize (70)
  60968. {
  60969. }
  60970. PreferencesPanel::~PreferencesPanel()
  60971. {
  60972. }
  60973. void PreferencesPanel::addSettingsPage (const String& title,
  60974. const Drawable* icon,
  60975. const Drawable* overIcon,
  60976. const Drawable* downIcon)
  60977. {
  60978. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60979. buttons.add (button);
  60980. button->setImages (icon, overIcon, downIcon);
  60981. button->setRadioGroupId (1);
  60982. button->addListener (this);
  60983. button->setClickingTogglesState (true);
  60984. button->setWantsKeyboardFocus (false);
  60985. addAndMakeVisible (button);
  60986. resized();
  60987. if (currentPage == 0)
  60988. setCurrentPage (title);
  60989. }
  60990. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  60991. {
  60992. DrawableImage icon, iconOver, iconDown;
  60993. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60994. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60995. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60996. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60997. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60998. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60999. }
  61000. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61001. {
  61002. setSize (dialogWidth, dialogHeight);
  61003. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61004. }
  61005. void PreferencesPanel::resized()
  61006. {
  61007. for (int i = 0; i < buttons.size(); ++i)
  61008. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61009. if (currentPage != 0)
  61010. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61011. }
  61012. void PreferencesPanel::paint (Graphics& g)
  61013. {
  61014. g.setColour (Colours::grey);
  61015. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61016. }
  61017. void PreferencesPanel::setCurrentPage (const String& pageName)
  61018. {
  61019. if (currentPageName != pageName)
  61020. {
  61021. currentPageName = pageName;
  61022. currentPage = 0;
  61023. currentPage = createComponentForPage (pageName);
  61024. if (currentPage != 0)
  61025. {
  61026. addAndMakeVisible (currentPage);
  61027. currentPage->toBack();
  61028. resized();
  61029. }
  61030. for (int i = 0; i < buttons.size(); ++i)
  61031. {
  61032. if (buttons.getUnchecked(i)->getName() == pageName)
  61033. {
  61034. buttons.getUnchecked(i)->setToggleState (true, false);
  61035. break;
  61036. }
  61037. }
  61038. }
  61039. }
  61040. void PreferencesPanel::buttonClicked (Button*)
  61041. {
  61042. for (int i = 0; i < buttons.size(); ++i)
  61043. {
  61044. if (buttons.getUnchecked(i)->getToggleState())
  61045. {
  61046. setCurrentPage (buttons.getUnchecked(i)->getName());
  61047. break;
  61048. }
  61049. }
  61050. }
  61051. END_JUCE_NAMESPACE
  61052. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61053. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61054. #if JUCE_WINDOWS || JUCE_LINUX
  61055. BEGIN_JUCE_NAMESPACE
  61056. SystemTrayIconComponent::SystemTrayIconComponent()
  61057. {
  61058. addToDesktop (0);
  61059. }
  61060. SystemTrayIconComponent::~SystemTrayIconComponent()
  61061. {
  61062. }
  61063. END_JUCE_NAMESPACE
  61064. #endif
  61065. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61066. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61067. BEGIN_JUCE_NAMESPACE
  61068. class AlertWindowTextEditor : public TextEditor
  61069. {
  61070. public:
  61071. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61072. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61073. {
  61074. setSelectAllWhenFocused (true);
  61075. }
  61076. void returnPressed()
  61077. {
  61078. // pass these up the component hierarchy to be trigger the buttons
  61079. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61080. }
  61081. void escapePressed()
  61082. {
  61083. // pass these up the component hierarchy to be trigger the buttons
  61084. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61085. }
  61086. private:
  61087. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61088. static juce_wchar getDefaultPasswordChar() throw()
  61089. {
  61090. #if JUCE_LINUX
  61091. return 0x2022;
  61092. #else
  61093. return 0x25cf;
  61094. #endif
  61095. }
  61096. };
  61097. AlertWindow::AlertWindow (const String& title,
  61098. const String& message,
  61099. AlertIconType iconType,
  61100. Component* associatedComponent_)
  61101. : TopLevelWindow (title, true),
  61102. alertIconType (iconType),
  61103. associatedComponent (associatedComponent_)
  61104. {
  61105. if (message.isEmpty())
  61106. text = " "; // to force an update if the message is empty
  61107. setMessage (message);
  61108. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61109. {
  61110. Component* const c = Desktop::getInstance().getComponent (i);
  61111. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61112. {
  61113. setAlwaysOnTop (true);
  61114. break;
  61115. }
  61116. }
  61117. if (! JUCEApplication::isStandaloneApp())
  61118. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61119. lookAndFeelChanged();
  61120. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61121. }
  61122. AlertWindow::~AlertWindow()
  61123. {
  61124. removeAllChildren();
  61125. }
  61126. void AlertWindow::userTriedToCloseWindow()
  61127. {
  61128. exitModalState (0);
  61129. }
  61130. void AlertWindow::setMessage (const String& message)
  61131. {
  61132. const String newMessage (message.substring (0, 2048));
  61133. if (text != newMessage)
  61134. {
  61135. text = newMessage;
  61136. font = getLookAndFeel().getAlertWindowMessageFont();
  61137. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61138. textLayout.setText (getName() + "\n\n", titleFont);
  61139. textLayout.appendText (text, font);
  61140. updateLayout (true);
  61141. repaint();
  61142. }
  61143. }
  61144. void AlertWindow::buttonClicked (Button* button)
  61145. {
  61146. if (button->getParentComponent() != 0)
  61147. button->getParentComponent()->exitModalState (button->getCommandID());
  61148. }
  61149. void AlertWindow::addButton (const String& name,
  61150. const int returnValue,
  61151. const KeyPress& shortcutKey1,
  61152. const KeyPress& shortcutKey2)
  61153. {
  61154. TextButton* const b = new TextButton (name, String::empty);
  61155. buttons.add (b);
  61156. b->setWantsKeyboardFocus (true);
  61157. b->setMouseClickGrabsKeyboardFocus (false);
  61158. b->setCommandToTrigger (0, returnValue, false);
  61159. b->addShortcut (shortcutKey1);
  61160. b->addShortcut (shortcutKey2);
  61161. b->addListener (this);
  61162. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61163. addAndMakeVisible (b, 0);
  61164. updateLayout (false);
  61165. }
  61166. int AlertWindow::getNumButtons() const
  61167. {
  61168. return buttons.size();
  61169. }
  61170. void AlertWindow::triggerButtonClick (const String& buttonName)
  61171. {
  61172. for (int i = buttons.size(); --i >= 0;)
  61173. {
  61174. TextButton* const b = buttons.getUnchecked(i);
  61175. if (buttonName == b->getName())
  61176. {
  61177. b->triggerClick();
  61178. break;
  61179. }
  61180. }
  61181. }
  61182. void AlertWindow::addTextEditor (const String& name,
  61183. const String& initialContents,
  61184. const String& onScreenLabel,
  61185. const bool isPasswordBox)
  61186. {
  61187. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61188. textBoxes.add (tc);
  61189. allComps.add (tc);
  61190. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61191. tc->setFont (font);
  61192. tc->setText (initialContents);
  61193. tc->setCaretPosition (initialContents.length());
  61194. addAndMakeVisible (tc);
  61195. textboxNames.add (onScreenLabel);
  61196. updateLayout (false);
  61197. }
  61198. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61199. {
  61200. for (int i = textBoxes.size(); --i >= 0;)
  61201. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61202. return textBoxes.getUnchecked(i);
  61203. return 0;
  61204. }
  61205. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61206. {
  61207. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61208. return t != 0 ? t->getText() : String::empty;
  61209. }
  61210. void AlertWindow::addComboBox (const String& name,
  61211. const StringArray& items,
  61212. const String& onScreenLabel)
  61213. {
  61214. ComboBox* const cb = new ComboBox (name);
  61215. comboBoxes.add (cb);
  61216. allComps.add (cb);
  61217. for (int i = 0; i < items.size(); ++i)
  61218. cb->addItem (items[i], i + 1);
  61219. addAndMakeVisible (cb);
  61220. cb->setSelectedItemIndex (0);
  61221. comboBoxNames.add (onScreenLabel);
  61222. updateLayout (false);
  61223. }
  61224. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61225. {
  61226. for (int i = comboBoxes.size(); --i >= 0;)
  61227. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61228. return comboBoxes.getUnchecked(i);
  61229. return 0;
  61230. }
  61231. class AlertTextComp : public TextEditor
  61232. {
  61233. public:
  61234. AlertTextComp (const String& message,
  61235. const Font& font)
  61236. {
  61237. setReadOnly (true);
  61238. setMultiLine (true, true);
  61239. setCaretVisible (false);
  61240. setScrollbarsShown (true);
  61241. lookAndFeelChanged();
  61242. setWantsKeyboardFocus (false);
  61243. setFont (font);
  61244. setText (message, false);
  61245. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61246. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61247. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61248. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61249. }
  61250. ~AlertTextComp()
  61251. {
  61252. }
  61253. int getPreferredWidth() const throw() { return bestWidth; }
  61254. void updateLayout (const int width)
  61255. {
  61256. TextLayout text;
  61257. text.appendText (getText(), getFont());
  61258. text.layout (width - 8, Justification::topLeft, true);
  61259. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61260. }
  61261. private:
  61262. int bestWidth;
  61263. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61264. };
  61265. void AlertWindow::addTextBlock (const String& textBlock)
  61266. {
  61267. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61268. textBlocks.add (c);
  61269. allComps.add (c);
  61270. addAndMakeVisible (c);
  61271. updateLayout (false);
  61272. }
  61273. void AlertWindow::addProgressBarComponent (double& progressValue)
  61274. {
  61275. ProgressBar* const pb = new ProgressBar (progressValue);
  61276. progressBars.add (pb);
  61277. allComps.add (pb);
  61278. addAndMakeVisible (pb);
  61279. updateLayout (false);
  61280. }
  61281. void AlertWindow::addCustomComponent (Component* const component)
  61282. {
  61283. customComps.add (component);
  61284. allComps.add (component);
  61285. addAndMakeVisible (component);
  61286. updateLayout (false);
  61287. }
  61288. int AlertWindow::getNumCustomComponents() const
  61289. {
  61290. return customComps.size();
  61291. }
  61292. Component* AlertWindow::getCustomComponent (const int index) const
  61293. {
  61294. return customComps [index];
  61295. }
  61296. Component* AlertWindow::removeCustomComponent (const int index)
  61297. {
  61298. Component* const c = getCustomComponent (index);
  61299. if (c != 0)
  61300. {
  61301. customComps.removeValue (c);
  61302. allComps.removeValue (c);
  61303. removeChildComponent (c);
  61304. updateLayout (false);
  61305. }
  61306. return c;
  61307. }
  61308. void AlertWindow::paint (Graphics& g)
  61309. {
  61310. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61311. g.setColour (findColour (textColourId));
  61312. g.setFont (getLookAndFeel().getAlertWindowFont());
  61313. int i;
  61314. for (i = textBoxes.size(); --i >= 0;)
  61315. {
  61316. const TextEditor* const te = textBoxes.getUnchecked(i);
  61317. g.drawFittedText (textboxNames[i],
  61318. te->getX(), te->getY() - 14,
  61319. te->getWidth(), 14,
  61320. Justification::centredLeft, 1);
  61321. }
  61322. for (i = comboBoxNames.size(); --i >= 0;)
  61323. {
  61324. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61325. g.drawFittedText (comboBoxNames[i],
  61326. cb->getX(), cb->getY() - 14,
  61327. cb->getWidth(), 14,
  61328. Justification::centredLeft, 1);
  61329. }
  61330. for (i = customComps.size(); --i >= 0;)
  61331. {
  61332. const Component* const c = customComps.getUnchecked(i);
  61333. g.drawFittedText (c->getName(),
  61334. c->getX(), c->getY() - 14,
  61335. c->getWidth(), 14,
  61336. Justification::centredLeft, 1);
  61337. }
  61338. }
  61339. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61340. {
  61341. const int titleH = 24;
  61342. const int iconWidth = 80;
  61343. const int wid = jmax (font.getStringWidth (text),
  61344. font.getStringWidth (getName()));
  61345. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61346. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61347. const int edgeGap = 10;
  61348. const int labelHeight = 18;
  61349. int iconSpace;
  61350. if (alertIconType == NoIcon)
  61351. {
  61352. textLayout.layout (w, Justification::horizontallyCentred, true);
  61353. iconSpace = 0;
  61354. }
  61355. else
  61356. {
  61357. textLayout.layout (w, Justification::left, true);
  61358. iconSpace = iconWidth;
  61359. }
  61360. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61361. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61362. const int textLayoutH = textLayout.getHeight();
  61363. const int textBottom = 16 + titleH + textLayoutH;
  61364. int h = textBottom;
  61365. int buttonW = 40;
  61366. int i;
  61367. for (i = 0; i < buttons.size(); ++i)
  61368. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61369. w = jmax (buttonW, w);
  61370. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61371. if (buttons.size() > 0)
  61372. h += 20 + buttons.getUnchecked(0)->getHeight();
  61373. for (i = customComps.size(); --i >= 0;)
  61374. {
  61375. Component* c = customComps.getUnchecked(i);
  61376. w = jmax (w, (c->getWidth() * 100) / 80);
  61377. h += 10 + c->getHeight();
  61378. if (c->getName().isNotEmpty())
  61379. h += labelHeight;
  61380. }
  61381. for (i = textBlocks.size(); --i >= 0;)
  61382. {
  61383. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61384. w = jmax (w, ac->getPreferredWidth());
  61385. }
  61386. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61387. for (i = textBlocks.size(); --i >= 0;)
  61388. {
  61389. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61390. ac->updateLayout ((int) (w * 0.8f));
  61391. h += ac->getHeight() + 10;
  61392. }
  61393. h = jmin (getParentHeight() - 50, h);
  61394. if (onlyIncreaseSize)
  61395. {
  61396. w = jmax (w, getWidth());
  61397. h = jmax (h, getHeight());
  61398. }
  61399. if (! isVisible())
  61400. {
  61401. centreAroundComponent (associatedComponent, w, h);
  61402. }
  61403. else
  61404. {
  61405. const int cx = getX() + getWidth() / 2;
  61406. const int cy = getY() + getHeight() / 2;
  61407. setBounds (cx - w / 2,
  61408. cy - h / 2,
  61409. w, h);
  61410. }
  61411. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61412. const int spacer = 16;
  61413. int totalWidth = -spacer;
  61414. for (i = buttons.size(); --i >= 0;)
  61415. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61416. int x = (w - totalWidth) / 2;
  61417. int y = (int) (getHeight() * 0.95f);
  61418. for (i = 0; i < buttons.size(); ++i)
  61419. {
  61420. TextButton* const c = buttons.getUnchecked(i);
  61421. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61422. c->setTopLeftPosition (x, ny);
  61423. if (ny < y)
  61424. y = ny;
  61425. x += c->getWidth() + spacer;
  61426. c->toFront (false);
  61427. }
  61428. y = textBottom;
  61429. for (i = 0; i < allComps.size(); ++i)
  61430. {
  61431. Component* const c = allComps.getUnchecked(i);
  61432. h = 22;
  61433. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61434. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61435. y += labelHeight;
  61436. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61437. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61438. y += labelHeight;
  61439. if (customComps.contains (c))
  61440. {
  61441. if (c->getName().isNotEmpty())
  61442. y += labelHeight;
  61443. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61444. h = c->getHeight();
  61445. }
  61446. else if (textBlocks.contains (c))
  61447. {
  61448. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61449. h = c->getHeight();
  61450. }
  61451. else
  61452. {
  61453. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61454. }
  61455. y += h + 10;
  61456. }
  61457. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61458. }
  61459. bool AlertWindow::containsAnyExtraComponents() const
  61460. {
  61461. return allComps.size() > 0;
  61462. }
  61463. void AlertWindow::mouseDown (const MouseEvent& e)
  61464. {
  61465. dragger.startDraggingComponent (this, e);
  61466. }
  61467. void AlertWindow::mouseDrag (const MouseEvent& e)
  61468. {
  61469. dragger.dragComponent (this, e, &constrainer);
  61470. }
  61471. bool AlertWindow::keyPressed (const KeyPress& key)
  61472. {
  61473. for (int i = buttons.size(); --i >= 0;)
  61474. {
  61475. TextButton* const b = buttons.getUnchecked(i);
  61476. if (b->isRegisteredForShortcut (key))
  61477. {
  61478. b->triggerClick();
  61479. return true;
  61480. }
  61481. }
  61482. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61483. {
  61484. exitModalState (0);
  61485. return true;
  61486. }
  61487. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61488. {
  61489. buttons.getUnchecked(0)->triggerClick();
  61490. return true;
  61491. }
  61492. return false;
  61493. }
  61494. void AlertWindow::lookAndFeelChanged()
  61495. {
  61496. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61497. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61498. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61499. }
  61500. int AlertWindow::getDesktopWindowStyleFlags() const
  61501. {
  61502. return getLookAndFeel().getAlertBoxWindowFlags();
  61503. }
  61504. class AlertWindowInfo
  61505. {
  61506. public:
  61507. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61508. AlertWindow::AlertIconType iconType_, int numButtons_)
  61509. : title (title_), message (message_), iconType (iconType_),
  61510. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61511. {
  61512. }
  61513. String title, message, button1, button2, button3;
  61514. AlertWindow::AlertIconType iconType;
  61515. int numButtons, returnValue;
  61516. WeakReference<Component> associatedComponent;
  61517. int showModal() const
  61518. {
  61519. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61520. return returnValue;
  61521. }
  61522. private:
  61523. void show()
  61524. {
  61525. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61526. : LookAndFeel::getDefaultLookAndFeel();
  61527. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61528. iconType, numButtons, associatedComponent));
  61529. jassert (alertBox != 0); // you have to return one of these!
  61530. returnValue = alertBox->runModalLoop();
  61531. }
  61532. static void* showCallback (void* userData)
  61533. {
  61534. static_cast <AlertWindowInfo*> (userData)->show();
  61535. return 0;
  61536. }
  61537. };
  61538. void AlertWindow::showMessageBox (AlertIconType iconType,
  61539. const String& title,
  61540. const String& message,
  61541. const String& buttonText,
  61542. Component* associatedComponent)
  61543. {
  61544. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61545. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61546. info.showModal();
  61547. }
  61548. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61549. const String& title,
  61550. const String& message,
  61551. const String& button1Text,
  61552. const String& button2Text,
  61553. Component* associatedComponent)
  61554. {
  61555. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61556. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61557. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61558. return info.showModal() != 0;
  61559. }
  61560. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61561. const String& title,
  61562. const String& message,
  61563. const String& button1Text,
  61564. const String& button2Text,
  61565. const String& button3Text,
  61566. Component* associatedComponent)
  61567. {
  61568. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61569. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61570. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61571. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61572. return info.showModal();
  61573. }
  61574. END_JUCE_NAMESPACE
  61575. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61576. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61577. BEGIN_JUCE_NAMESPACE
  61578. CallOutBox::CallOutBox (Component& contentComponent,
  61579. Component& componentToPointTo,
  61580. Component* const parentComponent)
  61581. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61582. {
  61583. addAndMakeVisible (&content);
  61584. if (parentComponent != 0)
  61585. {
  61586. parentComponent->addChildComponent (this);
  61587. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61588. parentComponent->getLocalBounds());
  61589. setVisible (true);
  61590. }
  61591. else
  61592. {
  61593. if (! JUCEApplication::isStandaloneApp())
  61594. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61595. updatePosition (componentToPointTo.getScreenBounds(),
  61596. componentToPointTo.getParentMonitorArea());
  61597. addToDesktop (ComponentPeer::windowIsTemporary);
  61598. }
  61599. }
  61600. CallOutBox::~CallOutBox()
  61601. {
  61602. }
  61603. void CallOutBox::setArrowSize (const float newSize)
  61604. {
  61605. arrowSize = newSize;
  61606. borderSpace = jmax (20, (int) arrowSize);
  61607. refreshPath();
  61608. }
  61609. void CallOutBox::paint (Graphics& g)
  61610. {
  61611. if (background.isNull())
  61612. {
  61613. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61614. Graphics g2 (background);
  61615. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61616. }
  61617. g.setColour (Colours::black);
  61618. g.drawImageAt (background, 0, 0);
  61619. }
  61620. void CallOutBox::resized()
  61621. {
  61622. content.setTopLeftPosition (borderSpace, borderSpace);
  61623. refreshPath();
  61624. }
  61625. void CallOutBox::moved()
  61626. {
  61627. refreshPath();
  61628. }
  61629. void CallOutBox::childBoundsChanged (Component*)
  61630. {
  61631. updatePosition (targetArea, availableArea);
  61632. }
  61633. bool CallOutBox::hitTest (int x, int y)
  61634. {
  61635. return outline.contains ((float) x, (float) y);
  61636. }
  61637. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61638. void CallOutBox::inputAttemptWhenModal()
  61639. {
  61640. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61641. if (targetArea.contains (mousePos))
  61642. {
  61643. // if you click on the area that originally popped-up the callout, you expect it
  61644. // to get rid of the box, but deleting the box here allows the click to pass through and
  61645. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61646. postCommandMessage (callOutBoxDismissCommandId);
  61647. }
  61648. else
  61649. {
  61650. exitModalState (0);
  61651. setVisible (false);
  61652. }
  61653. }
  61654. void CallOutBox::handleCommandMessage (int commandId)
  61655. {
  61656. Component::handleCommandMessage (commandId);
  61657. if (commandId == callOutBoxDismissCommandId)
  61658. {
  61659. exitModalState (0);
  61660. setVisible (false);
  61661. }
  61662. }
  61663. bool CallOutBox::keyPressed (const KeyPress& key)
  61664. {
  61665. if (key.isKeyCode (KeyPress::escapeKey))
  61666. {
  61667. inputAttemptWhenModal();
  61668. return true;
  61669. }
  61670. return false;
  61671. }
  61672. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61673. {
  61674. targetArea = newAreaToPointTo;
  61675. availableArea = newAreaToFitIn;
  61676. Rectangle<int> bounds (0, 0,
  61677. content.getWidth() + borderSpace * 2,
  61678. content.getHeight() + borderSpace * 2);
  61679. const int hw = bounds.getWidth() / 2;
  61680. const int hh = bounds.getHeight() / 2;
  61681. const float hwReduced = (float) (hw - borderSpace * 3);
  61682. const float hhReduced = (float) (hh - borderSpace * 3);
  61683. const float arrowIndent = borderSpace - arrowSize;
  61684. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61685. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61686. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61687. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61688. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61689. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61690. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61691. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61692. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61693. float nearest = 1.0e9f;
  61694. for (int i = 0; i < 4; ++i)
  61695. {
  61696. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61697. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61698. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61699. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61700. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61701. distanceFromCentre *= 2.0f;
  61702. if (distanceFromCentre < nearest)
  61703. {
  61704. nearest = distanceFromCentre;
  61705. targetPoint = targets[i];
  61706. bounds.setPosition ((int) (centre.getX() - hw),
  61707. (int) (centre.getY() - hh));
  61708. }
  61709. }
  61710. setBounds (bounds);
  61711. }
  61712. void CallOutBox::refreshPath()
  61713. {
  61714. repaint();
  61715. background = Image::null;
  61716. outline.clear();
  61717. const float gap = 4.5f;
  61718. const float cornerSize = 9.0f;
  61719. const float cornerSize2 = 2.0f * cornerSize;
  61720. const float arrowBaseWidth = arrowSize * 0.7f;
  61721. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61722. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61723. outline.startNewSubPath (left + cornerSize, top);
  61724. if (targetY <= top)
  61725. {
  61726. outline.lineTo (targetX - arrowBaseWidth, top);
  61727. outline.lineTo (targetX, targetY);
  61728. outline.lineTo (targetX + arrowBaseWidth, top);
  61729. }
  61730. outline.lineTo (right - cornerSize, top);
  61731. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61732. if (targetX >= right)
  61733. {
  61734. outline.lineTo (right, targetY - arrowBaseWidth);
  61735. outline.lineTo (targetX, targetY);
  61736. outline.lineTo (right, targetY + arrowBaseWidth);
  61737. }
  61738. outline.lineTo (right, bottom - cornerSize);
  61739. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61740. if (targetY >= bottom)
  61741. {
  61742. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61743. outline.lineTo (targetX, targetY);
  61744. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61745. }
  61746. outline.lineTo (left + cornerSize, bottom);
  61747. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61748. if (targetX <= left)
  61749. {
  61750. outline.lineTo (left, targetY + arrowBaseWidth);
  61751. outline.lineTo (targetX, targetY);
  61752. outline.lineTo (left, targetY - arrowBaseWidth);
  61753. }
  61754. outline.lineTo (left, top + cornerSize);
  61755. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61756. outline.closeSubPath();
  61757. }
  61758. END_JUCE_NAMESPACE
  61759. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61760. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61761. BEGIN_JUCE_NAMESPACE
  61762. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61763. static Array <ComponentPeer*> heavyweightPeers;
  61764. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61765. : component (component_),
  61766. styleFlags (styleFlags_),
  61767. lastPaintTime (0),
  61768. constrainer (0),
  61769. lastDragAndDropCompUnderMouse (0),
  61770. fakeMouseMessageSent (false),
  61771. isWindowMinimised (false)
  61772. {
  61773. heavyweightPeers.add (this);
  61774. }
  61775. ComponentPeer::~ComponentPeer()
  61776. {
  61777. heavyweightPeers.removeValue (this);
  61778. Desktop::getInstance().triggerFocusCallback();
  61779. }
  61780. int ComponentPeer::getNumPeers() throw()
  61781. {
  61782. return heavyweightPeers.size();
  61783. }
  61784. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61785. {
  61786. return heavyweightPeers [index];
  61787. }
  61788. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61789. {
  61790. for (int i = heavyweightPeers.size(); --i >= 0;)
  61791. {
  61792. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61793. if (peer->getComponent() == component)
  61794. return peer;
  61795. }
  61796. return 0;
  61797. }
  61798. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61799. {
  61800. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61801. }
  61802. void ComponentPeer::updateCurrentModifiers() throw()
  61803. {
  61804. ModifierKeys::updateCurrentModifiers();
  61805. }
  61806. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61807. {
  61808. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61809. jassert (mouse != 0); // not enough sources!
  61810. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61811. }
  61812. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61813. {
  61814. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61815. jassert (mouse != 0); // not enough sources!
  61816. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61817. }
  61818. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61819. {
  61820. Graphics g (&contextToPaintTo);
  61821. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61822. g.saveState();
  61823. #endif
  61824. JUCE_TRY
  61825. {
  61826. component->paintEntireComponent (g, true);
  61827. }
  61828. JUCE_CATCH_EXCEPTION
  61829. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61830. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61831. // clearly when things are being repainted.
  61832. g.restoreState();
  61833. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61834. (uint8) Random::getSystemRandom().nextInt (255),
  61835. (uint8) Random::getSystemRandom().nextInt (255),
  61836. (uint8) 0x50));
  61837. #endif
  61838. /** If this fails, it's probably be because your CPU floating-point precision mode has
  61839. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  61840. mess up a lot of the calculations that the library needs to do.
  61841. */
  61842. jassert (roundToInt (10.1f) == 10);
  61843. }
  61844. bool ComponentPeer::handleKeyPress (const int keyCode,
  61845. const juce_wchar textCharacter)
  61846. {
  61847. updateCurrentModifiers();
  61848. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61849. ? Component::getCurrentlyFocusedComponent()
  61850. : component;
  61851. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61852. {
  61853. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61854. if (currentModalComp != 0)
  61855. target = currentModalComp;
  61856. }
  61857. const KeyPress keyInfo (keyCode,
  61858. ModifierKeys::getCurrentModifiers().getRawFlags()
  61859. & ModifierKeys::allKeyboardModifiers,
  61860. textCharacter);
  61861. bool keyWasUsed = false;
  61862. while (target != 0)
  61863. {
  61864. const WeakReference<Component> deletionChecker (target);
  61865. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61866. if (keyListeners != 0)
  61867. {
  61868. for (int i = keyListeners->size(); --i >= 0;)
  61869. {
  61870. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  61871. if (keyWasUsed || deletionChecker == 0)
  61872. return keyWasUsed;
  61873. i = jmin (i, keyListeners->size());
  61874. }
  61875. }
  61876. keyWasUsed = target->keyPressed (keyInfo);
  61877. if (keyWasUsed || deletionChecker == 0)
  61878. break;
  61879. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61880. {
  61881. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61882. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61883. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61884. break;
  61885. }
  61886. target = target->getParentComponent();
  61887. }
  61888. return keyWasUsed;
  61889. }
  61890. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61891. {
  61892. updateCurrentModifiers();
  61893. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61894. ? Component::getCurrentlyFocusedComponent()
  61895. : component;
  61896. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61897. {
  61898. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61899. if (currentModalComp != 0)
  61900. target = currentModalComp;
  61901. }
  61902. bool keyWasUsed = false;
  61903. while (target != 0)
  61904. {
  61905. const WeakReference<Component> deletionChecker (target);
  61906. keyWasUsed = target->keyStateChanged (isKeyDown);
  61907. if (keyWasUsed || deletionChecker == 0)
  61908. break;
  61909. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61910. if (keyListeners != 0)
  61911. {
  61912. for (int i = keyListeners->size(); --i >= 0;)
  61913. {
  61914. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61915. if (keyWasUsed || deletionChecker == 0)
  61916. return keyWasUsed;
  61917. i = jmin (i, keyListeners->size());
  61918. }
  61919. }
  61920. target = target->getParentComponent();
  61921. }
  61922. return keyWasUsed;
  61923. }
  61924. void ComponentPeer::handleModifierKeysChange()
  61925. {
  61926. updateCurrentModifiers();
  61927. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61928. if (target == 0)
  61929. target = Component::getCurrentlyFocusedComponent();
  61930. if (target == 0)
  61931. target = component;
  61932. if (target != 0)
  61933. target->internalModifierKeysChanged();
  61934. }
  61935. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61936. {
  61937. Component* const c = Component::getCurrentlyFocusedComponent();
  61938. if (component->isParentOf (c))
  61939. {
  61940. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61941. if (ti != 0 && ti->isTextInputActive())
  61942. return ti;
  61943. }
  61944. return 0;
  61945. }
  61946. void ComponentPeer::handleBroughtToFront()
  61947. {
  61948. updateCurrentModifiers();
  61949. if (component != 0)
  61950. component->internalBroughtToFront();
  61951. }
  61952. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61953. {
  61954. constrainer = newConstrainer;
  61955. }
  61956. void ComponentPeer::handleMovedOrResized()
  61957. {
  61958. updateCurrentModifiers();
  61959. const bool nowMinimised = isMinimised();
  61960. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61961. {
  61962. const WeakReference<Component> deletionChecker (component);
  61963. const Rectangle<int> newBounds (getBounds());
  61964. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61965. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61966. if (wasMoved || wasResized)
  61967. {
  61968. component->bounds = newBounds;
  61969. if (wasResized)
  61970. component->repaint();
  61971. component->sendMovedResizedMessages (wasMoved, wasResized);
  61972. if (deletionChecker == 0)
  61973. return;
  61974. }
  61975. }
  61976. if (isWindowMinimised != nowMinimised)
  61977. {
  61978. isWindowMinimised = nowMinimised;
  61979. component->minimisationStateChanged (nowMinimised);
  61980. component->sendVisibilityChangeMessage();
  61981. }
  61982. if (! isFullScreen())
  61983. lastNonFullscreenBounds = component->getBounds();
  61984. }
  61985. void ComponentPeer::handleFocusGain()
  61986. {
  61987. updateCurrentModifiers();
  61988. if (component->isParentOf (lastFocusedComponent))
  61989. {
  61990. Component::currentlyFocusedComponent = lastFocusedComponent;
  61991. Desktop::getInstance().triggerFocusCallback();
  61992. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61993. }
  61994. else
  61995. {
  61996. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61997. component->grabKeyboardFocus();
  61998. else
  61999. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62000. }
  62001. }
  62002. void ComponentPeer::handleFocusLoss()
  62003. {
  62004. updateCurrentModifiers();
  62005. if (component->hasKeyboardFocus (true))
  62006. {
  62007. lastFocusedComponent = Component::currentlyFocusedComponent;
  62008. if (lastFocusedComponent != 0)
  62009. {
  62010. Component::currentlyFocusedComponent = 0;
  62011. Desktop::getInstance().triggerFocusCallback();
  62012. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62013. }
  62014. }
  62015. }
  62016. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62017. {
  62018. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62019. ? static_cast <Component*> (lastFocusedComponent)
  62020. : component;
  62021. }
  62022. void ComponentPeer::handleScreenSizeChange()
  62023. {
  62024. updateCurrentModifiers();
  62025. component->parentSizeChanged();
  62026. handleMovedOrResized();
  62027. }
  62028. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62029. {
  62030. lastNonFullscreenBounds = newBounds;
  62031. }
  62032. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62033. {
  62034. return lastNonFullscreenBounds;
  62035. }
  62036. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62037. {
  62038. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62039. }
  62040. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62041. {
  62042. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62043. }
  62044. namespace ComponentPeerHelpers
  62045. {
  62046. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62047. const StringArray& files,
  62048. FileDragAndDropTarget* const lastOne)
  62049. {
  62050. while (c != 0)
  62051. {
  62052. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62053. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62054. return t;
  62055. c = c->getParentComponent();
  62056. }
  62057. return 0;
  62058. }
  62059. }
  62060. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62061. {
  62062. updateCurrentModifiers();
  62063. FileDragAndDropTarget* lastTarget
  62064. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62065. FileDragAndDropTarget* newTarget = 0;
  62066. Component* const compUnderMouse = component->getComponentAt (position);
  62067. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62068. {
  62069. lastDragAndDropCompUnderMouse = compUnderMouse;
  62070. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62071. if (newTarget != lastTarget)
  62072. {
  62073. if (lastTarget != 0)
  62074. lastTarget->fileDragExit (files);
  62075. dragAndDropTargetComponent = 0;
  62076. if (newTarget != 0)
  62077. {
  62078. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62079. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62080. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62081. }
  62082. }
  62083. }
  62084. else
  62085. {
  62086. newTarget = lastTarget;
  62087. }
  62088. if (newTarget != 0)
  62089. {
  62090. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62091. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62092. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62093. }
  62094. }
  62095. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62096. {
  62097. handleFileDragMove (files, Point<int> (-1, -1));
  62098. jassert (dragAndDropTargetComponent == 0);
  62099. lastDragAndDropCompUnderMouse = 0;
  62100. }
  62101. // We'll use an async message to deliver the drop, because if the target decides
  62102. // to run a modal loop, it can gum-up the operating system..
  62103. class AsyncFileDropMessage : public CallbackMessage
  62104. {
  62105. public:
  62106. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62107. const Point<int>& position_, const StringArray& files_)
  62108. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62109. {
  62110. }
  62111. void messageCallback()
  62112. {
  62113. if (target != 0)
  62114. dropTarget->filesDropped (files, position.getX(), position.getY());
  62115. }
  62116. private:
  62117. WeakReference<Component> target;
  62118. FileDragAndDropTarget* const dropTarget;
  62119. const Point<int> position;
  62120. const StringArray files;
  62121. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62122. };
  62123. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62124. {
  62125. handleFileDragMove (files, position);
  62126. if (dragAndDropTargetComponent != 0)
  62127. {
  62128. FileDragAndDropTarget* const target
  62129. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62130. dragAndDropTargetComponent = 0;
  62131. lastDragAndDropCompUnderMouse = 0;
  62132. if (target != 0)
  62133. {
  62134. Component* const targetComp = dynamic_cast <Component*> (target);
  62135. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62136. {
  62137. targetComp->internalModalInputAttempt();
  62138. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62139. return;
  62140. }
  62141. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62142. }
  62143. }
  62144. }
  62145. void ComponentPeer::handleUserClosingWindow()
  62146. {
  62147. updateCurrentModifiers();
  62148. component->userTriedToCloseWindow();
  62149. }
  62150. void ComponentPeer::clearMaskedRegion()
  62151. {
  62152. maskedRegion.clear();
  62153. }
  62154. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62155. {
  62156. maskedRegion.add (x, y, w, h);
  62157. }
  62158. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62159. {
  62160. StringArray s;
  62161. s.add ("Software Renderer");
  62162. return s;
  62163. }
  62164. int ComponentPeer::getCurrentRenderingEngine() throw()
  62165. {
  62166. return 0;
  62167. }
  62168. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62169. {
  62170. }
  62171. END_JUCE_NAMESPACE
  62172. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62173. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62174. BEGIN_JUCE_NAMESPACE
  62175. DialogWindow::DialogWindow (const String& name,
  62176. const Colour& backgroundColour_,
  62177. const bool escapeKeyTriggersCloseButton_,
  62178. const bool addToDesktop_)
  62179. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62180. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62181. {
  62182. }
  62183. DialogWindow::~DialogWindow()
  62184. {
  62185. }
  62186. void DialogWindow::resized()
  62187. {
  62188. DocumentWindow::resized();
  62189. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62190. if (escapeKeyTriggersCloseButton
  62191. && getCloseButton() != 0
  62192. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62193. {
  62194. getCloseButton()->addShortcut (esc);
  62195. }
  62196. }
  62197. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62198. // VC compiler complains about the undefined copy constructor)
  62199. class TempDialogWindow : public DialogWindow
  62200. {
  62201. public:
  62202. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62203. : DialogWindow (title, colour, escapeCloses, true)
  62204. {
  62205. if (! JUCEApplication::isStandaloneApp())
  62206. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62207. }
  62208. void closeButtonPressed()
  62209. {
  62210. setVisible (false);
  62211. }
  62212. private:
  62213. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62214. };
  62215. int DialogWindow::showModalDialog (const String& dialogTitle,
  62216. Component* contentComponent,
  62217. Component* componentToCentreAround,
  62218. const Colour& colour,
  62219. const bool escapeKeyTriggersCloseButton,
  62220. const bool shouldBeResizable,
  62221. const bool useBottomRightCornerResizer)
  62222. {
  62223. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62224. dw.setContentComponent (contentComponent, true, true);
  62225. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62226. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62227. const int result = dw.runModalLoop();
  62228. dw.setContentComponent (0, false);
  62229. return result;
  62230. }
  62231. END_JUCE_NAMESPACE
  62232. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62233. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62234. BEGIN_JUCE_NAMESPACE
  62235. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62236. {
  62237. public:
  62238. ButtonListenerProxy (DocumentWindow& owner_)
  62239. : owner (owner_)
  62240. {
  62241. }
  62242. void buttonClicked (Button* button)
  62243. {
  62244. if (button == owner.getMinimiseButton())
  62245. owner.minimiseButtonPressed();
  62246. else if (button == owner.getMaximiseButton())
  62247. owner.maximiseButtonPressed();
  62248. else if (button == owner.getCloseButton())
  62249. owner.closeButtonPressed();
  62250. }
  62251. private:
  62252. DocumentWindow& owner;
  62253. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62254. };
  62255. DocumentWindow::DocumentWindow (const String& title,
  62256. const Colour& backgroundColour,
  62257. const int requiredButtons_,
  62258. const bool addToDesktop_)
  62259. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62260. titleBarHeight (26),
  62261. menuBarHeight (24),
  62262. requiredButtons (requiredButtons_),
  62263. #if JUCE_MAC
  62264. positionTitleBarButtonsOnLeft (true),
  62265. #else
  62266. positionTitleBarButtonsOnLeft (false),
  62267. #endif
  62268. drawTitleTextCentred (true),
  62269. menuBarModel (0)
  62270. {
  62271. setResizeLimits (128, 128, 32768, 32768);
  62272. lookAndFeelChanged();
  62273. }
  62274. DocumentWindow::~DocumentWindow()
  62275. {
  62276. // Don't delete or remove the resizer components yourself! They're managed by the
  62277. // DocumentWindow, and you should leave them alone! You may have deleted them
  62278. // accidentally by careless use of deleteAllChildren()..?
  62279. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62280. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62281. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62282. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62283. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62284. titleBarButtons[i] = 0;
  62285. menuBar = 0;
  62286. }
  62287. void DocumentWindow::repaintTitleBar()
  62288. {
  62289. repaint (getTitleBarArea());
  62290. }
  62291. void DocumentWindow::setName (const String& newName)
  62292. {
  62293. if (newName != getName())
  62294. {
  62295. Component::setName (newName);
  62296. repaintTitleBar();
  62297. }
  62298. }
  62299. void DocumentWindow::setIcon (const Image& imageToUse)
  62300. {
  62301. titleBarIcon = imageToUse;
  62302. repaintTitleBar();
  62303. }
  62304. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62305. {
  62306. titleBarHeight = newHeight;
  62307. resized();
  62308. repaintTitleBar();
  62309. }
  62310. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62311. const bool positionTitleBarButtonsOnLeft_)
  62312. {
  62313. requiredButtons = requiredButtons_;
  62314. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62315. lookAndFeelChanged();
  62316. }
  62317. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62318. {
  62319. drawTitleTextCentred = textShouldBeCentred;
  62320. repaintTitleBar();
  62321. }
  62322. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62323. {
  62324. if (menuBarModel != newMenuBarModel)
  62325. {
  62326. menuBar = 0;
  62327. menuBarModel = newMenuBarModel;
  62328. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62329. : getLookAndFeel().getDefaultMenuBarHeight();
  62330. if (menuBarModel != 0)
  62331. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62332. resized();
  62333. }
  62334. }
  62335. Component* DocumentWindow::getMenuBarComponent() const throw()
  62336. {
  62337. return menuBar;
  62338. }
  62339. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62340. {
  62341. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62342. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62343. if (menuBar != 0)
  62344. menuBar->setEnabled (isActiveWindow());
  62345. resized();
  62346. }
  62347. void DocumentWindow::closeButtonPressed()
  62348. {
  62349. /* If you've got a close button, you have to override this method to get
  62350. rid of your window!
  62351. If the window is just a pop-up, you should override this method and make
  62352. it delete the window in whatever way is appropriate for your app. E.g. you
  62353. might just want to call "delete this".
  62354. If your app is centred around this window such that the whole app should quit when
  62355. the window is closed, then you will probably want to use this method as an opportunity
  62356. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62357. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62358. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62359. or closing it via the taskbar icon on Windows).
  62360. */
  62361. jassertfalse;
  62362. }
  62363. void DocumentWindow::minimiseButtonPressed()
  62364. {
  62365. setMinimised (true);
  62366. }
  62367. void DocumentWindow::maximiseButtonPressed()
  62368. {
  62369. setFullScreen (! isFullScreen());
  62370. }
  62371. void DocumentWindow::paint (Graphics& g)
  62372. {
  62373. ResizableWindow::paint (g);
  62374. if (resizableBorder == 0)
  62375. {
  62376. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62377. const BorderSize<int> border (getBorderThickness());
  62378. g.fillRect (0, 0, getWidth(), border.getTop());
  62379. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62380. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62381. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62382. }
  62383. const Rectangle<int> titleBarArea (getTitleBarArea());
  62384. g.reduceClipRegion (titleBarArea);
  62385. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62386. int titleSpaceX1 = 6;
  62387. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62388. for (int i = 0; i < 3; ++i)
  62389. {
  62390. if (titleBarButtons[i] != 0)
  62391. {
  62392. if (positionTitleBarButtonsOnLeft)
  62393. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62394. else
  62395. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62396. }
  62397. }
  62398. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62399. titleBarArea.getWidth(),
  62400. titleBarArea.getHeight(),
  62401. titleSpaceX1,
  62402. jmax (1, titleSpaceX2 - titleSpaceX1),
  62403. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62404. ! drawTitleTextCentred);
  62405. }
  62406. void DocumentWindow::resized()
  62407. {
  62408. ResizableWindow::resized();
  62409. if (titleBarButtons[1] != 0)
  62410. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62411. const Rectangle<int> titleBarArea (getTitleBarArea());
  62412. getLookAndFeel()
  62413. .positionDocumentWindowButtons (*this,
  62414. titleBarArea.getX(), titleBarArea.getY(),
  62415. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62416. titleBarButtons[0],
  62417. titleBarButtons[1],
  62418. titleBarButtons[2],
  62419. positionTitleBarButtonsOnLeft);
  62420. if (menuBar != 0)
  62421. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62422. titleBarArea.getWidth(), menuBarHeight);
  62423. }
  62424. const BorderSize<int> DocumentWindow::getBorderThickness()
  62425. {
  62426. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62427. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62428. }
  62429. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62430. {
  62431. BorderSize<int> border (getBorderThickness());
  62432. border.setTop (border.getTop()
  62433. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62434. + (menuBar != 0 ? menuBarHeight : 0));
  62435. return border;
  62436. }
  62437. int DocumentWindow::getTitleBarHeight() const
  62438. {
  62439. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62440. }
  62441. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62442. {
  62443. const BorderSize<int> border (getBorderThickness());
  62444. return Rectangle<int> (border.getLeft(), border.getTop(),
  62445. getWidth() - border.getLeftAndRight(),
  62446. getTitleBarHeight());
  62447. }
  62448. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62449. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62450. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62451. int DocumentWindow::getDesktopWindowStyleFlags() const
  62452. {
  62453. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62454. if ((requiredButtons & minimiseButton) != 0)
  62455. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62456. if ((requiredButtons & maximiseButton) != 0)
  62457. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62458. if ((requiredButtons & closeButton) != 0)
  62459. styleFlags |= ComponentPeer::windowHasCloseButton;
  62460. return styleFlags;
  62461. }
  62462. void DocumentWindow::lookAndFeelChanged()
  62463. {
  62464. int i;
  62465. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62466. titleBarButtons[i] = 0;
  62467. if (! isUsingNativeTitleBar())
  62468. {
  62469. LookAndFeel& lf = getLookAndFeel();
  62470. if ((requiredButtons & minimiseButton) != 0)
  62471. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62472. if ((requiredButtons & maximiseButton) != 0)
  62473. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62474. if ((requiredButtons & closeButton) != 0)
  62475. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62476. for (i = 0; i < 3; ++i)
  62477. {
  62478. if (titleBarButtons[i] != 0)
  62479. {
  62480. if (buttonListener == 0)
  62481. buttonListener = new ButtonListenerProxy (*this);
  62482. titleBarButtons[i]->addListener (buttonListener);
  62483. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62484. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62485. Component::addAndMakeVisible (titleBarButtons[i]);
  62486. }
  62487. }
  62488. if (getCloseButton() != 0)
  62489. {
  62490. #if JUCE_MAC
  62491. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62492. #else
  62493. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62494. #endif
  62495. }
  62496. }
  62497. activeWindowStatusChanged();
  62498. ResizableWindow::lookAndFeelChanged();
  62499. }
  62500. void DocumentWindow::parentHierarchyChanged()
  62501. {
  62502. lookAndFeelChanged();
  62503. }
  62504. void DocumentWindow::activeWindowStatusChanged()
  62505. {
  62506. ResizableWindow::activeWindowStatusChanged();
  62507. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62508. if (titleBarButtons[i] != 0)
  62509. titleBarButtons[i]->setEnabled (isActiveWindow());
  62510. if (menuBar != 0)
  62511. menuBar->setEnabled (isActiveWindow());
  62512. }
  62513. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62514. {
  62515. if (getTitleBarArea().contains (e.x, e.y)
  62516. && getMaximiseButton() != 0)
  62517. {
  62518. getMaximiseButton()->triggerClick();
  62519. }
  62520. }
  62521. void DocumentWindow::userTriedToCloseWindow()
  62522. {
  62523. closeButtonPressed();
  62524. }
  62525. END_JUCE_NAMESPACE
  62526. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62527. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62528. BEGIN_JUCE_NAMESPACE
  62529. ResizableWindow::ResizableWindow (const String& name,
  62530. const bool addToDesktop_)
  62531. : TopLevelWindow (name, addToDesktop_),
  62532. resizeToFitContent (false),
  62533. fullscreen (false),
  62534. lastNonFullScreenPos (50, 50, 256, 256),
  62535. constrainer (0)
  62536. #if JUCE_DEBUG
  62537. , hasBeenResized (false)
  62538. #endif
  62539. {
  62540. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62541. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62542. if (addToDesktop_)
  62543. Component::addToDesktop (getDesktopWindowStyleFlags());
  62544. }
  62545. ResizableWindow::ResizableWindow (const String& name,
  62546. const Colour& backgroundColour_,
  62547. const bool addToDesktop_)
  62548. : TopLevelWindow (name, addToDesktop_),
  62549. resizeToFitContent (false),
  62550. fullscreen (false),
  62551. lastNonFullScreenPos (50, 50, 256, 256),
  62552. constrainer (0)
  62553. #if JUCE_DEBUG
  62554. , hasBeenResized (false)
  62555. #endif
  62556. {
  62557. setBackgroundColour (backgroundColour_);
  62558. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62559. if (addToDesktop_)
  62560. Component::addToDesktop (getDesktopWindowStyleFlags());
  62561. }
  62562. ResizableWindow::~ResizableWindow()
  62563. {
  62564. // Don't delete or remove the resizer components yourself! They're managed by the
  62565. // ResizableWindow, and you should leave them alone! You may have deleted them
  62566. // accidentally by careless use of deleteAllChildren()..?
  62567. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62568. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62569. resizableCorner = 0;
  62570. resizableBorder = 0;
  62571. contentComponent.deleteAndZero();
  62572. // have you been adding your own components directly to this window..? tut tut tut.
  62573. // Read the instructions for using a ResizableWindow!
  62574. jassert (getNumChildComponents() == 0);
  62575. }
  62576. int ResizableWindow::getDesktopWindowStyleFlags() const
  62577. {
  62578. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62579. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62580. styleFlags |= ComponentPeer::windowIsResizable;
  62581. return styleFlags;
  62582. }
  62583. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62584. const bool deleteOldOne,
  62585. const bool resizeToFit)
  62586. {
  62587. resizeToFitContent = resizeToFit;
  62588. if (newContentComponent != static_cast <Component*> (contentComponent))
  62589. {
  62590. if (deleteOldOne)
  62591. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62592. // external deletion of the content comp)
  62593. else
  62594. removeChildComponent (contentComponent);
  62595. contentComponent = newContentComponent;
  62596. Component::addAndMakeVisible (contentComponent);
  62597. }
  62598. if (resizeToFit)
  62599. childBoundsChanged (contentComponent);
  62600. resized(); // must always be called to position the new content comp
  62601. }
  62602. void ResizableWindow::setContentComponentSize (int width, int height)
  62603. {
  62604. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62605. const BorderSize<int> border (getContentComponentBorder());
  62606. setSize (width + border.getLeftAndRight(),
  62607. height + border.getTopAndBottom());
  62608. }
  62609. const BorderSize<int> ResizableWindow::getBorderThickness()
  62610. {
  62611. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62612. }
  62613. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  62614. {
  62615. return getBorderThickness();
  62616. }
  62617. void ResizableWindow::moved()
  62618. {
  62619. updateLastPos();
  62620. }
  62621. void ResizableWindow::visibilityChanged()
  62622. {
  62623. TopLevelWindow::visibilityChanged();
  62624. updateLastPos();
  62625. }
  62626. void ResizableWindow::resized()
  62627. {
  62628. if (resizableBorder != 0)
  62629. {
  62630. #if JUCE_WINDOWS || JUCE_LINUX
  62631. // hide the resizable border if the OS already provides one..
  62632. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62633. #else
  62634. resizableBorder->setVisible (! isFullScreen());
  62635. #endif
  62636. resizableBorder->setBorderThickness (getBorderThickness());
  62637. resizableBorder->setSize (getWidth(), getHeight());
  62638. resizableBorder->toBack();
  62639. }
  62640. if (resizableCorner != 0)
  62641. {
  62642. #if JUCE_MAC
  62643. // hide the resizable border if the OS already provides one..
  62644. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62645. #else
  62646. resizableCorner->setVisible (! isFullScreen());
  62647. #endif
  62648. const int resizerSize = 18;
  62649. resizableCorner->setBounds (getWidth() - resizerSize,
  62650. getHeight() - resizerSize,
  62651. resizerSize, resizerSize);
  62652. }
  62653. if (contentComponent != 0)
  62654. contentComponent->setBoundsInset (getContentComponentBorder());
  62655. updateLastPos();
  62656. #if JUCE_DEBUG
  62657. hasBeenResized = true;
  62658. #endif
  62659. }
  62660. void ResizableWindow::childBoundsChanged (Component* child)
  62661. {
  62662. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62663. {
  62664. // not going to look very good if this component has a zero size..
  62665. jassert (child->getWidth() > 0);
  62666. jassert (child->getHeight() > 0);
  62667. const BorderSize<int> borders (getContentComponentBorder());
  62668. setSize (child->getWidth() + borders.getLeftAndRight(),
  62669. child->getHeight() + borders.getTopAndBottom());
  62670. }
  62671. }
  62672. void ResizableWindow::activeWindowStatusChanged()
  62673. {
  62674. const BorderSize<int> border (getContentComponentBorder());
  62675. Rectangle<int> area (getLocalBounds());
  62676. repaint (area.removeFromTop (border.getTop()));
  62677. repaint (area.removeFromLeft (border.getLeft()));
  62678. repaint (area.removeFromRight (border.getRight()));
  62679. repaint (area.removeFromBottom (border.getBottom()));
  62680. }
  62681. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62682. const bool useBottomRightCornerResizer)
  62683. {
  62684. if (shouldBeResizable)
  62685. {
  62686. if (useBottomRightCornerResizer)
  62687. {
  62688. resizableBorder = 0;
  62689. if (resizableCorner == 0)
  62690. {
  62691. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62692. resizableCorner->setAlwaysOnTop (true);
  62693. }
  62694. }
  62695. else
  62696. {
  62697. resizableCorner = 0;
  62698. if (resizableBorder == 0)
  62699. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62700. }
  62701. }
  62702. else
  62703. {
  62704. resizableCorner = 0;
  62705. resizableBorder = 0;
  62706. }
  62707. if (isUsingNativeTitleBar())
  62708. recreateDesktopWindow();
  62709. childBoundsChanged (contentComponent);
  62710. resized();
  62711. }
  62712. bool ResizableWindow::isResizable() const throw()
  62713. {
  62714. return resizableCorner != 0
  62715. || resizableBorder != 0;
  62716. }
  62717. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62718. const int newMinimumHeight,
  62719. const int newMaximumWidth,
  62720. const int newMaximumHeight) throw()
  62721. {
  62722. // if you've set up a custom constrainer then these settings won't have any effect..
  62723. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62724. if (constrainer == 0)
  62725. setConstrainer (&defaultConstrainer);
  62726. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62727. newMaximumWidth, newMaximumHeight);
  62728. setBoundsConstrained (getBounds());
  62729. }
  62730. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62731. {
  62732. if (constrainer != newConstrainer)
  62733. {
  62734. constrainer = newConstrainer;
  62735. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62736. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62737. resizableCorner = 0;
  62738. resizableBorder = 0;
  62739. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62740. ComponentPeer* const peer = getPeer();
  62741. if (peer != 0)
  62742. peer->setConstrainer (newConstrainer);
  62743. }
  62744. }
  62745. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62746. {
  62747. if (constrainer != 0)
  62748. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62749. else
  62750. setBounds (bounds);
  62751. }
  62752. void ResizableWindow::paint (Graphics& g)
  62753. {
  62754. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62755. getBorderThickness(), *this);
  62756. if (! isFullScreen())
  62757. {
  62758. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62759. getBorderThickness(), *this);
  62760. }
  62761. #if JUCE_DEBUG
  62762. /* If this fails, then you've probably written a subclass with a resized()
  62763. callback but forgotten to make it call its parent class's resized() method.
  62764. It's important when you override methods like resized(), moved(),
  62765. etc., that you make sure the base class methods also get called.
  62766. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62767. because your content should all be inside the content component - and it's the
  62768. content component's resized() method that you should be using to do your
  62769. layout.
  62770. */
  62771. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62772. #endif
  62773. }
  62774. void ResizableWindow::lookAndFeelChanged()
  62775. {
  62776. resized();
  62777. if (isOnDesktop())
  62778. {
  62779. Component::addToDesktop (getDesktopWindowStyleFlags());
  62780. ComponentPeer* const peer = getPeer();
  62781. if (peer != 0)
  62782. peer->setConstrainer (constrainer);
  62783. }
  62784. }
  62785. const Colour ResizableWindow::getBackgroundColour() const throw()
  62786. {
  62787. return findColour (backgroundColourId, false);
  62788. }
  62789. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62790. {
  62791. Colour backgroundColour (newColour);
  62792. if (! Desktop::canUseSemiTransparentWindows())
  62793. backgroundColour = newColour.withAlpha (1.0f);
  62794. setColour (backgroundColourId, backgroundColour);
  62795. setOpaque (backgroundColour.isOpaque());
  62796. repaint();
  62797. }
  62798. bool ResizableWindow::isFullScreen() const
  62799. {
  62800. if (isOnDesktop())
  62801. {
  62802. ComponentPeer* const peer = getPeer();
  62803. return peer != 0 && peer->isFullScreen();
  62804. }
  62805. return fullscreen;
  62806. }
  62807. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62808. {
  62809. if (shouldBeFullScreen != isFullScreen())
  62810. {
  62811. updateLastPos();
  62812. fullscreen = shouldBeFullScreen;
  62813. if (isOnDesktop())
  62814. {
  62815. ComponentPeer* const peer = getPeer();
  62816. if (peer != 0)
  62817. {
  62818. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62819. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62820. peer->setFullScreen (shouldBeFullScreen);
  62821. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  62822. setBounds (lastPos);
  62823. }
  62824. else
  62825. {
  62826. jassertfalse;
  62827. }
  62828. }
  62829. else
  62830. {
  62831. if (shouldBeFullScreen)
  62832. setBounds (0, 0, getParentWidth(), getParentHeight());
  62833. else
  62834. setBounds (lastNonFullScreenPos);
  62835. }
  62836. resized();
  62837. }
  62838. }
  62839. bool ResizableWindow::isMinimised() const
  62840. {
  62841. ComponentPeer* const peer = getPeer();
  62842. return (peer != 0) && peer->isMinimised();
  62843. }
  62844. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62845. {
  62846. if (shouldMinimise != isMinimised())
  62847. {
  62848. ComponentPeer* const peer = getPeer();
  62849. if (peer != 0)
  62850. {
  62851. updateLastPos();
  62852. peer->setMinimised (shouldMinimise);
  62853. }
  62854. else
  62855. {
  62856. jassertfalse;
  62857. }
  62858. }
  62859. }
  62860. void ResizableWindow::updateLastPos()
  62861. {
  62862. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62863. {
  62864. lastNonFullScreenPos = getBounds();
  62865. }
  62866. }
  62867. void ResizableWindow::parentSizeChanged()
  62868. {
  62869. if (isFullScreen() && getParentComponent() != 0)
  62870. {
  62871. setBounds (0, 0, getParentWidth(), getParentHeight());
  62872. }
  62873. }
  62874. const String ResizableWindow::getWindowStateAsString()
  62875. {
  62876. updateLastPos();
  62877. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62878. }
  62879. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62880. {
  62881. StringArray tokens;
  62882. tokens.addTokens (s, false);
  62883. tokens.removeEmptyStrings();
  62884. tokens.trim();
  62885. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62886. const int firstCoord = fs ? 1 : 0;
  62887. if (tokens.size() != firstCoord + 4)
  62888. return false;
  62889. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62890. tokens[firstCoord + 1].getIntValue(),
  62891. tokens[firstCoord + 2].getIntValue(),
  62892. tokens[firstCoord + 3].getIntValue());
  62893. if (newPos.isEmpty())
  62894. return false;
  62895. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62896. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62897. if (peer != 0)
  62898. peer->getFrameSize().addTo (newPos);
  62899. if (! screen.contains (newPos))
  62900. {
  62901. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62902. jmin (newPos.getHeight(), screen.getHeight()));
  62903. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62904. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62905. }
  62906. if (peer != 0)
  62907. {
  62908. peer->getFrameSize().subtractFrom (newPos);
  62909. peer->setNonFullScreenBounds (newPos);
  62910. }
  62911. lastNonFullScreenPos = newPos;
  62912. setFullScreen (fs);
  62913. if (! fs)
  62914. setBoundsConstrained (newPos);
  62915. return true;
  62916. }
  62917. void ResizableWindow::mouseDown (const MouseEvent& e)
  62918. {
  62919. if (! isFullScreen())
  62920. dragger.startDraggingComponent (this, e);
  62921. }
  62922. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62923. {
  62924. if (! isFullScreen())
  62925. dragger.dragComponent (this, e, constrainer);
  62926. }
  62927. #if JUCE_DEBUG
  62928. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62929. {
  62930. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62931. manages its child components automatically, and if you add your own it'll cause
  62932. trouble. Instead, use setContentComponent() to give it a component which
  62933. will be automatically resized and kept in the right place - then you can add
  62934. subcomponents to the content comp. See the notes for the ResizableWindow class
  62935. for more info.
  62936. If you really know what you're doing and want to avoid this assertion, just call
  62937. Component::addChildComponent directly.
  62938. */
  62939. jassertfalse;
  62940. Component::addChildComponent (child, zOrder);
  62941. }
  62942. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62943. {
  62944. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62945. manages its child components automatically, and if you add your own it'll cause
  62946. trouble. Instead, use setContentComponent() to give it a component which
  62947. will be automatically resized and kept in the right place - then you can add
  62948. subcomponents to the content comp. See the notes for the ResizableWindow class
  62949. for more info.
  62950. If you really know what you're doing and want to avoid this assertion, just call
  62951. Component::addAndMakeVisible directly.
  62952. */
  62953. jassertfalse;
  62954. Component::addAndMakeVisible (child, zOrder);
  62955. }
  62956. #endif
  62957. END_JUCE_NAMESPACE
  62958. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62959. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62960. BEGIN_JUCE_NAMESPACE
  62961. SplashScreen::SplashScreen()
  62962. {
  62963. setOpaque (true);
  62964. }
  62965. SplashScreen::~SplashScreen()
  62966. {
  62967. }
  62968. void SplashScreen::show (const String& title,
  62969. const Image& backgroundImage_,
  62970. const int minimumTimeToDisplayFor,
  62971. const bool useDropShadow,
  62972. const bool removeOnMouseClick)
  62973. {
  62974. backgroundImage = backgroundImage_;
  62975. jassert (backgroundImage_.isValid());
  62976. if (backgroundImage_.isValid())
  62977. {
  62978. setOpaque (! backgroundImage_.hasAlphaChannel());
  62979. show (title,
  62980. backgroundImage_.getWidth(),
  62981. backgroundImage_.getHeight(),
  62982. minimumTimeToDisplayFor,
  62983. useDropShadow,
  62984. removeOnMouseClick);
  62985. }
  62986. }
  62987. void SplashScreen::show (const String& title,
  62988. const int width,
  62989. const int height,
  62990. const int minimumTimeToDisplayFor,
  62991. const bool useDropShadow,
  62992. const bool removeOnMouseClick)
  62993. {
  62994. setName (title);
  62995. setAlwaysOnTop (true);
  62996. setVisible (true);
  62997. centreWithSize (width, height);
  62998. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62999. toFront (false);
  63000. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63001. repaint();
  63002. originalClickCounter = removeOnMouseClick
  63003. ? Desktop::getMouseButtonClickCounter()
  63004. : std::numeric_limits<int>::max();
  63005. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63006. startTimer (50);
  63007. }
  63008. void SplashScreen::paint (Graphics& g)
  63009. {
  63010. g.setOpacity (1.0f);
  63011. g.drawImage (backgroundImage,
  63012. 0, 0, getWidth(), getHeight(),
  63013. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63014. }
  63015. void SplashScreen::timerCallback()
  63016. {
  63017. if (Time::getCurrentTime() > earliestTimeToDelete
  63018. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63019. {
  63020. delete this;
  63021. }
  63022. }
  63023. END_JUCE_NAMESPACE
  63024. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63025. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63026. BEGIN_JUCE_NAMESPACE
  63027. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63028. const bool hasProgressBar,
  63029. const bool hasCancelButton,
  63030. const int timeOutMsWhenCancelling_,
  63031. const String& cancelButtonText)
  63032. : Thread ("Juce Progress Window"),
  63033. progress (0.0),
  63034. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63035. {
  63036. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63037. .createAlertWindow (title, String::empty, cancelButtonText,
  63038. String::empty, String::empty,
  63039. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63040. if (hasProgressBar)
  63041. alertWindow->addProgressBarComponent (progress);
  63042. }
  63043. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63044. {
  63045. stopThread (timeOutMsWhenCancelling);
  63046. }
  63047. bool ThreadWithProgressWindow::runThread (const int priority)
  63048. {
  63049. startThread (priority);
  63050. startTimer (100);
  63051. {
  63052. const ScopedLock sl (messageLock);
  63053. alertWindow->setMessage (message);
  63054. }
  63055. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63056. stopThread (timeOutMsWhenCancelling);
  63057. alertWindow->setVisible (false);
  63058. return finishedNaturally;
  63059. }
  63060. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63061. {
  63062. progress = newProgress;
  63063. }
  63064. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63065. {
  63066. const ScopedLock sl (messageLock);
  63067. message = newStatusMessage;
  63068. }
  63069. void ThreadWithProgressWindow::timerCallback()
  63070. {
  63071. if (! isThreadRunning())
  63072. {
  63073. // thread has finished normally..
  63074. alertWindow->exitModalState (1);
  63075. alertWindow->setVisible (false);
  63076. }
  63077. else
  63078. {
  63079. const ScopedLock sl (messageLock);
  63080. alertWindow->setMessage (message);
  63081. }
  63082. }
  63083. END_JUCE_NAMESPACE
  63084. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63085. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63086. BEGIN_JUCE_NAMESPACE
  63087. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63088. const int millisecondsBeforeTipAppears_)
  63089. : Component ("tooltip"),
  63090. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63091. mouseClicks (0),
  63092. lastHideTime (0),
  63093. lastComponentUnderMouse (0),
  63094. changedCompsSinceShown (true)
  63095. {
  63096. if (Desktop::getInstance().getMainMouseSource().canHover())
  63097. startTimer (123);
  63098. setAlwaysOnTop (true);
  63099. setOpaque (true);
  63100. if (parentComponent != 0)
  63101. parentComponent->addChildComponent (this);
  63102. }
  63103. TooltipWindow::~TooltipWindow()
  63104. {
  63105. hide();
  63106. }
  63107. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63108. {
  63109. millisecondsBeforeTipAppears = newTimeMs;
  63110. }
  63111. void TooltipWindow::paint (Graphics& g)
  63112. {
  63113. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63114. }
  63115. void TooltipWindow::mouseEnter (const MouseEvent&)
  63116. {
  63117. hide();
  63118. }
  63119. void TooltipWindow::showFor (const String& tip)
  63120. {
  63121. jassert (tip.isNotEmpty());
  63122. if (tipShowing != tip)
  63123. repaint();
  63124. tipShowing = tip;
  63125. Point<int> mousePos (Desktop::getMousePosition());
  63126. if (getParentComponent() != 0)
  63127. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63128. int x, y, w, h;
  63129. getLookAndFeel().getTooltipSize (tip, w, h);
  63130. if (mousePos.getX() > getParentWidth() / 2)
  63131. x = mousePos.getX() - (w + 12);
  63132. else
  63133. x = mousePos.getX() + 24;
  63134. if (mousePos.getY() > getParentHeight() / 2)
  63135. y = mousePos.getY() - (h + 6);
  63136. else
  63137. y = mousePos.getY() + 6;
  63138. setBounds (x, y, w, h);
  63139. setVisible (true);
  63140. if (getParentComponent() == 0)
  63141. {
  63142. addToDesktop (ComponentPeer::windowHasDropShadow
  63143. | ComponentPeer::windowIsTemporary
  63144. | ComponentPeer::windowIgnoresKeyPresses);
  63145. }
  63146. toFront (false);
  63147. }
  63148. const String TooltipWindow::getTipFor (Component* const c)
  63149. {
  63150. if (c != 0
  63151. && Process::isForegroundProcess()
  63152. && ! Component::isMouseButtonDownAnywhere())
  63153. {
  63154. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63155. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63156. return ttc->getTooltip();
  63157. }
  63158. return String::empty;
  63159. }
  63160. void TooltipWindow::hide()
  63161. {
  63162. tipShowing = String::empty;
  63163. removeFromDesktop();
  63164. setVisible (false);
  63165. }
  63166. void TooltipWindow::timerCallback()
  63167. {
  63168. const unsigned int now = Time::getApproximateMillisecondCounter();
  63169. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63170. const String newTip (getTipFor (newComp));
  63171. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63172. lastComponentUnderMouse = newComp;
  63173. lastTipUnderMouse = newTip;
  63174. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63175. const bool mouseWasClicked = clickCount > mouseClicks;
  63176. mouseClicks = clickCount;
  63177. const Point<int> mousePos (Desktop::getMousePosition());
  63178. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63179. lastMousePos = mousePos;
  63180. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63181. lastCompChangeTime = now;
  63182. if (isVisible() || now < lastHideTime + 500)
  63183. {
  63184. // if a tip is currently visible (or has just disappeared), update to a new one
  63185. // immediately if needed..
  63186. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63187. {
  63188. if (isVisible())
  63189. {
  63190. lastHideTime = now;
  63191. hide();
  63192. }
  63193. }
  63194. else if (tipChanged)
  63195. {
  63196. showFor (newTip);
  63197. }
  63198. }
  63199. else
  63200. {
  63201. // if there isn't currently a tip, but one is needed, only let it
  63202. // appear after a timeout..
  63203. if (newTip.isNotEmpty()
  63204. && newTip != tipShowing
  63205. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63206. {
  63207. showFor (newTip);
  63208. }
  63209. }
  63210. }
  63211. END_JUCE_NAMESPACE
  63212. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63213. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63214. BEGIN_JUCE_NAMESPACE
  63215. /** Keeps track of the active top level window.
  63216. */
  63217. class TopLevelWindowManager : public Timer,
  63218. public DeletedAtShutdown
  63219. {
  63220. public:
  63221. TopLevelWindowManager()
  63222. : currentActive (0)
  63223. {
  63224. }
  63225. ~TopLevelWindowManager()
  63226. {
  63227. clearSingletonInstance();
  63228. }
  63229. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63230. void timerCallback()
  63231. {
  63232. startTimer (jmin (1731, getTimerInterval() * 2));
  63233. TopLevelWindow* active = 0;
  63234. if (Process::isForegroundProcess())
  63235. {
  63236. active = currentActive;
  63237. Component* const c = Component::getCurrentlyFocusedComponent();
  63238. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63239. if (tlw == 0 && c != 0)
  63240. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63241. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63242. if (tlw != 0)
  63243. active = tlw;
  63244. }
  63245. if (active != currentActive)
  63246. {
  63247. currentActive = active;
  63248. for (int i = windows.size(); --i >= 0;)
  63249. {
  63250. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63251. tlw->setWindowActive (isWindowActive (tlw));
  63252. i = jmin (i, windows.size() - 1);
  63253. }
  63254. Desktop::getInstance().triggerFocusCallback();
  63255. }
  63256. }
  63257. bool addWindow (TopLevelWindow* const w)
  63258. {
  63259. windows.add (w);
  63260. startTimer (10);
  63261. return isWindowActive (w);
  63262. }
  63263. void removeWindow (TopLevelWindow* const w)
  63264. {
  63265. startTimer (10);
  63266. if (currentActive == w)
  63267. currentActive = 0;
  63268. windows.removeValue (w);
  63269. if (windows.size() == 0)
  63270. deleteInstance();
  63271. }
  63272. Array <TopLevelWindow*> windows;
  63273. private:
  63274. TopLevelWindow* currentActive;
  63275. bool isWindowActive (TopLevelWindow* const tlw) const
  63276. {
  63277. return (tlw == currentActive
  63278. || tlw->isParentOf (currentActive)
  63279. || tlw->hasKeyboardFocus (true))
  63280. && tlw->isShowing();
  63281. }
  63282. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63283. };
  63284. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63285. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63286. {
  63287. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63288. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63289. }
  63290. TopLevelWindow::TopLevelWindow (const String& name,
  63291. const bool addToDesktop_)
  63292. : Component (name),
  63293. useDropShadow (true),
  63294. useNativeTitleBar (false),
  63295. windowIsActive_ (false)
  63296. {
  63297. setOpaque (true);
  63298. if (addToDesktop_)
  63299. Component::addToDesktop (getDesktopWindowStyleFlags());
  63300. else
  63301. setDropShadowEnabled (true);
  63302. setWantsKeyboardFocus (true);
  63303. setBroughtToFrontOnMouseClick (true);
  63304. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63305. }
  63306. TopLevelWindow::~TopLevelWindow()
  63307. {
  63308. shadower = 0;
  63309. TopLevelWindowManager::getInstance()->removeWindow (this);
  63310. }
  63311. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63312. {
  63313. if (hasKeyboardFocus (true))
  63314. TopLevelWindowManager::getInstance()->timerCallback();
  63315. else
  63316. TopLevelWindowManager::getInstance()->startTimer (10);
  63317. }
  63318. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63319. {
  63320. if (windowIsActive_ != isNowActive)
  63321. {
  63322. windowIsActive_ = isNowActive;
  63323. activeWindowStatusChanged();
  63324. }
  63325. }
  63326. void TopLevelWindow::activeWindowStatusChanged()
  63327. {
  63328. }
  63329. void TopLevelWindow::visibilityChanged()
  63330. {
  63331. if (isShowing()
  63332. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63333. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63334. {
  63335. toFront (true);
  63336. }
  63337. }
  63338. void TopLevelWindow::parentHierarchyChanged()
  63339. {
  63340. setDropShadowEnabled (useDropShadow);
  63341. }
  63342. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63343. {
  63344. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63345. if (useDropShadow)
  63346. styleFlags |= ComponentPeer::windowHasDropShadow;
  63347. if (useNativeTitleBar)
  63348. styleFlags |= ComponentPeer::windowHasTitleBar;
  63349. return styleFlags;
  63350. }
  63351. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63352. {
  63353. useDropShadow = useShadow;
  63354. if (isOnDesktop())
  63355. {
  63356. shadower = 0;
  63357. Component::addToDesktop (getDesktopWindowStyleFlags());
  63358. }
  63359. else
  63360. {
  63361. if (useShadow && isOpaque())
  63362. {
  63363. if (shadower == 0)
  63364. {
  63365. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63366. if (shadower != 0)
  63367. shadower->setOwner (this);
  63368. }
  63369. }
  63370. else
  63371. {
  63372. shadower = 0;
  63373. }
  63374. }
  63375. }
  63376. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63377. {
  63378. if (useNativeTitleBar != useNativeTitleBar_)
  63379. {
  63380. useNativeTitleBar = useNativeTitleBar_;
  63381. recreateDesktopWindow();
  63382. sendLookAndFeelChange();
  63383. }
  63384. }
  63385. void TopLevelWindow::recreateDesktopWindow()
  63386. {
  63387. if (isOnDesktop())
  63388. {
  63389. Component::addToDesktop (getDesktopWindowStyleFlags());
  63390. toFront (true);
  63391. }
  63392. }
  63393. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63394. {
  63395. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63396. because this class needs to make sure its layout corresponds with settings like whether
  63397. it's got a native title bar or not.
  63398. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63399. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63400. method, then add or remove whatever flags are necessary from this value before returning it.
  63401. */
  63402. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63403. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63404. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63405. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63406. sendLookAndFeelChange();
  63407. }
  63408. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63409. {
  63410. if (c == 0)
  63411. c = TopLevelWindow::getActiveTopLevelWindow();
  63412. if (c == 0)
  63413. {
  63414. centreWithSize (width, height);
  63415. }
  63416. else
  63417. {
  63418. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63419. Rectangle<int> parentArea (c->getParentMonitorArea());
  63420. if (getParentComponent() != 0)
  63421. {
  63422. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63423. parentArea = getParentComponent()->getLocalBounds();
  63424. }
  63425. parentArea.reduce (12, 12);
  63426. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63427. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63428. width, height);
  63429. }
  63430. }
  63431. int TopLevelWindow::getNumTopLevelWindows() throw()
  63432. {
  63433. return TopLevelWindowManager::getInstance()->windows.size();
  63434. }
  63435. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63436. {
  63437. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63438. }
  63439. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63440. {
  63441. TopLevelWindow* best = 0;
  63442. int bestNumTWLParents = -1;
  63443. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63444. {
  63445. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63446. if (tlw->isActiveWindow())
  63447. {
  63448. int numTWLParents = 0;
  63449. const Component* c = tlw->getParentComponent();
  63450. while (c != 0)
  63451. {
  63452. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63453. ++numTWLParents;
  63454. c = c->getParentComponent();
  63455. }
  63456. if (bestNumTWLParents < numTWLParents)
  63457. {
  63458. best = tlw;
  63459. bestNumTWLParents = numTWLParents;
  63460. }
  63461. }
  63462. }
  63463. return best;
  63464. }
  63465. END_JUCE_NAMESPACE
  63466. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63467. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63468. BEGIN_JUCE_NAMESPACE
  63469. MarkerList::MarkerList()
  63470. {
  63471. }
  63472. MarkerList::MarkerList (const MarkerList& other)
  63473. {
  63474. operator= (other);
  63475. }
  63476. MarkerList& MarkerList::operator= (const MarkerList& other)
  63477. {
  63478. if (other != *this)
  63479. {
  63480. markers.clear();
  63481. markers.addCopiesOf (other.markers);
  63482. markersHaveChanged();
  63483. }
  63484. return *this;
  63485. }
  63486. MarkerList::~MarkerList()
  63487. {
  63488. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63489. }
  63490. bool MarkerList::operator== (const MarkerList& other) const throw()
  63491. {
  63492. if (other.markers.size() != markers.size())
  63493. return false;
  63494. for (int i = markers.size(); --i >= 0;)
  63495. {
  63496. const Marker* const m1 = markers.getUnchecked(i);
  63497. jassert (m1 != 0);
  63498. const Marker* const m2 = other.getMarker (m1->name);
  63499. if (m2 == 0 || *m1 != *m2)
  63500. return false;
  63501. }
  63502. return true;
  63503. }
  63504. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63505. {
  63506. return ! operator== (other);
  63507. }
  63508. int MarkerList::getNumMarkers() const throw()
  63509. {
  63510. return markers.size();
  63511. }
  63512. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63513. {
  63514. return markers [index];
  63515. }
  63516. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63517. {
  63518. for (int i = 0; i < markers.size(); ++i)
  63519. {
  63520. const Marker* const m = markers.getUnchecked(i);
  63521. if (m->name == name)
  63522. return m;
  63523. }
  63524. return 0;
  63525. }
  63526. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63527. {
  63528. Marker* const m = const_cast <Marker*> (getMarker (name));
  63529. if (m != 0)
  63530. {
  63531. if (m->position != position)
  63532. {
  63533. m->position = position;
  63534. markersHaveChanged();
  63535. }
  63536. return;
  63537. }
  63538. markers.add (new Marker (name, position));
  63539. markersHaveChanged();
  63540. }
  63541. void MarkerList::removeMarker (const int index)
  63542. {
  63543. if (isPositiveAndBelow (index, markers.size()))
  63544. {
  63545. markers.remove (index);
  63546. markersHaveChanged();
  63547. }
  63548. }
  63549. void MarkerList::removeMarker (const String& name)
  63550. {
  63551. for (int i = 0; i < markers.size(); ++i)
  63552. {
  63553. const Marker* const m = markers.getUnchecked(i);
  63554. if (m->name == name)
  63555. {
  63556. markers.remove (i);
  63557. markersHaveChanged();
  63558. }
  63559. }
  63560. }
  63561. void MarkerList::markersHaveChanged()
  63562. {
  63563. listeners.call (&MarkerList::Listener::markersChanged, this);
  63564. }
  63565. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63566. {
  63567. }
  63568. void MarkerList::addListener (Listener* listener)
  63569. {
  63570. listeners.add (listener);
  63571. }
  63572. void MarkerList::removeListener (Listener* listener)
  63573. {
  63574. listeners.remove (listener);
  63575. }
  63576. MarkerList::Marker::Marker (const Marker& other)
  63577. : name (other.name), position (other.position)
  63578. {
  63579. }
  63580. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63581. : name (name_), position (position_)
  63582. {
  63583. }
  63584. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63585. {
  63586. return name == other.name && position == other.position;
  63587. }
  63588. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63589. {
  63590. return ! operator== (other);
  63591. }
  63592. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63593. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63594. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63595. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63596. : state (state_)
  63597. {
  63598. }
  63599. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63600. {
  63601. return state.getNumChildren();
  63602. }
  63603. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63604. {
  63605. return state.getChild (index);
  63606. }
  63607. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63608. {
  63609. return state.getChildWithProperty (nameProperty, name);
  63610. }
  63611. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63612. {
  63613. return marker.isAChildOf (state);
  63614. }
  63615. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63616. {
  63617. jassert (containsMarker (marker));
  63618. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63619. }
  63620. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63621. {
  63622. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63623. if (marker.isValid())
  63624. {
  63625. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63626. }
  63627. else
  63628. {
  63629. marker = ValueTree (markerTag);
  63630. marker.setProperty (nameProperty, m.name, 0);
  63631. marker.setProperty (posProperty, m.position.toString(), 0);
  63632. state.addChild (marker, -1, undoManager);
  63633. }
  63634. }
  63635. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63636. {
  63637. state.removeChild (marker, undoManager);
  63638. }
  63639. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  63640. {
  63641. if (parentComponent != 0)
  63642. {
  63643. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  63644. return marker.position.resolve (&scope);
  63645. }
  63646. else
  63647. {
  63648. return marker.position.resolve (0);
  63649. }
  63650. }
  63651. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63652. {
  63653. const int numMarkers = getNumMarkers();
  63654. StringArray updatedMarkers;
  63655. int i;
  63656. for (i = 0; i < numMarkers; ++i)
  63657. {
  63658. const ValueTree marker (state.getChild (i));
  63659. const String name (marker [nameProperty].toString());
  63660. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63661. updatedMarkers.add (name);
  63662. }
  63663. for (i = markerList.getNumMarkers(); --i >= 0;)
  63664. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63665. markerList.removeMarker (i);
  63666. }
  63667. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63668. {
  63669. state.removeAllChildren (undoManager);
  63670. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63671. setMarker (*markerList.getMarker(i), undoManager);
  63672. }
  63673. END_JUCE_NAMESPACE
  63674. /*** End of inlined file: juce_MarkerList.cpp ***/
  63675. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63676. BEGIN_JUCE_NAMESPACE
  63677. const String RelativeCoordinate::Strings::parent ("parent");
  63678. const String RelativeCoordinate::Strings::left ("left");
  63679. const String RelativeCoordinate::Strings::right ("right");
  63680. const String RelativeCoordinate::Strings::top ("top");
  63681. const String RelativeCoordinate::Strings::bottom ("bottom");
  63682. const String RelativeCoordinate::Strings::x ("x");
  63683. const String RelativeCoordinate::Strings::y ("y");
  63684. const String RelativeCoordinate::Strings::width ("width");
  63685. const String RelativeCoordinate::Strings::height ("height");
  63686. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  63687. {
  63688. if (s == Strings::left) return left;
  63689. if (s == Strings::right) return right;
  63690. if (s == Strings::top) return top;
  63691. if (s == Strings::bottom) return bottom;
  63692. if (s == Strings::x) return x;
  63693. if (s == Strings::y) return y;
  63694. if (s == Strings::width) return width;
  63695. if (s == Strings::height) return height;
  63696. if (s == Strings::parent) return parent;
  63697. return unknown;
  63698. }
  63699. RelativeCoordinate::RelativeCoordinate()
  63700. {
  63701. }
  63702. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63703. : term (term_)
  63704. {
  63705. }
  63706. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63707. : term (other.term)
  63708. {
  63709. }
  63710. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63711. {
  63712. term = other.term;
  63713. return *this;
  63714. }
  63715. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63716. : term (absoluteDistanceFromOrigin)
  63717. {
  63718. }
  63719. RelativeCoordinate::RelativeCoordinate (const String& s)
  63720. {
  63721. try
  63722. {
  63723. term = Expression (s);
  63724. }
  63725. catch (...)
  63726. {}
  63727. }
  63728. RelativeCoordinate::~RelativeCoordinate()
  63729. {
  63730. }
  63731. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63732. {
  63733. return term.toString() == other.term.toString();
  63734. }
  63735. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63736. {
  63737. return ! operator== (other);
  63738. }
  63739. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  63740. {
  63741. try
  63742. {
  63743. if (scope != 0)
  63744. return term.evaluate (*scope);
  63745. else
  63746. return term.evaluate();
  63747. }
  63748. catch (...)
  63749. {}
  63750. return 0.0;
  63751. }
  63752. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  63753. {
  63754. try
  63755. {
  63756. if (scope != 0)
  63757. term.evaluate (*scope);
  63758. else
  63759. term.evaluate();
  63760. }
  63761. catch (...)
  63762. {
  63763. return true;
  63764. }
  63765. return false;
  63766. }
  63767. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  63768. {
  63769. try
  63770. {
  63771. if (scope != 0)
  63772. {
  63773. term = term.adjustedToGiveNewResult (newPos, *scope);
  63774. }
  63775. else
  63776. {
  63777. Expression::Scope defaultScope;
  63778. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  63779. }
  63780. }
  63781. catch (...)
  63782. {}
  63783. }
  63784. bool RelativeCoordinate::isDynamic() const
  63785. {
  63786. return term.usesAnySymbols();
  63787. }
  63788. const String RelativeCoordinate::toString() const
  63789. {
  63790. return term.toString();
  63791. }
  63792. END_JUCE_NAMESPACE
  63793. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63794. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63795. BEGIN_JUCE_NAMESPACE
  63796. namespace RelativePointHelpers
  63797. {
  63798. void skipComma (const juce_wchar* const s, int& i)
  63799. {
  63800. while (CharacterFunctions::isWhitespace (s[i]))
  63801. ++i;
  63802. if (s[i] == ',')
  63803. ++i;
  63804. }
  63805. }
  63806. RelativePoint::RelativePoint()
  63807. {
  63808. }
  63809. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63810. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63811. {
  63812. }
  63813. RelativePoint::RelativePoint (const float x_, const float y_)
  63814. : x (x_), y (y_)
  63815. {
  63816. }
  63817. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63818. : x (x_), y (y_)
  63819. {
  63820. }
  63821. RelativePoint::RelativePoint (const String& s)
  63822. {
  63823. int i = 0;
  63824. x = RelativeCoordinate (Expression::parse (s, i));
  63825. RelativePointHelpers::skipComma (s, i);
  63826. y = RelativeCoordinate (Expression::parse (s, i));
  63827. }
  63828. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63829. {
  63830. return x == other.x && y == other.y;
  63831. }
  63832. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63833. {
  63834. return ! operator== (other);
  63835. }
  63836. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  63837. {
  63838. return Point<float> ((float) x.resolve (scope),
  63839. (float) y.resolve (scope));
  63840. }
  63841. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  63842. {
  63843. x.moveToAbsolute (newPos.getX(), scope);
  63844. y.moveToAbsolute (newPos.getY(), scope);
  63845. }
  63846. const String RelativePoint::toString() const
  63847. {
  63848. return x.toString() + ", " + y.toString();
  63849. }
  63850. bool RelativePoint::isDynamic() const
  63851. {
  63852. return x.isDynamic() || y.isDynamic();
  63853. }
  63854. END_JUCE_NAMESPACE
  63855. /*** End of inlined file: juce_RelativePoint.cpp ***/
  63856. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  63857. BEGIN_JUCE_NAMESPACE
  63858. namespace RelativeRectangleHelpers
  63859. {
  63860. inline void skipComma (const juce_wchar* const s, int& i)
  63861. {
  63862. while (CharacterFunctions::isWhitespace (s[i]))
  63863. ++i;
  63864. if (s[i] == ',')
  63865. ++i;
  63866. }
  63867. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  63868. {
  63869. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  63870. return true;
  63871. if (e.getType() == Expression::symbolType)
  63872. {
  63873. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  63874. {
  63875. case RelativeCoordinate::StandardStrings::x:
  63876. case RelativeCoordinate::StandardStrings::y:
  63877. case RelativeCoordinate::StandardStrings::left:
  63878. case RelativeCoordinate::StandardStrings::right:
  63879. case RelativeCoordinate::StandardStrings::top:
  63880. case RelativeCoordinate::StandardStrings::bottom: return false;
  63881. default: break;
  63882. }
  63883. return true;
  63884. }
  63885. else
  63886. {
  63887. for (int i = e.getNumInputs(); --i >= 0;)
  63888. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  63889. return true;
  63890. }
  63891. return false;
  63892. }
  63893. }
  63894. RelativeRectangle::RelativeRectangle()
  63895. {
  63896. }
  63897. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63898. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63899. : left (left_), right (right_), top (top_), bottom (bottom_)
  63900. {
  63901. }
  63902. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  63903. : left (rect.getX()),
  63904. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  63905. top (rect.getY()),
  63906. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  63907. {
  63908. }
  63909. RelativeRectangle::RelativeRectangle (const String& s)
  63910. {
  63911. int i = 0;
  63912. left = RelativeCoordinate (Expression::parse (s, i));
  63913. RelativeRectangleHelpers::skipComma (s, i);
  63914. top = RelativeCoordinate (Expression::parse (s, i));
  63915. RelativeRectangleHelpers::skipComma (s, i);
  63916. right = RelativeCoordinate (Expression::parse (s, i));
  63917. RelativeRectangleHelpers::skipComma (s, i);
  63918. bottom = RelativeCoordinate (Expression::parse (s, i));
  63919. }
  63920. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63921. {
  63922. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63923. }
  63924. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63925. {
  63926. return ! operator== (other);
  63927. }
  63928. // An expression context that can evaluate expressions using "this"
  63929. class RelativeRectangleLocalScope : public Expression::Scope
  63930. {
  63931. public:
  63932. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  63933. const Expression getSymbolValue (const String& symbol) const
  63934. {
  63935. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  63936. {
  63937. case RelativeCoordinate::StandardStrings::x:
  63938. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  63939. case RelativeCoordinate::StandardStrings::y:
  63940. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  63941. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  63942. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  63943. default: break;
  63944. }
  63945. return Expression::Scope::getSymbolValue (symbol);
  63946. }
  63947. private:
  63948. const RelativeRectangle& rect;
  63949. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  63950. };
  63951. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  63952. {
  63953. if (scope == 0)
  63954. {
  63955. RelativeRectangleLocalScope scope (*this);
  63956. return resolve (&scope);
  63957. }
  63958. else
  63959. {
  63960. const double l = left.resolve (scope);
  63961. const double r = right.resolve (scope);
  63962. const double t = top.resolve (scope);
  63963. const double b = bottom.resolve (scope);
  63964. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  63965. }
  63966. }
  63967. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  63968. {
  63969. left.moveToAbsolute (newPos.getX(), scope);
  63970. right.moveToAbsolute (newPos.getRight(), scope);
  63971. top.moveToAbsolute (newPos.getY(), scope);
  63972. bottom.moveToAbsolute (newPos.getBottom(), scope);
  63973. }
  63974. bool RelativeRectangle::isDynamic() const
  63975. {
  63976. using namespace RelativeRectangleHelpers;
  63977. return dependsOnSymbolsOtherThanThis (left.getExpression())
  63978. || dependsOnSymbolsOtherThanThis (right.getExpression())
  63979. || dependsOnSymbolsOtherThanThis (top.getExpression())
  63980. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  63981. }
  63982. const String RelativeRectangle::toString() const
  63983. {
  63984. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  63985. }
  63986. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  63987. {
  63988. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  63989. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  63990. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  63991. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  63992. }
  63993. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  63994. {
  63995. public:
  63996. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  63997. : RelativeCoordinatePositionerBase (component_),
  63998. rectangle (rectangle_)
  63999. {
  64000. }
  64001. bool registerCoordinates()
  64002. {
  64003. bool ok = addCoordinate (rectangle.left);
  64004. ok = addCoordinate (rectangle.right) && ok;
  64005. ok = addCoordinate (rectangle.top) && ok;
  64006. ok = addCoordinate (rectangle.bottom) && ok;
  64007. return ok;
  64008. }
  64009. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64010. {
  64011. return rectangle == other;
  64012. }
  64013. void applyToComponentBounds()
  64014. {
  64015. for (int i = 4; --i >= 0;)
  64016. {
  64017. ComponentScope scope (getComponent());
  64018. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64019. if (newBounds == getComponent().getBounds())
  64020. return;
  64021. getComponent().setBounds (newBounds);
  64022. }
  64023. jassertfalse; // must be a recursive reference!
  64024. }
  64025. private:
  64026. const RelativeRectangle rectangle;
  64027. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64028. };
  64029. void RelativeRectangle::applyToComponent (Component& component) const
  64030. {
  64031. if (isDynamic())
  64032. {
  64033. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64034. if (current == 0 || ! current->isUsingRectangle (*this))
  64035. {
  64036. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64037. component.setPositioner (p);
  64038. p->apply();
  64039. }
  64040. }
  64041. else
  64042. {
  64043. component.setPositioner (0);
  64044. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64045. }
  64046. }
  64047. END_JUCE_NAMESPACE
  64048. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64049. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64050. BEGIN_JUCE_NAMESPACE
  64051. RelativePointPath::RelativePointPath()
  64052. : usesNonZeroWinding (true),
  64053. containsDynamicPoints (false)
  64054. {
  64055. }
  64056. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64057. : usesNonZeroWinding (true),
  64058. containsDynamicPoints (false)
  64059. {
  64060. for (int i = 0; i < other.elements.size(); ++i)
  64061. elements.add (other.elements.getUnchecked(i)->clone());
  64062. }
  64063. RelativePointPath::RelativePointPath (const Path& path)
  64064. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64065. containsDynamicPoints (false)
  64066. {
  64067. for (Path::Iterator i (path); i.next();)
  64068. {
  64069. switch (i.elementType)
  64070. {
  64071. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64072. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64073. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64074. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64075. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64076. default: jassertfalse; break;
  64077. }
  64078. }
  64079. }
  64080. RelativePointPath::~RelativePointPath()
  64081. {
  64082. }
  64083. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64084. {
  64085. if (elements.size() != other.elements.size()
  64086. || usesNonZeroWinding != other.usesNonZeroWinding
  64087. || containsDynamicPoints != other.containsDynamicPoints)
  64088. return false;
  64089. for (int i = 0; i < elements.size(); ++i)
  64090. {
  64091. ElementBase* const e1 = elements.getUnchecked(i);
  64092. ElementBase* const e2 = other.elements.getUnchecked(i);
  64093. if (e1->type != e2->type)
  64094. return false;
  64095. int numPoints1, numPoints2;
  64096. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64097. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64098. jassert (numPoints1 == numPoints2);
  64099. for (int j = numPoints1; --j >= 0;)
  64100. if (points1[j] != points2[j])
  64101. return false;
  64102. }
  64103. return true;
  64104. }
  64105. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64106. {
  64107. return ! operator== (other);
  64108. }
  64109. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64110. {
  64111. elements.swapWithArray (other.elements);
  64112. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64113. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64114. }
  64115. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64116. {
  64117. for (int i = 0; i < elements.size(); ++i)
  64118. elements.getUnchecked(i)->addToPath (path, scope);
  64119. }
  64120. bool RelativePointPath::containsAnyDynamicPoints() const
  64121. {
  64122. return containsDynamicPoints;
  64123. }
  64124. void RelativePointPath::addElement (ElementBase* newElement)
  64125. {
  64126. if (newElement != 0)
  64127. {
  64128. elements.add (newElement);
  64129. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64130. }
  64131. }
  64132. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64133. {
  64134. }
  64135. bool RelativePointPath::ElementBase::isDynamic()
  64136. {
  64137. int numPoints;
  64138. const RelativePoint* const points = getControlPoints (numPoints);
  64139. for (int i = numPoints; --i >= 0;)
  64140. if (points[i].isDynamic())
  64141. return true;
  64142. return false;
  64143. }
  64144. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64145. : ElementBase (startSubPathElement), startPos (pos)
  64146. {
  64147. }
  64148. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64149. {
  64150. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64151. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64152. return v;
  64153. }
  64154. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64155. {
  64156. path.startNewSubPath (startPos.resolve (scope));
  64157. }
  64158. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64159. {
  64160. numPoints = 1;
  64161. return &startPos;
  64162. }
  64163. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64164. {
  64165. return new StartSubPath (startPos);
  64166. }
  64167. RelativePointPath::CloseSubPath::CloseSubPath()
  64168. : ElementBase (closeSubPathElement)
  64169. {
  64170. }
  64171. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64172. {
  64173. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64174. }
  64175. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64176. {
  64177. path.closeSubPath();
  64178. }
  64179. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64180. {
  64181. numPoints = 0;
  64182. return 0;
  64183. }
  64184. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64185. {
  64186. return new CloseSubPath();
  64187. }
  64188. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64189. : ElementBase (lineToElement), endPoint (endPoint_)
  64190. {
  64191. }
  64192. const ValueTree RelativePointPath::LineTo::createTree() const
  64193. {
  64194. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64195. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64196. return v;
  64197. }
  64198. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64199. {
  64200. path.lineTo (endPoint.resolve (scope));
  64201. }
  64202. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64203. {
  64204. numPoints = 1;
  64205. return &endPoint;
  64206. }
  64207. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64208. {
  64209. return new LineTo (endPoint);
  64210. }
  64211. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64212. : ElementBase (quadraticToElement)
  64213. {
  64214. controlPoints[0] = controlPoint;
  64215. controlPoints[1] = endPoint;
  64216. }
  64217. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64218. {
  64219. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64220. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64221. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64222. return v;
  64223. }
  64224. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64225. {
  64226. path.quadraticTo (controlPoints[0].resolve (scope),
  64227. controlPoints[1].resolve (scope));
  64228. }
  64229. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64230. {
  64231. numPoints = 2;
  64232. return controlPoints;
  64233. }
  64234. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64235. {
  64236. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64237. }
  64238. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64239. : ElementBase (cubicToElement)
  64240. {
  64241. controlPoints[0] = controlPoint1;
  64242. controlPoints[1] = controlPoint2;
  64243. controlPoints[2] = endPoint;
  64244. }
  64245. const ValueTree RelativePointPath::CubicTo::createTree() const
  64246. {
  64247. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64248. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64249. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64250. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64251. return v;
  64252. }
  64253. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64254. {
  64255. path.cubicTo (controlPoints[0].resolve (scope),
  64256. controlPoints[1].resolve (scope),
  64257. controlPoints[2].resolve (scope));
  64258. }
  64259. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64260. {
  64261. numPoints = 3;
  64262. return controlPoints;
  64263. }
  64264. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64265. {
  64266. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64267. }
  64268. END_JUCE_NAMESPACE
  64269. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64270. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64271. BEGIN_JUCE_NAMESPACE
  64272. RelativeParallelogram::RelativeParallelogram()
  64273. {
  64274. }
  64275. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64276. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64277. {
  64278. }
  64279. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64280. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64281. {
  64282. }
  64283. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64284. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64285. {
  64286. }
  64287. RelativeParallelogram::~RelativeParallelogram()
  64288. {
  64289. }
  64290. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64291. {
  64292. points[0] = topLeft.resolve (scope);
  64293. points[1] = topRight.resolve (scope);
  64294. points[2] = bottomLeft.resolve (scope);
  64295. }
  64296. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64297. {
  64298. resolveThreePoints (points, scope);
  64299. points[3] = points[1] + (points[2] - points[0]);
  64300. }
  64301. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64302. {
  64303. Point<float> points[4];
  64304. resolveFourCorners (points, scope);
  64305. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64306. }
  64307. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64308. {
  64309. Point<float> points[4];
  64310. resolveFourCorners (points, scope);
  64311. path.startNewSubPath (points[0]);
  64312. path.lineTo (points[1]);
  64313. path.lineTo (points[3]);
  64314. path.lineTo (points[2]);
  64315. path.closeSubPath();
  64316. }
  64317. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64318. {
  64319. Point<float> corners[3];
  64320. resolveThreePoints (corners, scope);
  64321. const Line<float> top (corners[0], corners[1]);
  64322. const Line<float> left (corners[0], corners[2]);
  64323. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64324. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64325. topRight.moveToAbsolute (newTopRight, scope);
  64326. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64327. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64328. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64329. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64330. }
  64331. bool RelativeParallelogram::isDynamic() const
  64332. {
  64333. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64334. }
  64335. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64336. {
  64337. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64338. }
  64339. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64340. {
  64341. return ! operator== (other);
  64342. }
  64343. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64344. {
  64345. const Point<float> tr (corners[1] - corners[0]);
  64346. const Point<float> bl (corners[2] - corners[0]);
  64347. target -= corners[0];
  64348. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64349. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64350. }
  64351. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64352. {
  64353. return corners[0]
  64354. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64355. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64356. }
  64357. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64358. {
  64359. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64360. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64361. }
  64362. END_JUCE_NAMESPACE
  64363. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64364. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64365. BEGIN_JUCE_NAMESPACE
  64366. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64367. : component (component_)
  64368. {
  64369. }
  64370. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64371. {
  64372. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64373. {
  64374. case RelativeCoordinate::StandardStrings::x:
  64375. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64376. case RelativeCoordinate::StandardStrings::y:
  64377. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64378. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64379. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64380. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64381. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64382. default: break;
  64383. }
  64384. MarkerList* list;
  64385. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64386. if (marker != 0)
  64387. return marker->position.getExpression();
  64388. return Expression::Scope::getSymbolValue (symbol);
  64389. }
  64390. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64391. {
  64392. Component* targetComp = 0;
  64393. if (scopeName == RelativeCoordinate::Strings::parent)
  64394. targetComp = component.getParentComponent();
  64395. else
  64396. targetComp = findSiblingComponent (scopeName);
  64397. if (targetComp != 0)
  64398. visitor.visit (ComponentScope (*targetComp));
  64399. else
  64400. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64401. }
  64402. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64403. {
  64404. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64405. }
  64406. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64407. {
  64408. Component* const parent = component.getParentComponent();
  64409. if (parent != 0)
  64410. {
  64411. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64412. {
  64413. Component* const c = parent->getChildComponent(i);
  64414. if (c->getComponentID() == componentID)
  64415. return c;
  64416. }
  64417. }
  64418. return 0;
  64419. }
  64420. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64421. {
  64422. const MarkerList::Marker* marker = 0;
  64423. Component* const parent = component.getParentComponent();
  64424. if (parent != 0)
  64425. {
  64426. list = parent->getMarkers (true);
  64427. if (list != 0)
  64428. marker = list->getMarker (name);
  64429. if (marker == 0)
  64430. {
  64431. list = parent->getMarkers (false);
  64432. if (list != 0)
  64433. marker = list->getMarker (name);
  64434. }
  64435. }
  64436. return marker;
  64437. }
  64438. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64439. {
  64440. public:
  64441. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64442. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64443. {
  64444. }
  64445. const Expression getSymbolValue (const String& symbol) const
  64446. {
  64447. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  64448. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  64449. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  64450. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  64451. {
  64452. positioner.registerComponentListener (component);
  64453. }
  64454. else
  64455. {
  64456. MarkerList* list;
  64457. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64458. if (marker != 0)
  64459. {
  64460. positioner.registerMarkerListListener (list);
  64461. }
  64462. else
  64463. {
  64464. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64465. positioner.registerMarkerListListener (component.getMarkers (true));
  64466. positioner.registerMarkerListListener (component.getMarkers (false));
  64467. ok = false;
  64468. }
  64469. }
  64470. return ComponentScope::getSymbolValue (symbol);
  64471. }
  64472. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64473. {
  64474. Component* targetComp = 0;
  64475. if (scopeName == RelativeCoordinate::Strings::parent)
  64476. targetComp = component.getParentComponent();
  64477. else
  64478. targetComp = findSiblingComponent (scopeName);
  64479. if (targetComp != 0)
  64480. {
  64481. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  64482. }
  64483. else
  64484. {
  64485. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  64486. Component* const parent = component.getParentComponent();
  64487. if (parent != 0)
  64488. positioner.registerComponentListener (*parent);
  64489. positioner.registerComponentListener (component);
  64490. ok = false;
  64491. }
  64492. }
  64493. private:
  64494. RelativeCoordinatePositionerBase& positioner;
  64495. bool& ok;
  64496. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  64497. };
  64498. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64499. : Component::Positioner (component_), registeredOk (false)
  64500. {
  64501. }
  64502. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64503. {
  64504. unregisterListeners();
  64505. }
  64506. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64507. {
  64508. apply();
  64509. }
  64510. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64511. {
  64512. apply();
  64513. }
  64514. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  64515. {
  64516. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  64517. apply();
  64518. }
  64519. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64520. {
  64521. jassert (sourceComponents.contains (&component));
  64522. sourceComponents.removeValue (&component);
  64523. registeredOk = false;
  64524. }
  64525. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64526. {
  64527. apply();
  64528. }
  64529. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64530. {
  64531. jassert (sourceMarkerLists.contains (markerList));
  64532. sourceMarkerLists.removeValue (markerList);
  64533. }
  64534. void RelativeCoordinatePositionerBase::apply()
  64535. {
  64536. if (! registeredOk)
  64537. {
  64538. unregisterListeners();
  64539. registeredOk = registerCoordinates();
  64540. }
  64541. applyToComponentBounds();
  64542. }
  64543. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64544. {
  64545. bool ok = true;
  64546. DependencyFinderScope finderScope (getComponent(), *this, ok);
  64547. coord.getExpression().evaluate (finderScope);
  64548. return ok;
  64549. }
  64550. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64551. {
  64552. const bool ok = addCoordinate (point.x);
  64553. return addCoordinate (point.y) && ok;
  64554. }
  64555. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  64556. {
  64557. if (! sourceComponents.contains (&comp))
  64558. {
  64559. comp.addComponentListener (this);
  64560. sourceComponents.add (&comp);
  64561. }
  64562. }
  64563. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64564. {
  64565. if (list != 0 && ! sourceMarkerLists.contains (list))
  64566. {
  64567. list->addListener (this);
  64568. sourceMarkerLists.add (list);
  64569. }
  64570. }
  64571. void RelativeCoordinatePositionerBase::unregisterListeners()
  64572. {
  64573. int i;
  64574. for (i = sourceComponents.size(); --i >= 0;)
  64575. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64576. for (i = sourceMarkerLists.size(); --i >= 0;)
  64577. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64578. sourceComponents.clear();
  64579. sourceMarkerLists.clear();
  64580. }
  64581. END_JUCE_NAMESPACE
  64582. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64583. #endif
  64584. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64585. /*** Start of inlined file: juce_Colour.cpp ***/
  64586. BEGIN_JUCE_NAMESPACE
  64587. namespace ColourHelpers
  64588. {
  64589. uint8 floatAlphaToInt (const float alpha) throw()
  64590. {
  64591. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64592. }
  64593. void convertHSBtoRGB (float h, float s, float v,
  64594. uint8& r, uint8& g, uint8& b) throw()
  64595. {
  64596. v = jlimit (0.0f, 1.0f, v);
  64597. v *= 255.0f;
  64598. const uint8 intV = (uint8) roundToInt (v);
  64599. if (s <= 0)
  64600. {
  64601. r = intV;
  64602. g = intV;
  64603. b = intV;
  64604. }
  64605. else
  64606. {
  64607. s = jmin (1.0f, s);
  64608. h = jlimit (0.0f, 1.0f, h);
  64609. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64610. const float f = h - std::floor (h);
  64611. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64612. const float y = v * (1.0f - s * f);
  64613. const float z = v * (1.0f - (s * (1.0f - f)));
  64614. if (h < 1.0f)
  64615. {
  64616. r = intV;
  64617. g = (uint8) roundToInt (z);
  64618. b = x;
  64619. }
  64620. else if (h < 2.0f)
  64621. {
  64622. r = (uint8) roundToInt (y);
  64623. g = intV;
  64624. b = x;
  64625. }
  64626. else if (h < 3.0f)
  64627. {
  64628. r = x;
  64629. g = intV;
  64630. b = (uint8) roundToInt (z);
  64631. }
  64632. else if (h < 4.0f)
  64633. {
  64634. r = x;
  64635. g = (uint8) roundToInt (y);
  64636. b = intV;
  64637. }
  64638. else if (h < 5.0f)
  64639. {
  64640. r = (uint8) roundToInt (z);
  64641. g = x;
  64642. b = intV;
  64643. }
  64644. else if (h < 6.0f)
  64645. {
  64646. r = intV;
  64647. g = x;
  64648. b = (uint8) roundToInt (y);
  64649. }
  64650. else
  64651. {
  64652. r = 0;
  64653. g = 0;
  64654. b = 0;
  64655. }
  64656. }
  64657. }
  64658. }
  64659. Colour::Colour() throw()
  64660. : argb (0)
  64661. {
  64662. }
  64663. Colour::Colour (const Colour& other) throw()
  64664. : argb (other.argb)
  64665. {
  64666. }
  64667. Colour& Colour::operator= (const Colour& other) throw()
  64668. {
  64669. argb = other.argb;
  64670. return *this;
  64671. }
  64672. bool Colour::operator== (const Colour& other) const throw()
  64673. {
  64674. return argb.getARGB() == other.argb.getARGB();
  64675. }
  64676. bool Colour::operator!= (const Colour& other) const throw()
  64677. {
  64678. return argb.getARGB() != other.argb.getARGB();
  64679. }
  64680. Colour::Colour (const uint32 argb_) throw()
  64681. : argb (argb_)
  64682. {
  64683. }
  64684. Colour::Colour (const uint8 red,
  64685. const uint8 green,
  64686. const uint8 blue) throw()
  64687. {
  64688. argb.setARGB (0xff, red, green, blue);
  64689. }
  64690. const Colour Colour::fromRGB (const uint8 red,
  64691. const uint8 green,
  64692. const uint8 blue) throw()
  64693. {
  64694. return Colour (red, green, blue);
  64695. }
  64696. Colour::Colour (const uint8 red,
  64697. const uint8 green,
  64698. const uint8 blue,
  64699. const uint8 alpha) throw()
  64700. {
  64701. argb.setARGB (alpha, red, green, blue);
  64702. }
  64703. const Colour Colour::fromRGBA (const uint8 red,
  64704. const uint8 green,
  64705. const uint8 blue,
  64706. const uint8 alpha) throw()
  64707. {
  64708. return Colour (red, green, blue, alpha);
  64709. }
  64710. Colour::Colour (const uint8 red,
  64711. const uint8 green,
  64712. const uint8 blue,
  64713. const float alpha) throw()
  64714. {
  64715. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64716. }
  64717. const Colour Colour::fromRGBAFloat (const uint8 red,
  64718. const uint8 green,
  64719. const uint8 blue,
  64720. const float alpha) throw()
  64721. {
  64722. return Colour (red, green, blue, alpha);
  64723. }
  64724. Colour::Colour (const float hue,
  64725. const float saturation,
  64726. const float brightness,
  64727. const float alpha) throw()
  64728. {
  64729. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64730. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64731. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64732. }
  64733. const Colour Colour::fromHSV (const float hue,
  64734. const float saturation,
  64735. const float brightness,
  64736. const float alpha) throw()
  64737. {
  64738. return Colour (hue, saturation, brightness, alpha);
  64739. }
  64740. Colour::Colour (const float hue,
  64741. const float saturation,
  64742. const float brightness,
  64743. const uint8 alpha) throw()
  64744. {
  64745. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64746. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64747. argb.setARGB (alpha, r, g, b);
  64748. }
  64749. Colour::~Colour() throw()
  64750. {
  64751. }
  64752. const PixelARGB Colour::getPixelARGB() const throw()
  64753. {
  64754. PixelARGB p (argb);
  64755. p.premultiply();
  64756. return p;
  64757. }
  64758. uint32 Colour::getARGB() const throw()
  64759. {
  64760. return argb.getARGB();
  64761. }
  64762. bool Colour::isTransparent() const throw()
  64763. {
  64764. return getAlpha() == 0;
  64765. }
  64766. bool Colour::isOpaque() const throw()
  64767. {
  64768. return getAlpha() == 0xff;
  64769. }
  64770. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64771. {
  64772. PixelARGB newCol (argb);
  64773. newCol.setAlpha (newAlpha);
  64774. return Colour (newCol.getARGB());
  64775. }
  64776. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64777. {
  64778. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64779. PixelARGB newCol (argb);
  64780. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64781. return Colour (newCol.getARGB());
  64782. }
  64783. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64784. {
  64785. jassert (alphaMultiplier >= 0);
  64786. PixelARGB newCol (argb);
  64787. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64788. return Colour (newCol.getARGB());
  64789. }
  64790. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64791. {
  64792. const int destAlpha = getAlpha();
  64793. if (destAlpha > 0)
  64794. {
  64795. const int invA = 0xff - (int) src.getAlpha();
  64796. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64797. if (resA > 0)
  64798. {
  64799. const int da = (invA * destAlpha) / resA;
  64800. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64801. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64802. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64803. (uint8) resA);
  64804. }
  64805. return *this;
  64806. }
  64807. else
  64808. {
  64809. return src;
  64810. }
  64811. }
  64812. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64813. {
  64814. if (proportionOfOther <= 0)
  64815. return *this;
  64816. if (proportionOfOther >= 1.0f)
  64817. return other;
  64818. PixelARGB c1 (getPixelARGB());
  64819. const PixelARGB c2 (other.getPixelARGB());
  64820. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64821. c1.unpremultiply();
  64822. return Colour (c1.getARGB());
  64823. }
  64824. float Colour::getFloatRed() const throw()
  64825. {
  64826. return getRed() / 255.0f;
  64827. }
  64828. float Colour::getFloatGreen() const throw()
  64829. {
  64830. return getGreen() / 255.0f;
  64831. }
  64832. float Colour::getFloatBlue() const throw()
  64833. {
  64834. return getBlue() / 255.0f;
  64835. }
  64836. float Colour::getFloatAlpha() const throw()
  64837. {
  64838. return getAlpha() / 255.0f;
  64839. }
  64840. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64841. {
  64842. const int r = getRed();
  64843. const int g = getGreen();
  64844. const int b = getBlue();
  64845. const int hi = jmax (r, g, b);
  64846. const int lo = jmin (r, g, b);
  64847. if (hi != 0)
  64848. {
  64849. s = (hi - lo) / (float) hi;
  64850. if (s != 0)
  64851. {
  64852. const float invDiff = 1.0f / (hi - lo);
  64853. const float red = (hi - r) * invDiff;
  64854. const float green = (hi - g) * invDiff;
  64855. const float blue = (hi - b) * invDiff;
  64856. if (r == hi)
  64857. h = blue - green;
  64858. else if (g == hi)
  64859. h = 2.0f + red - blue;
  64860. else
  64861. h = 4.0f + green - red;
  64862. h *= 1.0f / 6.0f;
  64863. if (h < 0)
  64864. ++h;
  64865. }
  64866. else
  64867. {
  64868. h = 0;
  64869. }
  64870. }
  64871. else
  64872. {
  64873. s = 0;
  64874. h = 0;
  64875. }
  64876. v = hi / 255.0f;
  64877. }
  64878. float Colour::getHue() const throw()
  64879. {
  64880. float h, s, b;
  64881. getHSB (h, s, b);
  64882. return h;
  64883. }
  64884. const Colour Colour::withHue (const float hue) const throw()
  64885. {
  64886. float h, s, b;
  64887. getHSB (h, s, b);
  64888. return Colour (hue, s, b, getAlpha());
  64889. }
  64890. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64891. {
  64892. float h, s, b;
  64893. getHSB (h, s, b);
  64894. h += amountToRotate;
  64895. h -= std::floor (h);
  64896. return Colour (h, s, b, getAlpha());
  64897. }
  64898. float Colour::getSaturation() const throw()
  64899. {
  64900. float h, s, b;
  64901. getHSB (h, s, b);
  64902. return s;
  64903. }
  64904. const Colour Colour::withSaturation (const float saturation) const throw()
  64905. {
  64906. float h, s, b;
  64907. getHSB (h, s, b);
  64908. return Colour (h, saturation, b, getAlpha());
  64909. }
  64910. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64911. {
  64912. float h, s, b;
  64913. getHSB (h, s, b);
  64914. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64915. }
  64916. float Colour::getBrightness() const throw()
  64917. {
  64918. float h, s, b;
  64919. getHSB (h, s, b);
  64920. return b;
  64921. }
  64922. const Colour Colour::withBrightness (const float brightness) const throw()
  64923. {
  64924. float h, s, b;
  64925. getHSB (h, s, b);
  64926. return Colour (h, s, brightness, getAlpha());
  64927. }
  64928. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64929. {
  64930. float h, s, b;
  64931. getHSB (h, s, b);
  64932. b *= amount;
  64933. if (b > 1.0f)
  64934. b = 1.0f;
  64935. return Colour (h, s, b, getAlpha());
  64936. }
  64937. const Colour Colour::brighter (float amount) const throw()
  64938. {
  64939. amount = 1.0f / (1.0f + amount);
  64940. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64941. (uint8) (255 - (amount * (255 - getGreen()))),
  64942. (uint8) (255 - (amount * (255 - getBlue()))),
  64943. getAlpha());
  64944. }
  64945. const Colour Colour::darker (float amount) const throw()
  64946. {
  64947. amount = 1.0f / (1.0f + amount);
  64948. return Colour ((uint8) (amount * getRed()),
  64949. (uint8) (amount * getGreen()),
  64950. (uint8) (amount * getBlue()),
  64951. getAlpha());
  64952. }
  64953. const Colour Colour::greyLevel (const float brightness) throw()
  64954. {
  64955. const uint8 level
  64956. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64957. return Colour (level, level, level);
  64958. }
  64959. const Colour Colour::contrasting (const float amount) const throw()
  64960. {
  64961. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64962. ? Colours::black
  64963. : Colours::white).withAlpha (amount));
  64964. }
  64965. const Colour Colour::contrasting (const Colour& colour1,
  64966. const Colour& colour2) throw()
  64967. {
  64968. const float b1 = colour1.getBrightness();
  64969. const float b2 = colour2.getBrightness();
  64970. float best = 0.0f;
  64971. float bestDist = 0.0f;
  64972. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64973. {
  64974. const float d1 = std::abs (i - b1);
  64975. const float d2 = std::abs (i - b2);
  64976. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64977. if (dist > bestDist)
  64978. {
  64979. best = i;
  64980. bestDist = dist;
  64981. }
  64982. }
  64983. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64984. .withBrightness (best);
  64985. }
  64986. const String Colour::toString() const
  64987. {
  64988. return String::toHexString ((int) argb.getARGB());
  64989. }
  64990. const Colour Colour::fromString (const String& encodedColourString)
  64991. {
  64992. return Colour ((uint32) encodedColourString.getHexValue32());
  64993. }
  64994. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64995. {
  64996. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64997. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64998. .toUpperCase();
  64999. }
  65000. END_JUCE_NAMESPACE
  65001. /*** End of inlined file: juce_Colour.cpp ***/
  65002. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65003. BEGIN_JUCE_NAMESPACE
  65004. ColourGradient::ColourGradient() throw()
  65005. {
  65006. #if JUCE_DEBUG
  65007. point1.setX (987654.0f);
  65008. #endif
  65009. }
  65010. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65011. const Colour& colour2, const float x2_, const float y2_,
  65012. const bool isRadial_)
  65013. : point1 (x1_, y1_),
  65014. point2 (x2_, y2_),
  65015. isRadial (isRadial_)
  65016. {
  65017. colours.add (ColourPoint (0.0, colour1));
  65018. colours.add (ColourPoint (1.0, colour2));
  65019. }
  65020. ColourGradient::~ColourGradient()
  65021. {
  65022. }
  65023. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65024. {
  65025. return point1 == other.point1 && point2 == other.point2
  65026. && isRadial == other.isRadial
  65027. && colours == other.colours;
  65028. }
  65029. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65030. {
  65031. return ! operator== (other);
  65032. }
  65033. void ColourGradient::clearColours()
  65034. {
  65035. colours.clear();
  65036. }
  65037. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65038. {
  65039. // must be within the two end-points
  65040. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65041. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65042. int i;
  65043. for (i = 0; i < colours.size(); ++i)
  65044. if (colours.getReference(i).position > pos)
  65045. break;
  65046. colours.insert (i, ColourPoint (pos, colour));
  65047. return i;
  65048. }
  65049. void ColourGradient::removeColour (int index)
  65050. {
  65051. jassert (index > 0 && index < colours.size() - 1);
  65052. colours.remove (index);
  65053. }
  65054. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65055. {
  65056. for (int i = 0; i < colours.size(); ++i)
  65057. {
  65058. Colour& c = colours.getReference(i).colour;
  65059. c = c.withMultipliedAlpha (multiplier);
  65060. }
  65061. }
  65062. int ColourGradient::getNumColours() const throw()
  65063. {
  65064. return colours.size();
  65065. }
  65066. double ColourGradient::getColourPosition (const int index) const throw()
  65067. {
  65068. if (isPositiveAndBelow (index, colours.size()))
  65069. return colours.getReference (index).position;
  65070. return 0;
  65071. }
  65072. const Colour ColourGradient::getColour (const int index) const throw()
  65073. {
  65074. if (isPositiveAndBelow (index, colours.size()))
  65075. return colours.getReference (index).colour;
  65076. return Colour();
  65077. }
  65078. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65079. {
  65080. if (isPositiveAndBelow (index, colours.size()))
  65081. colours.getReference (index).colour = newColour;
  65082. }
  65083. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65084. {
  65085. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65086. if (position <= 0 || colours.size() <= 1)
  65087. return colours.getReference(0).colour;
  65088. int i = colours.size() - 1;
  65089. while (position < colours.getReference(i).position)
  65090. --i;
  65091. const ColourPoint& p1 = colours.getReference (i);
  65092. if (i >= colours.size() - 1)
  65093. return p1.colour;
  65094. const ColourPoint& p2 = colours.getReference (i + 1);
  65095. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65096. }
  65097. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65098. {
  65099. #if JUCE_DEBUG
  65100. // trying to use the object without setting its co-ordinates? Have a careful read of
  65101. // the comments for the constructors.
  65102. jassert (point1.getX() != 987654.0f);
  65103. #endif
  65104. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65105. 3 * (int) point1.transformedBy (transform)
  65106. .getDistanceFrom (point2.transformedBy (transform)));
  65107. lookupTable.malloc (numEntries);
  65108. if (colours.size() >= 2)
  65109. {
  65110. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65111. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65112. int index = 0;
  65113. for (int j = 1; j < colours.size(); ++j)
  65114. {
  65115. const ColourPoint& p = colours.getReference (j);
  65116. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65117. const PixelARGB pix2 (p.colour.getPixelARGB());
  65118. for (int i = 0; i < numToDo; ++i)
  65119. {
  65120. jassert (index >= 0 && index < numEntries);
  65121. lookupTable[index] = pix1;
  65122. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65123. ++index;
  65124. }
  65125. pix1 = pix2;
  65126. }
  65127. while (index < numEntries)
  65128. lookupTable [index++] = pix1;
  65129. }
  65130. else
  65131. {
  65132. jassertfalse; // no colours specified!
  65133. }
  65134. return numEntries;
  65135. }
  65136. bool ColourGradient::isOpaque() const throw()
  65137. {
  65138. for (int i = 0; i < colours.size(); ++i)
  65139. if (! colours.getReference(i).colour.isOpaque())
  65140. return false;
  65141. return true;
  65142. }
  65143. bool ColourGradient::isInvisible() const throw()
  65144. {
  65145. for (int i = 0; i < colours.size(); ++i)
  65146. if (! colours.getReference(i).colour.isTransparent())
  65147. return false;
  65148. return true;
  65149. }
  65150. END_JUCE_NAMESPACE
  65151. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65152. /*** Start of inlined file: juce_Colours.cpp ***/
  65153. BEGIN_JUCE_NAMESPACE
  65154. const Colour Colours::transparentBlack (0);
  65155. const Colour Colours::transparentWhite (0x00ffffff);
  65156. const Colour Colours::aliceblue (0xfff0f8ff);
  65157. const Colour Colours::antiquewhite (0xfffaebd7);
  65158. const Colour Colours::aqua (0xff00ffff);
  65159. const Colour Colours::aquamarine (0xff7fffd4);
  65160. const Colour Colours::azure (0xfff0ffff);
  65161. const Colour Colours::beige (0xfff5f5dc);
  65162. const Colour Colours::bisque (0xffffe4c4);
  65163. const Colour Colours::black (0xff000000);
  65164. const Colour Colours::blanchedalmond (0xffffebcd);
  65165. const Colour Colours::blue (0xff0000ff);
  65166. const Colour Colours::blueviolet (0xff8a2be2);
  65167. const Colour Colours::brown (0xffa52a2a);
  65168. const Colour Colours::burlywood (0xffdeb887);
  65169. const Colour Colours::cadetblue (0xff5f9ea0);
  65170. const Colour Colours::chartreuse (0xff7fff00);
  65171. const Colour Colours::chocolate (0xffd2691e);
  65172. const Colour Colours::coral (0xffff7f50);
  65173. const Colour Colours::cornflowerblue (0xff6495ed);
  65174. const Colour Colours::cornsilk (0xfffff8dc);
  65175. const Colour Colours::crimson (0xffdc143c);
  65176. const Colour Colours::cyan (0xff00ffff);
  65177. const Colour Colours::darkblue (0xff00008b);
  65178. const Colour Colours::darkcyan (0xff008b8b);
  65179. const Colour Colours::darkgoldenrod (0xffb8860b);
  65180. const Colour Colours::darkgrey (0xff555555);
  65181. const Colour Colours::darkgreen (0xff006400);
  65182. const Colour Colours::darkkhaki (0xffbdb76b);
  65183. const Colour Colours::darkmagenta (0xff8b008b);
  65184. const Colour Colours::darkolivegreen (0xff556b2f);
  65185. const Colour Colours::darkorange (0xffff8c00);
  65186. const Colour Colours::darkorchid (0xff9932cc);
  65187. const Colour Colours::darkred (0xff8b0000);
  65188. const Colour Colours::darksalmon (0xffe9967a);
  65189. const Colour Colours::darkseagreen (0xff8fbc8f);
  65190. const Colour Colours::darkslateblue (0xff483d8b);
  65191. const Colour Colours::darkslategrey (0xff2f4f4f);
  65192. const Colour Colours::darkturquoise (0xff00ced1);
  65193. const Colour Colours::darkviolet (0xff9400d3);
  65194. const Colour Colours::deeppink (0xffff1493);
  65195. const Colour Colours::deepskyblue (0xff00bfff);
  65196. const Colour Colours::dimgrey (0xff696969);
  65197. const Colour Colours::dodgerblue (0xff1e90ff);
  65198. const Colour Colours::firebrick (0xffb22222);
  65199. const Colour Colours::floralwhite (0xfffffaf0);
  65200. const Colour Colours::forestgreen (0xff228b22);
  65201. const Colour Colours::fuchsia (0xffff00ff);
  65202. const Colour Colours::gainsboro (0xffdcdcdc);
  65203. const Colour Colours::gold (0xffffd700);
  65204. const Colour Colours::goldenrod (0xffdaa520);
  65205. const Colour Colours::grey (0xff808080);
  65206. const Colour Colours::green (0xff008000);
  65207. const Colour Colours::greenyellow (0xffadff2f);
  65208. const Colour Colours::honeydew (0xfff0fff0);
  65209. const Colour Colours::hotpink (0xffff69b4);
  65210. const Colour Colours::indianred (0xffcd5c5c);
  65211. const Colour Colours::indigo (0xff4b0082);
  65212. const Colour Colours::ivory (0xfffffff0);
  65213. const Colour Colours::khaki (0xfff0e68c);
  65214. const Colour Colours::lavender (0xffe6e6fa);
  65215. const Colour Colours::lavenderblush (0xfffff0f5);
  65216. const Colour Colours::lemonchiffon (0xfffffacd);
  65217. const Colour Colours::lightblue (0xffadd8e6);
  65218. const Colour Colours::lightcoral (0xfff08080);
  65219. const Colour Colours::lightcyan (0xffe0ffff);
  65220. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65221. const Colour Colours::lightgreen (0xff90ee90);
  65222. const Colour Colours::lightgrey (0xffd3d3d3);
  65223. const Colour Colours::lightpink (0xffffb6c1);
  65224. const Colour Colours::lightsalmon (0xffffa07a);
  65225. const Colour Colours::lightseagreen (0xff20b2aa);
  65226. const Colour Colours::lightskyblue (0xff87cefa);
  65227. const Colour Colours::lightslategrey (0xff778899);
  65228. const Colour Colours::lightsteelblue (0xffb0c4de);
  65229. const Colour Colours::lightyellow (0xffffffe0);
  65230. const Colour Colours::lime (0xff00ff00);
  65231. const Colour Colours::limegreen (0xff32cd32);
  65232. const Colour Colours::linen (0xfffaf0e6);
  65233. const Colour Colours::magenta (0xffff00ff);
  65234. const Colour Colours::maroon (0xff800000);
  65235. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65236. const Colour Colours::mediumblue (0xff0000cd);
  65237. const Colour Colours::mediumorchid (0xffba55d3);
  65238. const Colour Colours::mediumpurple (0xff9370db);
  65239. const Colour Colours::mediumseagreen (0xff3cb371);
  65240. const Colour Colours::mediumslateblue (0xff7b68ee);
  65241. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65242. const Colour Colours::mediumturquoise (0xff48d1cc);
  65243. const Colour Colours::mediumvioletred (0xffc71585);
  65244. const Colour Colours::midnightblue (0xff191970);
  65245. const Colour Colours::mintcream (0xfff5fffa);
  65246. const Colour Colours::mistyrose (0xffffe4e1);
  65247. const Colour Colours::navajowhite (0xffffdead);
  65248. const Colour Colours::navy (0xff000080);
  65249. const Colour Colours::oldlace (0xfffdf5e6);
  65250. const Colour Colours::olive (0xff808000);
  65251. const Colour Colours::olivedrab (0xff6b8e23);
  65252. const Colour Colours::orange (0xffffa500);
  65253. const Colour Colours::orangered (0xffff4500);
  65254. const Colour Colours::orchid (0xffda70d6);
  65255. const Colour Colours::palegoldenrod (0xffeee8aa);
  65256. const Colour Colours::palegreen (0xff98fb98);
  65257. const Colour Colours::paleturquoise (0xffafeeee);
  65258. const Colour Colours::palevioletred (0xffdb7093);
  65259. const Colour Colours::papayawhip (0xffffefd5);
  65260. const Colour Colours::peachpuff (0xffffdab9);
  65261. const Colour Colours::peru (0xffcd853f);
  65262. const Colour Colours::pink (0xffffc0cb);
  65263. const Colour Colours::plum (0xffdda0dd);
  65264. const Colour Colours::powderblue (0xffb0e0e6);
  65265. const Colour Colours::purple (0xff800080);
  65266. const Colour Colours::red (0xffff0000);
  65267. const Colour Colours::rosybrown (0xffbc8f8f);
  65268. const Colour Colours::royalblue (0xff4169e1);
  65269. const Colour Colours::saddlebrown (0xff8b4513);
  65270. const Colour Colours::salmon (0xfffa8072);
  65271. const Colour Colours::sandybrown (0xfff4a460);
  65272. const Colour Colours::seagreen (0xff2e8b57);
  65273. const Colour Colours::seashell (0xfffff5ee);
  65274. const Colour Colours::sienna (0xffa0522d);
  65275. const Colour Colours::silver (0xffc0c0c0);
  65276. const Colour Colours::skyblue (0xff87ceeb);
  65277. const Colour Colours::slateblue (0xff6a5acd);
  65278. const Colour Colours::slategrey (0xff708090);
  65279. const Colour Colours::snow (0xfffffafa);
  65280. const Colour Colours::springgreen (0xff00ff7f);
  65281. const Colour Colours::steelblue (0xff4682b4);
  65282. const Colour Colours::tan (0xffd2b48c);
  65283. const Colour Colours::teal (0xff008080);
  65284. const Colour Colours::thistle (0xffd8bfd8);
  65285. const Colour Colours::tomato (0xffff6347);
  65286. const Colour Colours::turquoise (0xff40e0d0);
  65287. const Colour Colours::violet (0xffee82ee);
  65288. const Colour Colours::wheat (0xfff5deb3);
  65289. const Colour Colours::white (0xffffffff);
  65290. const Colour Colours::whitesmoke (0xfff5f5f5);
  65291. const Colour Colours::yellow (0xffffff00);
  65292. const Colour Colours::yellowgreen (0xff9acd32);
  65293. const Colour Colours::findColourForName (const String& colourName,
  65294. const Colour& defaultColour)
  65295. {
  65296. static const int presets[] =
  65297. {
  65298. // (first value is the string's hashcode, second is ARGB)
  65299. 0x05978fff, 0xff000000, /* black */
  65300. 0x06bdcc29, 0xffffffff, /* white */
  65301. 0x002e305a, 0xff0000ff, /* blue */
  65302. 0x00308adf, 0xff808080, /* grey */
  65303. 0x05e0cf03, 0xff008000, /* green */
  65304. 0x0001b891, 0xffff0000, /* red */
  65305. 0xd43c6474, 0xffffff00, /* yellow */
  65306. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65307. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65308. 0x002dcebc, 0xff00ffff, /* aqua */
  65309. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65310. 0x0590228f, 0xfff0ffff, /* azure */
  65311. 0x05947fe4, 0xfff5f5dc, /* beige */
  65312. 0xad388e35, 0xffffe4c4, /* bisque */
  65313. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65314. 0x39129959, 0xff8a2be2, /* blueviolet */
  65315. 0x059a8136, 0xffa52a2a, /* brown */
  65316. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65317. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65318. 0x6b748956, 0xff7fff00, /* chartreuse */
  65319. 0x2903623c, 0xffd2691e, /* chocolate */
  65320. 0x05a74431, 0xffff7f50, /* coral */
  65321. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65322. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65323. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65324. 0x002ed323, 0xff00ffff, /* cyan */
  65325. 0x67cc74d0, 0xff00008b, /* darkblue */
  65326. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65327. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65328. 0x67cecf55, 0xff555555, /* darkgrey */
  65329. 0x920b194d, 0xff006400, /* darkgreen */
  65330. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65331. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65332. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65333. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65334. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65335. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65336. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65337. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65338. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65339. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65340. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65341. 0xc8769375, 0xff9400d3, /* darkviolet */
  65342. 0x25832862, 0xffff1493, /* deeppink */
  65343. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65344. 0x634c8b67, 0xff696969, /* dimgrey */
  65345. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65346. 0xef19e3cb, 0xffb22222, /* firebrick */
  65347. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65348. 0xd086fd06, 0xff228b22, /* forestgreen */
  65349. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65350. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65351. 0x00308060, 0xffffd700, /* gold */
  65352. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65353. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65354. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65355. 0x41892743, 0xffff69b4, /* hotpink */
  65356. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65357. 0xb969fed2, 0xff4b0082, /* indigo */
  65358. 0x05fef6a9, 0xfffffff0, /* ivory */
  65359. 0x06149302, 0xfff0e68c, /* khaki */
  65360. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65361. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65362. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65363. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65364. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65365. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65366. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65367. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65368. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65369. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65370. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65371. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65372. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65373. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65374. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65375. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65376. 0x0032afd5, 0xff00ff00, /* lime */
  65377. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65378. 0x06234efa, 0xfffaf0e6, /* linen */
  65379. 0x316858a9, 0xffff00ff, /* magenta */
  65380. 0xbf8ca470, 0xff800000, /* maroon */
  65381. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65382. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65383. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65384. 0x07556b71, 0xff9370db, /* mediumpurple */
  65385. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65386. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65387. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65388. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65389. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65390. 0x168eb32a, 0xff191970, /* midnightblue */
  65391. 0x4306b960, 0xfff5fffa, /* mintcream */
  65392. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65393. 0xe97218a6, 0xffffdead, /* navajowhite */
  65394. 0x00337bb6, 0xff000080, /* navy */
  65395. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65396. 0x064ee1db, 0xff808000, /* olive */
  65397. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65398. 0xc3de262e, 0xffffa500, /* orange */
  65399. 0x58bebba3, 0xffff4500, /* orangered */
  65400. 0xc3def8a3, 0xffda70d6, /* orchid */
  65401. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65402. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65403. 0x74022737, 0xffafeeee, /* paleturquoise */
  65404. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65405. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65406. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65407. 0x003472f8, 0xffcd853f, /* peru */
  65408. 0x00348176, 0xffffc0cb, /* pink */
  65409. 0x00348d94, 0xffdda0dd, /* plum */
  65410. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65411. 0xc5c507bc, 0xff800080, /* purple */
  65412. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65413. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65414. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65415. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65416. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65417. 0x34636c14, 0xff2e8b57, /* seagreen */
  65418. 0x3507fb41, 0xfffff5ee, /* seashell */
  65419. 0xca348772, 0xffa0522d, /* sienna */
  65420. 0xca37d30d, 0xffc0c0c0, /* silver */
  65421. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65422. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65423. 0x44ab37f8, 0xff708090, /* slategrey */
  65424. 0x0035f183, 0xfffffafa, /* snow */
  65425. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65426. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65427. 0x0001bfa1, 0xffd2b48c, /* tan */
  65428. 0x0036425c, 0xff008080, /* teal */
  65429. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65430. 0xcc41600a, 0xffff6347, /* tomato */
  65431. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65432. 0xcf57947f, 0xffee82ee, /* violet */
  65433. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65434. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65435. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65436. };
  65437. const int hash = colourName.trim().toLowerCase().hashCode();
  65438. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65439. if (presets [i] == hash)
  65440. return Colour (presets [i + 1]);
  65441. return defaultColour;
  65442. }
  65443. END_JUCE_NAMESPACE
  65444. /*** End of inlined file: juce_Colours.cpp ***/
  65445. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65446. BEGIN_JUCE_NAMESPACE
  65447. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65448. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65449. const Path& path, const AffineTransform& transform)
  65450. : bounds (bounds_),
  65451. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65452. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65453. needToCheckEmptinesss (true)
  65454. {
  65455. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65456. int* t = table;
  65457. for (int i = bounds.getHeight(); --i >= 0;)
  65458. {
  65459. *t = 0;
  65460. t += lineStrideElements;
  65461. }
  65462. const int topLimit = bounds.getY() << 8;
  65463. const int heightLimit = bounds.getHeight() << 8;
  65464. const int leftLimit = bounds.getX() << 8;
  65465. const int rightLimit = bounds.getRight() << 8;
  65466. PathFlatteningIterator iter (path, transform);
  65467. while (iter.next())
  65468. {
  65469. int y1 = roundToInt (iter.y1 * 256.0f);
  65470. int y2 = roundToInt (iter.y2 * 256.0f);
  65471. if (y1 != y2)
  65472. {
  65473. y1 -= topLimit;
  65474. y2 -= topLimit;
  65475. const int startY = y1;
  65476. int direction = -1;
  65477. if (y1 > y2)
  65478. {
  65479. swapVariables (y1, y2);
  65480. direction = 1;
  65481. }
  65482. if (y1 < 0)
  65483. y1 = 0;
  65484. if (y2 > heightLimit)
  65485. y2 = heightLimit;
  65486. if (y1 < y2)
  65487. {
  65488. const double startX = 256.0f * iter.x1;
  65489. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65490. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65491. do
  65492. {
  65493. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65494. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65495. if (x < leftLimit)
  65496. x = leftLimit;
  65497. else if (x >= rightLimit)
  65498. x = rightLimit - 1;
  65499. addEdgePoint (x, y1 >> 8, direction * step);
  65500. y1 += step;
  65501. }
  65502. while (y1 < y2);
  65503. }
  65504. }
  65505. }
  65506. sanitiseLevels (path.isUsingNonZeroWinding());
  65507. }
  65508. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65509. : bounds (rectangleToAdd),
  65510. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65511. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65512. needToCheckEmptinesss (true)
  65513. {
  65514. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65515. table[0] = 0;
  65516. const int x1 = rectangleToAdd.getX() << 8;
  65517. const int x2 = rectangleToAdd.getRight() << 8;
  65518. int* t = table;
  65519. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65520. {
  65521. t[0] = 2;
  65522. t[1] = x1;
  65523. t[2] = 255;
  65524. t[3] = x2;
  65525. t[4] = 0;
  65526. t += lineStrideElements;
  65527. }
  65528. }
  65529. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65530. : bounds (rectanglesToAdd.getBounds()),
  65531. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65532. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65533. needToCheckEmptinesss (true)
  65534. {
  65535. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65536. int* t = table;
  65537. for (int i = bounds.getHeight(); --i >= 0;)
  65538. {
  65539. *t = 0;
  65540. t += lineStrideElements;
  65541. }
  65542. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65543. {
  65544. const Rectangle<int>* const r = iter.getRectangle();
  65545. const int x1 = r->getX() << 8;
  65546. const int x2 = r->getRight() << 8;
  65547. int y = r->getY() - bounds.getY();
  65548. for (int j = r->getHeight(); --j >= 0;)
  65549. {
  65550. addEdgePoint (x1, y, 255);
  65551. addEdgePoint (x2, y, -255);
  65552. ++y;
  65553. }
  65554. }
  65555. sanitiseLevels (true);
  65556. }
  65557. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65558. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65559. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65560. 2 + (int) rectangleToAdd.getWidth(),
  65561. 2 + (int) rectangleToAdd.getHeight())),
  65562. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65563. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65564. needToCheckEmptinesss (true)
  65565. {
  65566. jassert (! rectangleToAdd.isEmpty());
  65567. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65568. table[0] = 0;
  65569. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65570. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65571. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65572. jassert (y1 < 256);
  65573. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65574. if (x2 <= x1 || y2 <= y1)
  65575. {
  65576. bounds.setHeight (0);
  65577. return;
  65578. }
  65579. int lineY = 0;
  65580. int* t = table;
  65581. if ((y1 >> 8) == (y2 >> 8))
  65582. {
  65583. t[0] = 2;
  65584. t[1] = x1;
  65585. t[2] = y2 - y1;
  65586. t[3] = x2;
  65587. t[4] = 0;
  65588. ++lineY;
  65589. t += lineStrideElements;
  65590. }
  65591. else
  65592. {
  65593. t[0] = 2;
  65594. t[1] = x1;
  65595. t[2] = 255 - (y1 & 255);
  65596. t[3] = x2;
  65597. t[4] = 0;
  65598. ++lineY;
  65599. t += lineStrideElements;
  65600. while (lineY < (y2 >> 8))
  65601. {
  65602. t[0] = 2;
  65603. t[1] = x1;
  65604. t[2] = 255;
  65605. t[3] = x2;
  65606. t[4] = 0;
  65607. ++lineY;
  65608. t += lineStrideElements;
  65609. }
  65610. jassert (lineY < bounds.getHeight());
  65611. t[0] = 2;
  65612. t[1] = x1;
  65613. t[2] = y2 & 255;
  65614. t[3] = x2;
  65615. t[4] = 0;
  65616. ++lineY;
  65617. t += lineStrideElements;
  65618. }
  65619. while (lineY < bounds.getHeight())
  65620. {
  65621. t[0] = 0;
  65622. t += lineStrideElements;
  65623. ++lineY;
  65624. }
  65625. }
  65626. EdgeTable::EdgeTable (const EdgeTable& other)
  65627. {
  65628. operator= (other);
  65629. }
  65630. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65631. {
  65632. bounds = other.bounds;
  65633. maxEdgesPerLine = other.maxEdgesPerLine;
  65634. lineStrideElements = other.lineStrideElements;
  65635. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65636. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65637. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65638. return *this;
  65639. }
  65640. EdgeTable::~EdgeTable()
  65641. {
  65642. }
  65643. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65644. {
  65645. while (--numLines >= 0)
  65646. {
  65647. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65648. src += srcLineStride;
  65649. dest += destLineStride;
  65650. }
  65651. }
  65652. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65653. {
  65654. // Convert the table from relative windings to absolute levels..
  65655. int* lineStart = table;
  65656. for (int i = bounds.getHeight(); --i >= 0;)
  65657. {
  65658. int* line = lineStart;
  65659. lineStart += lineStrideElements;
  65660. int num = *line;
  65661. if (num == 0)
  65662. continue;
  65663. int level = 0;
  65664. if (useNonZeroWinding)
  65665. {
  65666. while (--num > 0)
  65667. {
  65668. line += 2;
  65669. level += *line;
  65670. int corrected = abs (level);
  65671. if (corrected >> 8)
  65672. corrected = 255;
  65673. *line = corrected;
  65674. }
  65675. }
  65676. else
  65677. {
  65678. while (--num > 0)
  65679. {
  65680. line += 2;
  65681. level += *line;
  65682. int corrected = abs (level);
  65683. if (corrected >> 8)
  65684. {
  65685. corrected &= 511;
  65686. if (corrected >> 8)
  65687. corrected = 511 - corrected;
  65688. }
  65689. *line = corrected;
  65690. }
  65691. }
  65692. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65693. }
  65694. }
  65695. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65696. {
  65697. if (newNumEdgesPerLine != maxEdgesPerLine)
  65698. {
  65699. maxEdgesPerLine = newNumEdgesPerLine;
  65700. jassert (bounds.getHeight() > 0);
  65701. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65702. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65703. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65704. table.swapWith (newTable);
  65705. lineStrideElements = newLineStrideElements;
  65706. }
  65707. }
  65708. void EdgeTable::optimiseTable()
  65709. {
  65710. int maxLineElements = 0;
  65711. for (int i = bounds.getHeight(); --i >= 0;)
  65712. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65713. remapTableForNumEdges (maxLineElements);
  65714. }
  65715. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65716. {
  65717. jassert (y >= 0 && y < bounds.getHeight());
  65718. int* line = table + lineStrideElements * y;
  65719. const int numPoints = line[0];
  65720. int n = numPoints << 1;
  65721. if (n > 0)
  65722. {
  65723. while (n > 0)
  65724. {
  65725. const int cx = line [n - 1];
  65726. if (cx <= x)
  65727. {
  65728. if (cx == x)
  65729. {
  65730. line [n] += winding;
  65731. return;
  65732. }
  65733. break;
  65734. }
  65735. n -= 2;
  65736. }
  65737. if (numPoints >= maxEdgesPerLine)
  65738. {
  65739. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65740. jassert (numPoints < maxEdgesPerLine);
  65741. line = table + lineStrideElements * y;
  65742. }
  65743. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65744. }
  65745. line [n + 1] = x;
  65746. line [n + 2] = winding;
  65747. line[0]++;
  65748. }
  65749. void EdgeTable::translate (float dx, const int dy) throw()
  65750. {
  65751. bounds.translate ((int) std::floor (dx), dy);
  65752. int* lineStart = table;
  65753. const int intDx = (int) (dx * 256.0f);
  65754. for (int i = bounds.getHeight(); --i >= 0;)
  65755. {
  65756. int* line = lineStart;
  65757. lineStart += lineStrideElements;
  65758. int num = *line++;
  65759. while (--num >= 0)
  65760. {
  65761. *line += intDx;
  65762. line += 2;
  65763. }
  65764. }
  65765. }
  65766. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65767. {
  65768. jassert (y >= 0 && y < bounds.getHeight());
  65769. int* dest = table + lineStrideElements * y;
  65770. if (dest[0] == 0)
  65771. return;
  65772. int otherNumPoints = *otherLine;
  65773. if (otherNumPoints == 0)
  65774. {
  65775. *dest = 0;
  65776. return;
  65777. }
  65778. const int right = bounds.getRight() << 8;
  65779. // optimise for the common case where our line lies entirely within a
  65780. // single pair of points, as happens when clipping to a simple rect.
  65781. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65782. {
  65783. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65784. return;
  65785. }
  65786. ++otherLine;
  65787. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65788. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65789. memcpy (temp, dest, lineSizeBytes);
  65790. const int* src1 = temp;
  65791. int srcNum1 = *src1++;
  65792. int x1 = *src1++;
  65793. const int* src2 = otherLine;
  65794. int srcNum2 = otherNumPoints;
  65795. int x2 = *src2++;
  65796. int destIndex = 0, destTotal = 0;
  65797. int level1 = 0, level2 = 0;
  65798. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65799. while (srcNum1 > 0 && srcNum2 > 0)
  65800. {
  65801. int nextX;
  65802. if (x1 < x2)
  65803. {
  65804. nextX = x1;
  65805. level1 = *src1++;
  65806. x1 = *src1++;
  65807. --srcNum1;
  65808. }
  65809. else if (x1 == x2)
  65810. {
  65811. nextX = x1;
  65812. level1 = *src1++;
  65813. level2 = *src2++;
  65814. x1 = *src1++;
  65815. x2 = *src2++;
  65816. --srcNum1;
  65817. --srcNum2;
  65818. }
  65819. else
  65820. {
  65821. nextX = x2;
  65822. level2 = *src2++;
  65823. x2 = *src2++;
  65824. --srcNum2;
  65825. }
  65826. if (nextX > lastX)
  65827. {
  65828. if (nextX >= right)
  65829. break;
  65830. lastX = nextX;
  65831. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65832. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65833. if (nextLevel != lastLevel)
  65834. {
  65835. if (destTotal >= maxEdgesPerLine)
  65836. {
  65837. dest[0] = destTotal;
  65838. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65839. dest = table + lineStrideElements * y;
  65840. }
  65841. ++destTotal;
  65842. lastLevel = nextLevel;
  65843. dest[++destIndex] = nextX;
  65844. dest[++destIndex] = nextLevel;
  65845. }
  65846. }
  65847. }
  65848. if (lastLevel > 0)
  65849. {
  65850. if (destTotal >= maxEdgesPerLine)
  65851. {
  65852. dest[0] = destTotal;
  65853. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65854. dest = table + lineStrideElements * y;
  65855. }
  65856. ++destTotal;
  65857. dest[++destIndex] = right;
  65858. dest[++destIndex] = 0;
  65859. }
  65860. dest[0] = destTotal;
  65861. #if JUCE_DEBUG
  65862. int last = std::numeric_limits<int>::min();
  65863. for (int i = 0; i < dest[0]; ++i)
  65864. {
  65865. jassert (dest[i * 2 + 1] > last);
  65866. last = dest[i * 2 + 1];
  65867. }
  65868. jassert (dest [dest[0] * 2] == 0);
  65869. #endif
  65870. }
  65871. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65872. {
  65873. int* lastItem = dest + (dest[0] * 2 - 1);
  65874. if (x2 < lastItem[0])
  65875. {
  65876. if (x2 <= dest[1])
  65877. {
  65878. dest[0] = 0;
  65879. return;
  65880. }
  65881. while (x2 < lastItem[-2])
  65882. {
  65883. --(dest[0]);
  65884. lastItem -= 2;
  65885. }
  65886. lastItem[0] = x2;
  65887. lastItem[1] = 0;
  65888. }
  65889. if (x1 > dest[1])
  65890. {
  65891. while (lastItem[0] > x1)
  65892. lastItem -= 2;
  65893. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65894. if (itemsRemoved > 0)
  65895. {
  65896. dest[0] -= itemsRemoved;
  65897. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65898. }
  65899. dest[1] = x1;
  65900. }
  65901. }
  65902. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65903. {
  65904. const Rectangle<int> clipped (r.getIntersection (bounds));
  65905. if (clipped.isEmpty())
  65906. {
  65907. needToCheckEmptinesss = false;
  65908. bounds.setHeight (0);
  65909. }
  65910. else
  65911. {
  65912. const int top = clipped.getY() - bounds.getY();
  65913. const int bottom = clipped.getBottom() - bounds.getY();
  65914. if (bottom < bounds.getHeight())
  65915. bounds.setHeight (bottom);
  65916. if (clipped.getRight() < bounds.getRight())
  65917. bounds.setRight (clipped.getRight());
  65918. for (int i = top; --i >= 0;)
  65919. table [lineStrideElements * i] = 0;
  65920. if (clipped.getX() > bounds.getX())
  65921. {
  65922. const int x1 = clipped.getX() << 8;
  65923. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65924. int* line = table + lineStrideElements * top;
  65925. for (int i = bottom - top; --i >= 0;)
  65926. {
  65927. if (line[0] != 0)
  65928. clipEdgeTableLineToRange (line, x1, x2);
  65929. line += lineStrideElements;
  65930. }
  65931. }
  65932. needToCheckEmptinesss = true;
  65933. }
  65934. }
  65935. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65936. {
  65937. const Rectangle<int> clipped (r.getIntersection (bounds));
  65938. if (! clipped.isEmpty())
  65939. {
  65940. const int top = clipped.getY() - bounds.getY();
  65941. const int bottom = clipped.getBottom() - bounds.getY();
  65942. //XXX optimise here by shortening the table if it fills top or bottom
  65943. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65944. clipped.getX() << 8, 0,
  65945. clipped.getRight() << 8, 255,
  65946. std::numeric_limits<int>::max(), 0 };
  65947. for (int i = top; i < bottom; ++i)
  65948. intersectWithEdgeTableLine (i, rectLine);
  65949. needToCheckEmptinesss = true;
  65950. }
  65951. }
  65952. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65953. {
  65954. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65955. if (clipped.isEmpty())
  65956. {
  65957. needToCheckEmptinesss = false;
  65958. bounds.setHeight (0);
  65959. }
  65960. else
  65961. {
  65962. const int top = clipped.getY() - bounds.getY();
  65963. const int bottom = clipped.getBottom() - bounds.getY();
  65964. if (bottom < bounds.getHeight())
  65965. bounds.setHeight (bottom);
  65966. if (clipped.getRight() < bounds.getRight())
  65967. bounds.setRight (clipped.getRight());
  65968. int i = 0;
  65969. for (i = top; --i >= 0;)
  65970. table [lineStrideElements * i] = 0;
  65971. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65972. for (i = top; i < bottom; ++i)
  65973. {
  65974. intersectWithEdgeTableLine (i, otherLine);
  65975. otherLine += other.lineStrideElements;
  65976. }
  65977. needToCheckEmptinesss = true;
  65978. }
  65979. }
  65980. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  65981. {
  65982. y -= bounds.getY();
  65983. if (y < 0 || y >= bounds.getHeight())
  65984. return;
  65985. needToCheckEmptinesss = true;
  65986. if (numPixels <= 0)
  65987. {
  65988. table [lineStrideElements * y] = 0;
  65989. return;
  65990. }
  65991. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  65992. int destIndex = 0, lastLevel = 0;
  65993. while (--numPixels >= 0)
  65994. {
  65995. const int alpha = *mask;
  65996. mask += maskStride;
  65997. if (alpha != lastLevel)
  65998. {
  65999. tempLine[++destIndex] = (x << 8);
  66000. tempLine[++destIndex] = alpha;
  66001. lastLevel = alpha;
  66002. }
  66003. ++x;
  66004. }
  66005. if (lastLevel > 0)
  66006. {
  66007. tempLine[++destIndex] = (x << 8);
  66008. tempLine[++destIndex] = 0;
  66009. }
  66010. tempLine[0] = destIndex >> 1;
  66011. intersectWithEdgeTableLine (y, tempLine);
  66012. }
  66013. bool EdgeTable::isEmpty() throw()
  66014. {
  66015. if (needToCheckEmptinesss)
  66016. {
  66017. needToCheckEmptinesss = false;
  66018. int* t = table;
  66019. for (int i = bounds.getHeight(); --i >= 0;)
  66020. {
  66021. if (t[0] > 1)
  66022. return false;
  66023. t += lineStrideElements;
  66024. }
  66025. bounds.setHeight (0);
  66026. }
  66027. return bounds.getHeight() == 0;
  66028. }
  66029. END_JUCE_NAMESPACE
  66030. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66031. /*** Start of inlined file: juce_FillType.cpp ***/
  66032. BEGIN_JUCE_NAMESPACE
  66033. FillType::FillType() throw()
  66034. : colour (0xff000000), image (0)
  66035. {
  66036. }
  66037. FillType::FillType (const Colour& colour_) throw()
  66038. : colour (colour_), image (0)
  66039. {
  66040. }
  66041. FillType::FillType (const ColourGradient& gradient_)
  66042. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66043. {
  66044. }
  66045. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66046. : colour (0xff000000), image (image_), transform (transform_)
  66047. {
  66048. }
  66049. FillType::FillType (const FillType& other)
  66050. : colour (other.colour),
  66051. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66052. image (other.image), transform (other.transform)
  66053. {
  66054. }
  66055. FillType& FillType::operator= (const FillType& other)
  66056. {
  66057. if (this != &other)
  66058. {
  66059. colour = other.colour;
  66060. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66061. image = other.image;
  66062. transform = other.transform;
  66063. }
  66064. return *this;
  66065. }
  66066. FillType::~FillType() throw()
  66067. {
  66068. }
  66069. bool FillType::operator== (const FillType& other) const
  66070. {
  66071. return colour == other.colour && image == other.image
  66072. && transform == other.transform
  66073. && (gradient == other.gradient
  66074. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66075. }
  66076. bool FillType::operator!= (const FillType& other) const
  66077. {
  66078. return ! operator== (other);
  66079. }
  66080. void FillType::setColour (const Colour& newColour) throw()
  66081. {
  66082. gradient = 0;
  66083. image = Image::null;
  66084. colour = newColour;
  66085. }
  66086. void FillType::setGradient (const ColourGradient& newGradient)
  66087. {
  66088. if (gradient != 0)
  66089. {
  66090. *gradient = newGradient;
  66091. }
  66092. else
  66093. {
  66094. image = Image::null;
  66095. gradient = new ColourGradient (newGradient);
  66096. colour = Colours::black;
  66097. }
  66098. }
  66099. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66100. {
  66101. gradient = 0;
  66102. image = image_;
  66103. transform = transform_;
  66104. colour = Colours::black;
  66105. }
  66106. void FillType::setOpacity (const float newOpacity) throw()
  66107. {
  66108. colour = colour.withAlpha (newOpacity);
  66109. }
  66110. bool FillType::isInvisible() const throw()
  66111. {
  66112. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66113. }
  66114. END_JUCE_NAMESPACE
  66115. /*** End of inlined file: juce_FillType.cpp ***/
  66116. /*** Start of inlined file: juce_Graphics.cpp ***/
  66117. BEGIN_JUCE_NAMESPACE
  66118. namespace
  66119. {
  66120. template <typename Type>
  66121. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66122. {
  66123. const int maxVal = 0x3fffffff;
  66124. return (int) x >= -maxVal && (int) x <= maxVal
  66125. && (int) y >= -maxVal && (int) y <= maxVal
  66126. && (int) w >= -maxVal && (int) w <= maxVal
  66127. && (int) h >= -maxVal && (int) h <= maxVal;
  66128. }
  66129. }
  66130. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66131. {
  66132. }
  66133. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66134. {
  66135. }
  66136. Graphics::Graphics (const Image& imageToDrawOnto)
  66137. : context (imageToDrawOnto.createLowLevelContext()),
  66138. contextToDelete (context),
  66139. saveStatePending (false)
  66140. {
  66141. }
  66142. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66143. : context (internalContext),
  66144. saveStatePending (false)
  66145. {
  66146. }
  66147. Graphics::~Graphics()
  66148. {
  66149. }
  66150. void Graphics::resetToDefaultState()
  66151. {
  66152. saveStateIfPending();
  66153. context->setFill (FillType());
  66154. context->setFont (Font());
  66155. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66156. }
  66157. bool Graphics::isVectorDevice() const
  66158. {
  66159. return context->isVectorDevice();
  66160. }
  66161. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66162. {
  66163. saveStateIfPending();
  66164. return context->clipToRectangle (area);
  66165. }
  66166. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66167. {
  66168. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66169. }
  66170. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66171. {
  66172. saveStateIfPending();
  66173. return context->clipToRectangleList (clipRegion);
  66174. }
  66175. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66176. {
  66177. saveStateIfPending();
  66178. context->clipToPath (path, transform);
  66179. return ! context->isClipEmpty();
  66180. }
  66181. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66182. {
  66183. saveStateIfPending();
  66184. context->clipToImageAlpha (image, transform);
  66185. return ! context->isClipEmpty();
  66186. }
  66187. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66188. {
  66189. saveStateIfPending();
  66190. context->excludeClipRectangle (rectangleToExclude);
  66191. }
  66192. bool Graphics::isClipEmpty() const
  66193. {
  66194. return context->isClipEmpty();
  66195. }
  66196. const Rectangle<int> Graphics::getClipBounds() const
  66197. {
  66198. return context->getClipBounds();
  66199. }
  66200. void Graphics::saveState()
  66201. {
  66202. saveStateIfPending();
  66203. saveStatePending = true;
  66204. }
  66205. void Graphics::restoreState()
  66206. {
  66207. if (saveStatePending)
  66208. saveStatePending = false;
  66209. else
  66210. context->restoreState();
  66211. }
  66212. void Graphics::saveStateIfPending()
  66213. {
  66214. if (saveStatePending)
  66215. {
  66216. saveStatePending = false;
  66217. context->saveState();
  66218. }
  66219. }
  66220. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66221. {
  66222. saveStateIfPending();
  66223. context->setOrigin (newOriginX, newOriginY);
  66224. }
  66225. void Graphics::addTransform (const AffineTransform& transform)
  66226. {
  66227. saveStateIfPending();
  66228. context->addTransform (transform);
  66229. }
  66230. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66231. {
  66232. return context->clipRegionIntersects (area);
  66233. }
  66234. void Graphics::beginTransparencyLayer (float layerOpacity)
  66235. {
  66236. saveStateIfPending();
  66237. context->beginTransparencyLayer (layerOpacity);
  66238. }
  66239. void Graphics::endTransparencyLayer()
  66240. {
  66241. context->endTransparencyLayer();
  66242. }
  66243. void Graphics::setColour (const Colour& newColour)
  66244. {
  66245. saveStateIfPending();
  66246. context->setFill (newColour);
  66247. }
  66248. void Graphics::setOpacity (const float newOpacity)
  66249. {
  66250. saveStateIfPending();
  66251. context->setOpacity (newOpacity);
  66252. }
  66253. void Graphics::setGradientFill (const ColourGradient& gradient)
  66254. {
  66255. setFillType (gradient);
  66256. }
  66257. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66258. {
  66259. saveStateIfPending();
  66260. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66261. context->setOpacity (opacity);
  66262. }
  66263. void Graphics::setFillType (const FillType& newFill)
  66264. {
  66265. saveStateIfPending();
  66266. context->setFill (newFill);
  66267. }
  66268. void Graphics::setFont (const Font& newFont)
  66269. {
  66270. saveStateIfPending();
  66271. context->setFont (newFont);
  66272. }
  66273. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66274. {
  66275. saveStateIfPending();
  66276. Font f (context->getFont());
  66277. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66278. context->setFont (f);
  66279. }
  66280. const Font Graphics::getCurrentFont() const
  66281. {
  66282. return context->getFont();
  66283. }
  66284. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66285. {
  66286. if (text.isNotEmpty()
  66287. && startX < context->getClipBounds().getRight())
  66288. {
  66289. GlyphArrangement arr;
  66290. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66291. arr.draw (*this);
  66292. }
  66293. }
  66294. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66295. {
  66296. if (text.isNotEmpty())
  66297. {
  66298. GlyphArrangement arr;
  66299. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66300. arr.draw (*this, transform);
  66301. }
  66302. }
  66303. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66304. {
  66305. if (text.isNotEmpty()
  66306. && startX < context->getClipBounds().getRight())
  66307. {
  66308. GlyphArrangement arr;
  66309. arr.addJustifiedText (context->getFont(), text,
  66310. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66311. Justification::left);
  66312. arr.draw (*this);
  66313. }
  66314. }
  66315. void Graphics::drawText (const String& text,
  66316. const int x, const int y, const int width, const int height,
  66317. const Justification& justificationType,
  66318. const bool useEllipsesIfTooBig) const
  66319. {
  66320. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66321. {
  66322. GlyphArrangement arr;
  66323. arr.addCurtailedLineOfText (context->getFont(), text,
  66324. 0.0f, 0.0f, (float) width,
  66325. useEllipsesIfTooBig);
  66326. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66327. (float) x, (float) y, (float) width, (float) height,
  66328. justificationType);
  66329. arr.draw (*this);
  66330. }
  66331. }
  66332. void Graphics::drawFittedText (const String& text,
  66333. const int x, const int y, const int width, const int height,
  66334. const Justification& justification,
  66335. const int maximumNumberOfLines,
  66336. const float minimumHorizontalScale) const
  66337. {
  66338. if (text.isNotEmpty()
  66339. && width > 0 && height > 0
  66340. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66341. {
  66342. GlyphArrangement arr;
  66343. arr.addFittedText (context->getFont(), text,
  66344. (float) x, (float) y, (float) width, (float) height,
  66345. justification,
  66346. maximumNumberOfLines,
  66347. minimumHorizontalScale);
  66348. arr.draw (*this);
  66349. }
  66350. }
  66351. void Graphics::fillRect (int x, int y, int width, int height) const
  66352. {
  66353. // passing in a silly number can cause maths problems in rendering!
  66354. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66355. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66356. }
  66357. void Graphics::fillRect (const Rectangle<int>& r) const
  66358. {
  66359. context->fillRect (r, false);
  66360. }
  66361. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66362. {
  66363. // passing in a silly number can cause maths problems in rendering!
  66364. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66365. Path p;
  66366. p.addRectangle (x, y, width, height);
  66367. fillPath (p);
  66368. }
  66369. void Graphics::setPixel (int x, int y) const
  66370. {
  66371. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66372. }
  66373. void Graphics::fillAll() const
  66374. {
  66375. fillRect (context->getClipBounds());
  66376. }
  66377. void Graphics::fillAll (const Colour& colourToUse) const
  66378. {
  66379. if (! colourToUse.isTransparent())
  66380. {
  66381. const Rectangle<int> clip (context->getClipBounds());
  66382. context->saveState();
  66383. context->setFill (colourToUse);
  66384. context->fillRect (clip, false);
  66385. context->restoreState();
  66386. }
  66387. }
  66388. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66389. {
  66390. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66391. context->fillPath (path, transform);
  66392. }
  66393. void Graphics::strokePath (const Path& path,
  66394. const PathStrokeType& strokeType,
  66395. const AffineTransform& transform) const
  66396. {
  66397. Path stroke;
  66398. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66399. fillPath (stroke);
  66400. }
  66401. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66402. const int lineThickness) const
  66403. {
  66404. // passing in a silly number can cause maths problems in rendering!
  66405. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66406. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66407. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66408. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66409. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66410. }
  66411. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66412. {
  66413. // passing in a silly number can cause maths problems in rendering!
  66414. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66415. Path p;
  66416. p.addRectangle (x, y, width, lineThickness);
  66417. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66418. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66419. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66420. fillPath (p);
  66421. }
  66422. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66423. {
  66424. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66425. }
  66426. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66427. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66428. const bool useGradient, const bool sharpEdgeOnOutside) const
  66429. {
  66430. // passing in a silly number can cause maths problems in rendering!
  66431. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66432. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66433. {
  66434. context->saveState();
  66435. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66436. const float ramp = oldOpacity / bevelThickness;
  66437. for (int i = bevelThickness; --i >= 0;)
  66438. {
  66439. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66440. : oldOpacity;
  66441. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66442. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66443. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66444. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66445. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66446. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66447. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66448. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66449. }
  66450. context->restoreState();
  66451. }
  66452. }
  66453. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66454. {
  66455. // passing in a silly number can cause maths problems in rendering!
  66456. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66457. Path p;
  66458. p.addEllipse (x, y, width, height);
  66459. fillPath (p);
  66460. }
  66461. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66462. const float lineThickness) const
  66463. {
  66464. // passing in a silly number can cause maths problems in rendering!
  66465. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66466. Path p;
  66467. p.addEllipse (x, y, width, height);
  66468. strokePath (p, PathStrokeType (lineThickness));
  66469. }
  66470. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66471. {
  66472. // passing in a silly number can cause maths problems in rendering!
  66473. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66474. Path p;
  66475. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66476. fillPath (p);
  66477. }
  66478. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66479. {
  66480. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66481. }
  66482. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66483. const float cornerSize, const float lineThickness) const
  66484. {
  66485. // passing in a silly number can cause maths problems in rendering!
  66486. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66487. Path p;
  66488. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66489. strokePath (p, PathStrokeType (lineThickness));
  66490. }
  66491. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66492. {
  66493. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66494. }
  66495. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66496. {
  66497. Path p;
  66498. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66499. fillPath (p);
  66500. }
  66501. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66502. const int checkWidth, const int checkHeight,
  66503. const Colour& colour1, const Colour& colour2) const
  66504. {
  66505. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66506. if (checkWidth > 0 && checkHeight > 0)
  66507. {
  66508. context->saveState();
  66509. if (colour1 == colour2)
  66510. {
  66511. context->setFill (colour1);
  66512. context->fillRect (area, false);
  66513. }
  66514. else
  66515. {
  66516. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66517. if (! clipped.isEmpty())
  66518. {
  66519. context->clipToRectangle (clipped);
  66520. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66521. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66522. const int startX = area.getX() + checkNumX * checkWidth;
  66523. const int startY = area.getY() + checkNumY * checkHeight;
  66524. const int right = clipped.getRight();
  66525. const int bottom = clipped.getBottom();
  66526. for (int i = 0; i < 2; ++i)
  66527. {
  66528. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66529. int cy = i;
  66530. for (int y = startY; y < bottom; y += checkHeight)
  66531. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66532. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66533. }
  66534. }
  66535. }
  66536. context->restoreState();
  66537. }
  66538. }
  66539. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66540. {
  66541. context->drawVerticalLine (x, top, bottom);
  66542. }
  66543. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66544. {
  66545. context->drawHorizontalLine (y, left, right);
  66546. }
  66547. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  66548. {
  66549. context->drawLine (Line<float> (x1, y1, x2, y2));
  66550. }
  66551. void Graphics::drawLine (const Line<float>& line) const
  66552. {
  66553. context->drawLine (line);
  66554. }
  66555. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  66556. {
  66557. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  66558. }
  66559. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66560. {
  66561. Path p;
  66562. p.addLineSegment (line, lineThickness);
  66563. fillPath (p);
  66564. }
  66565. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  66566. const int numDashLengths, const float lineThickness, int n) const
  66567. {
  66568. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  66569. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  66570. const double totalLen = delta.getDistanceFromOrigin();
  66571. if (totalLen >= 0.1)
  66572. {
  66573. const double onePixAlpha = 1.0 / totalLen;
  66574. for (double alpha = 0.0; alpha < 1.0;)
  66575. {
  66576. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  66577. const double lastAlpha = alpha;
  66578. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  66579. n = (n + 1) % numDashLengths;
  66580. if ((n & 1) != 0)
  66581. {
  66582. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  66583. line.getStart() + (delta * alpha).toFloat());
  66584. if (lineThickness != 1.0f)
  66585. drawLine (segment, lineThickness);
  66586. else
  66587. context->drawLine (segment);
  66588. }
  66589. }
  66590. }
  66591. }
  66592. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66593. {
  66594. saveStateIfPending();
  66595. context->setInterpolationQuality (newQuality);
  66596. }
  66597. void Graphics::drawImageAt (const Image& imageToDraw,
  66598. const int topLeftX, const int topLeftY,
  66599. const bool fillAlphaChannelWithCurrentBrush) const
  66600. {
  66601. const int imageW = imageToDraw.getWidth();
  66602. const int imageH = imageToDraw.getHeight();
  66603. drawImage (imageToDraw,
  66604. topLeftX, topLeftY, imageW, imageH,
  66605. 0, 0, imageW, imageH,
  66606. fillAlphaChannelWithCurrentBrush);
  66607. }
  66608. void Graphics::drawImageWithin (const Image& imageToDraw,
  66609. const int destX, const int destY,
  66610. const int destW, const int destH,
  66611. const RectanglePlacement& placementWithinTarget,
  66612. const bool fillAlphaChannelWithCurrentBrush) const
  66613. {
  66614. // passing in a silly number can cause maths problems in rendering!
  66615. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66616. if (imageToDraw.isValid())
  66617. {
  66618. const int imageW = imageToDraw.getWidth();
  66619. const int imageH = imageToDraw.getHeight();
  66620. if (imageW > 0 && imageH > 0)
  66621. {
  66622. double newX = 0.0, newY = 0.0;
  66623. double newW = imageW;
  66624. double newH = imageH;
  66625. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66626. destX, destY, destW, destH);
  66627. if (newW > 0 && newH > 0)
  66628. {
  66629. drawImage (imageToDraw,
  66630. roundToInt (newX), roundToInt (newY),
  66631. roundToInt (newW), roundToInt (newH),
  66632. 0, 0, imageW, imageH,
  66633. fillAlphaChannelWithCurrentBrush);
  66634. }
  66635. }
  66636. }
  66637. }
  66638. void Graphics::drawImage (const Image& imageToDraw,
  66639. int dx, int dy, int dw, int dh,
  66640. int sx, int sy, int sw, int sh,
  66641. const bool fillAlphaChannelWithCurrentBrush) const
  66642. {
  66643. // passing in a silly number can cause maths problems in rendering!
  66644. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66645. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66646. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66647. {
  66648. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66649. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66650. .translated ((float) dx, (float) dy),
  66651. fillAlphaChannelWithCurrentBrush);
  66652. }
  66653. }
  66654. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66655. const AffineTransform& transform,
  66656. const bool fillAlphaChannelWithCurrentBrush) const
  66657. {
  66658. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66659. {
  66660. if (fillAlphaChannelWithCurrentBrush)
  66661. {
  66662. context->saveState();
  66663. context->clipToImageAlpha (imageToDraw, transform);
  66664. fillAll();
  66665. context->restoreState();
  66666. }
  66667. else
  66668. {
  66669. context->drawImage (imageToDraw, transform, false);
  66670. }
  66671. }
  66672. }
  66673. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66674. : context (g)
  66675. {
  66676. context.saveState();
  66677. }
  66678. Graphics::ScopedSaveState::~ScopedSaveState()
  66679. {
  66680. context.restoreState();
  66681. }
  66682. END_JUCE_NAMESPACE
  66683. /*** End of inlined file: juce_Graphics.cpp ***/
  66684. /*** Start of inlined file: juce_Justification.cpp ***/
  66685. BEGIN_JUCE_NAMESPACE
  66686. Justification::Justification (const Justification& other) throw()
  66687. : flags (other.flags)
  66688. {
  66689. }
  66690. Justification& Justification::operator= (const Justification& other) throw()
  66691. {
  66692. flags = other.flags;
  66693. return *this;
  66694. }
  66695. int Justification::getOnlyVerticalFlags() const throw()
  66696. {
  66697. return flags & (top | bottom | verticallyCentred);
  66698. }
  66699. int Justification::getOnlyHorizontalFlags() const throw()
  66700. {
  66701. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66702. }
  66703. END_JUCE_NAMESPACE
  66704. /*** End of inlined file: juce_Justification.cpp ***/
  66705. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66706. BEGIN_JUCE_NAMESPACE
  66707. // this will throw an assertion if you try to draw something that's not
  66708. // possible in postscript
  66709. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66710. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66711. #define notPossibleInPostscriptAssert jassertfalse
  66712. #else
  66713. #define notPossibleInPostscriptAssert
  66714. #endif
  66715. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66716. const String& documentTitle,
  66717. const int totalWidth_,
  66718. const int totalHeight_)
  66719. : out (resultingPostScript),
  66720. totalWidth (totalWidth_),
  66721. totalHeight (totalHeight_),
  66722. needToClip (true)
  66723. {
  66724. stateStack.add (new SavedState());
  66725. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66726. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66727. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66728. "\n%%BoundingBox: 0 0 600 824"
  66729. "\n%%Pages: 0"
  66730. "\n%%Creator: Raw Material Software JUCE"
  66731. "\n%%Title: " << documentTitle <<
  66732. "\n%%CreationDate: none"
  66733. "\n%%LanguageLevel: 2"
  66734. "\n%%EndComments"
  66735. "\n%%BeginProlog"
  66736. "\n%%BeginResource: JRes"
  66737. "\n/bd {bind def} bind def"
  66738. "\n/c {setrgbcolor} bd"
  66739. "\n/m {moveto} bd"
  66740. "\n/l {lineto} bd"
  66741. "\n/rl {rlineto} bd"
  66742. "\n/ct {curveto} bd"
  66743. "\n/cp {closepath} bd"
  66744. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66745. "\n/doclip {initclip newpath} bd"
  66746. "\n/endclip {clip newpath} bd"
  66747. "\n%%EndResource"
  66748. "\n%%EndProlog"
  66749. "\n%%BeginSetup"
  66750. "\n%%EndSetup"
  66751. "\n%%Page: 1 1"
  66752. "\n%%BeginPageSetup"
  66753. "\n%%EndPageSetup\n\n"
  66754. << "40 800 translate\n"
  66755. << scale << ' ' << scale << " scale\n\n";
  66756. }
  66757. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66758. {
  66759. }
  66760. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66761. {
  66762. return true;
  66763. }
  66764. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66765. {
  66766. if (x != 0 || y != 0)
  66767. {
  66768. stateStack.getLast()->xOffset += x;
  66769. stateStack.getLast()->yOffset += y;
  66770. needToClip = true;
  66771. }
  66772. }
  66773. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66774. {
  66775. //xxx
  66776. jassertfalse;
  66777. }
  66778. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66779. {
  66780. jassertfalse; //xxx
  66781. return 1.0f;
  66782. }
  66783. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66784. {
  66785. needToClip = true;
  66786. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66787. }
  66788. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66789. {
  66790. needToClip = true;
  66791. return stateStack.getLast()->clip.clipTo (clipRegion);
  66792. }
  66793. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66794. {
  66795. needToClip = true;
  66796. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66797. }
  66798. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66799. {
  66800. writeClip();
  66801. Path p (path);
  66802. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66803. writePath (p);
  66804. out << "clip\n";
  66805. }
  66806. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66807. {
  66808. needToClip = true;
  66809. jassertfalse; // xxx
  66810. }
  66811. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66812. {
  66813. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66814. }
  66815. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66816. {
  66817. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66818. -stateStack.getLast()->yOffset);
  66819. }
  66820. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66821. {
  66822. return stateStack.getLast()->clip.isEmpty();
  66823. }
  66824. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66825. : xOffset (0),
  66826. yOffset (0)
  66827. {
  66828. }
  66829. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66830. {
  66831. }
  66832. void LowLevelGraphicsPostScriptRenderer::saveState()
  66833. {
  66834. stateStack.add (new SavedState (*stateStack.getLast()));
  66835. }
  66836. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66837. {
  66838. jassert (stateStack.size() > 0);
  66839. if (stateStack.size() > 0)
  66840. stateStack.removeLast();
  66841. }
  66842. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66843. {
  66844. }
  66845. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66846. {
  66847. }
  66848. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66849. {
  66850. if (needToClip)
  66851. {
  66852. needToClip = false;
  66853. out << "doclip ";
  66854. int itemsOnLine = 0;
  66855. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66856. {
  66857. if (++itemsOnLine == 6)
  66858. {
  66859. itemsOnLine = 0;
  66860. out << '\n';
  66861. }
  66862. const Rectangle<int>& r = *i.getRectangle();
  66863. out << r.getX() << ' ' << -r.getY() << ' '
  66864. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66865. }
  66866. out << "endclip\n";
  66867. }
  66868. }
  66869. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66870. {
  66871. Colour c (Colours::white.overlaidWith (colour));
  66872. if (lastColour != c)
  66873. {
  66874. lastColour = c;
  66875. out << String (c.getFloatRed(), 3) << ' '
  66876. << String (c.getFloatGreen(), 3) << ' '
  66877. << String (c.getFloatBlue(), 3) << " c\n";
  66878. }
  66879. }
  66880. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66881. {
  66882. out << String (x, 2) << ' '
  66883. << String (-y, 2) << ' ';
  66884. }
  66885. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66886. {
  66887. out << "newpath ";
  66888. float lastX = 0.0f;
  66889. float lastY = 0.0f;
  66890. int itemsOnLine = 0;
  66891. Path::Iterator i (path);
  66892. while (i.next())
  66893. {
  66894. if (++itemsOnLine == 4)
  66895. {
  66896. itemsOnLine = 0;
  66897. out << '\n';
  66898. }
  66899. switch (i.elementType)
  66900. {
  66901. case Path::Iterator::startNewSubPath:
  66902. writeXY (i.x1, i.y1);
  66903. lastX = i.x1;
  66904. lastY = i.y1;
  66905. out << "m ";
  66906. break;
  66907. case Path::Iterator::lineTo:
  66908. writeXY (i.x1, i.y1);
  66909. lastX = i.x1;
  66910. lastY = i.y1;
  66911. out << "l ";
  66912. break;
  66913. case Path::Iterator::quadraticTo:
  66914. {
  66915. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66916. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66917. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66918. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66919. writeXY (cp1x, cp1y);
  66920. writeXY (cp2x, cp2y);
  66921. writeXY (i.x2, i.y2);
  66922. out << "ct ";
  66923. lastX = i.x2;
  66924. lastY = i.y2;
  66925. }
  66926. break;
  66927. case Path::Iterator::cubicTo:
  66928. writeXY (i.x1, i.y1);
  66929. writeXY (i.x2, i.y2);
  66930. writeXY (i.x3, i.y3);
  66931. out << "ct ";
  66932. lastX = i.x3;
  66933. lastY = i.y3;
  66934. break;
  66935. case Path::Iterator::closePath:
  66936. out << "cp ";
  66937. break;
  66938. default:
  66939. jassertfalse;
  66940. break;
  66941. }
  66942. }
  66943. out << '\n';
  66944. }
  66945. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66946. {
  66947. out << "[ "
  66948. << trans.mat00 << ' '
  66949. << trans.mat10 << ' '
  66950. << trans.mat01 << ' '
  66951. << trans.mat11 << ' '
  66952. << trans.mat02 << ' '
  66953. << trans.mat12 << " ] concat ";
  66954. }
  66955. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66956. {
  66957. stateStack.getLast()->fillType = fillType;
  66958. }
  66959. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66960. {
  66961. }
  66962. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66963. {
  66964. }
  66965. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66966. {
  66967. if (stateStack.getLast()->fillType.isColour())
  66968. {
  66969. writeClip();
  66970. writeColour (stateStack.getLast()->fillType.colour);
  66971. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66972. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66973. }
  66974. else
  66975. {
  66976. Path p;
  66977. p.addRectangle (r);
  66978. fillPath (p, AffineTransform::identity);
  66979. }
  66980. }
  66981. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66982. {
  66983. if (stateStack.getLast()->fillType.isColour())
  66984. {
  66985. writeClip();
  66986. Path p (path);
  66987. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66988. (float) stateStack.getLast()->yOffset));
  66989. writePath (p);
  66990. writeColour (stateStack.getLast()->fillType.colour);
  66991. out << "fill\n";
  66992. }
  66993. else if (stateStack.getLast()->fillType.isGradient())
  66994. {
  66995. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66996. // postscript can't do semi-transparent ones.
  66997. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66998. writeClip();
  66999. out << "gsave ";
  67000. {
  67001. Path p (path);
  67002. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67003. writePath (p);
  67004. out << "clip\n";
  67005. }
  67006. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67007. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67008. // time-being, this just fills it with the average colour..
  67009. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67010. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67011. out << "grestore\n";
  67012. }
  67013. }
  67014. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67015. const int sx, const int sy,
  67016. const int maxW, const int maxH) const
  67017. {
  67018. out << "{<\n";
  67019. const int w = jmin (maxW, im.getWidth());
  67020. const int h = jmin (maxH, im.getHeight());
  67021. int charsOnLine = 0;
  67022. const Image::BitmapData srcData (im, 0, 0, w, h);
  67023. Colour pixel;
  67024. for (int y = h; --y >= 0;)
  67025. {
  67026. for (int x = 0; x < w; ++x)
  67027. {
  67028. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67029. if (x >= sx && y >= sy)
  67030. {
  67031. if (im.isARGB())
  67032. {
  67033. PixelARGB p (*(const PixelARGB*) pixelData);
  67034. p.unpremultiply();
  67035. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67036. }
  67037. else if (im.isRGB())
  67038. {
  67039. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67040. }
  67041. else
  67042. {
  67043. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67044. }
  67045. }
  67046. else
  67047. {
  67048. pixel = Colours::transparentWhite;
  67049. }
  67050. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67051. out << String::toHexString (pixelValues, 3, 0);
  67052. charsOnLine += 3;
  67053. if (charsOnLine > 100)
  67054. {
  67055. out << '\n';
  67056. charsOnLine = 0;
  67057. }
  67058. }
  67059. }
  67060. out << "\n>}\n";
  67061. }
  67062. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67063. {
  67064. const int w = sourceImage.getWidth();
  67065. const int h = sourceImage.getHeight();
  67066. writeClip();
  67067. out << "gsave ";
  67068. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67069. .scaled (1.0f, -1.0f));
  67070. RectangleList imageClip;
  67071. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67072. out << "newpath ";
  67073. int itemsOnLine = 0;
  67074. for (RectangleList::Iterator i (imageClip); i.next();)
  67075. {
  67076. if (++itemsOnLine == 6)
  67077. {
  67078. out << '\n';
  67079. itemsOnLine = 0;
  67080. }
  67081. const Rectangle<int>& r = *i.getRectangle();
  67082. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67083. }
  67084. out << " clip newpath\n";
  67085. out << w << ' ' << h << " scale\n";
  67086. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67087. writeImage (sourceImage, 0, 0, w, h);
  67088. out << "false 3 colorimage grestore\n";
  67089. needToClip = true;
  67090. }
  67091. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67092. {
  67093. Path p;
  67094. p.addLineSegment (line, 1.0f);
  67095. fillPath (p, AffineTransform::identity);
  67096. }
  67097. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67098. {
  67099. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67100. }
  67101. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67102. {
  67103. drawLine (Line<float> (left, (float) y, right, (float) y));
  67104. }
  67105. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67106. {
  67107. stateStack.getLast()->font = newFont;
  67108. }
  67109. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67110. {
  67111. return stateStack.getLast()->font;
  67112. }
  67113. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67114. {
  67115. Path p;
  67116. Font& font = stateStack.getLast()->font;
  67117. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67118. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67119. }
  67120. END_JUCE_NAMESPACE
  67121. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67122. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67123. BEGIN_JUCE_NAMESPACE
  67124. #if JUCE_MSVC
  67125. #pragma warning (push)
  67126. #pragma warning (disable: 4127) // "expression is constant" warning
  67127. #if JUCE_DEBUG
  67128. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67129. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67130. #endif
  67131. #endif
  67132. namespace SoftwareRendererClasses
  67133. {
  67134. template <class PixelType, bool replaceExisting = false>
  67135. class SolidColourEdgeTableRenderer
  67136. {
  67137. public:
  67138. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67139. : data (data_),
  67140. sourceColour (colour)
  67141. {
  67142. if (sizeof (PixelType) == 3)
  67143. {
  67144. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67145. && sourceColour.getGreen() == sourceColour.getBlue();
  67146. filler[0].set (sourceColour);
  67147. filler[1].set (sourceColour);
  67148. filler[2].set (sourceColour);
  67149. filler[3].set (sourceColour);
  67150. }
  67151. }
  67152. forcedinline void setEdgeTableYPos (const int y) throw()
  67153. {
  67154. linePixels = (PixelType*) data.getLinePointer (y);
  67155. }
  67156. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67157. {
  67158. if (replaceExisting)
  67159. linePixels[x].set (sourceColour);
  67160. else
  67161. linePixels[x].blend (sourceColour, alphaLevel);
  67162. }
  67163. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67164. {
  67165. if (replaceExisting)
  67166. linePixels[x].set (sourceColour);
  67167. else
  67168. linePixels[x].blend (sourceColour);
  67169. }
  67170. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67171. {
  67172. PixelARGB p (sourceColour);
  67173. p.multiplyAlpha (alphaLevel);
  67174. PixelType* dest = linePixels + x;
  67175. if (replaceExisting || p.getAlpha() >= 0xff)
  67176. replaceLine (dest, p, width);
  67177. else
  67178. blendLine (dest, p, width);
  67179. }
  67180. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67181. {
  67182. PixelType* dest = linePixels + x;
  67183. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67184. replaceLine (dest, sourceColour, width);
  67185. else
  67186. blendLine (dest, sourceColour, width);
  67187. }
  67188. private:
  67189. const Image::BitmapData& data;
  67190. PixelType* linePixels;
  67191. PixelARGB sourceColour;
  67192. PixelRGB filler [4];
  67193. bool areRGBComponentsEqual;
  67194. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67195. {
  67196. do
  67197. {
  67198. dest->blend (colour);
  67199. ++dest;
  67200. } while (--width > 0);
  67201. }
  67202. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67203. {
  67204. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67205. {
  67206. memset (dest, colour.getRed(), width * 3);
  67207. }
  67208. else
  67209. {
  67210. if (width >> 5)
  67211. {
  67212. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67213. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67214. {
  67215. dest->set (colour);
  67216. ++dest;
  67217. --width;
  67218. }
  67219. while (width > 4)
  67220. {
  67221. int* d = reinterpret_cast<int*> (dest);
  67222. *d++ = intFiller[0];
  67223. *d++ = intFiller[1];
  67224. *d++ = intFiller[2];
  67225. dest = reinterpret_cast<PixelRGB*> (d);
  67226. width -= 4;
  67227. }
  67228. }
  67229. while (--width >= 0)
  67230. {
  67231. dest->set (colour);
  67232. ++dest;
  67233. }
  67234. }
  67235. }
  67236. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67237. {
  67238. memset (dest, colour.getAlpha(), width);
  67239. }
  67240. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67241. {
  67242. do
  67243. {
  67244. dest->set (colour);
  67245. ++dest;
  67246. } while (--width > 0);
  67247. }
  67248. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67249. };
  67250. class LinearGradientPixelGenerator
  67251. {
  67252. public:
  67253. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67254. : lookupTable (lookupTable_), numEntries (numEntries_)
  67255. {
  67256. jassert (numEntries_ >= 0);
  67257. Point<float> p1 (gradient.point1);
  67258. Point<float> p2 (gradient.point2);
  67259. if (! transform.isIdentity())
  67260. {
  67261. const Line<float> l (p2, p1);
  67262. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67263. p1.applyTransform (transform);
  67264. p2.applyTransform (transform);
  67265. p3.applyTransform (transform);
  67266. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67267. }
  67268. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67269. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67270. if (vertical)
  67271. {
  67272. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67273. start = roundToInt (p1.getY() * scale);
  67274. }
  67275. else if (horizontal)
  67276. {
  67277. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67278. start = roundToInt (p1.getX() * scale);
  67279. }
  67280. else
  67281. {
  67282. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67283. yTerm = p1.getY() - p1.getX() / grad;
  67284. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67285. grad *= scale;
  67286. }
  67287. }
  67288. forcedinline void setY (const int y) throw()
  67289. {
  67290. if (vertical)
  67291. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67292. else if (! horizontal)
  67293. start = roundToInt ((y - yTerm) * grad);
  67294. }
  67295. inline const PixelARGB getPixel (const int x) const throw()
  67296. {
  67297. return vertical ? linePix
  67298. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67299. }
  67300. private:
  67301. const PixelARGB* const lookupTable;
  67302. const int numEntries;
  67303. PixelARGB linePix;
  67304. int start, scale;
  67305. double grad, yTerm;
  67306. bool vertical, horizontal;
  67307. enum { numScaleBits = 12 };
  67308. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67309. };
  67310. class RadialGradientPixelGenerator
  67311. {
  67312. public:
  67313. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67314. const PixelARGB* const lookupTable_, const int numEntries_)
  67315. : lookupTable (lookupTable_),
  67316. numEntries (numEntries_),
  67317. gx1 (gradient.point1.getX()),
  67318. gy1 (gradient.point1.getY())
  67319. {
  67320. jassert (numEntries_ >= 0);
  67321. const Point<float> diff (gradient.point1 - gradient.point2);
  67322. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67323. invScale = numEntries / std::sqrt (maxDist);
  67324. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67325. }
  67326. forcedinline void setY (const int y) throw()
  67327. {
  67328. dy = y - gy1;
  67329. dy *= dy;
  67330. }
  67331. inline const PixelARGB getPixel (const int px) const throw()
  67332. {
  67333. double x = px - gx1;
  67334. x *= x;
  67335. x += dy;
  67336. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67337. }
  67338. protected:
  67339. const PixelARGB* const lookupTable;
  67340. const int numEntries;
  67341. const double gx1, gy1;
  67342. double maxDist, invScale, dy;
  67343. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67344. };
  67345. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67346. {
  67347. public:
  67348. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67349. const PixelARGB* const lookupTable_, const int numEntries_)
  67350. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67351. inverseTransform (transform.inverted())
  67352. {
  67353. tM10 = inverseTransform.mat10;
  67354. tM00 = inverseTransform.mat00;
  67355. }
  67356. forcedinline void setY (const int y) throw()
  67357. {
  67358. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67359. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67360. }
  67361. inline const PixelARGB getPixel (const int px) const throw()
  67362. {
  67363. double x = px;
  67364. const double y = tM10 * x + lineYM11;
  67365. x = tM00 * x + lineYM01;
  67366. x *= x;
  67367. x += y * y;
  67368. if (x >= maxDist)
  67369. return lookupTable [numEntries];
  67370. else
  67371. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67372. }
  67373. private:
  67374. double tM10, tM00, lineYM01, lineYM11;
  67375. const AffineTransform inverseTransform;
  67376. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67377. };
  67378. template <class PixelType, class GradientType>
  67379. class GradientEdgeTableRenderer : public GradientType
  67380. {
  67381. public:
  67382. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67383. const PixelARGB* const lookupTable_, const int numEntries_)
  67384. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67385. destData (destData_)
  67386. {
  67387. }
  67388. forcedinline void setEdgeTableYPos (const int y) throw()
  67389. {
  67390. linePixels = (PixelType*) destData.getLinePointer (y);
  67391. GradientType::setY (y);
  67392. }
  67393. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67394. {
  67395. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67396. }
  67397. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67398. {
  67399. linePixels[x].blend (GradientType::getPixel (x));
  67400. }
  67401. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67402. {
  67403. PixelType* dest = linePixels + x;
  67404. if (alphaLevel < 0xff)
  67405. {
  67406. do
  67407. {
  67408. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67409. } while (--width > 0);
  67410. }
  67411. else
  67412. {
  67413. do
  67414. {
  67415. (dest++)->blend (GradientType::getPixel (x++));
  67416. } while (--width > 0);
  67417. }
  67418. }
  67419. void handleEdgeTableLineFull (int x, int width) const throw()
  67420. {
  67421. PixelType* dest = linePixels + x;
  67422. do
  67423. {
  67424. (dest++)->blend (GradientType::getPixel (x++));
  67425. } while (--width > 0);
  67426. }
  67427. private:
  67428. const Image::BitmapData& destData;
  67429. PixelType* linePixels;
  67430. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67431. };
  67432. namespace RenderingHelpers
  67433. {
  67434. forcedinline int safeModulo (int n, const int divisor) throw()
  67435. {
  67436. jassert (divisor > 0);
  67437. n %= divisor;
  67438. return (n < 0) ? (n + divisor) : n;
  67439. }
  67440. }
  67441. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67442. class ImageFillEdgeTableRenderer
  67443. {
  67444. public:
  67445. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67446. const Image::BitmapData& srcData_,
  67447. const int extraAlpha_,
  67448. const int x, const int y)
  67449. : destData (destData_),
  67450. srcData (srcData_),
  67451. extraAlpha (extraAlpha_ + 1),
  67452. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67453. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67454. {
  67455. }
  67456. forcedinline void setEdgeTableYPos (int y) throw()
  67457. {
  67458. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67459. y -= yOffset;
  67460. if (repeatPattern)
  67461. {
  67462. jassert (y >= 0);
  67463. y %= srcData.height;
  67464. }
  67465. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67466. }
  67467. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67468. {
  67469. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67470. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67471. }
  67472. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67473. {
  67474. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67475. }
  67476. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67477. {
  67478. DestPixelType* dest = linePixels + x;
  67479. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67480. x -= xOffset;
  67481. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67482. if (alphaLevel < 0xfe)
  67483. {
  67484. do
  67485. {
  67486. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67487. } while (--width > 0);
  67488. }
  67489. else
  67490. {
  67491. if (repeatPattern)
  67492. {
  67493. do
  67494. {
  67495. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67496. } while (--width > 0);
  67497. }
  67498. else
  67499. {
  67500. copyRow (dest, sourceLineStart + x, width);
  67501. }
  67502. }
  67503. }
  67504. void handleEdgeTableLineFull (int x, int width) const throw()
  67505. {
  67506. DestPixelType* dest = linePixels + x;
  67507. x -= xOffset;
  67508. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67509. if (extraAlpha < 0xfe)
  67510. {
  67511. do
  67512. {
  67513. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67514. } while (--width > 0);
  67515. }
  67516. else
  67517. {
  67518. if (repeatPattern)
  67519. {
  67520. do
  67521. {
  67522. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67523. } while (--width > 0);
  67524. }
  67525. else
  67526. {
  67527. copyRow (dest, sourceLineStart + x, width);
  67528. }
  67529. }
  67530. }
  67531. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67532. {
  67533. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67534. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67535. uint8* mask = (uint8*) (s + x - xOffset);
  67536. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67537. mask += PixelARGB::indexA;
  67538. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67539. }
  67540. private:
  67541. const Image::BitmapData& destData;
  67542. const Image::BitmapData& srcData;
  67543. const int extraAlpha, xOffset, yOffset;
  67544. DestPixelType* linePixels;
  67545. SrcPixelType* sourceLineStart;
  67546. template <class PixelType1, class PixelType2>
  67547. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67548. {
  67549. do
  67550. {
  67551. dest++ ->blend (*src++);
  67552. } while (--width > 0);
  67553. }
  67554. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67555. {
  67556. memcpy (dest, src, width * sizeof (PixelRGB));
  67557. }
  67558. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67559. };
  67560. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67561. class TransformedImageFillEdgeTableRenderer
  67562. {
  67563. public:
  67564. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67565. const Image::BitmapData& srcData_,
  67566. const AffineTransform& transform,
  67567. const int extraAlpha_,
  67568. const bool betterQuality_)
  67569. : interpolator (transform,
  67570. betterQuality_ ? 0.5f : 0.0f,
  67571. betterQuality_ ? -128 : 0),
  67572. destData (destData_),
  67573. srcData (srcData_),
  67574. extraAlpha (extraAlpha_ + 1),
  67575. betterQuality (betterQuality_),
  67576. maxX (srcData_.width - 1),
  67577. maxY (srcData_.height - 1),
  67578. scratchSize (2048)
  67579. {
  67580. scratchBuffer.malloc (scratchSize);
  67581. }
  67582. forcedinline void setEdgeTableYPos (const int newY) throw()
  67583. {
  67584. y = newY;
  67585. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67586. }
  67587. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67588. {
  67589. SrcPixelType p;
  67590. generate (&p, x, 1);
  67591. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67592. }
  67593. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67594. {
  67595. SrcPixelType p;
  67596. generate (&p, x, 1);
  67597. linePixels[x].blend (p, extraAlpha);
  67598. }
  67599. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67600. {
  67601. if (width > scratchSize)
  67602. {
  67603. scratchSize = width;
  67604. scratchBuffer.malloc (scratchSize);
  67605. }
  67606. SrcPixelType* span = scratchBuffer;
  67607. generate (span, x, width);
  67608. DestPixelType* dest = linePixels + x;
  67609. alphaLevel *= extraAlpha;
  67610. alphaLevel >>= 8;
  67611. if (alphaLevel < 0xfe)
  67612. {
  67613. do
  67614. {
  67615. dest++ ->blend (*span++, alphaLevel);
  67616. } while (--width > 0);
  67617. }
  67618. else
  67619. {
  67620. do
  67621. {
  67622. dest++ ->blend (*span++);
  67623. } while (--width > 0);
  67624. }
  67625. }
  67626. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67627. {
  67628. handleEdgeTableLine (x, width, 255);
  67629. }
  67630. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67631. {
  67632. if (width > scratchSize)
  67633. {
  67634. scratchSize = width;
  67635. scratchBuffer.malloc (scratchSize);
  67636. }
  67637. y = y_;
  67638. generate (scratchBuffer.getData(), x, width);
  67639. et.clipLineToMask (x, y_,
  67640. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67641. sizeof (SrcPixelType), width);
  67642. }
  67643. private:
  67644. template <class PixelType>
  67645. void generate (PixelType* dest, const int x, int numPixels) throw()
  67646. {
  67647. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67648. do
  67649. {
  67650. int hiResX, hiResY;
  67651. this->interpolator.next (hiResX, hiResY);
  67652. int loResX = hiResX >> 8;
  67653. int loResY = hiResY >> 8;
  67654. if (repeatPattern)
  67655. {
  67656. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67657. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67658. }
  67659. if (betterQuality)
  67660. {
  67661. if (isPositiveAndBelow (loResX, maxX))
  67662. {
  67663. if (isPositiveAndBelow (loResY, maxY))
  67664. {
  67665. // In the centre of the image..
  67666. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67667. hiResX & 255, hiResY & 255);
  67668. ++dest;
  67669. continue;
  67670. }
  67671. else
  67672. {
  67673. // At a top or bottom edge..
  67674. if (! repeatPattern)
  67675. {
  67676. if (loResY < 0)
  67677. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67678. else
  67679. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67680. ++dest;
  67681. continue;
  67682. }
  67683. }
  67684. }
  67685. else
  67686. {
  67687. if (isPositiveAndBelow (loResY, maxY))
  67688. {
  67689. // At a left or right hand edge..
  67690. if (! repeatPattern)
  67691. {
  67692. if (loResX < 0)
  67693. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67694. else
  67695. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67696. ++dest;
  67697. continue;
  67698. }
  67699. }
  67700. }
  67701. }
  67702. if (! repeatPattern)
  67703. {
  67704. if (loResX < 0) loResX = 0;
  67705. if (loResY < 0) loResY = 0;
  67706. if (loResX > maxX) loResX = maxX;
  67707. if (loResY > maxY) loResY = maxY;
  67708. }
  67709. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67710. ++dest;
  67711. } while (--numPixels > 0);
  67712. }
  67713. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67714. {
  67715. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67716. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67717. c[0] += weight * src[0];
  67718. c[1] += weight * src[1];
  67719. c[2] += weight * src[2];
  67720. c[3] += weight * src[3];
  67721. weight = subPixelX * (256 - subPixelY);
  67722. c[0] += weight * src[4];
  67723. c[1] += weight * src[5];
  67724. c[2] += weight * src[6];
  67725. c[3] += weight * src[7];
  67726. src += this->srcData.lineStride;
  67727. weight = (256 - subPixelX) * subPixelY;
  67728. c[0] += weight * src[0];
  67729. c[1] += weight * src[1];
  67730. c[2] += weight * src[2];
  67731. c[3] += weight * src[3];
  67732. weight = subPixelX * subPixelY;
  67733. c[0] += weight * src[4];
  67734. c[1] += weight * src[5];
  67735. c[2] += weight * src[6];
  67736. c[3] += weight * src[7];
  67737. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67738. (uint8) (c[PixelARGB::indexR] >> 16),
  67739. (uint8) (c[PixelARGB::indexG] >> 16),
  67740. (uint8) (c[PixelARGB::indexB] >> 16));
  67741. }
  67742. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67743. {
  67744. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67745. uint32 weight = (256 - subPixelX) * alpha;
  67746. c[0] += weight * src[0];
  67747. c[1] += weight * src[1];
  67748. c[2] += weight * src[2];
  67749. c[3] += weight * src[3];
  67750. weight = subPixelX * alpha;
  67751. c[0] += weight * src[4];
  67752. c[1] += weight * src[5];
  67753. c[2] += weight * src[6];
  67754. c[3] += weight * src[7];
  67755. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67756. (uint8) (c[PixelARGB::indexR] >> 16),
  67757. (uint8) (c[PixelARGB::indexG] >> 16),
  67758. (uint8) (c[PixelARGB::indexB] >> 16));
  67759. }
  67760. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67761. {
  67762. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67763. uint32 weight = (256 - subPixelY) * alpha;
  67764. c[0] += weight * src[0];
  67765. c[1] += weight * src[1];
  67766. c[2] += weight * src[2];
  67767. c[3] += weight * src[3];
  67768. src += this->srcData.lineStride;
  67769. weight = subPixelY * alpha;
  67770. c[0] += weight * src[0];
  67771. c[1] += weight * src[1];
  67772. c[2] += weight * src[2];
  67773. c[3] += weight * src[3];
  67774. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67775. (uint8) (c[PixelARGB::indexR] >> 16),
  67776. (uint8) (c[PixelARGB::indexG] >> 16),
  67777. (uint8) (c[PixelARGB::indexB] >> 16));
  67778. }
  67779. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67780. {
  67781. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67782. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67783. c[0] += weight * src[0];
  67784. c[1] += weight * src[1];
  67785. c[2] += weight * src[2];
  67786. weight = subPixelX * (256 - subPixelY);
  67787. c[0] += weight * src[3];
  67788. c[1] += weight * src[4];
  67789. c[2] += weight * src[5];
  67790. src += this->srcData.lineStride;
  67791. weight = (256 - subPixelX) * subPixelY;
  67792. c[0] += weight * src[0];
  67793. c[1] += weight * src[1];
  67794. c[2] += weight * src[2];
  67795. weight = subPixelX * subPixelY;
  67796. c[0] += weight * src[3];
  67797. c[1] += weight * src[4];
  67798. c[2] += weight * src[5];
  67799. dest->setARGB ((uint8) 255,
  67800. (uint8) (c[PixelRGB::indexR] >> 16),
  67801. (uint8) (c[PixelRGB::indexG] >> 16),
  67802. (uint8) (c[PixelRGB::indexB] >> 16));
  67803. }
  67804. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67805. {
  67806. uint32 c[3] = { 128, 128, 128 };
  67807. uint32 weight = (256 - subPixelX);
  67808. c[0] += weight * src[0];
  67809. c[1] += weight * src[1];
  67810. c[2] += weight * src[2];
  67811. c[0] += subPixelX * src[3];
  67812. c[1] += subPixelX * src[4];
  67813. c[2] += subPixelX * src[5];
  67814. dest->setARGB ((uint8) 255,
  67815. (uint8) (c[PixelRGB::indexR] >> 8),
  67816. (uint8) (c[PixelRGB::indexG] >> 8),
  67817. (uint8) (c[PixelRGB::indexB] >> 8));
  67818. }
  67819. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67820. {
  67821. uint32 c[3] = { 128, 128, 128 };
  67822. uint32 weight = (256 - subPixelY);
  67823. c[0] += weight * src[0];
  67824. c[1] += weight * src[1];
  67825. c[2] += weight * src[2];
  67826. src += this->srcData.lineStride;
  67827. c[0] += subPixelY * src[0];
  67828. c[1] += subPixelY * src[1];
  67829. c[2] += subPixelY * src[2];
  67830. dest->setARGB ((uint8) 255,
  67831. (uint8) (c[PixelRGB::indexR] >> 8),
  67832. (uint8) (c[PixelRGB::indexG] >> 8),
  67833. (uint8) (c[PixelRGB::indexB] >> 8));
  67834. }
  67835. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67836. {
  67837. uint32 c = 256 * 128;
  67838. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67839. c += src[1] * (subPixelX * (256 - subPixelY));
  67840. src += this->srcData.lineStride;
  67841. c += src[0] * ((256 - subPixelX) * subPixelY);
  67842. c += src[1] * (subPixelX * subPixelY);
  67843. *((uint8*) dest) = (uint8) (c >> 16);
  67844. }
  67845. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67846. {
  67847. uint32 c = 256 * 128;
  67848. c += src[0] * (256 - subPixelX) * alpha;
  67849. c += src[1] * subPixelX * alpha;
  67850. *((uint8*) dest) = (uint8) (c >> 16);
  67851. }
  67852. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67853. {
  67854. uint32 c = 256 * 128;
  67855. c += src[0] * (256 - subPixelY) * alpha;
  67856. src += this->srcData.lineStride;
  67857. c += src[0] * subPixelY * alpha;
  67858. *((uint8*) dest) = (uint8) (c >> 16);
  67859. }
  67860. class TransformedImageSpanInterpolator
  67861. {
  67862. public:
  67863. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67864. : inverseTransform (transform.inverted()),
  67865. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67866. {}
  67867. void setStartOfLine (float x, float y, const int numPixels) throw()
  67868. {
  67869. jassert (numPixels > 0);
  67870. x += pixelOffset;
  67871. y += pixelOffset;
  67872. float x1 = x, y1 = y;
  67873. x += numPixels;
  67874. inverseTransform.transformPoints (x1, y1, x, y);
  67875. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67876. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67877. }
  67878. void next (int& x, int& y) throw()
  67879. {
  67880. x = xBresenham.n;
  67881. xBresenham.stepToNext();
  67882. y = yBresenham.n;
  67883. yBresenham.stepToNext();
  67884. }
  67885. private:
  67886. class BresenhamInterpolator
  67887. {
  67888. public:
  67889. BresenhamInterpolator() throw() {}
  67890. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67891. {
  67892. numSteps = numSteps_;
  67893. step = (n2 - n1) / numSteps;
  67894. remainder = modulo = (n2 - n1) % numSteps;
  67895. n = n1 + pixelOffsetInt;
  67896. if (modulo <= 0)
  67897. {
  67898. modulo += numSteps;
  67899. remainder += numSteps;
  67900. --step;
  67901. }
  67902. modulo -= numSteps;
  67903. }
  67904. forcedinline void stepToNext() throw()
  67905. {
  67906. modulo += remainder;
  67907. n += step;
  67908. if (modulo > 0)
  67909. {
  67910. modulo -= numSteps;
  67911. ++n;
  67912. }
  67913. }
  67914. int n;
  67915. private:
  67916. int numSteps, step, modulo, remainder;
  67917. };
  67918. const AffineTransform inverseTransform;
  67919. BresenhamInterpolator xBresenham, yBresenham;
  67920. const float pixelOffset;
  67921. const int pixelOffsetInt;
  67922. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67923. };
  67924. TransformedImageSpanInterpolator interpolator;
  67925. const Image::BitmapData& destData;
  67926. const Image::BitmapData& srcData;
  67927. const int extraAlpha;
  67928. const bool betterQuality;
  67929. const int maxX, maxY;
  67930. int y;
  67931. DestPixelType* linePixels;
  67932. HeapBlock <SrcPixelType> scratchBuffer;
  67933. int scratchSize;
  67934. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67935. };
  67936. class ClipRegionBase : public ReferenceCountedObject
  67937. {
  67938. public:
  67939. ClipRegionBase() {}
  67940. virtual ~ClipRegionBase() {}
  67941. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67942. virtual const Ptr clone() const = 0;
  67943. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67944. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67945. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67946. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67947. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67948. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67949. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67950. virtual const Ptr translated (const Point<int>& delta) = 0;
  67951. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67952. virtual const Rectangle<int> getClipBounds() const = 0;
  67953. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67954. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67955. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67956. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67957. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67958. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67959. protected:
  67960. template <class Iterator>
  67961. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67962. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67963. {
  67964. switch (destData.pixelFormat)
  67965. {
  67966. case Image::ARGB:
  67967. switch (srcData.pixelFormat)
  67968. {
  67969. case Image::ARGB:
  67970. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67971. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67972. break;
  67973. case Image::RGB:
  67974. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67975. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67976. break;
  67977. default:
  67978. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67979. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67980. break;
  67981. }
  67982. break;
  67983. case Image::RGB:
  67984. switch (srcData.pixelFormat)
  67985. {
  67986. case Image::ARGB:
  67987. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67988. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67989. break;
  67990. case Image::RGB:
  67991. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67992. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67993. break;
  67994. default:
  67995. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67996. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67997. break;
  67998. }
  67999. break;
  68000. default:
  68001. switch (srcData.pixelFormat)
  68002. {
  68003. case Image::ARGB:
  68004. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68005. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68006. break;
  68007. case Image::RGB:
  68008. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68009. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68010. break;
  68011. default:
  68012. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68013. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68014. break;
  68015. }
  68016. break;
  68017. }
  68018. }
  68019. template <class Iterator>
  68020. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68021. {
  68022. switch (destData.pixelFormat)
  68023. {
  68024. case Image::ARGB:
  68025. switch (srcData.pixelFormat)
  68026. {
  68027. case Image::ARGB:
  68028. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68029. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68030. break;
  68031. case Image::RGB:
  68032. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68033. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68034. break;
  68035. default:
  68036. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68037. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68038. break;
  68039. }
  68040. break;
  68041. case Image::RGB:
  68042. switch (srcData.pixelFormat)
  68043. {
  68044. case Image::ARGB:
  68045. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68046. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68047. break;
  68048. case Image::RGB:
  68049. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68050. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68051. break;
  68052. default:
  68053. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68054. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68055. break;
  68056. }
  68057. break;
  68058. default:
  68059. switch (srcData.pixelFormat)
  68060. {
  68061. case Image::ARGB:
  68062. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68063. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68064. break;
  68065. case Image::RGB:
  68066. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68067. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68068. break;
  68069. default:
  68070. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68071. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68072. break;
  68073. }
  68074. break;
  68075. }
  68076. }
  68077. template <class Iterator, class DestPixelType>
  68078. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68079. {
  68080. jassert (destData.pixelStride == sizeof (DestPixelType));
  68081. if (replaceContents)
  68082. {
  68083. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68084. iter.iterate (r);
  68085. }
  68086. else
  68087. {
  68088. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68089. iter.iterate (r);
  68090. }
  68091. }
  68092. template <class Iterator, class DestPixelType>
  68093. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68094. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68095. {
  68096. jassert (destData.pixelStride == sizeof (DestPixelType));
  68097. if (g.isRadial)
  68098. {
  68099. if (isIdentity)
  68100. {
  68101. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68102. iter.iterate (renderer);
  68103. }
  68104. else
  68105. {
  68106. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68107. iter.iterate (renderer);
  68108. }
  68109. }
  68110. else
  68111. {
  68112. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68113. iter.iterate (renderer);
  68114. }
  68115. }
  68116. };
  68117. class ClipRegion_EdgeTable : public ClipRegionBase
  68118. {
  68119. public:
  68120. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68121. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68122. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68123. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68124. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68125. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68126. ~ClipRegion_EdgeTable() {}
  68127. const Ptr clone() const
  68128. {
  68129. return new ClipRegion_EdgeTable (*this);
  68130. }
  68131. const Ptr applyClipTo (const Ptr& target) const
  68132. {
  68133. return target->clipToEdgeTable (edgeTable);
  68134. }
  68135. const Ptr clipToRectangle (const Rectangle<int>& r)
  68136. {
  68137. edgeTable.clipToRectangle (r);
  68138. return edgeTable.isEmpty() ? 0 : this;
  68139. }
  68140. const Ptr clipToRectangleList (const RectangleList& r)
  68141. {
  68142. RectangleList inverse (edgeTable.getMaximumBounds());
  68143. if (inverse.subtract (r))
  68144. for (RectangleList::Iterator iter (inverse); iter.next();)
  68145. edgeTable.excludeRectangle (*iter.getRectangle());
  68146. return edgeTable.isEmpty() ? 0 : this;
  68147. }
  68148. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68149. {
  68150. edgeTable.excludeRectangle (r);
  68151. return edgeTable.isEmpty() ? 0 : this;
  68152. }
  68153. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68154. {
  68155. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68156. edgeTable.clipToEdgeTable (et);
  68157. return edgeTable.isEmpty() ? 0 : this;
  68158. }
  68159. const Ptr clipToEdgeTable (const EdgeTable& et)
  68160. {
  68161. edgeTable.clipToEdgeTable (et);
  68162. return edgeTable.isEmpty() ? 0 : this;
  68163. }
  68164. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68165. {
  68166. const Image::BitmapData srcData (image, false);
  68167. if (transform.isOnlyTranslation())
  68168. {
  68169. // If our translation doesn't involve any distortion, just use a simple blit..
  68170. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68171. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68172. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68173. {
  68174. const int imageX = ((tx + 128) >> 8);
  68175. const int imageY = ((ty + 128) >> 8);
  68176. if (image.getFormat() == Image::ARGB)
  68177. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68178. else
  68179. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68180. return edgeTable.isEmpty() ? 0 : this;
  68181. }
  68182. }
  68183. if (transform.isSingularity())
  68184. return 0;
  68185. {
  68186. Path p;
  68187. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68188. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68189. edgeTable.clipToEdgeTable (et2);
  68190. }
  68191. if (! edgeTable.isEmpty())
  68192. {
  68193. if (image.getFormat() == Image::ARGB)
  68194. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68195. else
  68196. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68197. }
  68198. return edgeTable.isEmpty() ? 0 : this;
  68199. }
  68200. const Ptr translated (const Point<int>& delta)
  68201. {
  68202. edgeTable.translate ((float) delta.getX(), delta.getY());
  68203. return edgeTable.isEmpty() ? 0 : this;
  68204. }
  68205. bool clipRegionIntersects (const Rectangle<int>& r) const
  68206. {
  68207. return edgeTable.getMaximumBounds().intersects (r);
  68208. }
  68209. const Rectangle<int> getClipBounds() const
  68210. {
  68211. return edgeTable.getMaximumBounds();
  68212. }
  68213. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68214. {
  68215. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68216. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68217. if (! clipped.isEmpty())
  68218. {
  68219. ClipRegion_EdgeTable et (clipped);
  68220. et.edgeTable.clipToEdgeTable (edgeTable);
  68221. et.fillAllWithColour (destData, colour, replaceContents);
  68222. }
  68223. }
  68224. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68225. {
  68226. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68227. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68228. if (! clipped.isEmpty())
  68229. {
  68230. ClipRegion_EdgeTable et (clipped);
  68231. et.edgeTable.clipToEdgeTable (edgeTable);
  68232. et.fillAllWithColour (destData, colour, false);
  68233. }
  68234. }
  68235. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68236. {
  68237. switch (destData.pixelFormat)
  68238. {
  68239. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68240. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68241. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68242. }
  68243. }
  68244. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68245. {
  68246. HeapBlock <PixelARGB> lookupTable;
  68247. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68248. jassert (numLookupEntries > 0);
  68249. switch (destData.pixelFormat)
  68250. {
  68251. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68252. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68253. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68254. }
  68255. }
  68256. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68257. {
  68258. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68259. }
  68260. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68261. {
  68262. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68263. }
  68264. EdgeTable edgeTable;
  68265. private:
  68266. template <class SrcPixelType>
  68267. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68268. {
  68269. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68270. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68271. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68272. edgeTable.getMaximumBounds().getWidth());
  68273. }
  68274. template <class SrcPixelType>
  68275. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68276. {
  68277. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68278. edgeTable.clipToRectangle (r);
  68279. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68280. for (int y = 0; y < r.getHeight(); ++y)
  68281. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68282. }
  68283. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68284. };
  68285. class ClipRegion_RectangleList : public ClipRegionBase
  68286. {
  68287. public:
  68288. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68289. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68290. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68291. ~ClipRegion_RectangleList() {}
  68292. const Ptr clone() const
  68293. {
  68294. return new ClipRegion_RectangleList (*this);
  68295. }
  68296. const Ptr applyClipTo (const Ptr& target) const
  68297. {
  68298. return target->clipToRectangleList (clip);
  68299. }
  68300. const Ptr clipToRectangle (const Rectangle<int>& r)
  68301. {
  68302. clip.clipTo (r);
  68303. return clip.isEmpty() ? 0 : this;
  68304. }
  68305. const Ptr clipToRectangleList (const RectangleList& r)
  68306. {
  68307. clip.clipTo (r);
  68308. return clip.isEmpty() ? 0 : this;
  68309. }
  68310. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68311. {
  68312. clip.subtract (r);
  68313. return clip.isEmpty() ? 0 : this;
  68314. }
  68315. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68316. {
  68317. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68318. }
  68319. const Ptr clipToEdgeTable (const EdgeTable& et)
  68320. {
  68321. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68322. }
  68323. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68324. {
  68325. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68326. }
  68327. const Ptr translated (const Point<int>& delta)
  68328. {
  68329. clip.offsetAll (delta.getX(), delta.getY());
  68330. return clip.isEmpty() ? 0 : this;
  68331. }
  68332. bool clipRegionIntersects (const Rectangle<int>& r) const
  68333. {
  68334. return clip.intersects (r);
  68335. }
  68336. const Rectangle<int> getClipBounds() const
  68337. {
  68338. return clip.getBounds();
  68339. }
  68340. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68341. {
  68342. SubRectangleIterator iter (clip, area);
  68343. switch (destData.pixelFormat)
  68344. {
  68345. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68346. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68347. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68348. }
  68349. }
  68350. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68351. {
  68352. SubRectangleIteratorFloat iter (clip, area);
  68353. switch (destData.pixelFormat)
  68354. {
  68355. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68356. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68357. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68358. }
  68359. }
  68360. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68361. {
  68362. switch (destData.pixelFormat)
  68363. {
  68364. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68365. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68366. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68367. }
  68368. }
  68369. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68370. {
  68371. HeapBlock <PixelARGB> lookupTable;
  68372. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68373. jassert (numLookupEntries > 0);
  68374. switch (destData.pixelFormat)
  68375. {
  68376. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68377. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68378. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68379. }
  68380. }
  68381. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68382. {
  68383. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68384. }
  68385. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68386. {
  68387. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68388. }
  68389. RectangleList clip;
  68390. template <class Renderer>
  68391. void iterate (Renderer& r) const throw()
  68392. {
  68393. RectangleList::Iterator iter (clip);
  68394. while (iter.next())
  68395. {
  68396. const Rectangle<int> rect (*iter.getRectangle());
  68397. const int x = rect.getX();
  68398. const int w = rect.getWidth();
  68399. jassert (w > 0);
  68400. const int bottom = rect.getBottom();
  68401. for (int y = rect.getY(); y < bottom; ++y)
  68402. {
  68403. r.setEdgeTableYPos (y);
  68404. r.handleEdgeTableLineFull (x, w);
  68405. }
  68406. }
  68407. }
  68408. private:
  68409. class SubRectangleIterator
  68410. {
  68411. public:
  68412. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68413. : clip (clip_), area (area_)
  68414. {
  68415. }
  68416. template <class Renderer>
  68417. void iterate (Renderer& r) const throw()
  68418. {
  68419. RectangleList::Iterator iter (clip);
  68420. while (iter.next())
  68421. {
  68422. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68423. if (! rect.isEmpty())
  68424. {
  68425. const int x = rect.getX();
  68426. const int w = rect.getWidth();
  68427. const int bottom = rect.getBottom();
  68428. for (int y = rect.getY(); y < bottom; ++y)
  68429. {
  68430. r.setEdgeTableYPos (y);
  68431. r.handleEdgeTableLineFull (x, w);
  68432. }
  68433. }
  68434. }
  68435. }
  68436. private:
  68437. const RectangleList& clip;
  68438. const Rectangle<int> area;
  68439. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68440. };
  68441. class SubRectangleIteratorFloat
  68442. {
  68443. public:
  68444. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68445. : clip (clip_), area (area_)
  68446. {
  68447. }
  68448. template <class Renderer>
  68449. void iterate (Renderer& r) const throw()
  68450. {
  68451. int left = roundToInt (area.getX() * 256.0f);
  68452. int top = roundToInt (area.getY() * 256.0f);
  68453. int right = roundToInt (area.getRight() * 256.0f);
  68454. int bottom = roundToInt (area.getBottom() * 256.0f);
  68455. int totalTop, totalLeft, totalBottom, totalRight;
  68456. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68457. if ((top >> 8) == (bottom >> 8))
  68458. {
  68459. topAlpha = bottom - top;
  68460. bottomAlpha = 0;
  68461. totalTop = top >> 8;
  68462. totalBottom = bottom = top = totalTop + 1;
  68463. }
  68464. else
  68465. {
  68466. if ((top & 255) == 0)
  68467. {
  68468. topAlpha = 0;
  68469. top = totalTop = (top >> 8);
  68470. }
  68471. else
  68472. {
  68473. topAlpha = 255 - (top & 255);
  68474. totalTop = (top >> 8);
  68475. top = totalTop + 1;
  68476. }
  68477. bottomAlpha = bottom & 255;
  68478. bottom >>= 8;
  68479. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68480. }
  68481. if ((left >> 8) == (right >> 8))
  68482. {
  68483. leftAlpha = right - left;
  68484. rightAlpha = 0;
  68485. totalLeft = (left >> 8);
  68486. totalRight = right = left = totalLeft + 1;
  68487. }
  68488. else
  68489. {
  68490. if ((left & 255) == 0)
  68491. {
  68492. leftAlpha = 0;
  68493. left = totalLeft = (left >> 8);
  68494. }
  68495. else
  68496. {
  68497. leftAlpha = 255 - (left & 255);
  68498. totalLeft = (left >> 8);
  68499. left = totalLeft + 1;
  68500. }
  68501. rightAlpha = right & 255;
  68502. right >>= 8;
  68503. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68504. }
  68505. RectangleList::Iterator iter (clip);
  68506. while (iter.next())
  68507. {
  68508. const int clipLeft = iter.getRectangle()->getX();
  68509. const int clipRight = iter.getRectangle()->getRight();
  68510. const int clipTop = iter.getRectangle()->getY();
  68511. const int clipBottom = iter.getRectangle()->getBottom();
  68512. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68513. {
  68514. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68515. {
  68516. if (topAlpha != 0 && totalTop >= clipTop)
  68517. {
  68518. r.setEdgeTableYPos (totalTop);
  68519. r.handleEdgeTablePixel (left, topAlpha);
  68520. }
  68521. const int endY = jmin (bottom, clipBottom);
  68522. for (int y = jmax (clipTop, top); y < endY; ++y)
  68523. {
  68524. r.setEdgeTableYPos (y);
  68525. r.handleEdgeTablePixelFull (left);
  68526. }
  68527. if (bottomAlpha != 0 && bottom < clipBottom)
  68528. {
  68529. r.setEdgeTableYPos (bottom);
  68530. r.handleEdgeTablePixel (left, bottomAlpha);
  68531. }
  68532. }
  68533. else
  68534. {
  68535. const int clippedLeft = jmax (left, clipLeft);
  68536. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68537. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68538. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68539. if (topAlpha != 0 && totalTop >= clipTop)
  68540. {
  68541. r.setEdgeTableYPos (totalTop);
  68542. if (doLeftAlpha)
  68543. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68544. if (clippedWidth > 0)
  68545. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68546. if (doRightAlpha)
  68547. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68548. }
  68549. const int endY = jmin (bottom, clipBottom);
  68550. for (int y = jmax (clipTop, top); y < endY; ++y)
  68551. {
  68552. r.setEdgeTableYPos (y);
  68553. if (doLeftAlpha)
  68554. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68555. if (clippedWidth > 0)
  68556. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68557. if (doRightAlpha)
  68558. r.handleEdgeTablePixel (right, rightAlpha);
  68559. }
  68560. if (bottomAlpha != 0 && bottom < clipBottom)
  68561. {
  68562. r.setEdgeTableYPos (bottom);
  68563. if (doLeftAlpha)
  68564. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68565. if (clippedWidth > 0)
  68566. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68567. if (doRightAlpha)
  68568. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68569. }
  68570. }
  68571. }
  68572. }
  68573. }
  68574. private:
  68575. const RectangleList& clip;
  68576. const Rectangle<float>& area;
  68577. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68578. };
  68579. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68580. };
  68581. }
  68582. class LowLevelGraphicsSoftwareRenderer::SavedState
  68583. {
  68584. public:
  68585. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68586. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68587. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68588. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68589. {
  68590. }
  68591. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68592. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68593. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68594. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68595. {
  68596. }
  68597. SavedState (const SavedState& other)
  68598. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68599. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68600. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68601. interpolationQuality (other.interpolationQuality)
  68602. {
  68603. }
  68604. void setOrigin (const int x, const int y) throw()
  68605. {
  68606. if (isOnlyTranslated)
  68607. {
  68608. xOffset += x;
  68609. yOffset += y;
  68610. }
  68611. else
  68612. {
  68613. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68614. }
  68615. }
  68616. void addTransform (const AffineTransform& t)
  68617. {
  68618. if ((! isOnlyTranslated)
  68619. || (! t.isOnlyTranslation())
  68620. || (int) (t.getTranslationX() * 256.0f) != 0
  68621. || (int) (t.getTranslationY() * 256.0f) != 0)
  68622. {
  68623. complexTransform = getTransformWith (t);
  68624. isOnlyTranslated = false;
  68625. }
  68626. else
  68627. {
  68628. xOffset += (int) t.getTranslationX();
  68629. yOffset += (int) t.getTranslationY();
  68630. }
  68631. }
  68632. float getScaleFactor() const
  68633. {
  68634. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68635. }
  68636. bool clipToRectangle (const Rectangle<int>& r)
  68637. {
  68638. if (clip != 0)
  68639. {
  68640. if (isOnlyTranslated)
  68641. {
  68642. cloneClipIfMultiplyReferenced();
  68643. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68644. }
  68645. else
  68646. {
  68647. Path p;
  68648. p.addRectangle (r);
  68649. clipToPath (p, AffineTransform::identity);
  68650. }
  68651. }
  68652. return clip != 0;
  68653. }
  68654. bool clipToRectangleList (const RectangleList& r)
  68655. {
  68656. if (clip != 0)
  68657. {
  68658. if (isOnlyTranslated)
  68659. {
  68660. cloneClipIfMultiplyReferenced();
  68661. RectangleList offsetList (r);
  68662. offsetList.offsetAll (xOffset, yOffset);
  68663. clip = clip->clipToRectangleList (offsetList);
  68664. }
  68665. else
  68666. {
  68667. clipToPath (r.toPath(), AffineTransform::identity);
  68668. }
  68669. }
  68670. return clip != 0;
  68671. }
  68672. bool excludeClipRectangle (const Rectangle<int>& r)
  68673. {
  68674. if (clip != 0)
  68675. {
  68676. cloneClipIfMultiplyReferenced();
  68677. if (isOnlyTranslated)
  68678. {
  68679. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68680. }
  68681. else
  68682. {
  68683. Path p;
  68684. p.addRectangle (r.toFloat());
  68685. p.applyTransform (complexTransform);
  68686. p.addRectangle (clip->getClipBounds().toFloat());
  68687. p.setUsingNonZeroWinding (false);
  68688. clip = clip->clipToPath (p, AffineTransform::identity);
  68689. }
  68690. }
  68691. return clip != 0;
  68692. }
  68693. void clipToPath (const Path& p, const AffineTransform& transform)
  68694. {
  68695. if (clip != 0)
  68696. {
  68697. cloneClipIfMultiplyReferenced();
  68698. clip = clip->clipToPath (p, getTransformWith (transform));
  68699. }
  68700. }
  68701. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68702. {
  68703. if (clip != 0)
  68704. {
  68705. if (sourceImage.hasAlphaChannel())
  68706. {
  68707. cloneClipIfMultiplyReferenced();
  68708. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68709. interpolationQuality != Graphics::lowResamplingQuality);
  68710. }
  68711. else
  68712. {
  68713. Path p;
  68714. p.addRectangle (sourceImage.getBounds());
  68715. clipToPath (p, t);
  68716. }
  68717. }
  68718. }
  68719. bool clipRegionIntersects (const Rectangle<int>& r) const
  68720. {
  68721. if (clip != 0)
  68722. {
  68723. if (isOnlyTranslated)
  68724. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68725. else
  68726. return getClipBounds().intersects (r);
  68727. }
  68728. return false;
  68729. }
  68730. const Rectangle<int> getUntransformedClipBounds() const
  68731. {
  68732. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68733. }
  68734. const Rectangle<int> getClipBounds() const
  68735. {
  68736. if (clip != 0)
  68737. {
  68738. if (isOnlyTranslated)
  68739. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68740. else
  68741. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68742. }
  68743. return Rectangle<int>();
  68744. }
  68745. SavedState* beginTransparencyLayer (float opacity)
  68746. {
  68747. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68748. SavedState* s = new SavedState (*this);
  68749. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68750. s->compositionAlpha = opacity;
  68751. if (s->isOnlyTranslated)
  68752. {
  68753. s->xOffset -= layerBounds.getX();
  68754. s->yOffset -= layerBounds.getY();
  68755. }
  68756. else
  68757. {
  68758. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68759. (float) -layerBounds.getY()));
  68760. }
  68761. s->cloneClipIfMultiplyReferenced();
  68762. s->clip = s->clip->translated (-layerBounds.getPosition());
  68763. return s;
  68764. }
  68765. void endTransparencyLayer (SavedState& layerState)
  68766. {
  68767. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68768. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68769. g->setOpacity (layerState.compositionAlpha);
  68770. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68771. (float) layerBounds.getY()), false);
  68772. }
  68773. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68774. {
  68775. if (clip != 0)
  68776. {
  68777. if (isOnlyTranslated)
  68778. {
  68779. if (fillType.isColour())
  68780. {
  68781. Image::BitmapData destData (image, true);
  68782. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68783. }
  68784. else
  68785. {
  68786. const Rectangle<int> totalClip (clip->getClipBounds());
  68787. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68788. if (! clipped.isEmpty())
  68789. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68790. }
  68791. }
  68792. else
  68793. {
  68794. Path p;
  68795. p.addRectangle (r);
  68796. fillPath (p, AffineTransform::identity);
  68797. }
  68798. }
  68799. }
  68800. void fillRect (const Rectangle<float>& r)
  68801. {
  68802. if (clip != 0)
  68803. {
  68804. if (isOnlyTranslated)
  68805. {
  68806. if (fillType.isColour())
  68807. {
  68808. Image::BitmapData destData (image, true);
  68809. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68810. }
  68811. else
  68812. {
  68813. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68814. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68815. if (! clipped.isEmpty())
  68816. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68817. }
  68818. }
  68819. else
  68820. {
  68821. Path p;
  68822. p.addRectangle (r);
  68823. fillPath (p, AffineTransform::identity);
  68824. }
  68825. }
  68826. }
  68827. void fillPath (const Path& path, const AffineTransform& transform)
  68828. {
  68829. if (clip != 0)
  68830. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68831. }
  68832. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68833. {
  68834. jassert (isOnlyTranslated);
  68835. if (clip != 0)
  68836. {
  68837. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68838. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68839. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68840. fillShape (shapeToFill, false);
  68841. }
  68842. }
  68843. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68844. {
  68845. jassert (clip != 0);
  68846. shapeToFill = clip->applyClipTo (shapeToFill);
  68847. if (shapeToFill != 0)
  68848. {
  68849. Image::BitmapData destData (image, true);
  68850. if (fillType.isGradient())
  68851. {
  68852. jassert (! replaceContents); // that option is just for solid colours
  68853. ColourGradient g2 (*(fillType.gradient));
  68854. g2.multiplyOpacity (fillType.getOpacity());
  68855. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68856. const bool isIdentity = transform.isOnlyTranslation();
  68857. if (isIdentity)
  68858. {
  68859. // If our translation doesn't involve any distortion, we can speed it up..
  68860. g2.point1.applyTransform (transform);
  68861. g2.point2.applyTransform (transform);
  68862. transform = AffineTransform::identity;
  68863. }
  68864. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68865. }
  68866. else if (fillType.isTiledImage())
  68867. {
  68868. renderImage (fillType.image, fillType.transform, shapeToFill);
  68869. }
  68870. else
  68871. {
  68872. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68873. }
  68874. }
  68875. }
  68876. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68877. {
  68878. const AffineTransform transform (getTransformWith (t));
  68879. const Image::BitmapData destData (image, true);
  68880. const Image::BitmapData srcData (sourceImage, false);
  68881. const int alpha = fillType.colour.getAlpha();
  68882. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68883. if (transform.isOnlyTranslation())
  68884. {
  68885. // If our translation doesn't involve any distortion, just use a simple blit..
  68886. int tx = (int) (transform.getTranslationX() * 256.0f);
  68887. int ty = (int) (transform.getTranslationY() * 256.0f);
  68888. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68889. {
  68890. tx = ((tx + 128) >> 8);
  68891. ty = ((ty + 128) >> 8);
  68892. if (tiledFillClipRegion != 0)
  68893. {
  68894. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68895. }
  68896. else
  68897. {
  68898. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68899. c = clip->applyClipTo (c);
  68900. if (c != 0)
  68901. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68902. }
  68903. return;
  68904. }
  68905. }
  68906. if (transform.isSingularity())
  68907. return;
  68908. if (tiledFillClipRegion != 0)
  68909. {
  68910. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68911. }
  68912. else
  68913. {
  68914. Path p;
  68915. p.addRectangle (sourceImage.getBounds());
  68916. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68917. c = c->clipToPath (p, transform);
  68918. if (c != 0)
  68919. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68920. }
  68921. }
  68922. Image image;
  68923. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68924. private:
  68925. AffineTransform complexTransform;
  68926. int xOffset, yOffset;
  68927. float compositionAlpha;
  68928. public:
  68929. bool isOnlyTranslated;
  68930. Font font;
  68931. FillType fillType;
  68932. Graphics::ResamplingQuality interpolationQuality;
  68933. private:
  68934. void cloneClipIfMultiplyReferenced()
  68935. {
  68936. if (clip->getReferenceCount() > 1)
  68937. clip = clip->clone();
  68938. }
  68939. const AffineTransform getTransform() const
  68940. {
  68941. if (isOnlyTranslated)
  68942. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68943. return complexTransform;
  68944. }
  68945. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68946. {
  68947. if (isOnlyTranslated)
  68948. return userTransform.translated ((float) xOffset, (float) yOffset);
  68949. return userTransform.followedBy (complexTransform);
  68950. }
  68951. SavedState& operator= (const SavedState&);
  68952. };
  68953. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68954. : image (image_),
  68955. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  68956. {
  68957. }
  68958. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68959. const RectangleList& initialClip)
  68960. : image (image_),
  68961. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  68962. {
  68963. }
  68964. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68965. {
  68966. }
  68967. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68968. {
  68969. return false;
  68970. }
  68971. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68972. {
  68973. currentState->setOrigin (x, y);
  68974. }
  68975. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  68976. {
  68977. currentState->addTransform (transform);
  68978. }
  68979. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  68980. {
  68981. return currentState->getScaleFactor();
  68982. }
  68983. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68984. {
  68985. return currentState->clipToRectangle (r);
  68986. }
  68987. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68988. {
  68989. return currentState->clipToRectangleList (clipRegion);
  68990. }
  68991. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68992. {
  68993. currentState->excludeClipRectangle (r);
  68994. }
  68995. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68996. {
  68997. currentState->clipToPath (path, transform);
  68998. }
  68999. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69000. {
  69001. currentState->clipToImageAlpha (sourceImage, transform);
  69002. }
  69003. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69004. {
  69005. return currentState->clipRegionIntersects (r);
  69006. }
  69007. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69008. {
  69009. return currentState->getClipBounds();
  69010. }
  69011. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69012. {
  69013. return currentState->clip == 0;
  69014. }
  69015. void LowLevelGraphicsSoftwareRenderer::saveState()
  69016. {
  69017. stateStack.add (new SavedState (*currentState));
  69018. }
  69019. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69020. {
  69021. SavedState* const top = stateStack.getLast();
  69022. if (top != 0)
  69023. {
  69024. currentState = top;
  69025. stateStack.removeLast (1, false);
  69026. }
  69027. else
  69028. {
  69029. jassertfalse; // trying to pop with an empty stack!
  69030. }
  69031. }
  69032. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69033. {
  69034. saveState();
  69035. currentState = currentState->beginTransparencyLayer (opacity);
  69036. }
  69037. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69038. {
  69039. const ScopedPointer<SavedState> layer (currentState);
  69040. restoreState();
  69041. currentState->endTransparencyLayer (*layer);
  69042. }
  69043. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69044. {
  69045. currentState->fillType = fillType;
  69046. }
  69047. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69048. {
  69049. currentState->fillType.setOpacity (newOpacity);
  69050. }
  69051. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69052. {
  69053. currentState->interpolationQuality = quality;
  69054. }
  69055. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69056. {
  69057. currentState->fillRect (r, replaceExistingContents);
  69058. }
  69059. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69060. {
  69061. currentState->fillPath (path, transform);
  69062. }
  69063. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69064. {
  69065. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69066. }
  69067. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69068. {
  69069. Path p;
  69070. p.addLineSegment (line, 1.0f);
  69071. fillPath (p, AffineTransform::identity);
  69072. }
  69073. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69074. {
  69075. if (bottom > top)
  69076. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69077. }
  69078. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69079. {
  69080. if (right > left)
  69081. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69082. }
  69083. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69084. {
  69085. public:
  69086. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69087. void draw (SavedState& state, float x, const float y) const
  69088. {
  69089. if (snapToIntegerCoordinate)
  69090. x = std::floor (x + 0.5f);
  69091. if (edgeTable != 0)
  69092. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69093. }
  69094. void generate (const Font& newFont, const int glyphNumber)
  69095. {
  69096. font = newFont;
  69097. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69098. glyph = glyphNumber;
  69099. edgeTable = 0;
  69100. Path glyphPath;
  69101. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69102. if (! glyphPath.isEmpty())
  69103. {
  69104. const float fontHeight = font.getHeight();
  69105. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69106. #if JUCE_MAC || JUCE_IOS
  69107. .translated (0.0f, -0.5f)
  69108. #endif
  69109. );
  69110. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69111. glyphPath, transform);
  69112. }
  69113. }
  69114. Font font;
  69115. int glyph, lastAccessCount;
  69116. bool snapToIntegerCoordinate;
  69117. private:
  69118. ScopedPointer <EdgeTable> edgeTable;
  69119. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69120. };
  69121. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69122. {
  69123. public:
  69124. GlyphCache()
  69125. : accessCounter (0), hits (0), misses (0)
  69126. {
  69127. addNewGlyphSlots (120);
  69128. }
  69129. ~GlyphCache()
  69130. {
  69131. clearSingletonInstance();
  69132. }
  69133. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69134. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69135. {
  69136. ++accessCounter;
  69137. int oldestCounter = std::numeric_limits<int>::max();
  69138. CachedGlyph* oldest = 0;
  69139. for (int i = glyphs.size(); --i >= 0;)
  69140. {
  69141. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69142. if (glyph->glyph == glyphNumber && glyph->font == font)
  69143. {
  69144. ++hits;
  69145. glyph->lastAccessCount = accessCounter;
  69146. glyph->draw (state, x, y);
  69147. return;
  69148. }
  69149. if (glyph->lastAccessCount <= oldestCounter)
  69150. {
  69151. oldestCounter = glyph->lastAccessCount;
  69152. oldest = glyph;
  69153. }
  69154. }
  69155. if (hits + ++misses > (glyphs.size() << 4))
  69156. {
  69157. if (misses * 2 > hits)
  69158. addNewGlyphSlots (32);
  69159. hits = misses = 0;
  69160. oldest = glyphs.getLast();
  69161. }
  69162. jassert (oldest != 0);
  69163. oldest->lastAccessCount = accessCounter;
  69164. oldest->generate (font, glyphNumber);
  69165. oldest->draw (state, x, y);
  69166. }
  69167. private:
  69168. friend class OwnedArray <CachedGlyph>;
  69169. OwnedArray <CachedGlyph> glyphs;
  69170. int accessCounter, hits, misses;
  69171. void addNewGlyphSlots (int num)
  69172. {
  69173. while (--num >= 0)
  69174. glyphs.add (new CachedGlyph());
  69175. }
  69176. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69177. };
  69178. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69179. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69180. {
  69181. currentState->font = newFont;
  69182. }
  69183. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69184. {
  69185. return currentState->font;
  69186. }
  69187. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69188. {
  69189. Font& f = currentState->font;
  69190. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69191. {
  69192. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69193. transform.getTranslationX(),
  69194. transform.getTranslationY());
  69195. }
  69196. else
  69197. {
  69198. Path p;
  69199. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69200. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69201. }
  69202. }
  69203. #if JUCE_MSVC
  69204. #pragma warning (pop)
  69205. #if JUCE_DEBUG
  69206. #pragma optimize ("", on) // resets optimisations to the project defaults
  69207. #endif
  69208. #endif
  69209. END_JUCE_NAMESPACE
  69210. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69211. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69212. BEGIN_JUCE_NAMESPACE
  69213. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69214. : flags (other.flags)
  69215. {
  69216. }
  69217. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69218. {
  69219. flags = other.flags;
  69220. return *this;
  69221. }
  69222. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69223. const double dx, const double dy, const double dw, const double dh) const throw()
  69224. {
  69225. if (w == 0 || h == 0)
  69226. return;
  69227. if ((flags & stretchToFit) != 0)
  69228. {
  69229. x = dx;
  69230. y = dy;
  69231. w = dw;
  69232. h = dh;
  69233. }
  69234. else
  69235. {
  69236. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69237. : jmin (dw / w, dh / h);
  69238. if ((flags & onlyReduceInSize) != 0)
  69239. scale = jmin (scale, 1.0);
  69240. if ((flags & onlyIncreaseInSize) != 0)
  69241. scale = jmax (scale, 1.0);
  69242. w *= scale;
  69243. h *= scale;
  69244. if ((flags & xLeft) != 0)
  69245. x = dx;
  69246. else if ((flags & xRight) != 0)
  69247. x = dx + dw - w;
  69248. else
  69249. x = dx + (dw - w) * 0.5;
  69250. if ((flags & yTop) != 0)
  69251. y = dy;
  69252. else if ((flags & yBottom) != 0)
  69253. y = dy + dh - h;
  69254. else
  69255. y = dy + (dh - h) * 0.5;
  69256. }
  69257. }
  69258. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69259. {
  69260. if (source.isEmpty())
  69261. return AffineTransform::identity;
  69262. float newX = destination.getX();
  69263. float newY = destination.getY();
  69264. float scaleX = destination.getWidth() / source.getWidth();
  69265. float scaleY = destination.getHeight() / source.getHeight();
  69266. if ((flags & stretchToFit) == 0)
  69267. {
  69268. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69269. : jmin (scaleX, scaleY);
  69270. if ((flags & onlyReduceInSize) != 0)
  69271. scaleX = jmin (scaleX, 1.0f);
  69272. if ((flags & onlyIncreaseInSize) != 0)
  69273. scaleX = jmax (scaleX, 1.0f);
  69274. scaleY = scaleX;
  69275. if ((flags & xRight) != 0)
  69276. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69277. else if ((flags & xLeft) == 0)
  69278. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69279. if ((flags & yBottom) != 0)
  69280. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69281. else if ((flags & yTop) == 0)
  69282. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69283. }
  69284. return AffineTransform::translation (-source.getX(), -source.getY())
  69285. .scaled (scaleX, scaleY)
  69286. .translated (newX, newY);
  69287. }
  69288. END_JUCE_NAMESPACE
  69289. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69290. /*** Start of inlined file: juce_Drawable.cpp ***/
  69291. BEGIN_JUCE_NAMESPACE
  69292. Drawable::Drawable()
  69293. {
  69294. setInterceptsMouseClicks (false, false);
  69295. setPaintingIsUnclipped (true);
  69296. }
  69297. Drawable::~Drawable()
  69298. {
  69299. }
  69300. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69301. {
  69302. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69303. }
  69304. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69305. {
  69306. Graphics::ScopedSaveState ss (g);
  69307. const float oldOpacity = getAlpha();
  69308. setAlpha (opacity);
  69309. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69310. (float) -originRelativeToComponent.getY())
  69311. .followedBy (getTransform())
  69312. .followedBy (transform));
  69313. if (! g.isClipEmpty())
  69314. paintEntireComponent (g, false);
  69315. setAlpha (oldOpacity);
  69316. }
  69317. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69318. {
  69319. draw (g, opacity, AffineTransform::translation (x, y));
  69320. }
  69321. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69322. {
  69323. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69324. }
  69325. DrawableComposite* Drawable::getParent() const
  69326. {
  69327. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69328. }
  69329. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69330. {
  69331. g.setOrigin (originRelativeToComponent.getX(),
  69332. originRelativeToComponent.getY());
  69333. }
  69334. void Drawable::parentHierarchyChanged()
  69335. {
  69336. setBoundsToEnclose (getDrawableBounds());
  69337. }
  69338. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69339. {
  69340. Drawable* const parent = getParent();
  69341. Point<int> parentOrigin;
  69342. if (parent != 0)
  69343. parentOrigin = parent->originRelativeToComponent;
  69344. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69345. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69346. setBounds (newBounds);
  69347. }
  69348. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69349. {
  69350. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69351. }
  69352. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69353. {
  69354. if (! area.isEmpty())
  69355. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69356. }
  69357. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69358. {
  69359. Drawable* result = 0;
  69360. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69361. if (image.isValid())
  69362. {
  69363. DrawableImage* const di = new DrawableImage();
  69364. di->setImage (image);
  69365. result = di;
  69366. }
  69367. else
  69368. {
  69369. const String asString (String::createStringFromData (data, (int) numBytes));
  69370. XmlDocument doc (asString);
  69371. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69372. if (outer != 0 && outer->hasTagName ("svg"))
  69373. {
  69374. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69375. if (svg != 0)
  69376. result = Drawable::createFromSVG (*svg);
  69377. }
  69378. }
  69379. return result;
  69380. }
  69381. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69382. {
  69383. MemoryOutputStream mo;
  69384. mo.writeFromInputStream (dataSource, -1);
  69385. return createFromImageData (mo.getData(), mo.getDataSize());
  69386. }
  69387. Drawable* Drawable::createFromImageFile (const File& file)
  69388. {
  69389. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69390. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69391. }
  69392. template <class DrawableClass>
  69393. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69394. {
  69395. public:
  69396. DrawableTypeHandler()
  69397. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69398. {
  69399. }
  69400. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69401. {
  69402. DrawableClass* const d = new DrawableClass();
  69403. if (parent != 0)
  69404. parent->addAndMakeVisible (d);
  69405. updateComponentFromState (d, state);
  69406. return d;
  69407. }
  69408. void updateComponentFromState (Component* component, const ValueTree& state)
  69409. {
  69410. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69411. jassert (d != 0);
  69412. d->refreshFromValueTree (state, *this->getBuilder());
  69413. }
  69414. };
  69415. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69416. {
  69417. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69418. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69419. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69420. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69421. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69422. }
  69423. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69424. {
  69425. ComponentBuilder builder (tree);
  69426. builder.setImageProvider (imageProvider);
  69427. registerDrawableTypeHandlers (builder);
  69428. ScopedPointer<Component> comp (builder.createComponent());
  69429. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69430. if (d != 0)
  69431. comp.release();
  69432. return d;
  69433. }
  69434. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69435. : state (state_)
  69436. {
  69437. }
  69438. const String Drawable::ValueTreeWrapperBase::getID() const
  69439. {
  69440. return state [ComponentBuilder::idProperty];
  69441. }
  69442. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69443. {
  69444. if (newID.isEmpty())
  69445. state.removeProperty (ComponentBuilder::idProperty, 0);
  69446. else
  69447. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69448. }
  69449. END_JUCE_NAMESPACE
  69450. /*** End of inlined file: juce_Drawable.cpp ***/
  69451. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69452. BEGIN_JUCE_NAMESPACE
  69453. DrawableShape::DrawableShape()
  69454. : strokeType (0.0f),
  69455. mainFill (Colours::black),
  69456. strokeFill (Colours::black)
  69457. {
  69458. }
  69459. DrawableShape::DrawableShape (const DrawableShape& other)
  69460. : strokeType (other.strokeType),
  69461. mainFill (other.mainFill),
  69462. strokeFill (other.strokeFill)
  69463. {
  69464. }
  69465. DrawableShape::~DrawableShape()
  69466. {
  69467. }
  69468. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69469. {
  69470. public:
  69471. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69472. : RelativeCoordinatePositionerBase (component_),
  69473. owner (component_),
  69474. fill (fill_),
  69475. isMainFill (isMainFill_)
  69476. {
  69477. }
  69478. bool registerCoordinates()
  69479. {
  69480. bool ok = addPoint (fill.gradientPoint1);
  69481. ok = addPoint (fill.gradientPoint2) && ok;
  69482. return addPoint (fill.gradientPoint3) && ok;
  69483. }
  69484. void applyToComponentBounds()
  69485. {
  69486. ComponentScope scope (owner);
  69487. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  69488. : owner.strokeFill.recalculateCoords (&scope))
  69489. owner.repaint();
  69490. }
  69491. private:
  69492. DrawableShape& owner;
  69493. const DrawableShape::RelativeFillType fill;
  69494. const bool isMainFill;
  69495. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69496. };
  69497. void DrawableShape::setFill (const FillType& newFill)
  69498. {
  69499. setFill (RelativeFillType (newFill));
  69500. }
  69501. void DrawableShape::setStrokeFill (const FillType& newFill)
  69502. {
  69503. setStrokeFill (RelativeFillType (newFill));
  69504. }
  69505. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69506. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69507. {
  69508. if (fill != newFill)
  69509. {
  69510. fill = newFill;
  69511. positioner = 0;
  69512. if (fill.isDynamic())
  69513. {
  69514. positioner = new RelativePositioner (*this, fill, true);
  69515. positioner->apply();
  69516. }
  69517. else
  69518. {
  69519. fill.recalculateCoords (0);
  69520. }
  69521. repaint();
  69522. }
  69523. }
  69524. void DrawableShape::setFill (const RelativeFillType& newFill)
  69525. {
  69526. setFillInternal (mainFill, newFill, mainFillPositioner);
  69527. }
  69528. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69529. {
  69530. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69531. }
  69532. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69533. {
  69534. if (strokeType != newStrokeType)
  69535. {
  69536. strokeType = newStrokeType;
  69537. strokeChanged();
  69538. }
  69539. }
  69540. void DrawableShape::setStrokeThickness (const float newThickness)
  69541. {
  69542. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69543. }
  69544. bool DrawableShape::isStrokeVisible() const throw()
  69545. {
  69546. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69547. }
  69548. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69549. {
  69550. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69551. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69552. }
  69553. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69554. {
  69555. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69556. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69557. state.setStrokeType (strokeType, undoManager);
  69558. }
  69559. void DrawableShape::paint (Graphics& g)
  69560. {
  69561. transformContextToCorrectOrigin (g);
  69562. g.setFillType (mainFill.fill);
  69563. g.fillPath (path);
  69564. if (isStrokeVisible())
  69565. {
  69566. g.setFillType (strokeFill.fill);
  69567. g.fillPath (strokePath);
  69568. }
  69569. }
  69570. void DrawableShape::pathChanged()
  69571. {
  69572. strokeChanged();
  69573. }
  69574. void DrawableShape::strokeChanged()
  69575. {
  69576. strokePath.clear();
  69577. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69578. setBoundsToEnclose (getDrawableBounds());
  69579. repaint();
  69580. }
  69581. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69582. {
  69583. if (isStrokeVisible())
  69584. return strokePath.getBounds();
  69585. else
  69586. return path.getBounds();
  69587. }
  69588. bool DrawableShape::hitTest (int x, int y)
  69589. {
  69590. const float globalX = (float) (x - originRelativeToComponent.getX());
  69591. const float globalY = (float) (y - originRelativeToComponent.getY());
  69592. return path.contains (globalX, globalY)
  69593. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69594. }
  69595. DrawableShape::RelativeFillType::RelativeFillType()
  69596. {
  69597. }
  69598. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69599. : fill (fill_)
  69600. {
  69601. if (fill.isGradient())
  69602. {
  69603. const ColourGradient& g = *fill.gradient;
  69604. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69605. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69606. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69607. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69608. .transformedBy (fill.transform);
  69609. fill.transform = AffineTransform::identity;
  69610. }
  69611. }
  69612. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69613. : fill (other.fill),
  69614. gradientPoint1 (other.gradientPoint1),
  69615. gradientPoint2 (other.gradientPoint2),
  69616. gradientPoint3 (other.gradientPoint3)
  69617. {
  69618. }
  69619. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69620. {
  69621. fill = other.fill;
  69622. gradientPoint1 = other.gradientPoint1;
  69623. gradientPoint2 = other.gradientPoint2;
  69624. gradientPoint3 = other.gradientPoint3;
  69625. return *this;
  69626. }
  69627. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69628. {
  69629. return fill == other.fill
  69630. && ((! fill.isGradient())
  69631. || (gradientPoint1 == other.gradientPoint1
  69632. && gradientPoint2 == other.gradientPoint2
  69633. && gradientPoint3 == other.gradientPoint3));
  69634. }
  69635. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69636. {
  69637. return ! operator== (other);
  69638. }
  69639. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  69640. {
  69641. if (fill.isGradient())
  69642. {
  69643. const Point<float> g1 (gradientPoint1.resolve (scope));
  69644. const Point<float> g2 (gradientPoint2.resolve (scope));
  69645. AffineTransform t;
  69646. ColourGradient& g = *fill.gradient;
  69647. if (g.isRadial)
  69648. {
  69649. const Point<float> g3 (gradientPoint3.resolve (scope));
  69650. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69651. g1.getY() + g1.getX() - g2.getX());
  69652. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69653. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69654. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69655. }
  69656. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69657. {
  69658. g.point1 = g1;
  69659. g.point2 = g2;
  69660. fill.transform = t;
  69661. return true;
  69662. }
  69663. }
  69664. return false;
  69665. }
  69666. bool DrawableShape::RelativeFillType::isDynamic() const
  69667. {
  69668. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69669. }
  69670. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69671. {
  69672. if (fill.isColour())
  69673. {
  69674. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69675. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69676. }
  69677. else if (fill.isGradient())
  69678. {
  69679. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69680. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69681. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69682. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69683. const ColourGradient& cg = *fill.gradient;
  69684. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69685. String s;
  69686. for (int i = 0; i < cg.getNumColours(); ++i)
  69687. s << ' ' << cg.getColourPosition (i)
  69688. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69689. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69690. }
  69691. else if (fill.isTiledImage())
  69692. {
  69693. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69694. if (imageProvider != 0)
  69695. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69696. if (fill.getOpacity() < 1.0f)
  69697. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69698. else
  69699. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69700. }
  69701. else
  69702. {
  69703. jassertfalse;
  69704. }
  69705. }
  69706. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69707. {
  69708. const String newType (v [FillAndStrokeState::type].toString());
  69709. if (newType == "solid")
  69710. {
  69711. const String colourString (v [FillAndStrokeState::colour].toString());
  69712. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69713. : (uint32) colourString.getHexValue32()));
  69714. return true;
  69715. }
  69716. else if (newType == "gradient")
  69717. {
  69718. ColourGradient g;
  69719. g.isRadial = v [FillAndStrokeState::radial];
  69720. StringArray colourSteps;
  69721. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69722. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69723. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69724. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69725. fill.setGradient (g);
  69726. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69727. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69728. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69729. return true;
  69730. }
  69731. else if (newType == "image")
  69732. {
  69733. Image im;
  69734. if (imageProvider != 0)
  69735. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69736. fill.setTiledImage (im, AffineTransform::identity);
  69737. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69738. return true;
  69739. }
  69740. jassertfalse;
  69741. return false;
  69742. }
  69743. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69744. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69745. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69746. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69747. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69748. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69749. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69750. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69751. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69752. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69753. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69754. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69755. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69756. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69757. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69758. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69759. : Drawable::ValueTreeWrapperBase (state_)
  69760. {
  69761. }
  69762. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69763. {
  69764. DrawableShape::RelativeFillType f;
  69765. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69766. return f;
  69767. }
  69768. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69769. {
  69770. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69771. if (v.isValid())
  69772. return v;
  69773. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69774. return getFillState (fillOrStrokeType);
  69775. }
  69776. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69777. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69778. {
  69779. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69780. newFill.writeTo (v, imageProvider, undoManager);
  69781. }
  69782. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69783. {
  69784. const String jointStyleString (state [jointStyle].toString());
  69785. const String capStyleString (state [capStyle].toString());
  69786. return PathStrokeType (state [strokeWidth],
  69787. jointStyleString == "curved" ? PathStrokeType::curved
  69788. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69789. : PathStrokeType::mitered),
  69790. capStyleString == "square" ? PathStrokeType::square
  69791. : (capStyleString == "round" ? PathStrokeType::rounded
  69792. : PathStrokeType::butt));
  69793. }
  69794. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69795. {
  69796. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69797. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69798. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69799. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69800. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69801. }
  69802. END_JUCE_NAMESPACE
  69803. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69804. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69805. BEGIN_JUCE_NAMESPACE
  69806. DrawableComposite::DrawableComposite()
  69807. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69808. updateBoundsReentrant (false)
  69809. {
  69810. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69811. RelativeCoordinate (100.0),
  69812. RelativeCoordinate (0.0),
  69813. RelativeCoordinate (100.0)));
  69814. }
  69815. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69816. : bounds (other.bounds),
  69817. markersX (other.markersX),
  69818. markersY (other.markersY),
  69819. updateBoundsReentrant (false)
  69820. {
  69821. for (int i = 0; i < other.getNumChildComponents(); ++i)
  69822. {
  69823. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  69824. if (d != 0)
  69825. addAndMakeVisible (d->createCopy());
  69826. }
  69827. }
  69828. DrawableComposite::~DrawableComposite()
  69829. {
  69830. deleteAllChildren();
  69831. }
  69832. Drawable* DrawableComposite::createCopy() const
  69833. {
  69834. return new DrawableComposite (*this);
  69835. }
  69836. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69837. {
  69838. Rectangle<float> r;
  69839. for (int i = getNumChildComponents(); --i >= 0;)
  69840. {
  69841. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  69842. if (d != 0)
  69843. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  69844. : d->getDrawableBounds());
  69845. }
  69846. return r;
  69847. }
  69848. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  69849. {
  69850. return xAxis ? &markersX : &markersY;
  69851. }
  69852. const RelativeRectangle DrawableComposite::getContentArea() const
  69853. {
  69854. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  69855. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  69856. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  69857. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  69858. }
  69859. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69860. {
  69861. markersX.setMarker (contentLeftMarkerName, newArea.left);
  69862. markersX.setMarker (contentRightMarkerName, newArea.right);
  69863. markersY.setMarker (contentTopMarkerName, newArea.top);
  69864. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  69865. }
  69866. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  69867. {
  69868. if (bounds != newBounds)
  69869. {
  69870. bounds = newBounds;
  69871. if (bounds.isDynamic())
  69872. {
  69873. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  69874. setPositioner (p);
  69875. p->apply();
  69876. }
  69877. else
  69878. {
  69879. setPositioner (0);
  69880. recalculateCoordinates (0);
  69881. }
  69882. }
  69883. }
  69884. void DrawableComposite::resetBoundingBoxToContentArea()
  69885. {
  69886. const RelativeRectangle content (getContentArea());
  69887. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69888. RelativePoint (content.right, content.top),
  69889. RelativePoint (content.left, content.bottom)));
  69890. }
  69891. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69892. {
  69893. const Rectangle<float> activeArea (getDrawableBounds());
  69894. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69895. RelativeCoordinate (activeArea.getRight()),
  69896. RelativeCoordinate (activeArea.getY()),
  69897. RelativeCoordinate (activeArea.getBottom())));
  69898. resetBoundingBoxToContentArea();
  69899. }
  69900. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  69901. {
  69902. bool ok = positioner.addPoint (bounds.topLeft);
  69903. ok = positioner.addPoint (bounds.topRight) && ok;
  69904. return positioner.addPoint (bounds.bottomLeft) && ok;
  69905. }
  69906. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  69907. {
  69908. Point<float> resolved[3];
  69909. bounds.resolveThreePoints (resolved, scope);
  69910. const Rectangle<float> content (getContentArea().resolve (scope));
  69911. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69912. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69913. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69914. if (t.isSingularity())
  69915. t = AffineTransform::identity;
  69916. setTransform (t);
  69917. }
  69918. void DrawableComposite::parentHierarchyChanged()
  69919. {
  69920. DrawableComposite* parent = getParent();
  69921. if (parent != 0)
  69922. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69923. }
  69924. void DrawableComposite::childBoundsChanged (Component*)
  69925. {
  69926. updateBoundsToFitChildren();
  69927. }
  69928. void DrawableComposite::childrenChanged()
  69929. {
  69930. updateBoundsToFitChildren();
  69931. }
  69932. void DrawableComposite::updateBoundsToFitChildren()
  69933. {
  69934. if (! updateBoundsReentrant)
  69935. {
  69936. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  69937. Rectangle<int> childArea;
  69938. for (int i = getNumChildComponents(); --i >= 0;)
  69939. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  69940. const Point<int> delta (childArea.getPosition());
  69941. childArea += getPosition();
  69942. if (childArea != getBounds())
  69943. {
  69944. if (! delta.isOrigin())
  69945. {
  69946. originRelativeToComponent -= delta;
  69947. for (int i = getNumChildComponents(); --i >= 0;)
  69948. {
  69949. Component* const c = getChildComponent(i);
  69950. if (c != 0)
  69951. c->setBounds (c->getBounds() - delta);
  69952. }
  69953. }
  69954. setBounds (childArea);
  69955. }
  69956. }
  69957. }
  69958. const char* const DrawableComposite::contentLeftMarkerName = "left";
  69959. const char* const DrawableComposite::contentRightMarkerName = "right";
  69960. const char* const DrawableComposite::contentTopMarkerName = "top";
  69961. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  69962. const Identifier DrawableComposite::valueTreeType ("Group");
  69963. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69964. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69965. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69966. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69967. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69968. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69969. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69970. : ValueTreeWrapperBase (state_)
  69971. {
  69972. jassert (state.hasType (valueTreeType));
  69973. }
  69974. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69975. {
  69976. return state.getChildWithName (childGroupTag);
  69977. }
  69978. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69979. {
  69980. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69981. }
  69982. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69983. {
  69984. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69985. state.getProperty (topRight, "100, 0"),
  69986. state.getProperty (bottomLeft, "0, 100"));
  69987. }
  69988. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69989. {
  69990. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69991. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69992. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69993. }
  69994. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69995. {
  69996. const RelativeRectangle content (getContentArea());
  69997. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69998. RelativePoint (content.right, content.top),
  69999. RelativePoint (content.left, content.bottom)), undoManager);
  70000. }
  70001. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70002. {
  70003. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70004. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70005. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70006. markersX.getMarker (markersX.getMarkerState (1)).position,
  70007. markersY.getMarker (markersY.getMarkerState (0)).position,
  70008. markersY.getMarker (markersY.getMarkerState (1)).position);
  70009. }
  70010. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70011. {
  70012. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70013. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70014. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70015. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70016. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70017. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70018. }
  70019. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70020. {
  70021. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70022. }
  70023. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70024. {
  70025. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70026. }
  70027. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70028. {
  70029. const ValueTreeWrapper wrapper (tree);
  70030. setComponentID (wrapper.getID());
  70031. wrapper.getMarkerList (true).applyTo (markersX);
  70032. wrapper.getMarkerList (false).applyTo (markersY);
  70033. setBoundingBox (wrapper.getBoundingBox());
  70034. builder.updateChildComponents (*this, wrapper.getChildList());
  70035. }
  70036. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70037. {
  70038. ValueTree tree (valueTreeType);
  70039. ValueTreeWrapper v (tree);
  70040. v.setID (getComponentID());
  70041. v.setBoundingBox (bounds, 0);
  70042. ValueTree childList (v.getChildListCreating (0));
  70043. for (int i = 0; i < getNumChildComponents(); ++i)
  70044. {
  70045. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70046. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70047. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70048. }
  70049. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70050. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70051. return tree;
  70052. }
  70053. END_JUCE_NAMESPACE
  70054. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70055. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70056. BEGIN_JUCE_NAMESPACE
  70057. DrawableImage::DrawableImage()
  70058. : image (0),
  70059. opacity (1.0f),
  70060. overlayColour (0x00000000)
  70061. {
  70062. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70063. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70064. }
  70065. DrawableImage::DrawableImage (const DrawableImage& other)
  70066. : image (other.image),
  70067. opacity (other.opacity),
  70068. overlayColour (other.overlayColour),
  70069. bounds (other.bounds)
  70070. {
  70071. }
  70072. DrawableImage::~DrawableImage()
  70073. {
  70074. }
  70075. void DrawableImage::setImage (const Image& imageToUse)
  70076. {
  70077. image = imageToUse;
  70078. setBounds (imageToUse.getBounds());
  70079. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70080. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70081. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70082. recalculateCoordinates (0);
  70083. repaint();
  70084. }
  70085. void DrawableImage::setOpacity (const float newOpacity)
  70086. {
  70087. opacity = newOpacity;
  70088. }
  70089. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70090. {
  70091. overlayColour = newOverlayColour;
  70092. }
  70093. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70094. {
  70095. if (bounds != newBounds)
  70096. {
  70097. bounds = newBounds;
  70098. if (bounds.isDynamic())
  70099. {
  70100. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70101. setPositioner (p);
  70102. p->apply();
  70103. }
  70104. else
  70105. {
  70106. setPositioner (0);
  70107. recalculateCoordinates (0);
  70108. }
  70109. }
  70110. }
  70111. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70112. {
  70113. bool ok = positioner.addPoint (bounds.topLeft);
  70114. ok = positioner.addPoint (bounds.topRight) && ok;
  70115. return positioner.addPoint (bounds.bottomLeft) && ok;
  70116. }
  70117. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70118. {
  70119. if (image.isValid())
  70120. {
  70121. Point<float> resolved[3];
  70122. bounds.resolveThreePoints (resolved, scope);
  70123. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70124. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70125. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70126. tr.getX(), tr.getY(),
  70127. bl.getX(), bl.getY()));
  70128. if (t.isSingularity())
  70129. t = AffineTransform::identity;
  70130. setTransform (t);
  70131. }
  70132. }
  70133. void DrawableImage::paint (Graphics& g)
  70134. {
  70135. if (image.isValid())
  70136. {
  70137. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70138. {
  70139. g.setOpacity (opacity);
  70140. g.drawImageAt (image, 0, 0, false);
  70141. }
  70142. if (! overlayColour.isTransparent())
  70143. {
  70144. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70145. g.drawImageAt (image, 0, 0, true);
  70146. }
  70147. }
  70148. }
  70149. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70150. {
  70151. return image.getBounds().toFloat();
  70152. }
  70153. bool DrawableImage::hitTest (int x, int y) const
  70154. {
  70155. return (! image.isNull())
  70156. && image.getPixelAt (x, y).getAlpha() >= 127;
  70157. }
  70158. Drawable* DrawableImage::createCopy() const
  70159. {
  70160. return new DrawableImage (*this);
  70161. }
  70162. const Identifier DrawableImage::valueTreeType ("Image");
  70163. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70164. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70165. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70166. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70167. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70168. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70169. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70170. : ValueTreeWrapperBase (state_)
  70171. {
  70172. jassert (state.hasType (valueTreeType));
  70173. }
  70174. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70175. {
  70176. return state [image];
  70177. }
  70178. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70179. {
  70180. return state.getPropertyAsValue (image, undoManager);
  70181. }
  70182. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70183. {
  70184. state.setProperty (image, newIdentifier, undoManager);
  70185. }
  70186. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70187. {
  70188. return (float) state.getProperty (opacity, 1.0);
  70189. }
  70190. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70191. {
  70192. if (! state.hasProperty (opacity))
  70193. state.setProperty (opacity, 1.0, undoManager);
  70194. return state.getPropertyAsValue (opacity, undoManager);
  70195. }
  70196. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70197. {
  70198. state.setProperty (opacity, newOpacity, undoManager);
  70199. }
  70200. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70201. {
  70202. return Colour (state [overlay].toString().getHexValue32());
  70203. }
  70204. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70205. {
  70206. if (newColour.isTransparent())
  70207. state.removeProperty (overlay, undoManager);
  70208. else
  70209. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70210. }
  70211. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70212. {
  70213. return state.getPropertyAsValue (overlay, undoManager);
  70214. }
  70215. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70216. {
  70217. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70218. state.getProperty (topRight, "100, 0"),
  70219. state.getProperty (bottomLeft, "0, 100"));
  70220. }
  70221. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70222. {
  70223. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70224. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70225. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70226. }
  70227. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70228. {
  70229. const ValueTreeWrapper controller (tree);
  70230. setComponentID (controller.getID());
  70231. const float newOpacity = controller.getOpacity();
  70232. const Colour newOverlayColour (controller.getOverlayColour());
  70233. Image newImage;
  70234. const var imageIdentifier (controller.getImageIdentifier());
  70235. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70236. if (builder.getImageProvider() != 0)
  70237. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70238. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70239. if (bounds != newBounds || newOpacity != opacity
  70240. || overlayColour != newOverlayColour || image != newImage)
  70241. {
  70242. repaint();
  70243. opacity = newOpacity;
  70244. overlayColour = newOverlayColour;
  70245. if (image != newImage)
  70246. setImage (newImage);
  70247. setBoundingBox (newBounds);
  70248. }
  70249. }
  70250. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70251. {
  70252. ValueTree tree (valueTreeType);
  70253. ValueTreeWrapper v (tree);
  70254. v.setID (getComponentID());
  70255. v.setOpacity (opacity, 0);
  70256. v.setOverlayColour (overlayColour, 0);
  70257. v.setBoundingBox (bounds, 0);
  70258. if (image.isValid())
  70259. {
  70260. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70261. if (imageProvider != 0)
  70262. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70263. }
  70264. return tree;
  70265. }
  70266. END_JUCE_NAMESPACE
  70267. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70268. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70269. BEGIN_JUCE_NAMESPACE
  70270. DrawablePath::DrawablePath()
  70271. {
  70272. }
  70273. DrawablePath::DrawablePath (const DrawablePath& other)
  70274. : DrawableShape (other)
  70275. {
  70276. if (other.relativePath != 0)
  70277. setPath (*other.relativePath);
  70278. else
  70279. setPath (other.path);
  70280. }
  70281. DrawablePath::~DrawablePath()
  70282. {
  70283. }
  70284. Drawable* DrawablePath::createCopy() const
  70285. {
  70286. return new DrawablePath (*this);
  70287. }
  70288. void DrawablePath::setPath (const Path& newPath)
  70289. {
  70290. path = newPath;
  70291. pathChanged();
  70292. }
  70293. const Path& DrawablePath::getPath() const
  70294. {
  70295. return path;
  70296. }
  70297. const Path& DrawablePath::getStrokePath() const
  70298. {
  70299. return strokePath;
  70300. }
  70301. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70302. {
  70303. Path newPath;
  70304. newRelativePath.createPath (newPath, scope);
  70305. if (path != newPath)
  70306. {
  70307. path.swapWithPath (newPath);
  70308. pathChanged();
  70309. }
  70310. }
  70311. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70312. {
  70313. public:
  70314. RelativePositioner (DrawablePath& component_)
  70315. : RelativeCoordinatePositionerBase (component_),
  70316. owner (component_)
  70317. {
  70318. }
  70319. bool registerCoordinates()
  70320. {
  70321. bool ok = true;
  70322. jassert (owner.relativePath != 0);
  70323. const RelativePointPath& path = *owner.relativePath;
  70324. for (int i = 0; i < path.elements.size(); ++i)
  70325. {
  70326. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70327. int numPoints;
  70328. RelativePoint* const points = e->getControlPoints (numPoints);
  70329. for (int j = numPoints; --j >= 0;)
  70330. ok = addPoint (points[j]) && ok;
  70331. }
  70332. return ok;
  70333. }
  70334. void applyToComponentBounds()
  70335. {
  70336. jassert (owner.relativePath != 0);
  70337. ComponentScope scope (getComponent());
  70338. owner.applyRelativePath (*owner.relativePath, &scope);
  70339. }
  70340. private:
  70341. DrawablePath& owner;
  70342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70343. };
  70344. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70345. {
  70346. if (newRelativePath.containsAnyDynamicPoints())
  70347. {
  70348. if (relativePath == 0 || newRelativePath != *relativePath)
  70349. {
  70350. relativePath = new RelativePointPath (newRelativePath);
  70351. RelativePositioner* const p = new RelativePositioner (*this);
  70352. setPositioner (p);
  70353. p->apply();
  70354. }
  70355. }
  70356. else
  70357. {
  70358. relativePath = 0;
  70359. applyRelativePath (newRelativePath, 0);
  70360. }
  70361. }
  70362. const Identifier DrawablePath::valueTreeType ("Path");
  70363. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70364. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70365. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70366. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70367. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70368. : FillAndStrokeState (state_)
  70369. {
  70370. jassert (state.hasType (valueTreeType));
  70371. }
  70372. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70373. {
  70374. return state.getOrCreateChildWithName (path, 0);
  70375. }
  70376. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70377. {
  70378. return state [nonZeroWinding];
  70379. }
  70380. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70381. {
  70382. state.setProperty (nonZeroWinding, b, undoManager);
  70383. }
  70384. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70385. {
  70386. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70387. ValueTree pathTree (getPathState());
  70388. pathTree.removeAllChildren (undoManager);
  70389. for (int i = 0; i < relativePath.elements.size(); ++i)
  70390. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70391. }
  70392. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70393. {
  70394. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70395. RelativePoint points[3];
  70396. const ValueTree pathTree (state.getChildWithName (path));
  70397. const int num = pathTree.getNumChildren();
  70398. for (int i = 0; i < num; ++i)
  70399. {
  70400. const Element e (pathTree.getChild(i));
  70401. const int numCps = e.getNumControlPoints();
  70402. for (int j = 0; j < numCps; ++j)
  70403. points[j] = e.getControlPoint (j);
  70404. const Identifier type (e.getType());
  70405. RelativePointPath::ElementBase* newElement = 0;
  70406. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70407. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70408. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70409. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70410. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70411. else jassertfalse;
  70412. relativePath.addElement (newElement);
  70413. }
  70414. }
  70415. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70416. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70417. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70418. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70419. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70420. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70421. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70422. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70423. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70424. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70425. : state (state_)
  70426. {
  70427. }
  70428. DrawablePath::ValueTreeWrapper::Element::~Element()
  70429. {
  70430. }
  70431. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70432. {
  70433. return ValueTreeWrapper (state.getParent().getParent());
  70434. }
  70435. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70436. {
  70437. return Element (state.getSibling (-1));
  70438. }
  70439. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70440. {
  70441. const Identifier i (state.getType());
  70442. if (i == startSubPathElement || i == lineToElement) return 1;
  70443. if (i == quadraticToElement) return 2;
  70444. if (i == cubicToElement) return 3;
  70445. return 0;
  70446. }
  70447. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70448. {
  70449. jassert (index >= 0 && index < getNumControlPoints());
  70450. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70451. }
  70452. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70453. {
  70454. jassert (index >= 0 && index < getNumControlPoints());
  70455. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70456. }
  70457. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70458. {
  70459. jassert (index >= 0 && index < getNumControlPoints());
  70460. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70461. }
  70462. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70463. {
  70464. const Identifier i (state.getType());
  70465. if (i == startSubPathElement)
  70466. return getControlPoint (0);
  70467. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70468. return getPreviousElement().getEndPoint();
  70469. }
  70470. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70471. {
  70472. const Identifier i (state.getType());
  70473. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70474. if (i == quadraticToElement) return getControlPoint (1);
  70475. if (i == cubicToElement) return getControlPoint (2);
  70476. jassert (i == closeSubPathElement);
  70477. return RelativePoint();
  70478. }
  70479. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  70480. {
  70481. const Identifier i (state.getType());
  70482. if (i == lineToElement || i == closeSubPathElement)
  70483. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  70484. if (i == cubicToElement)
  70485. {
  70486. Path p;
  70487. p.startNewSubPath (getStartPoint().resolve (scope));
  70488. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  70489. return p.getLength();
  70490. }
  70491. if (i == quadraticToElement)
  70492. {
  70493. Path p;
  70494. p.startNewSubPath (getStartPoint().resolve (scope));
  70495. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  70496. return p.getLength();
  70497. }
  70498. jassert (i == startSubPathElement);
  70499. return 0;
  70500. }
  70501. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70502. {
  70503. return state [mode].toString();
  70504. }
  70505. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70506. {
  70507. if (state.hasType (cubicToElement))
  70508. state.setProperty (mode, newMode, undoManager);
  70509. }
  70510. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70511. {
  70512. const Identifier i (state.getType());
  70513. if (i == quadraticToElement || i == cubicToElement)
  70514. {
  70515. ValueTree newState (lineToElement);
  70516. Element e (newState);
  70517. e.setControlPoint (0, getEndPoint(), undoManager);
  70518. state = newState;
  70519. }
  70520. }
  70521. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  70522. {
  70523. const Identifier i (state.getType());
  70524. if (i == lineToElement || i == quadraticToElement)
  70525. {
  70526. ValueTree newState (cubicToElement);
  70527. Element e (newState);
  70528. const RelativePoint start (getStartPoint());
  70529. const RelativePoint end (getEndPoint());
  70530. const Point<float> startResolved (start.resolve (scope));
  70531. const Point<float> endResolved (end.resolve (scope));
  70532. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70533. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70534. e.setControlPoint (2, end, undoManager);
  70535. state = newState;
  70536. }
  70537. }
  70538. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70539. {
  70540. const Identifier i (state.getType());
  70541. if (i != startSubPathElement)
  70542. {
  70543. ValueTree newState (startSubPathElement);
  70544. Element e (newState);
  70545. e.setControlPoint (0, getEndPoint(), undoManager);
  70546. state = newState;
  70547. }
  70548. }
  70549. namespace DrawablePathHelpers
  70550. {
  70551. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70552. {
  70553. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70554. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70555. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70556. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70557. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70558. return newCp1 + (newCp2 - newCp1) * proportion;
  70559. }
  70560. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70561. {
  70562. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70563. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70564. return mid1 + (mid2 - mid1) * proportion;
  70565. }
  70566. }
  70567. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  70568. {
  70569. using namespace DrawablePathHelpers;
  70570. const Identifier type (state.getType());
  70571. float bestProp = 0;
  70572. if (type == cubicToElement)
  70573. {
  70574. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70575. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70576. float bestDistance = std::numeric_limits<float>::max();
  70577. for (int i = 110; --i >= 0;)
  70578. {
  70579. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70580. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70581. const float distance = centre.getDistanceFrom (targetPoint);
  70582. if (distance < bestDistance)
  70583. {
  70584. bestProp = prop;
  70585. bestDistance = distance;
  70586. }
  70587. }
  70588. }
  70589. else if (type == quadraticToElement)
  70590. {
  70591. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70592. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70593. float bestDistance = std::numeric_limits<float>::max();
  70594. for (int i = 110; --i >= 0;)
  70595. {
  70596. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70597. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70598. const float distance = centre.getDistanceFrom (targetPoint);
  70599. if (distance < bestDistance)
  70600. {
  70601. bestProp = prop;
  70602. bestDistance = distance;
  70603. }
  70604. }
  70605. }
  70606. else if (type == lineToElement)
  70607. {
  70608. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70609. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70610. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70611. }
  70612. return bestProp;
  70613. }
  70614. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  70615. {
  70616. ValueTree newTree;
  70617. const Identifier type (state.getType());
  70618. if (type == cubicToElement)
  70619. {
  70620. float bestProp = findProportionAlongLine (targetPoint, scope);
  70621. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70622. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70623. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70624. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70625. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70626. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70627. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70628. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70629. setControlPoint (0, mid1, undoManager);
  70630. setControlPoint (1, newCp1, undoManager);
  70631. setControlPoint (2, newCentre, undoManager);
  70632. setModeOfEndPoint (roundedMode, undoManager);
  70633. Element newElement (newTree = ValueTree (cubicToElement));
  70634. newElement.setControlPoint (0, newCp2, 0);
  70635. newElement.setControlPoint (1, mid3, 0);
  70636. newElement.setControlPoint (2, rp4, 0);
  70637. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70638. }
  70639. else if (type == quadraticToElement)
  70640. {
  70641. float bestProp = findProportionAlongLine (targetPoint, scope);
  70642. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70643. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70644. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70645. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70646. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70647. setControlPoint (0, mid1, undoManager);
  70648. setControlPoint (1, newCentre, undoManager);
  70649. setModeOfEndPoint (roundedMode, undoManager);
  70650. Element newElement (newTree = ValueTree (quadraticToElement));
  70651. newElement.setControlPoint (0, mid2, 0);
  70652. newElement.setControlPoint (1, rp3, 0);
  70653. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70654. }
  70655. else if (type == lineToElement)
  70656. {
  70657. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70658. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70659. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70660. setControlPoint (0, newPoint, undoManager);
  70661. Element newElement (newTree = ValueTree (lineToElement));
  70662. newElement.setControlPoint (0, rp2, 0);
  70663. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70664. }
  70665. else if (type == closeSubPathElement)
  70666. {
  70667. }
  70668. return newTree;
  70669. }
  70670. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70671. {
  70672. state.getParent().removeChild (state, undoManager);
  70673. }
  70674. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70675. {
  70676. ValueTreeWrapper v (tree);
  70677. setComponentID (v.getID());
  70678. refreshFillTypes (v, builder.getImageProvider());
  70679. setStrokeType (v.getStrokeType());
  70680. RelativePointPath newRelativePath;
  70681. v.writeTo (newRelativePath);
  70682. setPath (newRelativePath);
  70683. }
  70684. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70685. {
  70686. ValueTree tree (valueTreeType);
  70687. ValueTreeWrapper v (tree);
  70688. v.setID (getComponentID());
  70689. writeTo (v, imageProvider, 0);
  70690. if (relativePath != 0)
  70691. v.readFrom (*relativePath, 0);
  70692. else
  70693. v.readFrom (RelativePointPath (path), 0);
  70694. return tree;
  70695. }
  70696. END_JUCE_NAMESPACE
  70697. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70698. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70699. BEGIN_JUCE_NAMESPACE
  70700. DrawableRectangle::DrawableRectangle()
  70701. {
  70702. }
  70703. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70704. : DrawableShape (other),
  70705. bounds (other.bounds),
  70706. cornerSize (other.cornerSize)
  70707. {
  70708. }
  70709. DrawableRectangle::~DrawableRectangle()
  70710. {
  70711. }
  70712. Drawable* DrawableRectangle::createCopy() const
  70713. {
  70714. return new DrawableRectangle (*this);
  70715. }
  70716. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70717. {
  70718. if (bounds != newBounds)
  70719. {
  70720. bounds = newBounds;
  70721. rebuildPath();
  70722. }
  70723. }
  70724. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70725. {
  70726. if (cornerSize != newSize)
  70727. {
  70728. cornerSize = newSize;
  70729. rebuildPath();
  70730. }
  70731. }
  70732. void DrawableRectangle::rebuildPath()
  70733. {
  70734. if (bounds.isDynamic() || cornerSize.isDynamic())
  70735. {
  70736. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70737. setPositioner (p);
  70738. p->apply();
  70739. }
  70740. else
  70741. {
  70742. setPositioner (0);
  70743. recalculateCoordinates (0);
  70744. }
  70745. }
  70746. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70747. {
  70748. bool ok = positioner.addPoint (bounds.topLeft);
  70749. ok = positioner.addPoint (bounds.topRight) && ok;
  70750. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70751. return positioner.addPoint (cornerSize) && ok;
  70752. }
  70753. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  70754. {
  70755. Point<float> points[3];
  70756. bounds.resolveThreePoints (points, scope);
  70757. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  70758. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  70759. const float w = Line<float> (points[0], points[1]).getLength();
  70760. const float h = Line<float> (points[0], points[2]).getLength();
  70761. Path newPath;
  70762. if (cornerSizeX > 0 && cornerSizeY > 0)
  70763. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70764. else
  70765. newPath.addRectangle (0, 0, w, h);
  70766. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70767. w, 0, points[1].getX(), points[1].getY(),
  70768. 0, h, points[2].getX(), points[2].getY()));
  70769. if (path != newPath)
  70770. {
  70771. path.swapWithPath (newPath);
  70772. pathChanged();
  70773. }
  70774. }
  70775. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70776. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70777. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70778. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70779. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70780. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70781. : FillAndStrokeState (state_)
  70782. {
  70783. jassert (state.hasType (valueTreeType));
  70784. }
  70785. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70786. {
  70787. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70788. state.getProperty (topRight, "100, 0"),
  70789. state.getProperty (bottomLeft, "0, 100"));
  70790. }
  70791. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70792. {
  70793. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70794. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70795. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70796. }
  70797. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70798. {
  70799. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70800. }
  70801. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70802. {
  70803. return RelativePoint (state [cornerSize]);
  70804. }
  70805. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70806. {
  70807. return state.getPropertyAsValue (cornerSize, undoManager);
  70808. }
  70809. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70810. {
  70811. ValueTreeWrapper v (tree);
  70812. setComponentID (v.getID());
  70813. refreshFillTypes (v, builder.getImageProvider());
  70814. setStrokeType (v.getStrokeType());
  70815. setRectangle (v.getRectangle());
  70816. setCornerSize (v.getCornerSize());
  70817. }
  70818. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70819. {
  70820. ValueTree tree (valueTreeType);
  70821. ValueTreeWrapper v (tree);
  70822. v.setID (getComponentID());
  70823. writeTo (v, imageProvider, 0);
  70824. v.setRectangle (bounds, 0);
  70825. v.setCornerSize (cornerSize, 0);
  70826. return tree;
  70827. }
  70828. END_JUCE_NAMESPACE
  70829. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70830. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70831. BEGIN_JUCE_NAMESPACE
  70832. DrawableText::DrawableText()
  70833. : colour (Colours::black),
  70834. justification (Justification::centredLeft)
  70835. {
  70836. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70837. RelativePoint (50.0f, 0.0f),
  70838. RelativePoint (0.0f, 20.0f)));
  70839. setFont (Font (15.0f), true);
  70840. }
  70841. DrawableText::DrawableText (const DrawableText& other)
  70842. : bounds (other.bounds),
  70843. fontSizeControlPoint (other.fontSizeControlPoint),
  70844. font (other.font),
  70845. text (other.text),
  70846. colour (other.colour),
  70847. justification (other.justification)
  70848. {
  70849. }
  70850. DrawableText::~DrawableText()
  70851. {
  70852. }
  70853. void DrawableText::setText (const String& newText)
  70854. {
  70855. if (text != newText)
  70856. {
  70857. text = newText;
  70858. refreshBounds();
  70859. }
  70860. }
  70861. void DrawableText::setColour (const Colour& newColour)
  70862. {
  70863. if (colour != newColour)
  70864. {
  70865. colour = newColour;
  70866. repaint();
  70867. }
  70868. }
  70869. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70870. {
  70871. if (font != newFont)
  70872. {
  70873. font = newFont;
  70874. if (applySizeAndScale)
  70875. {
  70876. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  70877. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70878. }
  70879. refreshBounds();
  70880. }
  70881. }
  70882. void DrawableText::setJustification (const Justification& newJustification)
  70883. {
  70884. justification = newJustification;
  70885. repaint();
  70886. }
  70887. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70888. {
  70889. if (bounds != newBounds)
  70890. {
  70891. bounds = newBounds;
  70892. refreshBounds();
  70893. }
  70894. }
  70895. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70896. {
  70897. if (fontSizeControlPoint != newPoint)
  70898. {
  70899. fontSizeControlPoint = newPoint;
  70900. refreshBounds();
  70901. }
  70902. }
  70903. void DrawableText::refreshBounds()
  70904. {
  70905. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  70906. {
  70907. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  70908. setPositioner (p);
  70909. p->apply();
  70910. }
  70911. else
  70912. {
  70913. setPositioner (0);
  70914. recalculateCoordinates (0);
  70915. }
  70916. }
  70917. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70918. {
  70919. bool ok = positioner.addPoint (bounds.topLeft);
  70920. ok = positioner.addPoint (bounds.topRight) && ok;
  70921. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70922. return positioner.addPoint (fontSizeControlPoint) && ok;
  70923. }
  70924. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  70925. {
  70926. bounds.resolveThreePoints (resolvedPoints, scope);
  70927. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70928. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70929. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  70930. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70931. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70932. scaledFont = font;
  70933. scaledFont.setHeight (fontHeight);
  70934. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  70935. setBoundsToEnclose (getDrawableBounds());
  70936. repaint();
  70937. }
  70938. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  70939. {
  70940. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70941. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70942. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  70943. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  70944. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  70945. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  70946. }
  70947. void DrawableText::paint (Graphics& g)
  70948. {
  70949. transformContextToCorrectOrigin (g);
  70950. g.setColour (colour);
  70951. GlyphArrangement ga;
  70952. const AffineTransform transform (getArrangementAndTransform (ga));
  70953. ga.draw (g, transform);
  70954. }
  70955. const Rectangle<float> DrawableText::getDrawableBounds() const
  70956. {
  70957. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  70958. }
  70959. Drawable* DrawableText::createCopy() const
  70960. {
  70961. return new DrawableText (*this);
  70962. }
  70963. const Identifier DrawableText::valueTreeType ("Text");
  70964. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70965. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70966. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70967. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70968. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70969. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70970. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70971. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70972. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70973. : ValueTreeWrapperBase (state_)
  70974. {
  70975. jassert (state.hasType (valueTreeType));
  70976. }
  70977. const String DrawableText::ValueTreeWrapper::getText() const
  70978. {
  70979. return state [text].toString();
  70980. }
  70981. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70982. {
  70983. state.setProperty (text, newText, undoManager);
  70984. }
  70985. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70986. {
  70987. return state.getPropertyAsValue (text, undoManager);
  70988. }
  70989. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70990. {
  70991. return Colour::fromString (state [colour].toString());
  70992. }
  70993. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70994. {
  70995. state.setProperty (colour, newColour.toString(), undoManager);
  70996. }
  70997. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70998. {
  70999. return Justification ((int) state [justification]);
  71000. }
  71001. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71002. {
  71003. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71004. }
  71005. const Font DrawableText::ValueTreeWrapper::getFont() const
  71006. {
  71007. return Font::fromString (state [font]);
  71008. }
  71009. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71010. {
  71011. state.setProperty (font, newFont.toString(), undoManager);
  71012. }
  71013. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71014. {
  71015. return state.getPropertyAsValue (font, undoManager);
  71016. }
  71017. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71018. {
  71019. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71020. }
  71021. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71022. {
  71023. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71024. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71025. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71026. }
  71027. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71028. {
  71029. return state [fontSizeAnchor].toString();
  71030. }
  71031. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71032. {
  71033. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71034. }
  71035. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71036. {
  71037. ValueTreeWrapper v (tree);
  71038. setComponentID (v.getID());
  71039. const RelativeParallelogram newBounds (v.getBoundingBox());
  71040. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71041. const Colour newColour (v.getColour());
  71042. const Justification newJustification (v.getJustification());
  71043. const String newText (v.getText());
  71044. const Font newFont (v.getFont());
  71045. if (text != newText || font != newFont || justification != newJustification
  71046. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71047. {
  71048. setBoundingBox (newBounds);
  71049. setFontSizeControlPoint (newFontPoint);
  71050. setColour (newColour);
  71051. setFont (newFont, false);
  71052. setJustification (newJustification);
  71053. setText (newText);
  71054. }
  71055. }
  71056. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71057. {
  71058. ValueTree tree (valueTreeType);
  71059. ValueTreeWrapper v (tree);
  71060. v.setID (getComponentID());
  71061. v.setText (text, 0);
  71062. v.setFont (font, 0);
  71063. v.setJustification (justification, 0);
  71064. v.setColour (colour, 0);
  71065. v.setBoundingBox (bounds, 0);
  71066. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71067. return tree;
  71068. }
  71069. END_JUCE_NAMESPACE
  71070. /*** End of inlined file: juce_DrawableText.cpp ***/
  71071. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71072. BEGIN_JUCE_NAMESPACE
  71073. class SVGState
  71074. {
  71075. public:
  71076. SVGState (const XmlElement* const topLevel)
  71077. : topLevelXml (topLevel),
  71078. elementX (0), elementY (0),
  71079. width (512), height (512),
  71080. viewBoxW (0), viewBoxH (0)
  71081. {
  71082. }
  71083. ~SVGState()
  71084. {
  71085. }
  71086. Drawable* parseSVGElement (const XmlElement& xml)
  71087. {
  71088. if (! xml.hasTagName ("svg"))
  71089. return 0;
  71090. DrawableComposite* const drawable = new DrawableComposite();
  71091. drawable->setName (xml.getStringAttribute ("id"));
  71092. SVGState newState (*this);
  71093. if (xml.hasAttribute ("transform"))
  71094. newState.addTransform (xml);
  71095. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71096. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71097. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71098. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71099. if (xml.hasAttribute ("viewBox"))
  71100. {
  71101. const String viewParams (xml.getStringAttribute ("viewBox"));
  71102. int i = 0;
  71103. float vx, vy, vw, vh;
  71104. if (parseCoords (viewParams, vx, vy, i, true)
  71105. && parseCoords (viewParams, vw, vh, i, true)
  71106. && vw > 0
  71107. && vh > 0)
  71108. {
  71109. newState.viewBoxW = vw;
  71110. newState.viewBoxH = vh;
  71111. int placementFlags = 0;
  71112. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71113. if (aspect.containsIgnoreCase ("none"))
  71114. {
  71115. placementFlags = RectanglePlacement::stretchToFit;
  71116. }
  71117. else
  71118. {
  71119. if (aspect.containsIgnoreCase ("slice"))
  71120. placementFlags |= RectanglePlacement::fillDestination;
  71121. if (aspect.containsIgnoreCase ("xMin"))
  71122. placementFlags |= RectanglePlacement::xLeft;
  71123. else if (aspect.containsIgnoreCase ("xMax"))
  71124. placementFlags |= RectanglePlacement::xRight;
  71125. else
  71126. placementFlags |= RectanglePlacement::xMid;
  71127. if (aspect.containsIgnoreCase ("yMin"))
  71128. placementFlags |= RectanglePlacement::yTop;
  71129. else if (aspect.containsIgnoreCase ("yMax"))
  71130. placementFlags |= RectanglePlacement::yBottom;
  71131. else
  71132. placementFlags |= RectanglePlacement::yMid;
  71133. }
  71134. const RectanglePlacement placement (placementFlags);
  71135. newState.transform
  71136. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71137. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71138. .followedBy (newState.transform);
  71139. }
  71140. }
  71141. else
  71142. {
  71143. if (viewBoxW == 0)
  71144. newState.viewBoxW = newState.width;
  71145. if (viewBoxH == 0)
  71146. newState.viewBoxH = newState.height;
  71147. }
  71148. newState.parseSubElements (xml, drawable);
  71149. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71150. return drawable;
  71151. }
  71152. private:
  71153. const XmlElement* const topLevelXml;
  71154. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71155. AffineTransform transform;
  71156. String cssStyleText;
  71157. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71158. {
  71159. forEachXmlChildElement (xml, e)
  71160. {
  71161. Drawable* d = 0;
  71162. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71163. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71164. else if (e->hasTagName ("path")) d = parsePath (*e);
  71165. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71166. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71167. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71168. else if (e->hasTagName ("line")) d = parseLine (*e);
  71169. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71170. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71171. else if (e->hasTagName ("text")) d = parseText (*e);
  71172. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71173. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71174. parentDrawable->addAndMakeVisible (d);
  71175. }
  71176. }
  71177. DrawableComposite* parseSwitch (const XmlElement& xml)
  71178. {
  71179. const XmlElement* const group = xml.getChildByName ("g");
  71180. if (group != 0)
  71181. return parseGroupElement (*group);
  71182. return 0;
  71183. }
  71184. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71185. {
  71186. DrawableComposite* const drawable = new DrawableComposite();
  71187. drawable->setName (xml.getStringAttribute ("id"));
  71188. if (xml.hasAttribute ("transform"))
  71189. {
  71190. SVGState newState (*this);
  71191. newState.addTransform (xml);
  71192. newState.parseSubElements (xml, drawable);
  71193. }
  71194. else
  71195. {
  71196. parseSubElements (xml, drawable);
  71197. }
  71198. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71199. return drawable;
  71200. }
  71201. Drawable* parsePath (const XmlElement& xml) const
  71202. {
  71203. const String d (xml.getStringAttribute ("d").trimStart());
  71204. Path path;
  71205. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71206. path.setUsingNonZeroWinding (false);
  71207. int index = 0;
  71208. float lastX = 0, lastY = 0;
  71209. float lastX2 = 0, lastY2 = 0;
  71210. juce_wchar lastCommandChar = 0;
  71211. bool isRelative = true;
  71212. bool carryOn = true;
  71213. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71214. while (d[index] != 0)
  71215. {
  71216. float x, y, x2, y2, x3, y3;
  71217. if (validCommandChars.containsChar (d[index]))
  71218. {
  71219. lastCommandChar = d [index++];
  71220. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71221. }
  71222. switch (lastCommandChar)
  71223. {
  71224. case 'M':
  71225. case 'm':
  71226. case 'L':
  71227. case 'l':
  71228. if (parseCoords (d, x, y, index, false))
  71229. {
  71230. if (isRelative)
  71231. {
  71232. x += lastX;
  71233. y += lastY;
  71234. }
  71235. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71236. {
  71237. path.startNewSubPath (x, y);
  71238. lastCommandChar = 'l';
  71239. }
  71240. else
  71241. path.lineTo (x, y);
  71242. lastX2 = lastX;
  71243. lastY2 = lastY;
  71244. lastX = x;
  71245. lastY = y;
  71246. }
  71247. else
  71248. {
  71249. ++index;
  71250. }
  71251. break;
  71252. case 'H':
  71253. case 'h':
  71254. if (parseCoord (d, x, index, false, true))
  71255. {
  71256. if (isRelative)
  71257. x += lastX;
  71258. path.lineTo (x, lastY);
  71259. lastX2 = lastX;
  71260. lastX = x;
  71261. }
  71262. else
  71263. {
  71264. ++index;
  71265. }
  71266. break;
  71267. case 'V':
  71268. case 'v':
  71269. if (parseCoord (d, y, index, false, false))
  71270. {
  71271. if (isRelative)
  71272. y += lastY;
  71273. path.lineTo (lastX, y);
  71274. lastY2 = lastY;
  71275. lastY = y;
  71276. }
  71277. else
  71278. {
  71279. ++index;
  71280. }
  71281. break;
  71282. case 'C':
  71283. case 'c':
  71284. if (parseCoords (d, x, y, index, false)
  71285. && parseCoords (d, x2, y2, index, false)
  71286. && parseCoords (d, x3, y3, index, false))
  71287. {
  71288. if (isRelative)
  71289. {
  71290. x += lastX;
  71291. y += lastY;
  71292. x2 += lastX;
  71293. y2 += lastY;
  71294. x3 += lastX;
  71295. y3 += lastY;
  71296. }
  71297. path.cubicTo (x, y, x2, y2, x3, y3);
  71298. lastX2 = x2;
  71299. lastY2 = y2;
  71300. lastX = x3;
  71301. lastY = y3;
  71302. }
  71303. else
  71304. {
  71305. ++index;
  71306. }
  71307. break;
  71308. case 'S':
  71309. case 's':
  71310. if (parseCoords (d, x, y, index, false)
  71311. && parseCoords (d, x3, y3, index, false))
  71312. {
  71313. if (isRelative)
  71314. {
  71315. x += lastX;
  71316. y += lastY;
  71317. x3 += lastX;
  71318. y3 += lastY;
  71319. }
  71320. x2 = lastX + (lastX - lastX2);
  71321. y2 = lastY + (lastY - lastY2);
  71322. path.cubicTo (x2, y2, x, y, x3, y3);
  71323. lastX2 = x;
  71324. lastY2 = y;
  71325. lastX = x3;
  71326. lastY = y3;
  71327. }
  71328. else
  71329. {
  71330. ++index;
  71331. }
  71332. break;
  71333. case 'Q':
  71334. case 'q':
  71335. if (parseCoords (d, x, y, index, false)
  71336. && parseCoords (d, x2, y2, index, false))
  71337. {
  71338. if (isRelative)
  71339. {
  71340. x += lastX;
  71341. y += lastY;
  71342. x2 += lastX;
  71343. y2 += lastY;
  71344. }
  71345. path.quadraticTo (x, y, x2, y2);
  71346. lastX2 = x;
  71347. lastY2 = y;
  71348. lastX = x2;
  71349. lastY = y2;
  71350. }
  71351. else
  71352. {
  71353. ++index;
  71354. }
  71355. break;
  71356. case 'T':
  71357. case 't':
  71358. if (parseCoords (d, x, y, index, false))
  71359. {
  71360. if (isRelative)
  71361. {
  71362. x += lastX;
  71363. y += lastY;
  71364. }
  71365. x2 = lastX + (lastX - lastX2);
  71366. y2 = lastY + (lastY - lastY2);
  71367. path.quadraticTo (x2, y2, x, y);
  71368. lastX2 = x2;
  71369. lastY2 = y2;
  71370. lastX = x;
  71371. lastY = y;
  71372. }
  71373. else
  71374. {
  71375. ++index;
  71376. }
  71377. break;
  71378. case 'A':
  71379. case 'a':
  71380. if (parseCoords (d, x, y, index, false))
  71381. {
  71382. String num;
  71383. if (parseNextNumber (d, num, index, false))
  71384. {
  71385. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71386. if (parseNextNumber (d, num, index, false))
  71387. {
  71388. const bool largeArc = num.getIntValue() != 0;
  71389. if (parseNextNumber (d, num, index, false))
  71390. {
  71391. const bool sweep = num.getIntValue() != 0;
  71392. if (parseCoords (d, x2, y2, index, false))
  71393. {
  71394. if (isRelative)
  71395. {
  71396. x2 += lastX;
  71397. y2 += lastY;
  71398. }
  71399. if (lastX != x2 || lastY != y2)
  71400. {
  71401. double centreX, centreY, startAngle, deltaAngle;
  71402. double rx = x, ry = y;
  71403. endpointToCentreParameters (lastX, lastY, x2, y2,
  71404. angle, largeArc, sweep,
  71405. rx, ry, centreX, centreY,
  71406. startAngle, deltaAngle);
  71407. path.addCentredArc ((float) centreX, (float) centreY,
  71408. (float) rx, (float) ry,
  71409. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71410. false);
  71411. path.lineTo (x2, y2);
  71412. }
  71413. lastX2 = lastX;
  71414. lastY2 = lastY;
  71415. lastX = x2;
  71416. lastY = y2;
  71417. }
  71418. }
  71419. }
  71420. }
  71421. }
  71422. else
  71423. {
  71424. ++index;
  71425. }
  71426. break;
  71427. case 'Z':
  71428. case 'z':
  71429. path.closeSubPath();
  71430. while (CharacterFunctions::isWhitespace (d [index]))
  71431. ++index;
  71432. break;
  71433. default:
  71434. carryOn = false;
  71435. break;
  71436. }
  71437. if (! carryOn)
  71438. break;
  71439. }
  71440. return parseShape (xml, path);
  71441. }
  71442. Drawable* parseRect (const XmlElement& xml) const
  71443. {
  71444. Path rect;
  71445. const bool hasRX = xml.hasAttribute ("rx");
  71446. const bool hasRY = xml.hasAttribute ("ry");
  71447. if (hasRX || hasRY)
  71448. {
  71449. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71450. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71451. if (! hasRX)
  71452. rx = ry;
  71453. else if (! hasRY)
  71454. ry = rx;
  71455. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71456. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71457. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71458. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71459. rx, ry);
  71460. }
  71461. else
  71462. {
  71463. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71464. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71465. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71466. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71467. }
  71468. return parseShape (xml, rect);
  71469. }
  71470. Drawable* parseCircle (const XmlElement& xml) const
  71471. {
  71472. Path circle;
  71473. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71474. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71475. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71476. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71477. return parseShape (xml, circle);
  71478. }
  71479. Drawable* parseEllipse (const XmlElement& xml) const
  71480. {
  71481. Path ellipse;
  71482. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71483. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71484. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71485. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71486. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71487. return parseShape (xml, ellipse);
  71488. }
  71489. Drawable* parseLine (const XmlElement& xml) const
  71490. {
  71491. Path line;
  71492. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71493. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71494. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71495. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71496. line.startNewSubPath (x1, y1);
  71497. line.lineTo (x2, y2);
  71498. return parseShape (xml, line);
  71499. }
  71500. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71501. {
  71502. const String points (xml.getStringAttribute ("points"));
  71503. Path path;
  71504. int index = 0;
  71505. float x, y;
  71506. if (parseCoords (points, x, y, index, true))
  71507. {
  71508. float firstX = x;
  71509. float firstY = y;
  71510. float lastX = 0, lastY = 0;
  71511. path.startNewSubPath (x, y);
  71512. while (parseCoords (points, x, y, index, true))
  71513. {
  71514. lastX = x;
  71515. lastY = y;
  71516. path.lineTo (x, y);
  71517. }
  71518. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71519. path.closeSubPath();
  71520. }
  71521. return parseShape (xml, path);
  71522. }
  71523. Drawable* parseShape (const XmlElement& xml, Path& path,
  71524. const bool shouldParseTransform = true) const
  71525. {
  71526. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71527. {
  71528. SVGState newState (*this);
  71529. newState.addTransform (xml);
  71530. return newState.parseShape (xml, path, false);
  71531. }
  71532. DrawablePath* dp = new DrawablePath();
  71533. dp->setName (xml.getStringAttribute ("id"));
  71534. dp->setFill (Colours::transparentBlack);
  71535. path.applyTransform (transform);
  71536. dp->setPath (path);
  71537. Path::Iterator iter (path);
  71538. bool containsClosedSubPath = false;
  71539. while (iter.next())
  71540. {
  71541. if (iter.elementType == Path::Iterator::closePath)
  71542. {
  71543. containsClosedSubPath = true;
  71544. break;
  71545. }
  71546. }
  71547. dp->setFill (getPathFillType (path,
  71548. getStyleAttribute (&xml, "fill"),
  71549. getStyleAttribute (&xml, "fill-opacity"),
  71550. getStyleAttribute (&xml, "opacity"),
  71551. containsClosedSubPath ? Colours::black
  71552. : Colours::transparentBlack));
  71553. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71554. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71555. {
  71556. dp->setStrokeFill (getPathFillType (path, strokeType,
  71557. getStyleAttribute (&xml, "stroke-opacity"),
  71558. getStyleAttribute (&xml, "opacity"),
  71559. Colours::transparentBlack));
  71560. dp->setStrokeType (getStrokeFor (&xml));
  71561. }
  71562. return dp;
  71563. }
  71564. const XmlElement* findLinkedElement (const XmlElement* e) const
  71565. {
  71566. const String id (e->getStringAttribute ("xlink:href"));
  71567. if (! id.startsWithChar ('#'))
  71568. return 0;
  71569. return findElementForId (topLevelXml, id.substring (1));
  71570. }
  71571. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71572. {
  71573. if (fillXml == 0)
  71574. return;
  71575. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71576. {
  71577. int index = 0;
  71578. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71579. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71580. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71581. double offset = e->getDoubleAttribute ("offset");
  71582. if (e->getStringAttribute ("offset").containsChar ('%'))
  71583. offset *= 0.01;
  71584. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71585. }
  71586. }
  71587. const FillType getPathFillType (const Path& path,
  71588. const String& fill,
  71589. const String& fillOpacity,
  71590. const String& overallOpacity,
  71591. const Colour& defaultColour) const
  71592. {
  71593. float opacity = 1.0f;
  71594. if (overallOpacity.isNotEmpty())
  71595. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71596. if (fillOpacity.isNotEmpty())
  71597. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71598. if (fill.startsWithIgnoreCase ("url"))
  71599. {
  71600. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71601. .upToLastOccurrenceOf (")", false, false).trim());
  71602. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71603. if (fillXml != 0
  71604. && (fillXml->hasTagName ("linearGradient")
  71605. || fillXml->hasTagName ("radialGradient")))
  71606. {
  71607. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71608. ColourGradient gradient;
  71609. addGradientStopsIn (gradient, inheritedFrom);
  71610. addGradientStopsIn (gradient, fillXml);
  71611. if (gradient.getNumColours() > 0)
  71612. {
  71613. gradient.addColour (0.0, gradient.getColour (0));
  71614. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71615. }
  71616. else
  71617. {
  71618. gradient.addColour (0.0, Colours::black);
  71619. gradient.addColour (1.0, Colours::black);
  71620. }
  71621. if (overallOpacity.isNotEmpty())
  71622. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71623. jassert (gradient.getNumColours() > 0);
  71624. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71625. float gradientWidth = viewBoxW;
  71626. float gradientHeight = viewBoxH;
  71627. float dx = 0.0f;
  71628. float dy = 0.0f;
  71629. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71630. if (! userSpace)
  71631. {
  71632. const Rectangle<float> bounds (path.getBounds());
  71633. dx = bounds.getX();
  71634. dy = bounds.getY();
  71635. gradientWidth = bounds.getWidth();
  71636. gradientHeight = bounds.getHeight();
  71637. }
  71638. if (gradient.isRadial)
  71639. {
  71640. if (userSpace)
  71641. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71642. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71643. else
  71644. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71645. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71646. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71647. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71648. //xxx (the fx, fy focal point isn't handled properly here..)
  71649. }
  71650. else
  71651. {
  71652. if (userSpace)
  71653. {
  71654. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71655. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71656. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71657. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71658. }
  71659. else
  71660. {
  71661. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71662. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71663. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71664. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71665. }
  71666. if (gradient.point1 == gradient.point2)
  71667. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71668. }
  71669. FillType type (gradient);
  71670. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71671. .followedBy (transform);
  71672. return type;
  71673. }
  71674. }
  71675. if (fill.equalsIgnoreCase ("none"))
  71676. return Colours::transparentBlack;
  71677. int i = 0;
  71678. const Colour colour (parseColour (fill, i, defaultColour));
  71679. return colour.withMultipliedAlpha (opacity);
  71680. }
  71681. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71682. {
  71683. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71684. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71685. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71686. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71687. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71688. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71689. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71690. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71691. if (join.equalsIgnoreCase ("round"))
  71692. joinStyle = PathStrokeType::curved;
  71693. else if (join.equalsIgnoreCase ("bevel"))
  71694. joinStyle = PathStrokeType::beveled;
  71695. if (cap.equalsIgnoreCase ("round"))
  71696. capStyle = PathStrokeType::rounded;
  71697. else if (cap.equalsIgnoreCase ("square"))
  71698. capStyle = PathStrokeType::square;
  71699. float ox = 0.0f, oy = 0.0f;
  71700. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71701. transform.transformPoints (ox, oy, x, y);
  71702. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71703. joinStyle, capStyle);
  71704. }
  71705. Drawable* parseText (const XmlElement& xml)
  71706. {
  71707. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71708. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71709. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71710. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71711. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71712. //xxx not done text yet!
  71713. forEachXmlChildElement (xml, e)
  71714. {
  71715. if (e->isTextElement())
  71716. {
  71717. const String text (e->getText());
  71718. Path path;
  71719. Drawable* s = parseShape (*e, path);
  71720. delete s; // xxx not finished!
  71721. }
  71722. else if (e->hasTagName ("tspan"))
  71723. {
  71724. Drawable* s = parseText (*e);
  71725. delete s; // xxx not finished!
  71726. }
  71727. }
  71728. return 0;
  71729. }
  71730. void addTransform (const XmlElement& xml)
  71731. {
  71732. transform = parseTransform (xml.getStringAttribute ("transform"))
  71733. .followedBy (transform);
  71734. }
  71735. bool parseCoord (const String& s, float& value, int& index,
  71736. const bool allowUnits, const bool isX) const
  71737. {
  71738. String number;
  71739. if (! parseNextNumber (s, number, index, allowUnits))
  71740. {
  71741. value = 0;
  71742. return false;
  71743. }
  71744. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71745. return true;
  71746. }
  71747. bool parseCoords (const String& s, float& x, float& y,
  71748. int& index, const bool allowUnits) const
  71749. {
  71750. return parseCoord (s, x, index, allowUnits, true)
  71751. && parseCoord (s, y, index, allowUnits, false);
  71752. }
  71753. float getCoordLength (const String& s, const float sizeForProportions) const
  71754. {
  71755. float n = s.getFloatValue();
  71756. const int len = s.length();
  71757. if (len > 2)
  71758. {
  71759. const float dpi = 96.0f;
  71760. const juce_wchar n1 = s [len - 2];
  71761. const juce_wchar n2 = s [len - 1];
  71762. if (n1 == 'i' && n2 == 'n')
  71763. n *= dpi;
  71764. else if (n1 == 'm' && n2 == 'm')
  71765. n *= dpi / 25.4f;
  71766. else if (n1 == 'c' && n2 == 'm')
  71767. n *= dpi / 2.54f;
  71768. else if (n1 == 'p' && n2 == 'c')
  71769. n *= 15.0f;
  71770. else if (n2 == '%')
  71771. n *= 0.01f * sizeForProportions;
  71772. }
  71773. return n;
  71774. }
  71775. void getCoordList (Array <float>& coords, const String& list,
  71776. const bool allowUnits, const bool isX) const
  71777. {
  71778. int index = 0;
  71779. float value;
  71780. while (parseCoord (list, value, index, allowUnits, isX))
  71781. coords.add (value);
  71782. }
  71783. void parseCSSStyle (const XmlElement& xml)
  71784. {
  71785. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71786. }
  71787. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71788. const String& defaultValue = String::empty) const
  71789. {
  71790. if (xml->hasAttribute (attributeName))
  71791. return xml->getStringAttribute (attributeName, defaultValue);
  71792. const String styleAtt (xml->getStringAttribute ("style"));
  71793. if (styleAtt.isNotEmpty())
  71794. {
  71795. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71796. if (value.isNotEmpty())
  71797. return value;
  71798. }
  71799. else if (xml->hasAttribute ("class"))
  71800. {
  71801. const String className ("." + xml->getStringAttribute ("class"));
  71802. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71803. if (index < 0)
  71804. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71805. if (index >= 0)
  71806. {
  71807. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71808. if (openBracket > index)
  71809. {
  71810. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71811. if (closeBracket > openBracket)
  71812. {
  71813. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71814. if (value.isNotEmpty())
  71815. return value;
  71816. }
  71817. }
  71818. }
  71819. }
  71820. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71821. if (xml != 0)
  71822. return getStyleAttribute (xml, attributeName, defaultValue);
  71823. return defaultValue;
  71824. }
  71825. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71826. {
  71827. if (xml->hasAttribute (attributeName))
  71828. return xml->getStringAttribute (attributeName);
  71829. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71830. if (xml != 0)
  71831. return getInheritedAttribute (xml, attributeName);
  71832. return String::empty;
  71833. }
  71834. static bool isIdentifierChar (const juce_wchar c)
  71835. {
  71836. return CharacterFunctions::isLetter (c) || c == '-';
  71837. }
  71838. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71839. {
  71840. int i = 0;
  71841. for (;;)
  71842. {
  71843. i = list.indexOf (i, attributeName);
  71844. if (i < 0)
  71845. break;
  71846. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71847. && ! isIdentifierChar (list [i + attributeName.length()]))
  71848. {
  71849. i = list.indexOfChar (i, ':');
  71850. if (i < 0)
  71851. break;
  71852. int end = list.indexOfChar (i, ';');
  71853. if (end < 0)
  71854. end = 0x7ffff;
  71855. return list.substring (i + 1, end).trim();
  71856. }
  71857. ++i;
  71858. }
  71859. return defaultValue;
  71860. }
  71861. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71862. {
  71863. const juce_wchar* const s = source;
  71864. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71865. ++index;
  71866. int start = index;
  71867. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71868. ++index;
  71869. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71870. ++index;
  71871. if ((s[index] == 'e' || s[index] == 'E')
  71872. && (CharacterFunctions::isDigit (s[index + 1])
  71873. || s[index + 1] == '-'
  71874. || s[index + 1] == '+'))
  71875. {
  71876. index += 2;
  71877. while (CharacterFunctions::isDigit (s[index]))
  71878. ++index;
  71879. }
  71880. if (allowUnits)
  71881. {
  71882. while (CharacterFunctions::isLetter (s[index]))
  71883. ++index;
  71884. }
  71885. if (index == start)
  71886. return false;
  71887. value = String (s + start, index - start);
  71888. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71889. ++index;
  71890. return true;
  71891. }
  71892. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71893. {
  71894. if (s [index] == '#')
  71895. {
  71896. uint32 hex [6];
  71897. zeromem (hex, sizeof (hex));
  71898. int numChars = 0;
  71899. for (int i = 6; --i >= 0;)
  71900. {
  71901. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71902. if (hexValue >= 0)
  71903. hex [numChars++] = hexValue;
  71904. else
  71905. break;
  71906. }
  71907. if (numChars <= 3)
  71908. return Colour ((uint8) (hex [0] * 0x11),
  71909. (uint8) (hex [1] * 0x11),
  71910. (uint8) (hex [2] * 0x11));
  71911. else
  71912. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71913. (uint8) ((hex [2] << 4) + hex [3]),
  71914. (uint8) ((hex [4] << 4) + hex [5]));
  71915. }
  71916. else if (s [index] == 'r'
  71917. && s [index + 1] == 'g'
  71918. && s [index + 2] == 'b')
  71919. {
  71920. const int openBracket = s.indexOfChar (index, '(');
  71921. const int closeBracket = s.indexOfChar (openBracket, ')');
  71922. if (openBracket >= 3 && closeBracket > openBracket)
  71923. {
  71924. index = closeBracket;
  71925. StringArray tokens;
  71926. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71927. tokens.trim();
  71928. tokens.removeEmptyStrings();
  71929. if (tokens[0].containsChar ('%'))
  71930. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71931. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71932. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71933. else
  71934. return Colour ((uint8) tokens[0].getIntValue(),
  71935. (uint8) tokens[1].getIntValue(),
  71936. (uint8) tokens[2].getIntValue());
  71937. }
  71938. }
  71939. return Colours::findColourForName (s, defaultColour);
  71940. }
  71941. static const AffineTransform parseTransform (String t)
  71942. {
  71943. AffineTransform result;
  71944. while (t.isNotEmpty())
  71945. {
  71946. StringArray tokens;
  71947. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71948. .upToFirstOccurrenceOf (")", false, false),
  71949. ", ", String::empty);
  71950. tokens.removeEmptyStrings (true);
  71951. float numbers [6];
  71952. for (int i = 0; i < 6; ++i)
  71953. numbers[i] = tokens[i].getFloatValue();
  71954. AffineTransform trans;
  71955. if (t.startsWithIgnoreCase ("matrix"))
  71956. {
  71957. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71958. numbers[1], numbers[3], numbers[5]);
  71959. }
  71960. else if (t.startsWithIgnoreCase ("translate"))
  71961. {
  71962. jassert (tokens.size() == 2);
  71963. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71964. }
  71965. else if (t.startsWithIgnoreCase ("scale"))
  71966. {
  71967. if (tokens.size() == 1)
  71968. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71969. else
  71970. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71971. }
  71972. else if (t.startsWithIgnoreCase ("rotate"))
  71973. {
  71974. if (tokens.size() != 3)
  71975. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71976. else
  71977. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71978. numbers[1], numbers[2]);
  71979. }
  71980. else if (t.startsWithIgnoreCase ("skewX"))
  71981. {
  71982. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71983. 0.0f, 1.0f, 0.0f);
  71984. }
  71985. else if (t.startsWithIgnoreCase ("skewY"))
  71986. {
  71987. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71988. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71989. }
  71990. result = trans.followedBy (result);
  71991. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71992. }
  71993. return result;
  71994. }
  71995. static void endpointToCentreParameters (const double x1, const double y1,
  71996. const double x2, const double y2,
  71997. const double angle,
  71998. const bool largeArc, const bool sweep,
  71999. double& rx, double& ry,
  72000. double& centreX, double& centreY,
  72001. double& startAngle, double& deltaAngle)
  72002. {
  72003. const double midX = (x1 - x2) * 0.5;
  72004. const double midY = (y1 - y2) * 0.5;
  72005. const double cosAngle = cos (angle);
  72006. const double sinAngle = sin (angle);
  72007. const double xp = cosAngle * midX + sinAngle * midY;
  72008. const double yp = cosAngle * midY - sinAngle * midX;
  72009. const double xp2 = xp * xp;
  72010. const double yp2 = yp * yp;
  72011. double rx2 = rx * rx;
  72012. double ry2 = ry * ry;
  72013. const double s = (xp2 / rx2) + (yp2 / ry2);
  72014. double c;
  72015. if (s <= 1.0)
  72016. {
  72017. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72018. / (( rx2 * yp2) + (ry2 * xp2))));
  72019. if (largeArc == sweep)
  72020. c = -c;
  72021. }
  72022. else
  72023. {
  72024. const double s2 = std::sqrt (s);
  72025. rx *= s2;
  72026. ry *= s2;
  72027. rx2 = rx * rx;
  72028. ry2 = ry * ry;
  72029. c = 0;
  72030. }
  72031. const double cpx = ((rx * yp) / ry) * c;
  72032. const double cpy = ((-ry * xp) / rx) * c;
  72033. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72034. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72035. const double ux = (xp - cpx) / rx;
  72036. const double uy = (yp - cpy) / ry;
  72037. const double vx = (-xp - cpx) / rx;
  72038. const double vy = (-yp - cpy) / ry;
  72039. const double length = juce_hypot (ux, uy);
  72040. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72041. if (uy < 0)
  72042. startAngle = -startAngle;
  72043. startAngle += double_Pi * 0.5;
  72044. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72045. / (length * juce_hypot (vx, vy))));
  72046. if ((ux * vy) - (uy * vx) < 0)
  72047. deltaAngle = -deltaAngle;
  72048. if (sweep)
  72049. {
  72050. if (deltaAngle < 0)
  72051. deltaAngle += double_Pi * 2.0;
  72052. }
  72053. else
  72054. {
  72055. if (deltaAngle > 0)
  72056. deltaAngle -= double_Pi * 2.0;
  72057. }
  72058. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72059. }
  72060. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72061. {
  72062. forEachXmlChildElement (*parent, e)
  72063. {
  72064. if (e->compareAttribute ("id", id))
  72065. return e;
  72066. const XmlElement* const found = findElementForId (e, id);
  72067. if (found != 0)
  72068. return found;
  72069. }
  72070. return 0;
  72071. }
  72072. SVGState& operator= (const SVGState&);
  72073. };
  72074. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72075. {
  72076. SVGState state (&svgDocument);
  72077. return state.parseSVGElement (svgDocument);
  72078. }
  72079. END_JUCE_NAMESPACE
  72080. /*** End of inlined file: juce_SVGParser.cpp ***/
  72081. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72082. BEGIN_JUCE_NAMESPACE
  72083. #if JUCE_MSVC && JUCE_DEBUG
  72084. #pragma optimize ("t", on)
  72085. #endif
  72086. DropShadowEffect::DropShadowEffect()
  72087. : offsetX (0),
  72088. offsetY (0),
  72089. radius (4),
  72090. opacity (0.6f)
  72091. {
  72092. }
  72093. DropShadowEffect::~DropShadowEffect()
  72094. {
  72095. }
  72096. void DropShadowEffect::setShadowProperties (const float newRadius,
  72097. const float newOpacity,
  72098. const int newShadowOffsetX,
  72099. const int newShadowOffsetY)
  72100. {
  72101. radius = jmax (1.1f, newRadius);
  72102. offsetX = newShadowOffsetX;
  72103. offsetY = newShadowOffsetY;
  72104. opacity = newOpacity;
  72105. }
  72106. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72107. {
  72108. const int w = image.getWidth();
  72109. const int h = image.getHeight();
  72110. Image shadowImage (Image::SingleChannel, w, h, false);
  72111. const Image::BitmapData srcData (image, false);
  72112. const Image::BitmapData destData (shadowImage, true);
  72113. const int filter = roundToInt (63.0f / radius);
  72114. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72115. for (int x = w; --x >= 0;)
  72116. {
  72117. int shadowAlpha = 0;
  72118. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72119. uint8* shadowPix = destData.data + x;
  72120. for (int y = h; --y >= 0;)
  72121. {
  72122. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72123. *shadowPix = (uint8) shadowAlpha;
  72124. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72125. shadowPix += destData.lineStride;
  72126. }
  72127. }
  72128. for (int y = h; --y >= 0;)
  72129. {
  72130. int shadowAlpha = 0;
  72131. uint8* shadowPix = destData.getLinePointer (y);
  72132. for (int x = w; --x >= 0;)
  72133. {
  72134. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72135. *shadowPix++ = (uint8) shadowAlpha;
  72136. }
  72137. }
  72138. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72139. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72140. g.setOpacity (alpha);
  72141. g.drawImageAt (image, 0, 0);
  72142. }
  72143. #if JUCE_MSVC && JUCE_DEBUG
  72144. #pragma optimize ("", on) // resets optimisations to the project defaults
  72145. #endif
  72146. END_JUCE_NAMESPACE
  72147. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72148. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72149. BEGIN_JUCE_NAMESPACE
  72150. GlowEffect::GlowEffect()
  72151. : radius (2.0f),
  72152. colour (Colours::white)
  72153. {
  72154. }
  72155. GlowEffect::~GlowEffect()
  72156. {
  72157. }
  72158. void GlowEffect::setGlowProperties (const float newRadius,
  72159. const Colour& newColour)
  72160. {
  72161. radius = newRadius;
  72162. colour = newColour;
  72163. }
  72164. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72165. {
  72166. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72167. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72168. blurKernel.createGaussianBlur (radius);
  72169. blurKernel.rescaleAllValues (radius);
  72170. blurKernel.applyToImage (temp, image, image.getBounds());
  72171. g.setColour (colour.withMultipliedAlpha (alpha));
  72172. g.drawImageAt (temp, 0, 0, true);
  72173. g.setOpacity (alpha);
  72174. g.drawImageAt (image, 0, 0, false);
  72175. }
  72176. END_JUCE_NAMESPACE
  72177. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72178. /*** Start of inlined file: juce_Font.cpp ***/
  72179. BEGIN_JUCE_NAMESPACE
  72180. namespace FontValues
  72181. {
  72182. float limitFontHeight (const float height) throw()
  72183. {
  72184. return jlimit (0.1f, 10000.0f, height);
  72185. }
  72186. const float defaultFontHeight = 14.0f;
  72187. String fallbackFont;
  72188. }
  72189. class TypefaceCache : public DeletedAtShutdown
  72190. {
  72191. public:
  72192. TypefaceCache()
  72193. : counter (0)
  72194. {
  72195. setSize (10);
  72196. }
  72197. ~TypefaceCache()
  72198. {
  72199. clearSingletonInstance();
  72200. }
  72201. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72202. void setSize (const int numToCache)
  72203. {
  72204. faces.clear();
  72205. faces.insertMultiple (-1, CachedFace(), numToCache);
  72206. }
  72207. const Typeface::Ptr findTypefaceFor (const Font& font)
  72208. {
  72209. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72210. const String faceName (font.getTypefaceName());
  72211. int i;
  72212. for (i = faces.size(); --i >= 0;)
  72213. {
  72214. CachedFace& face = faces.getReference(i);
  72215. if (face.flags == flags
  72216. && face.typefaceName == faceName
  72217. && face.typeface->isSuitableForFont (font))
  72218. {
  72219. face.lastUsageCount = ++counter;
  72220. return face.typeface;
  72221. }
  72222. }
  72223. int replaceIndex = 0;
  72224. int bestLastUsageCount = std::numeric_limits<int>::max();
  72225. for (i = faces.size(); --i >= 0;)
  72226. {
  72227. const int lu = faces.getReference(i).lastUsageCount;
  72228. if (bestLastUsageCount > lu)
  72229. {
  72230. bestLastUsageCount = lu;
  72231. replaceIndex = i;
  72232. }
  72233. }
  72234. CachedFace& face = faces.getReference (replaceIndex);
  72235. face.typefaceName = faceName;
  72236. face.flags = flags;
  72237. face.lastUsageCount = ++counter;
  72238. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72239. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72240. if (defaultFace == 0 && font == Font())
  72241. defaultFace = face.typeface;
  72242. return face.typeface;
  72243. }
  72244. const Typeface::Ptr getDefaultTypeface() const throw()
  72245. {
  72246. return defaultFace;
  72247. }
  72248. private:
  72249. struct CachedFace
  72250. {
  72251. CachedFace() throw()
  72252. : lastUsageCount (0), flags (-1)
  72253. {
  72254. }
  72255. // Although it seems a bit wacky to store the name here, it's because it may be a
  72256. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72257. // Since the typeface itself doesn't know that it may have this alias, the name under
  72258. // which it was fetched needs to be stored separately.
  72259. String typefaceName;
  72260. int lastUsageCount, flags;
  72261. Typeface::Ptr typeface;
  72262. };
  72263. Array <CachedFace> faces;
  72264. Typeface::Ptr defaultFace;
  72265. int counter;
  72266. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72267. };
  72268. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72269. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72270. {
  72271. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72272. }
  72273. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72274. : typefaceName (Font::getDefaultSansSerifFontName()),
  72275. height (height_),
  72276. horizontalScale (1.0f),
  72277. kerning (0),
  72278. ascent (0),
  72279. styleFlags (styleFlags_),
  72280. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72281. {
  72282. }
  72283. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72284. : typefaceName (typefaceName_),
  72285. height (height_),
  72286. horizontalScale (1.0f),
  72287. kerning (0),
  72288. ascent (0),
  72289. styleFlags (styleFlags_),
  72290. typeface (0)
  72291. {
  72292. }
  72293. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72294. : typefaceName (typeface_->getName()),
  72295. height (FontValues::defaultFontHeight),
  72296. horizontalScale (1.0f),
  72297. kerning (0),
  72298. ascent (0),
  72299. styleFlags (Font::plain),
  72300. typeface (typeface_)
  72301. {
  72302. }
  72303. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72304. : typefaceName (other.typefaceName),
  72305. height (other.height),
  72306. horizontalScale (other.horizontalScale),
  72307. kerning (other.kerning),
  72308. ascent (other.ascent),
  72309. styleFlags (other.styleFlags),
  72310. typeface (other.typeface)
  72311. {
  72312. }
  72313. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72314. {
  72315. return height == other.height
  72316. && styleFlags == other.styleFlags
  72317. && horizontalScale == other.horizontalScale
  72318. && kerning == other.kerning
  72319. && typefaceName == other.typefaceName;
  72320. }
  72321. Font::Font()
  72322. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72323. {
  72324. }
  72325. Font::Font (const float fontHeight, const int styleFlags_)
  72326. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72327. {
  72328. }
  72329. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72330. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72331. {
  72332. }
  72333. Font::Font (const Typeface::Ptr& typeface)
  72334. : font (new SharedFontInternal (typeface))
  72335. {
  72336. }
  72337. Font::Font (const Font& other) throw()
  72338. : font (other.font)
  72339. {
  72340. }
  72341. Font& Font::operator= (const Font& other) throw()
  72342. {
  72343. font = other.font;
  72344. return *this;
  72345. }
  72346. Font::~Font() throw()
  72347. {
  72348. }
  72349. bool Font::operator== (const Font& other) const throw()
  72350. {
  72351. return font == other.font
  72352. || *font == *other.font;
  72353. }
  72354. bool Font::operator!= (const Font& other) const throw()
  72355. {
  72356. return ! operator== (other);
  72357. }
  72358. void Font::dupeInternalIfShared()
  72359. {
  72360. if (font->getReferenceCount() > 1)
  72361. font = new SharedFontInternal (*font);
  72362. }
  72363. const String Font::getDefaultSansSerifFontName()
  72364. {
  72365. static const String name ("<Sans-Serif>");
  72366. return name;
  72367. }
  72368. const String Font::getDefaultSerifFontName()
  72369. {
  72370. static const String name ("<Serif>");
  72371. return name;
  72372. }
  72373. const String Font::getDefaultMonospacedFontName()
  72374. {
  72375. static const String name ("<Monospaced>");
  72376. return name;
  72377. }
  72378. void Font::setTypefaceName (const String& faceName)
  72379. {
  72380. if (faceName != font->typefaceName)
  72381. {
  72382. dupeInternalIfShared();
  72383. font->typefaceName = faceName;
  72384. font->typeface = 0;
  72385. font->ascent = 0;
  72386. }
  72387. }
  72388. const String Font::getFallbackFontName()
  72389. {
  72390. return FontValues::fallbackFont;
  72391. }
  72392. void Font::setFallbackFontName (const String& name)
  72393. {
  72394. FontValues::fallbackFont = name;
  72395. }
  72396. void Font::setHeight (float newHeight)
  72397. {
  72398. newHeight = FontValues::limitFontHeight (newHeight);
  72399. if (font->height != newHeight)
  72400. {
  72401. dupeInternalIfShared();
  72402. font->height = newHeight;
  72403. }
  72404. }
  72405. void Font::setHeightWithoutChangingWidth (float newHeight)
  72406. {
  72407. newHeight = FontValues::limitFontHeight (newHeight);
  72408. if (font->height != newHeight)
  72409. {
  72410. dupeInternalIfShared();
  72411. font->horizontalScale *= (font->height / newHeight);
  72412. font->height = newHeight;
  72413. }
  72414. }
  72415. void Font::setStyleFlags (const int newFlags)
  72416. {
  72417. if (font->styleFlags != newFlags)
  72418. {
  72419. dupeInternalIfShared();
  72420. font->styleFlags = newFlags;
  72421. font->typeface = 0;
  72422. font->ascent = 0;
  72423. }
  72424. }
  72425. void Font::setSizeAndStyle (float newHeight,
  72426. const int newStyleFlags,
  72427. const float newHorizontalScale,
  72428. const float newKerningAmount)
  72429. {
  72430. newHeight = FontValues::limitFontHeight (newHeight);
  72431. if (font->height != newHeight
  72432. || font->horizontalScale != newHorizontalScale
  72433. || font->kerning != newKerningAmount)
  72434. {
  72435. dupeInternalIfShared();
  72436. font->height = newHeight;
  72437. font->horizontalScale = newHorizontalScale;
  72438. font->kerning = newKerningAmount;
  72439. }
  72440. setStyleFlags (newStyleFlags);
  72441. }
  72442. void Font::setHorizontalScale (const float scaleFactor)
  72443. {
  72444. dupeInternalIfShared();
  72445. font->horizontalScale = scaleFactor;
  72446. }
  72447. void Font::setExtraKerningFactor (const float extraKerning)
  72448. {
  72449. dupeInternalIfShared();
  72450. font->kerning = extraKerning;
  72451. }
  72452. void Font::setBold (const bool shouldBeBold)
  72453. {
  72454. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72455. : (font->styleFlags & ~bold));
  72456. }
  72457. const Font Font::boldened() const
  72458. {
  72459. Font f (*this);
  72460. f.setBold (true);
  72461. return f;
  72462. }
  72463. bool Font::isBold() const throw()
  72464. {
  72465. return (font->styleFlags & bold) != 0;
  72466. }
  72467. void Font::setItalic (const bool shouldBeItalic)
  72468. {
  72469. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72470. : (font->styleFlags & ~italic));
  72471. }
  72472. const Font Font::italicised() const
  72473. {
  72474. Font f (*this);
  72475. f.setItalic (true);
  72476. return f;
  72477. }
  72478. bool Font::isItalic() const throw()
  72479. {
  72480. return (font->styleFlags & italic) != 0;
  72481. }
  72482. void Font::setUnderline (const bool shouldBeUnderlined)
  72483. {
  72484. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72485. : (font->styleFlags & ~underlined));
  72486. }
  72487. bool Font::isUnderlined() const throw()
  72488. {
  72489. return (font->styleFlags & underlined) != 0;
  72490. }
  72491. float Font::getAscent() const
  72492. {
  72493. if (font->ascent == 0)
  72494. font->ascent = getTypeface()->getAscent();
  72495. return font->height * font->ascent;
  72496. }
  72497. float Font::getDescent() const
  72498. {
  72499. return font->height - getAscent();
  72500. }
  72501. int Font::getStringWidth (const String& text) const
  72502. {
  72503. return roundToInt (getStringWidthFloat (text));
  72504. }
  72505. float Font::getStringWidthFloat (const String& text) const
  72506. {
  72507. float w = getTypeface()->getStringWidth (text);
  72508. if (font->kerning != 0)
  72509. w += font->kerning * text.length();
  72510. return w * font->height * font->horizontalScale;
  72511. }
  72512. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72513. {
  72514. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72515. const float scale = font->height * font->horizontalScale;
  72516. const int num = xOffsets.size();
  72517. if (num > 0)
  72518. {
  72519. float* const x = &(xOffsets.getReference(0));
  72520. if (font->kerning != 0)
  72521. {
  72522. for (int i = 0; i < num; ++i)
  72523. x[i] = (x[i] + i * font->kerning) * scale;
  72524. }
  72525. else
  72526. {
  72527. for (int i = 0; i < num; ++i)
  72528. x[i] *= scale;
  72529. }
  72530. }
  72531. }
  72532. void Font::findFonts (Array<Font>& destArray)
  72533. {
  72534. const StringArray names (findAllTypefaceNames());
  72535. for (int i = 0; i < names.size(); ++i)
  72536. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72537. }
  72538. const String Font::toString() const
  72539. {
  72540. String s (getTypefaceName());
  72541. if (s == getDefaultSansSerifFontName())
  72542. s = String::empty;
  72543. else
  72544. s += "; ";
  72545. s += String (getHeight(), 1);
  72546. if (isBold())
  72547. s += " bold";
  72548. if (isItalic())
  72549. s += " italic";
  72550. return s;
  72551. }
  72552. const Font Font::fromString (const String& fontDescription)
  72553. {
  72554. String name;
  72555. const int separator = fontDescription.indexOfChar (';');
  72556. if (separator > 0)
  72557. name = fontDescription.substring (0, separator).trim();
  72558. if (name.isEmpty())
  72559. name = getDefaultSansSerifFontName();
  72560. String sizeAndStyle (fontDescription.substring (separator + 1));
  72561. float height = sizeAndStyle.getFloatValue();
  72562. if (height <= 0)
  72563. height = 10.0f;
  72564. int flags = Font::plain;
  72565. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72566. flags |= Font::bold;
  72567. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72568. flags |= Font::italic;
  72569. return Font (name, height, flags);
  72570. }
  72571. Typeface* Font::getTypeface() const
  72572. {
  72573. if (font->typeface == 0)
  72574. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72575. return font->typeface;
  72576. }
  72577. END_JUCE_NAMESPACE
  72578. /*** End of inlined file: juce_Font.cpp ***/
  72579. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72580. BEGIN_JUCE_NAMESPACE
  72581. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72582. const juce_wchar character_, const int glyph_)
  72583. : x (x_),
  72584. y (y_),
  72585. w (w_),
  72586. font (font_),
  72587. character (character_),
  72588. glyph (glyph_)
  72589. {
  72590. }
  72591. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72592. : x (other.x),
  72593. y (other.y),
  72594. w (other.w),
  72595. font (other.font),
  72596. character (other.character),
  72597. glyph (other.glyph)
  72598. {
  72599. }
  72600. void PositionedGlyph::draw (const Graphics& g) const
  72601. {
  72602. if (! isWhitespace())
  72603. {
  72604. g.getInternalContext()->setFont (font);
  72605. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72606. }
  72607. }
  72608. void PositionedGlyph::draw (const Graphics& g,
  72609. const AffineTransform& transform) const
  72610. {
  72611. if (! isWhitespace())
  72612. {
  72613. g.getInternalContext()->setFont (font);
  72614. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72615. .followedBy (transform));
  72616. }
  72617. }
  72618. void PositionedGlyph::createPath (Path& path) const
  72619. {
  72620. if (! isWhitespace())
  72621. {
  72622. Typeface* const t = font.getTypeface();
  72623. if (t != 0)
  72624. {
  72625. Path p;
  72626. t->getOutlineForGlyph (glyph, p);
  72627. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72628. .translated (x, y));
  72629. }
  72630. }
  72631. }
  72632. bool PositionedGlyph::hitTest (float px, float py) const
  72633. {
  72634. if (getBounds().contains (px, py) && ! isWhitespace())
  72635. {
  72636. Typeface* const t = font.getTypeface();
  72637. if (t != 0)
  72638. {
  72639. Path p;
  72640. t->getOutlineForGlyph (glyph, p);
  72641. AffineTransform::translation (-x, -y)
  72642. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72643. .transformPoint (px, py);
  72644. return p.contains (px, py);
  72645. }
  72646. }
  72647. return false;
  72648. }
  72649. void PositionedGlyph::moveBy (const float deltaX,
  72650. const float deltaY)
  72651. {
  72652. x += deltaX;
  72653. y += deltaY;
  72654. }
  72655. GlyphArrangement::GlyphArrangement()
  72656. {
  72657. glyphs.ensureStorageAllocated (128);
  72658. }
  72659. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72660. {
  72661. addGlyphArrangement (other);
  72662. }
  72663. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72664. {
  72665. if (this != &other)
  72666. {
  72667. clear();
  72668. addGlyphArrangement (other);
  72669. }
  72670. return *this;
  72671. }
  72672. GlyphArrangement::~GlyphArrangement()
  72673. {
  72674. }
  72675. void GlyphArrangement::clear()
  72676. {
  72677. glyphs.clear();
  72678. }
  72679. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72680. {
  72681. jassert (isPositiveAndBelow (index, glyphs.size()));
  72682. return *glyphs [index];
  72683. }
  72684. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72685. {
  72686. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72687. glyphs.addCopiesOf (other.glyphs);
  72688. }
  72689. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72690. {
  72691. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72692. }
  72693. void GlyphArrangement::addLineOfText (const Font& font,
  72694. const String& text,
  72695. const float xOffset,
  72696. const float yOffset)
  72697. {
  72698. addCurtailedLineOfText (font, text,
  72699. xOffset, yOffset,
  72700. 1.0e10f, false);
  72701. }
  72702. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72703. const String& text,
  72704. float xOffset,
  72705. const float yOffset,
  72706. const float maxWidthPixels,
  72707. const bool useEllipsis)
  72708. {
  72709. if (text.isNotEmpty())
  72710. {
  72711. Array <int> newGlyphs;
  72712. Array <float> xOffsets;
  72713. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72714. const int textLen = newGlyphs.size();
  72715. const juce_wchar* const unicodeText = text;
  72716. for (int i = 0; i < textLen; ++i)
  72717. {
  72718. const float thisX = xOffsets.getUnchecked (i);
  72719. const float nextX = xOffsets.getUnchecked (i + 1);
  72720. if (nextX > maxWidthPixels + 1.0f)
  72721. {
  72722. // curtail the string if it's too wide..
  72723. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72724. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72725. break;
  72726. }
  72727. else
  72728. {
  72729. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72730. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72731. }
  72732. }
  72733. }
  72734. }
  72735. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72736. const int startIndex, int endIndex)
  72737. {
  72738. int numDeleted = 0;
  72739. if (glyphs.size() > 0)
  72740. {
  72741. Array<int> dotGlyphs;
  72742. Array<float> dotXs;
  72743. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72744. const float dx = dotXs[1];
  72745. float xOffset = 0.0f, yOffset = 0.0f;
  72746. while (endIndex > startIndex)
  72747. {
  72748. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72749. xOffset = pg->x;
  72750. yOffset = pg->y;
  72751. glyphs.remove (endIndex);
  72752. ++numDeleted;
  72753. if (xOffset + dx * 3 <= maxXPos)
  72754. break;
  72755. }
  72756. for (int i = 3; --i >= 0;)
  72757. {
  72758. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72759. font, '.', dotGlyphs.getFirst()));
  72760. --numDeleted;
  72761. xOffset += dx;
  72762. if (xOffset > maxXPos)
  72763. break;
  72764. }
  72765. }
  72766. return numDeleted;
  72767. }
  72768. void GlyphArrangement::addJustifiedText (const Font& font,
  72769. const String& text,
  72770. float x, float y,
  72771. const float maxLineWidth,
  72772. const Justification& horizontalLayout)
  72773. {
  72774. int lineStartIndex = glyphs.size();
  72775. addLineOfText (font, text, x, y);
  72776. const float originalY = y;
  72777. while (lineStartIndex < glyphs.size())
  72778. {
  72779. int i = lineStartIndex;
  72780. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72781. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72782. ++i;
  72783. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72784. int lastWordBreakIndex = -1;
  72785. while (i < glyphs.size())
  72786. {
  72787. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72788. const juce_wchar c = pg->getCharacter();
  72789. if (c == '\r' || c == '\n')
  72790. {
  72791. ++i;
  72792. if (c == '\r' && i < glyphs.size()
  72793. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72794. ++i;
  72795. break;
  72796. }
  72797. else if (pg->isWhitespace())
  72798. {
  72799. lastWordBreakIndex = i + 1;
  72800. }
  72801. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72802. {
  72803. if (lastWordBreakIndex >= 0)
  72804. i = lastWordBreakIndex;
  72805. break;
  72806. }
  72807. ++i;
  72808. }
  72809. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72810. float currentLineEndX = currentLineStartX;
  72811. for (int j = i; --j >= lineStartIndex;)
  72812. {
  72813. if (! glyphs.getUnchecked (j)->isWhitespace())
  72814. {
  72815. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72816. break;
  72817. }
  72818. }
  72819. float deltaX = 0.0f;
  72820. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72821. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72822. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72823. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72824. else if (horizontalLayout.testFlags (Justification::right))
  72825. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72826. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72827. x + deltaX - currentLineStartX, y - originalY);
  72828. lineStartIndex = i;
  72829. y += font.getHeight();
  72830. }
  72831. }
  72832. void GlyphArrangement::addFittedText (const Font& f,
  72833. const String& text,
  72834. const float x, const float y,
  72835. const float width, const float height,
  72836. const Justification& layout,
  72837. int maximumLines,
  72838. const float minimumHorizontalScale)
  72839. {
  72840. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72841. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72842. if (text.containsAnyOf ("\r\n"))
  72843. {
  72844. GlyphArrangement ga;
  72845. ga.addJustifiedText (f, text, x, y, width, layout);
  72846. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72847. float dy = y - bb.getY();
  72848. if (layout.testFlags (Justification::verticallyCentred))
  72849. dy += (height - bb.getHeight()) * 0.5f;
  72850. else if (layout.testFlags (Justification::bottom))
  72851. dy += height - bb.getHeight();
  72852. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72853. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72854. for (int i = 0; i < ga.glyphs.size(); ++i)
  72855. glyphs.add (ga.glyphs.getUnchecked (i));
  72856. ga.glyphs.clear (false);
  72857. return;
  72858. }
  72859. int startIndex = glyphs.size();
  72860. addLineOfText (f, text.trim(), x, y);
  72861. if (glyphs.size() > startIndex)
  72862. {
  72863. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72864. - glyphs.getUnchecked (startIndex)->getLeft();
  72865. if (lineWidth <= 0)
  72866. return;
  72867. if (lineWidth * minimumHorizontalScale < width)
  72868. {
  72869. if (lineWidth > width)
  72870. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72871. width / lineWidth);
  72872. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72873. x, y, width, height, layout);
  72874. }
  72875. else if (maximumLines <= 1)
  72876. {
  72877. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72878. x, y, width, height, f, layout, minimumHorizontalScale);
  72879. }
  72880. else
  72881. {
  72882. Font font (f);
  72883. String txt (text.trim());
  72884. const int length = txt.length();
  72885. const int originalStartIndex = startIndex;
  72886. int numLines = 1;
  72887. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72888. maximumLines = 1;
  72889. maximumLines = jmin (maximumLines, length);
  72890. while (numLines < maximumLines)
  72891. {
  72892. ++numLines;
  72893. const float newFontHeight = height / (float) numLines;
  72894. if (newFontHeight < font.getHeight())
  72895. {
  72896. font.setHeight (jmax (8.0f, newFontHeight));
  72897. removeRangeOfGlyphs (startIndex, -1);
  72898. addLineOfText (font, txt, x, y);
  72899. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72900. - glyphs.getUnchecked (startIndex)->getLeft();
  72901. }
  72902. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72903. break;
  72904. }
  72905. if (numLines < 1)
  72906. numLines = 1;
  72907. float lineY = y;
  72908. float widthPerLine = lineWidth / numLines;
  72909. int lastLineStartIndex = 0;
  72910. for (int line = 0; line < numLines; ++line)
  72911. {
  72912. int i = startIndex;
  72913. lastLineStartIndex = i;
  72914. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72915. if (line == numLines - 1)
  72916. {
  72917. widthPerLine = width;
  72918. i = glyphs.size();
  72919. }
  72920. else
  72921. {
  72922. while (i < glyphs.size())
  72923. {
  72924. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72925. if (lineWidth > widthPerLine)
  72926. {
  72927. // got to a point where the line's too long, so skip forward to find a
  72928. // good place to break it..
  72929. const int searchStartIndex = i;
  72930. while (i < glyphs.size())
  72931. {
  72932. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72933. {
  72934. if (glyphs.getUnchecked (i)->isWhitespace()
  72935. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72936. {
  72937. ++i;
  72938. break;
  72939. }
  72940. }
  72941. else
  72942. {
  72943. // can't find a suitable break, so try looking backwards..
  72944. i = searchStartIndex;
  72945. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72946. {
  72947. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72948. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72949. {
  72950. i -= back - 1;
  72951. break;
  72952. }
  72953. }
  72954. break;
  72955. }
  72956. ++i;
  72957. }
  72958. break;
  72959. }
  72960. ++i;
  72961. }
  72962. int wsStart = i;
  72963. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72964. --wsStart;
  72965. int wsEnd = i;
  72966. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72967. ++wsEnd;
  72968. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72969. i = jmax (wsStart, startIndex + 1);
  72970. }
  72971. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72972. x, lineY, width, font.getHeight(), font,
  72973. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72974. minimumHorizontalScale);
  72975. startIndex = i;
  72976. lineY += font.getHeight();
  72977. if (startIndex >= glyphs.size())
  72978. break;
  72979. }
  72980. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72981. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72982. }
  72983. }
  72984. }
  72985. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72986. const float dx, const float dy)
  72987. {
  72988. jassert (startIndex >= 0);
  72989. if (dx != 0.0f || dy != 0.0f)
  72990. {
  72991. if (num < 0 || startIndex + num > glyphs.size())
  72992. num = glyphs.size() - startIndex;
  72993. while (--num >= 0)
  72994. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72995. }
  72996. }
  72997. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72998. const Justification& justification, float minimumHorizontalScale)
  72999. {
  73000. int numDeleted = 0;
  73001. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73002. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73003. if (lineWidth > w)
  73004. {
  73005. if (minimumHorizontalScale < 1.0f)
  73006. {
  73007. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73008. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73009. }
  73010. if (lineWidth > w)
  73011. {
  73012. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73013. numGlyphs -= numDeleted;
  73014. }
  73015. }
  73016. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73017. return numDeleted;
  73018. }
  73019. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73020. const float horizontalScaleFactor)
  73021. {
  73022. jassert (startIndex >= 0);
  73023. if (num < 0 || startIndex + num > glyphs.size())
  73024. num = glyphs.size() - startIndex;
  73025. if (num > 0)
  73026. {
  73027. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73028. while (--num >= 0)
  73029. {
  73030. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73031. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73032. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73033. pg->w *= horizontalScaleFactor;
  73034. }
  73035. }
  73036. }
  73037. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73038. {
  73039. jassert (startIndex >= 0);
  73040. if (num < 0 || startIndex + num > glyphs.size())
  73041. num = glyphs.size() - startIndex;
  73042. Rectangle<float> result;
  73043. while (--num >= 0)
  73044. {
  73045. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73046. if (includeWhitespace || ! pg->isWhitespace())
  73047. result = result.getUnion (pg->getBounds());
  73048. }
  73049. return result;
  73050. }
  73051. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73052. const float x, const float y, const float width, const float height,
  73053. const Justification& justification)
  73054. {
  73055. jassert (num >= 0 && startIndex >= 0);
  73056. if (glyphs.size() > 0 && num > 0)
  73057. {
  73058. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73059. | Justification::horizontallyCentred)));
  73060. float deltaX = 0.0f;
  73061. if (justification.testFlags (Justification::horizontallyJustified))
  73062. deltaX = x - bb.getX();
  73063. else if (justification.testFlags (Justification::horizontallyCentred))
  73064. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73065. else if (justification.testFlags (Justification::right))
  73066. deltaX = (x + width) - bb.getRight();
  73067. else
  73068. deltaX = x - bb.getX();
  73069. float deltaY = 0.0f;
  73070. if (justification.testFlags (Justification::top))
  73071. deltaY = y - bb.getY();
  73072. else if (justification.testFlags (Justification::bottom))
  73073. deltaY = (y + height) - bb.getBottom();
  73074. else
  73075. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73076. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73077. if (justification.testFlags (Justification::horizontallyJustified))
  73078. {
  73079. int lineStart = 0;
  73080. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73081. int i;
  73082. for (i = 0; i < num; ++i)
  73083. {
  73084. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73085. if (glyphY != baseY)
  73086. {
  73087. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73088. lineStart = i;
  73089. baseY = glyphY;
  73090. }
  73091. }
  73092. if (i > lineStart)
  73093. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73094. }
  73095. }
  73096. }
  73097. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73098. {
  73099. if (start + num < glyphs.size()
  73100. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73101. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73102. {
  73103. int numSpaces = 0;
  73104. int spacesAtEnd = 0;
  73105. for (int i = 0; i < num; ++i)
  73106. {
  73107. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73108. {
  73109. ++spacesAtEnd;
  73110. ++numSpaces;
  73111. }
  73112. else
  73113. {
  73114. spacesAtEnd = 0;
  73115. }
  73116. }
  73117. numSpaces -= spacesAtEnd;
  73118. if (numSpaces > 0)
  73119. {
  73120. const float startX = glyphs.getUnchecked (start)->getLeft();
  73121. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73122. const float extraPaddingBetweenWords
  73123. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73124. float deltaX = 0.0f;
  73125. for (int i = 0; i < num; ++i)
  73126. {
  73127. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73128. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73129. deltaX += extraPaddingBetweenWords;
  73130. }
  73131. }
  73132. }
  73133. }
  73134. void GlyphArrangement::draw (const Graphics& g) const
  73135. {
  73136. for (int i = 0; i < glyphs.size(); ++i)
  73137. {
  73138. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73139. if (pg->font.isUnderlined())
  73140. {
  73141. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73142. float nextX = pg->x + pg->w;
  73143. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73144. nextX = glyphs.getUnchecked (i + 1)->x;
  73145. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73146. nextX - pg->x, lineThickness);
  73147. }
  73148. pg->draw (g);
  73149. }
  73150. }
  73151. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73152. {
  73153. for (int i = 0; i < glyphs.size(); ++i)
  73154. {
  73155. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73156. if (pg->font.isUnderlined())
  73157. {
  73158. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73159. float nextX = pg->x + pg->w;
  73160. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73161. nextX = glyphs.getUnchecked (i + 1)->x;
  73162. Path p;
  73163. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73164. nextX, pg->y + lineThickness * 2.0f),
  73165. lineThickness);
  73166. g.fillPath (p, transform);
  73167. }
  73168. pg->draw (g, transform);
  73169. }
  73170. }
  73171. void GlyphArrangement::createPath (Path& path) const
  73172. {
  73173. for (int i = 0; i < glyphs.size(); ++i)
  73174. glyphs.getUnchecked (i)->createPath (path);
  73175. }
  73176. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73177. {
  73178. for (int i = 0; i < glyphs.size(); ++i)
  73179. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73180. return i;
  73181. return -1;
  73182. }
  73183. END_JUCE_NAMESPACE
  73184. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73185. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73186. BEGIN_JUCE_NAMESPACE
  73187. class TextLayout::Token
  73188. {
  73189. public:
  73190. Token (const String& t,
  73191. const Font& f,
  73192. const bool isWhitespace_)
  73193. : text (t),
  73194. font (f),
  73195. x(0),
  73196. y(0),
  73197. isWhitespace (isWhitespace_)
  73198. {
  73199. w = font.getStringWidth (t);
  73200. h = roundToInt (f.getHeight());
  73201. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73202. }
  73203. Token (const Token& other)
  73204. : text (other.text),
  73205. font (other.font),
  73206. x (other.x),
  73207. y (other.y),
  73208. w (other.w),
  73209. h (other.h),
  73210. line (other.line),
  73211. lineHeight (other.lineHeight),
  73212. isWhitespace (other.isWhitespace),
  73213. isNewLine (other.isNewLine)
  73214. {
  73215. }
  73216. void draw (Graphics& g,
  73217. const int xOffset,
  73218. const int yOffset)
  73219. {
  73220. if (! isWhitespace)
  73221. {
  73222. g.setFont (font);
  73223. g.drawSingleLineText (text.trimEnd(),
  73224. xOffset + x,
  73225. yOffset + y + (lineHeight - h)
  73226. + roundToInt (font.getAscent()));
  73227. }
  73228. }
  73229. String text;
  73230. Font font;
  73231. int x, y, w, h;
  73232. int line, lineHeight;
  73233. bool isWhitespace, isNewLine;
  73234. private:
  73235. JUCE_LEAK_DETECTOR (Token);
  73236. };
  73237. TextLayout::TextLayout()
  73238. : totalLines (0)
  73239. {
  73240. tokens.ensureStorageAllocated (64);
  73241. }
  73242. TextLayout::TextLayout (const String& text, const Font& font)
  73243. : totalLines (0)
  73244. {
  73245. tokens.ensureStorageAllocated (64);
  73246. appendText (text, font);
  73247. }
  73248. TextLayout::TextLayout (const TextLayout& other)
  73249. : totalLines (0)
  73250. {
  73251. *this = other;
  73252. }
  73253. TextLayout& TextLayout::operator= (const TextLayout& other)
  73254. {
  73255. if (this != &other)
  73256. {
  73257. clear();
  73258. totalLines = other.totalLines;
  73259. tokens.addCopiesOf (other.tokens);
  73260. }
  73261. return *this;
  73262. }
  73263. TextLayout::~TextLayout()
  73264. {
  73265. clear();
  73266. }
  73267. void TextLayout::clear()
  73268. {
  73269. tokens.clear();
  73270. totalLines = 0;
  73271. }
  73272. bool TextLayout::isEmpty() const
  73273. {
  73274. return tokens.size() == 0;
  73275. }
  73276. void TextLayout::appendText (const String& text, const Font& font)
  73277. {
  73278. const juce_wchar* t = text;
  73279. String currentString;
  73280. int lastCharType = 0;
  73281. for (;;)
  73282. {
  73283. const juce_wchar c = *t++;
  73284. if (c == 0)
  73285. break;
  73286. int charType;
  73287. if (c == '\r' || c == '\n')
  73288. {
  73289. charType = 0;
  73290. }
  73291. else if (CharacterFunctions::isWhitespace (c))
  73292. {
  73293. charType = 2;
  73294. }
  73295. else
  73296. {
  73297. charType = 1;
  73298. }
  73299. if (charType == 0 || charType != lastCharType)
  73300. {
  73301. if (currentString.isNotEmpty())
  73302. {
  73303. tokens.add (new Token (currentString, font,
  73304. lastCharType == 2 || lastCharType == 0));
  73305. }
  73306. currentString = String::charToString (c);
  73307. if (c == '\r' && *t == '\n')
  73308. currentString += *t++;
  73309. }
  73310. else
  73311. {
  73312. currentString += c;
  73313. }
  73314. lastCharType = charType;
  73315. }
  73316. if (currentString.isNotEmpty())
  73317. tokens.add (new Token (currentString, font, lastCharType == 2));
  73318. }
  73319. void TextLayout::setText (const String& text, const Font& font)
  73320. {
  73321. clear();
  73322. appendText (text, font);
  73323. }
  73324. void TextLayout::layout (int maxWidth,
  73325. const Justification& justification,
  73326. const bool attemptToBalanceLineLengths)
  73327. {
  73328. if (attemptToBalanceLineLengths)
  73329. {
  73330. const int originalW = maxWidth;
  73331. int bestWidth = maxWidth;
  73332. float bestLineProportion = 0.0f;
  73333. while (maxWidth > originalW / 2)
  73334. {
  73335. layout (maxWidth, justification, false);
  73336. if (getNumLines() <= 1)
  73337. return;
  73338. const int lastLineW = getLineWidth (getNumLines() - 1);
  73339. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73340. const float prop = lastLineW / (float) lastButOneLineW;
  73341. if (prop > 0.9f)
  73342. return;
  73343. if (prop > bestLineProportion)
  73344. {
  73345. bestLineProportion = prop;
  73346. bestWidth = maxWidth;
  73347. }
  73348. maxWidth -= 10;
  73349. }
  73350. layout (bestWidth, justification, false);
  73351. }
  73352. else
  73353. {
  73354. int x = 0;
  73355. int y = 0;
  73356. int h = 0;
  73357. totalLines = 0;
  73358. int i;
  73359. for (i = 0; i < tokens.size(); ++i)
  73360. {
  73361. Token* const t = tokens.getUnchecked(i);
  73362. t->x = x;
  73363. t->y = y;
  73364. t->line = totalLines;
  73365. x += t->w;
  73366. h = jmax (h, t->h);
  73367. const Token* nextTok = tokens [i + 1];
  73368. if (nextTok == 0)
  73369. break;
  73370. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73371. {
  73372. // finished a line, so go back and update the heights of the things on it
  73373. for (int j = i; j >= 0; --j)
  73374. {
  73375. Token* const tok = tokens.getUnchecked(j);
  73376. if (tok->line == totalLines)
  73377. tok->lineHeight = h;
  73378. else
  73379. break;
  73380. }
  73381. x = 0;
  73382. y += h;
  73383. h = 0;
  73384. ++totalLines;
  73385. }
  73386. }
  73387. // finished a line, so go back and update the heights of the things on it
  73388. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73389. {
  73390. Token* const t = tokens.getUnchecked(j);
  73391. if (t->line == totalLines)
  73392. t->lineHeight = h;
  73393. else
  73394. break;
  73395. }
  73396. ++totalLines;
  73397. if (! justification.testFlags (Justification::left))
  73398. {
  73399. int totalW = getWidth();
  73400. for (i = totalLines; --i >= 0;)
  73401. {
  73402. const int lineW = getLineWidth (i);
  73403. int dx = 0;
  73404. if (justification.testFlags (Justification::horizontallyCentred))
  73405. dx = (totalW - lineW) / 2;
  73406. else if (justification.testFlags (Justification::right))
  73407. dx = totalW - lineW;
  73408. for (int j = tokens.size(); --j >= 0;)
  73409. {
  73410. Token* const t = tokens.getUnchecked(j);
  73411. if (t->line == i)
  73412. t->x += dx;
  73413. }
  73414. }
  73415. }
  73416. }
  73417. }
  73418. int TextLayout::getLineWidth (const int lineNumber) const
  73419. {
  73420. int maxW = 0;
  73421. for (int i = tokens.size(); --i >= 0;)
  73422. {
  73423. const Token* const t = tokens.getUnchecked(i);
  73424. if (t->line == lineNumber && ! t->isWhitespace)
  73425. maxW = jmax (maxW, t->x + t->w);
  73426. }
  73427. return maxW;
  73428. }
  73429. int TextLayout::getWidth() const
  73430. {
  73431. int maxW = 0;
  73432. for (int i = tokens.size(); --i >= 0;)
  73433. {
  73434. const Token* const t = tokens.getUnchecked(i);
  73435. if (! t->isWhitespace)
  73436. maxW = jmax (maxW, t->x + t->w);
  73437. }
  73438. return maxW;
  73439. }
  73440. int TextLayout::getHeight() const
  73441. {
  73442. int maxH = 0;
  73443. for (int i = tokens.size(); --i >= 0;)
  73444. {
  73445. const Token* const t = tokens.getUnchecked(i);
  73446. if (! t->isWhitespace)
  73447. maxH = jmax (maxH, t->y + t->h);
  73448. }
  73449. return maxH;
  73450. }
  73451. void TextLayout::draw (Graphics& g,
  73452. const int xOffset,
  73453. const int yOffset) const
  73454. {
  73455. for (int i = tokens.size(); --i >= 0;)
  73456. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73457. }
  73458. void TextLayout::drawWithin (Graphics& g,
  73459. int x, int y, int w, int h,
  73460. const Justification& justification) const
  73461. {
  73462. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73463. x, y, w, h);
  73464. draw (g, x, y);
  73465. }
  73466. END_JUCE_NAMESPACE
  73467. /*** End of inlined file: juce_TextLayout.cpp ***/
  73468. /*** Start of inlined file: juce_Typeface.cpp ***/
  73469. BEGIN_JUCE_NAMESPACE
  73470. Typeface::Typeface (const String& name_) throw()
  73471. : name (name_), isFallbackFont (false)
  73472. {
  73473. }
  73474. Typeface::~Typeface()
  73475. {
  73476. }
  73477. const Typeface::Ptr Typeface::getFallbackTypeface()
  73478. {
  73479. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73480. Typeface* t = fallbackFont.getTypeface();
  73481. t->isFallbackFont = true;
  73482. return t;
  73483. }
  73484. class CustomTypeface::GlyphInfo
  73485. {
  73486. public:
  73487. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73488. : character (character_), path (path_), width (width_)
  73489. {
  73490. }
  73491. struct KerningPair
  73492. {
  73493. juce_wchar character2;
  73494. float kerningAmount;
  73495. };
  73496. void addKerningPair (const juce_wchar subsequentCharacter,
  73497. const float extraKerningAmount) throw()
  73498. {
  73499. KerningPair kp;
  73500. kp.character2 = subsequentCharacter;
  73501. kp.kerningAmount = extraKerningAmount;
  73502. kerningPairs.add (kp);
  73503. }
  73504. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73505. {
  73506. if (subsequentCharacter != 0)
  73507. {
  73508. for (int i = kerningPairs.size(); --i >= 0;)
  73509. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73510. return width + kerningPairs.getReference(i).kerningAmount;
  73511. }
  73512. return width;
  73513. }
  73514. const juce_wchar character;
  73515. const Path path;
  73516. float width;
  73517. Array <KerningPair> kerningPairs;
  73518. private:
  73519. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73520. };
  73521. CustomTypeface::CustomTypeface()
  73522. : Typeface (String::empty)
  73523. {
  73524. clear();
  73525. }
  73526. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73527. : Typeface (String::empty)
  73528. {
  73529. clear();
  73530. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73531. BufferedInputStream in (gzin, 32768);
  73532. name = in.readString();
  73533. isBold = in.readBool();
  73534. isItalic = in.readBool();
  73535. ascent = in.readFloat();
  73536. defaultCharacter = (juce_wchar) in.readShort();
  73537. int i, numChars = in.readInt();
  73538. for (i = 0; i < numChars; ++i)
  73539. {
  73540. const juce_wchar c = (juce_wchar) in.readShort();
  73541. const float width = in.readFloat();
  73542. Path p;
  73543. p.loadPathFromStream (in);
  73544. addGlyph (c, p, width);
  73545. }
  73546. const int numKerningPairs = in.readInt();
  73547. for (i = 0; i < numKerningPairs; ++i)
  73548. {
  73549. const juce_wchar char1 = (juce_wchar) in.readShort();
  73550. const juce_wchar char2 = (juce_wchar) in.readShort();
  73551. addKerningPair (char1, char2, in.readFloat());
  73552. }
  73553. }
  73554. CustomTypeface::~CustomTypeface()
  73555. {
  73556. }
  73557. void CustomTypeface::clear()
  73558. {
  73559. defaultCharacter = 0;
  73560. ascent = 1.0f;
  73561. isBold = isItalic = false;
  73562. zeromem (lookupTable, sizeof (lookupTable));
  73563. glyphs.clear();
  73564. }
  73565. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73566. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73567. {
  73568. name = name_;
  73569. defaultCharacter = defaultCharacter_;
  73570. ascent = ascent_;
  73571. isBold = isBold_;
  73572. isItalic = isItalic_;
  73573. }
  73574. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73575. {
  73576. // Check that you're not trying to add the same character twice..
  73577. jassert (findGlyph (character, false) == 0);
  73578. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73579. lookupTable [character] = (short) glyphs.size();
  73580. glyphs.add (new GlyphInfo (character, path, width));
  73581. }
  73582. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73583. {
  73584. if (extraAmount != 0)
  73585. {
  73586. GlyphInfo* const g = findGlyph (char1, true);
  73587. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73588. if (g != 0)
  73589. g->addKerningPair (char2, extraAmount);
  73590. }
  73591. }
  73592. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73593. {
  73594. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73595. return glyphs [(int) lookupTable [(int) character]];
  73596. for (int i = 0; i < glyphs.size(); ++i)
  73597. {
  73598. GlyphInfo* const g = glyphs.getUnchecked(i);
  73599. if (g->character == character)
  73600. return g;
  73601. }
  73602. if (loadIfNeeded && loadGlyphIfPossible (character))
  73603. return findGlyph (character, false);
  73604. return 0;
  73605. }
  73606. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73607. {
  73608. GlyphInfo* glyph = findGlyph (character, true);
  73609. if (glyph == 0)
  73610. {
  73611. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73612. glyph = findGlyph (L' ', true);
  73613. if (glyph == 0)
  73614. {
  73615. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73616. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73617. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73618. {
  73619. Path path;
  73620. fallbackTypeface->getOutlineForGlyph (character, path);
  73621. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73622. }
  73623. if (glyph == 0)
  73624. glyph = findGlyph (defaultCharacter, true);
  73625. }
  73626. }
  73627. return glyph;
  73628. }
  73629. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73630. {
  73631. return false;
  73632. }
  73633. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73634. {
  73635. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73636. for (int i = 0; i < numCharacters; ++i)
  73637. {
  73638. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73639. Array <int> glyphIndexes;
  73640. Array <float> offsets;
  73641. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73642. const int glyphIndex = glyphIndexes.getFirst();
  73643. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73644. {
  73645. const float glyphWidth = offsets[1];
  73646. Path p;
  73647. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73648. addGlyph (c, p, glyphWidth);
  73649. for (int j = glyphs.size() - 1; --j >= 0;)
  73650. {
  73651. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73652. glyphIndexes.clearQuick();
  73653. offsets.clearQuick();
  73654. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73655. if (offsets.size() > 1)
  73656. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73657. }
  73658. }
  73659. }
  73660. }
  73661. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73662. {
  73663. GZIPCompressorOutputStream out (&outputStream);
  73664. out.writeString (name);
  73665. out.writeBool (isBold);
  73666. out.writeBool (isItalic);
  73667. out.writeFloat (ascent);
  73668. out.writeShort ((short) (unsigned short) defaultCharacter);
  73669. out.writeInt (glyphs.size());
  73670. int i, numKerningPairs = 0;
  73671. for (i = 0; i < glyphs.size(); ++i)
  73672. {
  73673. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73674. out.writeShort ((short) (unsigned short) g->character);
  73675. out.writeFloat (g->width);
  73676. g->path.writePathToStream (out);
  73677. numKerningPairs += g->kerningPairs.size();
  73678. }
  73679. out.writeInt (numKerningPairs);
  73680. for (i = 0; i < glyphs.size(); ++i)
  73681. {
  73682. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73683. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73684. {
  73685. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73686. out.writeShort ((short) (unsigned short) g->character);
  73687. out.writeShort ((short) (unsigned short) p.character2);
  73688. out.writeFloat (p.kerningAmount);
  73689. }
  73690. }
  73691. return true;
  73692. }
  73693. float CustomTypeface::getAscent() const
  73694. {
  73695. return ascent;
  73696. }
  73697. float CustomTypeface::getDescent() const
  73698. {
  73699. return 1.0f - ascent;
  73700. }
  73701. float CustomTypeface::getStringWidth (const String& text)
  73702. {
  73703. float x = 0;
  73704. const juce_wchar* t = text;
  73705. while (*t != 0)
  73706. {
  73707. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73708. if (glyph == 0 && ! isFallbackFont)
  73709. {
  73710. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73711. if (fallbackTypeface != 0)
  73712. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73713. }
  73714. if (glyph != 0)
  73715. x += glyph->getHorizontalSpacing (*t);
  73716. }
  73717. return x;
  73718. }
  73719. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73720. {
  73721. xOffsets.add (0);
  73722. float x = 0;
  73723. const juce_wchar* t = text;
  73724. while (*t != 0)
  73725. {
  73726. const juce_wchar c = *t++;
  73727. const GlyphInfo* const glyph = findGlyph (c, true);
  73728. if (glyph == 0 && ! isFallbackFont)
  73729. {
  73730. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73731. if (fallbackTypeface != 0)
  73732. {
  73733. Array <int> subGlyphs;
  73734. Array <float> subOffsets;
  73735. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73736. if (subGlyphs.size() > 0)
  73737. {
  73738. resultGlyphs.add (subGlyphs.getFirst());
  73739. x += subOffsets[1];
  73740. xOffsets.add (x);
  73741. }
  73742. }
  73743. }
  73744. if (glyph != 0)
  73745. {
  73746. x += glyph->getHorizontalSpacing (*t);
  73747. resultGlyphs.add ((int) glyph->character);
  73748. xOffsets.add (x);
  73749. }
  73750. }
  73751. }
  73752. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73753. {
  73754. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73755. if (glyph == 0 && ! isFallbackFont)
  73756. {
  73757. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73758. if (fallbackTypeface != 0)
  73759. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73760. }
  73761. if (glyph != 0)
  73762. {
  73763. path = glyph->path;
  73764. return true;
  73765. }
  73766. return false;
  73767. }
  73768. END_JUCE_NAMESPACE
  73769. /*** End of inlined file: juce_Typeface.cpp ***/
  73770. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73771. BEGIN_JUCE_NAMESPACE
  73772. AffineTransform::AffineTransform() throw()
  73773. : mat00 (1.0f), mat01 (0), mat02 (0),
  73774. mat10 (0), mat11 (1.0f), mat12 (0)
  73775. {
  73776. }
  73777. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73778. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73779. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73780. {
  73781. }
  73782. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73783. const float mat10_, const float mat11_, const float mat12_) throw()
  73784. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73785. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73786. {
  73787. }
  73788. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73789. {
  73790. mat00 = other.mat00;
  73791. mat01 = other.mat01;
  73792. mat02 = other.mat02;
  73793. mat10 = other.mat10;
  73794. mat11 = other.mat11;
  73795. mat12 = other.mat12;
  73796. return *this;
  73797. }
  73798. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73799. {
  73800. return mat00 == other.mat00
  73801. && mat01 == other.mat01
  73802. && mat02 == other.mat02
  73803. && mat10 == other.mat10
  73804. && mat11 == other.mat11
  73805. && mat12 == other.mat12;
  73806. }
  73807. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73808. {
  73809. return ! operator== (other);
  73810. }
  73811. bool AffineTransform::isIdentity() const throw()
  73812. {
  73813. return (mat01 == 0)
  73814. && (mat02 == 0)
  73815. && (mat10 == 0)
  73816. && (mat12 == 0)
  73817. && (mat00 == 1.0f)
  73818. && (mat11 == 1.0f);
  73819. }
  73820. const AffineTransform AffineTransform::identity;
  73821. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73822. {
  73823. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73824. other.mat00 * mat01 + other.mat01 * mat11,
  73825. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73826. other.mat10 * mat00 + other.mat11 * mat10,
  73827. other.mat10 * mat01 + other.mat11 * mat11,
  73828. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73829. }
  73830. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73831. {
  73832. return AffineTransform (mat00, mat01, mat02 + dx,
  73833. mat10, mat11, mat12 + dy);
  73834. }
  73835. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73836. {
  73837. return AffineTransform (1.0f, 0, dx,
  73838. 0, 1.0f, dy);
  73839. }
  73840. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73841. {
  73842. const float cosRad = std::cos (rad);
  73843. const float sinRad = std::sin (rad);
  73844. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73845. cosRad * mat01 + -sinRad * mat11,
  73846. cosRad * mat02 + -sinRad * mat12,
  73847. sinRad * mat00 + cosRad * mat10,
  73848. sinRad * mat01 + cosRad * mat11,
  73849. sinRad * mat02 + cosRad * mat12);
  73850. }
  73851. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73852. {
  73853. const float cosRad = std::cos (rad);
  73854. const float sinRad = std::sin (rad);
  73855. return AffineTransform (cosRad, -sinRad, 0,
  73856. sinRad, cosRad, 0);
  73857. }
  73858. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73859. {
  73860. const float cosRad = std::cos (rad);
  73861. const float sinRad = std::sin (rad);
  73862. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73863. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73864. }
  73865. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73866. {
  73867. return followedBy (rotation (angle, pivotX, pivotY));
  73868. }
  73869. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73870. {
  73871. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73872. factorY * mat10, factorY * mat11, factorY * mat12);
  73873. }
  73874. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73875. {
  73876. return AffineTransform (factorX, 0, 0,
  73877. 0, factorY, 0);
  73878. }
  73879. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73880. const float pivotX, const float pivotY) const throw()
  73881. {
  73882. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73883. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73884. }
  73885. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73886. const float pivotX, const float pivotY) throw()
  73887. {
  73888. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73889. 0, factorY, pivotY * (1.0f - factorY));
  73890. }
  73891. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73892. {
  73893. return AffineTransform (1.0f, shearX, 0,
  73894. shearY, 1.0f, 0);
  73895. }
  73896. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73897. {
  73898. return AffineTransform (mat00 + shearX * mat10,
  73899. mat01 + shearX * mat11,
  73900. mat02 + shearX * mat12,
  73901. shearY * mat00 + mat10,
  73902. shearY * mat01 + mat11,
  73903. shearY * mat02 + mat12);
  73904. }
  73905. const AffineTransform AffineTransform::inverted() const throw()
  73906. {
  73907. double determinant = (mat00 * mat11 - mat10 * mat01);
  73908. if (determinant != 0.0)
  73909. {
  73910. determinant = 1.0 / determinant;
  73911. const float dst00 = (float) (mat11 * determinant);
  73912. const float dst10 = (float) (-mat10 * determinant);
  73913. const float dst01 = (float) (-mat01 * determinant);
  73914. const float dst11 = (float) (mat00 * determinant);
  73915. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73916. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73917. }
  73918. else
  73919. {
  73920. // singularity..
  73921. return *this;
  73922. }
  73923. }
  73924. bool AffineTransform::isSingularity() const throw()
  73925. {
  73926. return (mat00 * mat11 - mat10 * mat01) == 0;
  73927. }
  73928. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73929. const float x10, const float y10,
  73930. const float x01, const float y01) throw()
  73931. {
  73932. return AffineTransform (x10 - x00, x01 - x00, x00,
  73933. y10 - y00, y01 - y00, y00);
  73934. }
  73935. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73936. const float sx2, const float sy2, const float tx2, const float ty2,
  73937. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73938. {
  73939. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73940. .inverted()
  73941. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73942. }
  73943. bool AffineTransform::isOnlyTranslation() const throw()
  73944. {
  73945. return (mat01 == 0)
  73946. && (mat10 == 0)
  73947. && (mat00 == 1.0f)
  73948. && (mat11 == 1.0f);
  73949. }
  73950. float AffineTransform::getScaleFactor() const throw()
  73951. {
  73952. return juce_hypot (mat00 + mat01, mat10 + mat11);
  73953. }
  73954. END_JUCE_NAMESPACE
  73955. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73956. /*** Start of inlined file: juce_Path.cpp ***/
  73957. BEGIN_JUCE_NAMESPACE
  73958. // tests that some co-ords aren't NaNs
  73959. #define CHECK_COORDS_ARE_VALID(x, y) \
  73960. jassert (x == x && y == y);
  73961. namespace PathHelpers
  73962. {
  73963. const float ellipseAngularIncrement = 0.05f;
  73964. const String nextToken (const juce_wchar*& t)
  73965. {
  73966. while (CharacterFunctions::isWhitespace (*t))
  73967. ++t;
  73968. const juce_wchar* const start = t;
  73969. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73970. ++t;
  73971. return String (start, (int) (t - start));
  73972. }
  73973. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  73974. {
  73975. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  73976. }
  73977. }
  73978. const float Path::lineMarker = 100001.0f;
  73979. const float Path::moveMarker = 100002.0f;
  73980. const float Path::quadMarker = 100003.0f;
  73981. const float Path::cubicMarker = 100004.0f;
  73982. const float Path::closeSubPathMarker = 100005.0f;
  73983. Path::Path()
  73984. : numElements (0),
  73985. pathXMin (0),
  73986. pathXMax (0),
  73987. pathYMin (0),
  73988. pathYMax (0),
  73989. useNonZeroWinding (true)
  73990. {
  73991. }
  73992. Path::~Path()
  73993. {
  73994. }
  73995. Path::Path (const Path& other)
  73996. : numElements (other.numElements),
  73997. pathXMin (other.pathXMin),
  73998. pathXMax (other.pathXMax),
  73999. pathYMin (other.pathYMin),
  74000. pathYMax (other.pathYMax),
  74001. useNonZeroWinding (other.useNonZeroWinding)
  74002. {
  74003. if (numElements > 0)
  74004. {
  74005. data.setAllocatedSize ((int) numElements);
  74006. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74007. }
  74008. }
  74009. Path& Path::operator= (const Path& other)
  74010. {
  74011. if (this != &other)
  74012. {
  74013. data.ensureAllocatedSize ((int) other.numElements);
  74014. numElements = other.numElements;
  74015. pathXMin = other.pathXMin;
  74016. pathXMax = other.pathXMax;
  74017. pathYMin = other.pathYMin;
  74018. pathYMax = other.pathYMax;
  74019. useNonZeroWinding = other.useNonZeroWinding;
  74020. if (numElements > 0)
  74021. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74022. }
  74023. return *this;
  74024. }
  74025. bool Path::operator== (const Path& other) const throw()
  74026. {
  74027. return ! operator!= (other);
  74028. }
  74029. bool Path::operator!= (const Path& other) const throw()
  74030. {
  74031. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74032. return true;
  74033. for (size_t i = 0; i < numElements; ++i)
  74034. if (data.elements[i] != other.data.elements[i])
  74035. return true;
  74036. return false;
  74037. }
  74038. void Path::clear() throw()
  74039. {
  74040. numElements = 0;
  74041. pathXMin = 0;
  74042. pathYMin = 0;
  74043. pathYMax = 0;
  74044. pathXMax = 0;
  74045. }
  74046. void Path::swapWithPath (Path& other) throw()
  74047. {
  74048. data.swapWith (other.data);
  74049. swapVariables <size_t> (numElements, other.numElements);
  74050. swapVariables <float> (pathXMin, other.pathXMin);
  74051. swapVariables <float> (pathXMax, other.pathXMax);
  74052. swapVariables <float> (pathYMin, other.pathYMin);
  74053. swapVariables <float> (pathYMax, other.pathYMax);
  74054. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74055. }
  74056. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74057. {
  74058. useNonZeroWinding = isNonZero;
  74059. }
  74060. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74061. const bool preserveProportions) throw()
  74062. {
  74063. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74064. }
  74065. bool Path::isEmpty() const throw()
  74066. {
  74067. size_t i = 0;
  74068. while (i < numElements)
  74069. {
  74070. const float type = data.elements [i++];
  74071. if (type == moveMarker)
  74072. {
  74073. i += 2;
  74074. }
  74075. else if (type == lineMarker
  74076. || type == quadMarker
  74077. || type == cubicMarker)
  74078. {
  74079. return false;
  74080. }
  74081. }
  74082. return true;
  74083. }
  74084. const Rectangle<float> Path::getBounds() const throw()
  74085. {
  74086. return Rectangle<float> (pathXMin, pathYMin,
  74087. pathXMax - pathXMin,
  74088. pathYMax - pathYMin);
  74089. }
  74090. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74091. {
  74092. return getBounds().transformed (transform);
  74093. }
  74094. void Path::startNewSubPath (const float x, const float y)
  74095. {
  74096. CHECK_COORDS_ARE_VALID (x, y);
  74097. if (numElements == 0)
  74098. {
  74099. pathXMin = pathXMax = x;
  74100. pathYMin = pathYMax = y;
  74101. }
  74102. else
  74103. {
  74104. pathXMin = jmin (pathXMin, x);
  74105. pathXMax = jmax (pathXMax, x);
  74106. pathYMin = jmin (pathYMin, y);
  74107. pathYMax = jmax (pathYMax, y);
  74108. }
  74109. data.ensureAllocatedSize ((int) numElements + 3);
  74110. data.elements [numElements++] = moveMarker;
  74111. data.elements [numElements++] = x;
  74112. data.elements [numElements++] = y;
  74113. }
  74114. void Path::startNewSubPath (const Point<float>& start)
  74115. {
  74116. startNewSubPath (start.getX(), start.getY());
  74117. }
  74118. void Path::lineTo (const float x, const float y)
  74119. {
  74120. CHECK_COORDS_ARE_VALID (x, y);
  74121. if (numElements == 0)
  74122. startNewSubPath (0, 0);
  74123. data.ensureAllocatedSize ((int) numElements + 3);
  74124. data.elements [numElements++] = lineMarker;
  74125. data.elements [numElements++] = x;
  74126. data.elements [numElements++] = y;
  74127. pathXMin = jmin (pathXMin, x);
  74128. pathXMax = jmax (pathXMax, x);
  74129. pathYMin = jmin (pathYMin, y);
  74130. pathYMax = jmax (pathYMax, y);
  74131. }
  74132. void Path::lineTo (const Point<float>& end)
  74133. {
  74134. lineTo (end.getX(), end.getY());
  74135. }
  74136. void Path::quadraticTo (const float x1, const float y1,
  74137. const float x2, const float y2)
  74138. {
  74139. CHECK_COORDS_ARE_VALID (x1, y1);
  74140. CHECK_COORDS_ARE_VALID (x2, y2);
  74141. if (numElements == 0)
  74142. startNewSubPath (0, 0);
  74143. data.ensureAllocatedSize ((int) numElements + 5);
  74144. data.elements [numElements++] = quadMarker;
  74145. data.elements [numElements++] = x1;
  74146. data.elements [numElements++] = y1;
  74147. data.elements [numElements++] = x2;
  74148. data.elements [numElements++] = y2;
  74149. pathXMin = jmin (pathXMin, x1, x2);
  74150. pathXMax = jmax (pathXMax, x1, x2);
  74151. pathYMin = jmin (pathYMin, y1, y2);
  74152. pathYMax = jmax (pathYMax, y1, y2);
  74153. }
  74154. void Path::quadraticTo (const Point<float>& controlPoint,
  74155. const Point<float>& endPoint)
  74156. {
  74157. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74158. endPoint.getX(), endPoint.getY());
  74159. }
  74160. void Path::cubicTo (const float x1, const float y1,
  74161. const float x2, const float y2,
  74162. const float x3, const float y3)
  74163. {
  74164. CHECK_COORDS_ARE_VALID (x1, y1);
  74165. CHECK_COORDS_ARE_VALID (x2, y2);
  74166. CHECK_COORDS_ARE_VALID (x3, y3);
  74167. if (numElements == 0)
  74168. startNewSubPath (0, 0);
  74169. data.ensureAllocatedSize ((int) numElements + 7);
  74170. data.elements [numElements++] = cubicMarker;
  74171. data.elements [numElements++] = x1;
  74172. data.elements [numElements++] = y1;
  74173. data.elements [numElements++] = x2;
  74174. data.elements [numElements++] = y2;
  74175. data.elements [numElements++] = x3;
  74176. data.elements [numElements++] = y3;
  74177. pathXMin = jmin (pathXMin, x1, x2, x3);
  74178. pathXMax = jmax (pathXMax, x1, x2, x3);
  74179. pathYMin = jmin (pathYMin, y1, y2, y3);
  74180. pathYMax = jmax (pathYMax, y1, y2, y3);
  74181. }
  74182. void Path::cubicTo (const Point<float>& controlPoint1,
  74183. const Point<float>& controlPoint2,
  74184. const Point<float>& endPoint)
  74185. {
  74186. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74187. controlPoint2.getX(), controlPoint2.getY(),
  74188. endPoint.getX(), endPoint.getY());
  74189. }
  74190. void Path::closeSubPath()
  74191. {
  74192. if (numElements > 0
  74193. && data.elements [numElements - 1] != closeSubPathMarker)
  74194. {
  74195. data.ensureAllocatedSize ((int) numElements + 1);
  74196. data.elements [numElements++] = closeSubPathMarker;
  74197. }
  74198. }
  74199. const Point<float> Path::getCurrentPosition() const
  74200. {
  74201. int i = (int) numElements - 1;
  74202. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74203. {
  74204. while (i >= 0)
  74205. {
  74206. if (data.elements[i] == moveMarker)
  74207. {
  74208. i += 2;
  74209. break;
  74210. }
  74211. --i;
  74212. }
  74213. }
  74214. if (i > 0)
  74215. return Point<float> (data.elements [i - 1], data.elements [i]);
  74216. return Point<float>();
  74217. }
  74218. void Path::addRectangle (const float x, const float y,
  74219. const float w, const float h)
  74220. {
  74221. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74222. if (w < 0)
  74223. swapVariables (x1, x2);
  74224. if (h < 0)
  74225. swapVariables (y1, y2);
  74226. data.ensureAllocatedSize ((int) numElements + 13);
  74227. if (numElements == 0)
  74228. {
  74229. pathXMin = x1;
  74230. pathXMax = x2;
  74231. pathYMin = y1;
  74232. pathYMax = y2;
  74233. }
  74234. else
  74235. {
  74236. pathXMin = jmin (pathXMin, x1);
  74237. pathXMax = jmax (pathXMax, x2);
  74238. pathYMin = jmin (pathYMin, y1);
  74239. pathYMax = jmax (pathYMax, y2);
  74240. }
  74241. data.elements [numElements++] = moveMarker;
  74242. data.elements [numElements++] = x1;
  74243. data.elements [numElements++] = y2;
  74244. data.elements [numElements++] = lineMarker;
  74245. data.elements [numElements++] = x1;
  74246. data.elements [numElements++] = y1;
  74247. data.elements [numElements++] = lineMarker;
  74248. data.elements [numElements++] = x2;
  74249. data.elements [numElements++] = y1;
  74250. data.elements [numElements++] = lineMarker;
  74251. data.elements [numElements++] = x2;
  74252. data.elements [numElements++] = y2;
  74253. data.elements [numElements++] = closeSubPathMarker;
  74254. }
  74255. void Path::addRoundedRectangle (const float x, const float y,
  74256. const float w, const float h,
  74257. float csx,
  74258. float csy)
  74259. {
  74260. csx = jmin (csx, w * 0.5f);
  74261. csy = jmin (csy, h * 0.5f);
  74262. const float cs45x = csx * 0.45f;
  74263. const float cs45y = csy * 0.45f;
  74264. const float x2 = x + w;
  74265. const float y2 = y + h;
  74266. startNewSubPath (x + csx, y);
  74267. lineTo (x2 - csx, y);
  74268. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74269. lineTo (x2, y2 - csy);
  74270. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74271. lineTo (x + csx, y2);
  74272. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74273. lineTo (x, y + csy);
  74274. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74275. closeSubPath();
  74276. }
  74277. void Path::addRoundedRectangle (const float x, const float y,
  74278. const float w, const float h,
  74279. float cs)
  74280. {
  74281. addRoundedRectangle (x, y, w, h, cs, cs);
  74282. }
  74283. void Path::addTriangle (const float x1, const float y1,
  74284. const float x2, const float y2,
  74285. const float x3, const float y3)
  74286. {
  74287. startNewSubPath (x1, y1);
  74288. lineTo (x2, y2);
  74289. lineTo (x3, y3);
  74290. closeSubPath();
  74291. }
  74292. void Path::addQuadrilateral (const float x1, const float y1,
  74293. const float x2, const float y2,
  74294. const float x3, const float y3,
  74295. const float x4, const float y4)
  74296. {
  74297. startNewSubPath (x1, y1);
  74298. lineTo (x2, y2);
  74299. lineTo (x3, y3);
  74300. lineTo (x4, y4);
  74301. closeSubPath();
  74302. }
  74303. void Path::addEllipse (const float x, const float y,
  74304. const float w, const float h)
  74305. {
  74306. const float hw = w * 0.5f;
  74307. const float hw55 = hw * 0.55f;
  74308. const float hh = h * 0.5f;
  74309. const float hh55 = hh * 0.55f;
  74310. const float cx = x + hw;
  74311. const float cy = y + hh;
  74312. startNewSubPath (cx, cy - hh);
  74313. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74314. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74315. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74316. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74317. closeSubPath();
  74318. }
  74319. void Path::addArc (const float x, const float y,
  74320. const float w, const float h,
  74321. const float fromRadians,
  74322. const float toRadians,
  74323. const bool startAsNewSubPath)
  74324. {
  74325. const float radiusX = w / 2.0f;
  74326. const float radiusY = h / 2.0f;
  74327. addCentredArc (x + radiusX,
  74328. y + radiusY,
  74329. radiusX, radiusY,
  74330. 0.0f,
  74331. fromRadians, toRadians,
  74332. startAsNewSubPath);
  74333. }
  74334. void Path::addCentredArc (const float centreX, const float centreY,
  74335. const float radiusX, const float radiusY,
  74336. const float rotationOfEllipse,
  74337. const float fromRadians,
  74338. const float toRadians,
  74339. const bool startAsNewSubPath)
  74340. {
  74341. if (radiusX > 0.0f && radiusY > 0.0f)
  74342. {
  74343. const Point<float> centre (centreX, centreY);
  74344. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74345. float angle = fromRadians;
  74346. if (startAsNewSubPath)
  74347. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74348. if (fromRadians < toRadians)
  74349. {
  74350. if (startAsNewSubPath)
  74351. angle += PathHelpers::ellipseAngularIncrement;
  74352. while (angle < toRadians)
  74353. {
  74354. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74355. angle += PathHelpers::ellipseAngularIncrement;
  74356. }
  74357. }
  74358. else
  74359. {
  74360. if (startAsNewSubPath)
  74361. angle -= PathHelpers::ellipseAngularIncrement;
  74362. while (angle > toRadians)
  74363. {
  74364. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74365. angle -= PathHelpers::ellipseAngularIncrement;
  74366. }
  74367. }
  74368. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74369. }
  74370. }
  74371. void Path::addPieSegment (const float x, const float y,
  74372. const float width, const float height,
  74373. const float fromRadians,
  74374. const float toRadians,
  74375. const float innerCircleProportionalSize)
  74376. {
  74377. float radiusX = width * 0.5f;
  74378. float radiusY = height * 0.5f;
  74379. const Point<float> centre (x + radiusX, y + radiusY);
  74380. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74381. addArc (x, y, width, height, fromRadians, toRadians);
  74382. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74383. {
  74384. closeSubPath();
  74385. if (innerCircleProportionalSize > 0)
  74386. {
  74387. radiusX *= innerCircleProportionalSize;
  74388. radiusY *= innerCircleProportionalSize;
  74389. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74390. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74391. }
  74392. }
  74393. else
  74394. {
  74395. if (innerCircleProportionalSize > 0)
  74396. {
  74397. radiusX *= innerCircleProportionalSize;
  74398. radiusY *= innerCircleProportionalSize;
  74399. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74400. }
  74401. else
  74402. {
  74403. lineTo (centre);
  74404. }
  74405. }
  74406. closeSubPath();
  74407. }
  74408. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74409. {
  74410. const Line<float> reversed (line.reversed());
  74411. lineThickness *= 0.5f;
  74412. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74413. lineTo (line.getPointAlongLine (0, -lineThickness));
  74414. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74415. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74416. closeSubPath();
  74417. }
  74418. void Path::addArrow (const Line<float>& line, float lineThickness,
  74419. float arrowheadWidth, float arrowheadLength)
  74420. {
  74421. const Line<float> reversed (line.reversed());
  74422. lineThickness *= 0.5f;
  74423. arrowheadWidth *= 0.5f;
  74424. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74425. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74426. lineTo (line.getPointAlongLine (0, -lineThickness));
  74427. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74428. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74429. lineTo (line.getEnd());
  74430. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74431. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74432. closeSubPath();
  74433. }
  74434. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74435. const float radius, const float startAngle)
  74436. {
  74437. jassert (numberOfSides > 1); // this would be silly.
  74438. if (numberOfSides > 1)
  74439. {
  74440. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74441. for (int i = 0; i < numberOfSides; ++i)
  74442. {
  74443. const float angle = startAngle + i * angleBetweenPoints;
  74444. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74445. if (i == 0)
  74446. startNewSubPath (p);
  74447. else
  74448. lineTo (p);
  74449. }
  74450. closeSubPath();
  74451. }
  74452. }
  74453. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74454. const float innerRadius, const float outerRadius, const float startAngle)
  74455. {
  74456. jassert (numberOfPoints > 1); // this would be silly.
  74457. if (numberOfPoints > 1)
  74458. {
  74459. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74460. for (int i = 0; i < numberOfPoints; ++i)
  74461. {
  74462. const float angle = startAngle + i * angleBetweenPoints;
  74463. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74464. if (i == 0)
  74465. startNewSubPath (p);
  74466. else
  74467. lineTo (p);
  74468. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74469. }
  74470. closeSubPath();
  74471. }
  74472. }
  74473. void Path::addBubble (float x, float y,
  74474. float w, float h,
  74475. float cs,
  74476. float tipX,
  74477. float tipY,
  74478. int whichSide,
  74479. float arrowPos,
  74480. float arrowWidth)
  74481. {
  74482. if (w > 1.0f && h > 1.0f)
  74483. {
  74484. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74485. const float cs2 = 2.0f * cs;
  74486. startNewSubPath (x + cs, y);
  74487. if (whichSide == 0)
  74488. {
  74489. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74490. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74491. lineTo (arrowX1, y);
  74492. lineTo (tipX, tipY);
  74493. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74494. }
  74495. lineTo (x + w - cs, y);
  74496. if (cs > 0.0f)
  74497. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74498. if (whichSide == 3)
  74499. {
  74500. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74501. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74502. lineTo (x + w, arrowY1);
  74503. lineTo (tipX, tipY);
  74504. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74505. }
  74506. lineTo (x + w, y + h - cs);
  74507. if (cs > 0.0f)
  74508. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74509. if (whichSide == 2)
  74510. {
  74511. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74512. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74513. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74514. lineTo (tipX, tipY);
  74515. lineTo (arrowX1, y + h);
  74516. }
  74517. lineTo (x + cs, y + h);
  74518. if (cs > 0.0f)
  74519. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74520. if (whichSide == 1)
  74521. {
  74522. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74523. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74524. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74525. lineTo (tipX, tipY);
  74526. lineTo (x, arrowY1);
  74527. }
  74528. lineTo (x, y + cs);
  74529. if (cs > 0.0f)
  74530. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74531. closeSubPath();
  74532. }
  74533. }
  74534. void Path::addPath (const Path& other)
  74535. {
  74536. size_t i = 0;
  74537. while (i < other.numElements)
  74538. {
  74539. const float type = other.data.elements [i++];
  74540. if (type == moveMarker)
  74541. {
  74542. startNewSubPath (other.data.elements [i],
  74543. other.data.elements [i + 1]);
  74544. i += 2;
  74545. }
  74546. else if (type == lineMarker)
  74547. {
  74548. lineTo (other.data.elements [i],
  74549. other.data.elements [i + 1]);
  74550. i += 2;
  74551. }
  74552. else if (type == quadMarker)
  74553. {
  74554. quadraticTo (other.data.elements [i],
  74555. other.data.elements [i + 1],
  74556. other.data.elements [i + 2],
  74557. other.data.elements [i + 3]);
  74558. i += 4;
  74559. }
  74560. else if (type == cubicMarker)
  74561. {
  74562. cubicTo (other.data.elements [i],
  74563. other.data.elements [i + 1],
  74564. other.data.elements [i + 2],
  74565. other.data.elements [i + 3],
  74566. other.data.elements [i + 4],
  74567. other.data.elements [i + 5]);
  74568. i += 6;
  74569. }
  74570. else if (type == closeSubPathMarker)
  74571. {
  74572. closeSubPath();
  74573. }
  74574. else
  74575. {
  74576. // something's gone wrong with the element list!
  74577. jassertfalse;
  74578. }
  74579. }
  74580. }
  74581. void Path::addPath (const Path& other,
  74582. const AffineTransform& transformToApply)
  74583. {
  74584. size_t i = 0;
  74585. while (i < other.numElements)
  74586. {
  74587. const float type = other.data.elements [i++];
  74588. if (type == closeSubPathMarker)
  74589. {
  74590. closeSubPath();
  74591. }
  74592. else
  74593. {
  74594. float x = other.data.elements [i++];
  74595. float y = other.data.elements [i++];
  74596. transformToApply.transformPoint (x, y);
  74597. if (type == moveMarker)
  74598. {
  74599. startNewSubPath (x, y);
  74600. }
  74601. else if (type == lineMarker)
  74602. {
  74603. lineTo (x, y);
  74604. }
  74605. else if (type == quadMarker)
  74606. {
  74607. float x2 = other.data.elements [i++];
  74608. float y2 = other.data.elements [i++];
  74609. transformToApply.transformPoint (x2, y2);
  74610. quadraticTo (x, y, x2, y2);
  74611. }
  74612. else if (type == cubicMarker)
  74613. {
  74614. float x2 = other.data.elements [i++];
  74615. float y2 = other.data.elements [i++];
  74616. float x3 = other.data.elements [i++];
  74617. float y3 = other.data.elements [i++];
  74618. transformToApply.transformPoints (x2, y2, x3, y3);
  74619. cubicTo (x, y, x2, y2, x3, y3);
  74620. }
  74621. else
  74622. {
  74623. // something's gone wrong with the element list!
  74624. jassertfalse;
  74625. }
  74626. }
  74627. }
  74628. }
  74629. void Path::applyTransform (const AffineTransform& transform) throw()
  74630. {
  74631. size_t i = 0;
  74632. pathYMin = pathXMin = 0;
  74633. pathYMax = pathXMax = 0;
  74634. bool setMaxMin = false;
  74635. while (i < numElements)
  74636. {
  74637. const float type = data.elements [i++];
  74638. if (type == moveMarker)
  74639. {
  74640. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74641. if (setMaxMin)
  74642. {
  74643. pathXMin = jmin (pathXMin, data.elements [i]);
  74644. pathXMax = jmax (pathXMax, data.elements [i]);
  74645. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74646. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74647. }
  74648. else
  74649. {
  74650. pathXMin = pathXMax = data.elements [i];
  74651. pathYMin = pathYMax = data.elements [i + 1];
  74652. setMaxMin = true;
  74653. }
  74654. i += 2;
  74655. }
  74656. else if (type == lineMarker)
  74657. {
  74658. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74659. pathXMin = jmin (pathXMin, data.elements [i]);
  74660. pathXMax = jmax (pathXMax, data.elements [i]);
  74661. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74662. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74663. i += 2;
  74664. }
  74665. else if (type == quadMarker)
  74666. {
  74667. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74668. data.elements [i + 2], data.elements [i + 3]);
  74669. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74670. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74671. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74672. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74673. i += 4;
  74674. }
  74675. else if (type == cubicMarker)
  74676. {
  74677. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74678. data.elements [i + 2], data.elements [i + 3],
  74679. data.elements [i + 4], data.elements [i + 5]);
  74680. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74681. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74682. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74683. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74684. i += 6;
  74685. }
  74686. }
  74687. }
  74688. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74689. const float w, const float h,
  74690. const bool preserveProportions,
  74691. const Justification& justification) const
  74692. {
  74693. Rectangle<float> bounds (getBounds());
  74694. if (preserveProportions)
  74695. {
  74696. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74697. return AffineTransform::identity;
  74698. float newW, newH;
  74699. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74700. if (srcRatio > h / w)
  74701. {
  74702. newW = h / srcRatio;
  74703. newH = h;
  74704. }
  74705. else
  74706. {
  74707. newW = w;
  74708. newH = w * srcRatio;
  74709. }
  74710. float newXCentre = x;
  74711. float newYCentre = y;
  74712. if (justification.testFlags (Justification::left))
  74713. newXCentre += newW * 0.5f;
  74714. else if (justification.testFlags (Justification::right))
  74715. newXCentre += w - newW * 0.5f;
  74716. else
  74717. newXCentre += w * 0.5f;
  74718. if (justification.testFlags (Justification::top))
  74719. newYCentre += newH * 0.5f;
  74720. else if (justification.testFlags (Justification::bottom))
  74721. newYCentre += h - newH * 0.5f;
  74722. else
  74723. newYCentre += h * 0.5f;
  74724. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74725. bounds.getHeight() * -0.5f - bounds.getY())
  74726. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74727. .translated (newXCentre, newYCentre);
  74728. }
  74729. else
  74730. {
  74731. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74732. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74733. .translated (x, y);
  74734. }
  74735. }
  74736. bool Path::contains (const float x, const float y, const float tolerance) const
  74737. {
  74738. if (x <= pathXMin || x >= pathXMax
  74739. || y <= pathYMin || y >= pathYMax)
  74740. return false;
  74741. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74742. int positiveCrossings = 0;
  74743. int negativeCrossings = 0;
  74744. while (i.next())
  74745. {
  74746. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74747. {
  74748. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74749. if (intersectX <= x)
  74750. {
  74751. if (i.y1 < i.y2)
  74752. ++positiveCrossings;
  74753. else
  74754. ++negativeCrossings;
  74755. }
  74756. }
  74757. }
  74758. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74759. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74760. }
  74761. bool Path::contains (const Point<float>& point, const float tolerance) const
  74762. {
  74763. return contains (point.getX(), point.getY(), tolerance);
  74764. }
  74765. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74766. {
  74767. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74768. Point<float> intersection;
  74769. while (i.next())
  74770. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74771. return true;
  74772. return false;
  74773. }
  74774. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74775. {
  74776. Line<float> result (line);
  74777. const bool startInside = contains (line.getStart());
  74778. const bool endInside = contains (line.getEnd());
  74779. if (startInside == endInside)
  74780. {
  74781. if (keepSectionOutsidePath == startInside)
  74782. result = Line<float>();
  74783. }
  74784. else
  74785. {
  74786. PathFlatteningIterator i (*this, AffineTransform::identity);
  74787. Point<float> intersection;
  74788. while (i.next())
  74789. {
  74790. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74791. {
  74792. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74793. result.setStart (intersection);
  74794. else
  74795. result.setEnd (intersection);
  74796. }
  74797. }
  74798. }
  74799. return result;
  74800. }
  74801. float Path::getLength (const AffineTransform& transform) const
  74802. {
  74803. float length = 0;
  74804. PathFlatteningIterator i (*this, transform);
  74805. while (i.next())
  74806. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74807. return length;
  74808. }
  74809. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74810. {
  74811. PathFlatteningIterator i (*this, transform);
  74812. while (i.next())
  74813. {
  74814. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74815. const float lineLength = line.getLength();
  74816. if (distanceFromStart <= lineLength)
  74817. return line.getPointAlongLine (distanceFromStart);
  74818. distanceFromStart -= lineLength;
  74819. }
  74820. return Point<float> (i.x2, i.y2);
  74821. }
  74822. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74823. const AffineTransform& transform) const
  74824. {
  74825. PathFlatteningIterator i (*this, transform);
  74826. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74827. float length = 0;
  74828. Point<float> pointOnLine;
  74829. while (i.next())
  74830. {
  74831. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74832. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74833. if (distance < bestDistance)
  74834. {
  74835. bestDistance = distance;
  74836. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74837. pointOnPath = pointOnLine;
  74838. }
  74839. length += line.getLength();
  74840. }
  74841. return bestPosition;
  74842. }
  74843. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74844. {
  74845. if (cornerRadius <= 0.01f)
  74846. return *this;
  74847. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74848. size_t n = 0;
  74849. bool lastWasLine = false, firstWasLine = false;
  74850. Path p;
  74851. while (n < numElements)
  74852. {
  74853. const float type = data.elements [n++];
  74854. if (type == moveMarker)
  74855. {
  74856. indexOfPathStart = p.numElements;
  74857. indexOfPathStartThis = n - 1;
  74858. const float x = data.elements [n++];
  74859. const float y = data.elements [n++];
  74860. p.startNewSubPath (x, y);
  74861. lastWasLine = false;
  74862. firstWasLine = (data.elements [n] == lineMarker);
  74863. }
  74864. else if (type == lineMarker || type == closeSubPathMarker)
  74865. {
  74866. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74867. if (type == lineMarker)
  74868. {
  74869. endX = data.elements [n++];
  74870. endY = data.elements [n++];
  74871. if (n > 8)
  74872. {
  74873. startX = data.elements [n - 8];
  74874. startY = data.elements [n - 7];
  74875. joinX = data.elements [n - 5];
  74876. joinY = data.elements [n - 4];
  74877. }
  74878. }
  74879. else
  74880. {
  74881. endX = data.elements [indexOfPathStartThis + 1];
  74882. endY = data.elements [indexOfPathStartThis + 2];
  74883. if (n > 6)
  74884. {
  74885. startX = data.elements [n - 6];
  74886. startY = data.elements [n - 5];
  74887. joinX = data.elements [n - 3];
  74888. joinY = data.elements [n - 2];
  74889. }
  74890. }
  74891. if (lastWasLine)
  74892. {
  74893. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74894. if (len1 > 0)
  74895. {
  74896. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74897. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74898. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74899. }
  74900. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74901. if (len2 > 0)
  74902. {
  74903. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74904. p.quadraticTo (joinX, joinY,
  74905. (float) (joinX + (endX - joinX) * propNeeded),
  74906. (float) (joinY + (endY - joinY) * propNeeded));
  74907. }
  74908. p.lineTo (endX, endY);
  74909. }
  74910. else if (type == lineMarker)
  74911. {
  74912. p.lineTo (endX, endY);
  74913. lastWasLine = true;
  74914. }
  74915. if (type == closeSubPathMarker)
  74916. {
  74917. if (firstWasLine)
  74918. {
  74919. startX = data.elements [n - 3];
  74920. startY = data.elements [n - 2];
  74921. joinX = endX;
  74922. joinY = endY;
  74923. endX = data.elements [indexOfPathStartThis + 4];
  74924. endY = data.elements [indexOfPathStartThis + 5];
  74925. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74926. if (len1 > 0)
  74927. {
  74928. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74929. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74930. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74931. }
  74932. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74933. if (len2 > 0)
  74934. {
  74935. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74936. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74937. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74938. p.quadraticTo (joinX, joinY, endX, endY);
  74939. p.data.elements [indexOfPathStart + 1] = endX;
  74940. p.data.elements [indexOfPathStart + 2] = endY;
  74941. }
  74942. }
  74943. p.closeSubPath();
  74944. }
  74945. }
  74946. else if (type == quadMarker)
  74947. {
  74948. lastWasLine = false;
  74949. const float x1 = data.elements [n++];
  74950. const float y1 = data.elements [n++];
  74951. const float x2 = data.elements [n++];
  74952. const float y2 = data.elements [n++];
  74953. p.quadraticTo (x1, y1, x2, y2);
  74954. }
  74955. else if (type == cubicMarker)
  74956. {
  74957. lastWasLine = false;
  74958. const float x1 = data.elements [n++];
  74959. const float y1 = data.elements [n++];
  74960. const float x2 = data.elements [n++];
  74961. const float y2 = data.elements [n++];
  74962. const float x3 = data.elements [n++];
  74963. const float y3 = data.elements [n++];
  74964. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74965. }
  74966. }
  74967. return p;
  74968. }
  74969. void Path::loadPathFromStream (InputStream& source)
  74970. {
  74971. while (! source.isExhausted())
  74972. {
  74973. switch (source.readByte())
  74974. {
  74975. case 'm':
  74976. {
  74977. const float x = source.readFloat();
  74978. const float y = source.readFloat();
  74979. startNewSubPath (x, y);
  74980. break;
  74981. }
  74982. case 'l':
  74983. {
  74984. const float x = source.readFloat();
  74985. const float y = source.readFloat();
  74986. lineTo (x, y);
  74987. break;
  74988. }
  74989. case 'q':
  74990. {
  74991. const float x1 = source.readFloat();
  74992. const float y1 = source.readFloat();
  74993. const float x2 = source.readFloat();
  74994. const float y2 = source.readFloat();
  74995. quadraticTo (x1, y1, x2, y2);
  74996. break;
  74997. }
  74998. case 'b':
  74999. {
  75000. const float x1 = source.readFloat();
  75001. const float y1 = source.readFloat();
  75002. const float x2 = source.readFloat();
  75003. const float y2 = source.readFloat();
  75004. const float x3 = source.readFloat();
  75005. const float y3 = source.readFloat();
  75006. cubicTo (x1, y1, x2, y2, x3, y3);
  75007. break;
  75008. }
  75009. case 'c':
  75010. closeSubPath();
  75011. break;
  75012. case 'n':
  75013. useNonZeroWinding = true;
  75014. break;
  75015. case 'z':
  75016. useNonZeroWinding = false;
  75017. break;
  75018. case 'e':
  75019. return; // end of path marker
  75020. default:
  75021. jassertfalse; // illegal char in the stream
  75022. break;
  75023. }
  75024. }
  75025. }
  75026. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75027. {
  75028. MemoryInputStream in (pathData, numberOfBytes, false);
  75029. loadPathFromStream (in);
  75030. }
  75031. void Path::writePathToStream (OutputStream& dest) const
  75032. {
  75033. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75034. size_t i = 0;
  75035. while (i < numElements)
  75036. {
  75037. const float type = data.elements [i++];
  75038. if (type == moveMarker)
  75039. {
  75040. dest.writeByte ('m');
  75041. dest.writeFloat (data.elements [i++]);
  75042. dest.writeFloat (data.elements [i++]);
  75043. }
  75044. else if (type == lineMarker)
  75045. {
  75046. dest.writeByte ('l');
  75047. dest.writeFloat (data.elements [i++]);
  75048. dest.writeFloat (data.elements [i++]);
  75049. }
  75050. else if (type == quadMarker)
  75051. {
  75052. dest.writeByte ('q');
  75053. dest.writeFloat (data.elements [i++]);
  75054. dest.writeFloat (data.elements [i++]);
  75055. dest.writeFloat (data.elements [i++]);
  75056. dest.writeFloat (data.elements [i++]);
  75057. }
  75058. else if (type == cubicMarker)
  75059. {
  75060. dest.writeByte ('b');
  75061. dest.writeFloat (data.elements [i++]);
  75062. dest.writeFloat (data.elements [i++]);
  75063. dest.writeFloat (data.elements [i++]);
  75064. dest.writeFloat (data.elements [i++]);
  75065. dest.writeFloat (data.elements [i++]);
  75066. dest.writeFloat (data.elements [i++]);
  75067. }
  75068. else if (type == closeSubPathMarker)
  75069. {
  75070. dest.writeByte ('c');
  75071. }
  75072. }
  75073. dest.writeByte ('e'); // marks the end-of-path
  75074. }
  75075. const String Path::toString() const
  75076. {
  75077. MemoryOutputStream s (2048);
  75078. if (! useNonZeroWinding)
  75079. s << 'a';
  75080. size_t i = 0;
  75081. float lastMarker = 0.0f;
  75082. while (i < numElements)
  75083. {
  75084. const float marker = data.elements [i++];
  75085. char markerChar = 0;
  75086. int numCoords = 0;
  75087. if (marker == moveMarker)
  75088. {
  75089. markerChar = 'm';
  75090. numCoords = 2;
  75091. }
  75092. else if (marker == lineMarker)
  75093. {
  75094. markerChar = 'l';
  75095. numCoords = 2;
  75096. }
  75097. else if (marker == quadMarker)
  75098. {
  75099. markerChar = 'q';
  75100. numCoords = 4;
  75101. }
  75102. else if (marker == cubicMarker)
  75103. {
  75104. markerChar = 'c';
  75105. numCoords = 6;
  75106. }
  75107. else
  75108. {
  75109. jassert (marker == closeSubPathMarker);
  75110. markerChar = 'z';
  75111. }
  75112. if (marker != lastMarker)
  75113. {
  75114. if (s.getDataSize() != 0)
  75115. s << ' ';
  75116. s << markerChar;
  75117. lastMarker = marker;
  75118. }
  75119. while (--numCoords >= 0 && i < numElements)
  75120. {
  75121. String coord (data.elements [i++], 3);
  75122. while (coord.endsWithChar ('0') && coord != "0")
  75123. coord = coord.dropLastCharacters (1);
  75124. if (coord.endsWithChar ('.'))
  75125. coord = coord.dropLastCharacters (1);
  75126. if (s.getDataSize() != 0)
  75127. s << ' ';
  75128. s << coord;
  75129. }
  75130. }
  75131. return s.toUTF8();
  75132. }
  75133. void Path::restoreFromString (const String& stringVersion)
  75134. {
  75135. clear();
  75136. setUsingNonZeroWinding (true);
  75137. const juce_wchar* t = stringVersion;
  75138. juce_wchar marker = 'm';
  75139. int numValues = 2;
  75140. float values [6];
  75141. for (;;)
  75142. {
  75143. const String token (PathHelpers::nextToken (t));
  75144. const juce_wchar firstChar = token[0];
  75145. int startNum = 0;
  75146. if (firstChar == 0)
  75147. break;
  75148. if (firstChar == 'm' || firstChar == 'l')
  75149. {
  75150. marker = firstChar;
  75151. numValues = 2;
  75152. }
  75153. else if (firstChar == 'q')
  75154. {
  75155. marker = firstChar;
  75156. numValues = 4;
  75157. }
  75158. else if (firstChar == 'c')
  75159. {
  75160. marker = firstChar;
  75161. numValues = 6;
  75162. }
  75163. else if (firstChar == 'z')
  75164. {
  75165. marker = firstChar;
  75166. numValues = 0;
  75167. }
  75168. else if (firstChar == 'a')
  75169. {
  75170. setUsingNonZeroWinding (false);
  75171. continue;
  75172. }
  75173. else
  75174. {
  75175. ++startNum;
  75176. values [0] = token.getFloatValue();
  75177. }
  75178. for (int i = startNum; i < numValues; ++i)
  75179. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75180. switch (marker)
  75181. {
  75182. case 'm': startNewSubPath (values[0], values[1]); break;
  75183. case 'l': lineTo (values[0], values[1]); break;
  75184. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75185. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75186. case 'z': closeSubPath(); break;
  75187. default: jassertfalse; break; // illegal string format?
  75188. }
  75189. }
  75190. }
  75191. Path::Iterator::Iterator (const Path& path_)
  75192. : path (path_),
  75193. index (0)
  75194. {
  75195. }
  75196. Path::Iterator::~Iterator()
  75197. {
  75198. }
  75199. bool Path::Iterator::next()
  75200. {
  75201. const float* const elements = path.data.elements;
  75202. if (index < path.numElements)
  75203. {
  75204. const float type = elements [index++];
  75205. if (type == moveMarker)
  75206. {
  75207. elementType = startNewSubPath;
  75208. x1 = elements [index++];
  75209. y1 = elements [index++];
  75210. }
  75211. else if (type == lineMarker)
  75212. {
  75213. elementType = lineTo;
  75214. x1 = elements [index++];
  75215. y1 = elements [index++];
  75216. }
  75217. else if (type == quadMarker)
  75218. {
  75219. elementType = quadraticTo;
  75220. x1 = elements [index++];
  75221. y1 = elements [index++];
  75222. x2 = elements [index++];
  75223. y2 = elements [index++];
  75224. }
  75225. else if (type == cubicMarker)
  75226. {
  75227. elementType = cubicTo;
  75228. x1 = elements [index++];
  75229. y1 = elements [index++];
  75230. x2 = elements [index++];
  75231. y2 = elements [index++];
  75232. x3 = elements [index++];
  75233. y3 = elements [index++];
  75234. }
  75235. else if (type == closeSubPathMarker)
  75236. {
  75237. elementType = closePath;
  75238. }
  75239. return true;
  75240. }
  75241. return false;
  75242. }
  75243. END_JUCE_NAMESPACE
  75244. /*** End of inlined file: juce_Path.cpp ***/
  75245. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75246. BEGIN_JUCE_NAMESPACE
  75247. #if JUCE_MSVC && JUCE_DEBUG
  75248. #pragma optimize ("t", on)
  75249. #endif
  75250. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75251. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75252. const AffineTransform& transform_,
  75253. const float tolerance)
  75254. : x2 (0),
  75255. y2 (0),
  75256. closesSubPath (false),
  75257. subPathIndex (-1),
  75258. path (path_),
  75259. transform (transform_),
  75260. points (path_.data.elements),
  75261. toleranceSquared (tolerance * tolerance),
  75262. subPathCloseX (0),
  75263. subPathCloseY (0),
  75264. isIdentityTransform (transform_.isIdentity()),
  75265. stackBase (32),
  75266. index (0),
  75267. stackSize (32)
  75268. {
  75269. stackPos = stackBase;
  75270. }
  75271. PathFlatteningIterator::~PathFlatteningIterator()
  75272. {
  75273. }
  75274. bool PathFlatteningIterator::next()
  75275. {
  75276. x1 = x2;
  75277. y1 = y2;
  75278. float x3 = 0;
  75279. float y3 = 0;
  75280. float x4 = 0;
  75281. float y4 = 0;
  75282. float type;
  75283. for (;;)
  75284. {
  75285. if (stackPos == stackBase)
  75286. {
  75287. if (index >= path.numElements)
  75288. {
  75289. return false;
  75290. }
  75291. else
  75292. {
  75293. type = points [index++];
  75294. if (type != Path::closeSubPathMarker)
  75295. {
  75296. x2 = points [index++];
  75297. y2 = points [index++];
  75298. if (type == Path::quadMarker)
  75299. {
  75300. x3 = points [index++];
  75301. y3 = points [index++];
  75302. if (! isIdentityTransform)
  75303. transform.transformPoints (x2, y2, x3, y3);
  75304. }
  75305. else if (type == Path::cubicMarker)
  75306. {
  75307. x3 = points [index++];
  75308. y3 = points [index++];
  75309. x4 = points [index++];
  75310. y4 = points [index++];
  75311. if (! isIdentityTransform)
  75312. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75313. }
  75314. else
  75315. {
  75316. if (! isIdentityTransform)
  75317. transform.transformPoint (x2, y2);
  75318. }
  75319. }
  75320. }
  75321. }
  75322. else
  75323. {
  75324. type = *--stackPos;
  75325. if (type != Path::closeSubPathMarker)
  75326. {
  75327. x2 = *--stackPos;
  75328. y2 = *--stackPos;
  75329. if (type == Path::quadMarker)
  75330. {
  75331. x3 = *--stackPos;
  75332. y3 = *--stackPos;
  75333. }
  75334. else if (type == Path::cubicMarker)
  75335. {
  75336. x3 = *--stackPos;
  75337. y3 = *--stackPos;
  75338. x4 = *--stackPos;
  75339. y4 = *--stackPos;
  75340. }
  75341. }
  75342. }
  75343. if (type == Path::lineMarker)
  75344. {
  75345. ++subPathIndex;
  75346. closesSubPath = (stackPos == stackBase)
  75347. && (index < path.numElements)
  75348. && (points [index] == Path::closeSubPathMarker)
  75349. && x2 == subPathCloseX
  75350. && y2 == subPathCloseY;
  75351. return true;
  75352. }
  75353. else if (type == Path::quadMarker)
  75354. {
  75355. const size_t offset = (size_t) (stackPos - stackBase);
  75356. if (offset >= stackSize - 10)
  75357. {
  75358. stackSize <<= 1;
  75359. stackBase.realloc (stackSize);
  75360. stackPos = stackBase + offset;
  75361. }
  75362. const float m1x = (x1 + x2) * 0.5f;
  75363. const float m1y = (y1 + y2) * 0.5f;
  75364. const float m2x = (x2 + x3) * 0.5f;
  75365. const float m2y = (y2 + y3) * 0.5f;
  75366. const float m3x = (m1x + m2x) * 0.5f;
  75367. const float m3y = (m1y + m2y) * 0.5f;
  75368. const float errorX = m3x - x2;
  75369. const float errorY = m3y - y2;
  75370. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75371. {
  75372. *stackPos++ = y3;
  75373. *stackPos++ = x3;
  75374. *stackPos++ = m2y;
  75375. *stackPos++ = m2x;
  75376. *stackPos++ = Path::quadMarker;
  75377. *stackPos++ = m3y;
  75378. *stackPos++ = m3x;
  75379. *stackPos++ = m1y;
  75380. *stackPos++ = m1x;
  75381. *stackPos++ = Path::quadMarker;
  75382. }
  75383. else
  75384. {
  75385. *stackPos++ = y3;
  75386. *stackPos++ = x3;
  75387. *stackPos++ = Path::lineMarker;
  75388. *stackPos++ = m3y;
  75389. *stackPos++ = m3x;
  75390. *stackPos++ = Path::lineMarker;
  75391. }
  75392. jassert (stackPos < stackBase + stackSize);
  75393. }
  75394. else if (type == Path::cubicMarker)
  75395. {
  75396. const size_t offset = (size_t) (stackPos - stackBase);
  75397. if (offset >= stackSize - 16)
  75398. {
  75399. stackSize <<= 1;
  75400. stackBase.realloc (stackSize);
  75401. stackPos = stackBase + offset;
  75402. }
  75403. const float m1x = (x1 + x2) * 0.5f;
  75404. const float m1y = (y1 + y2) * 0.5f;
  75405. const float m2x = (x3 + x2) * 0.5f;
  75406. const float m2y = (y3 + y2) * 0.5f;
  75407. const float m3x = (x3 + x4) * 0.5f;
  75408. const float m3y = (y3 + y4) * 0.5f;
  75409. const float m4x = (m1x + m2x) * 0.5f;
  75410. const float m4y = (m1y + m2y) * 0.5f;
  75411. const float m5x = (m3x + m2x) * 0.5f;
  75412. const float m5y = (m3y + m2y) * 0.5f;
  75413. const float error1X = m4x - x2;
  75414. const float error1Y = m4y - y2;
  75415. const float error2X = m5x - x3;
  75416. const float error2Y = m5y - y3;
  75417. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75418. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75419. {
  75420. *stackPos++ = y4;
  75421. *stackPos++ = x4;
  75422. *stackPos++ = m3y;
  75423. *stackPos++ = m3x;
  75424. *stackPos++ = m5y;
  75425. *stackPos++ = m5x;
  75426. *stackPos++ = Path::cubicMarker;
  75427. *stackPos++ = (m4y + m5y) * 0.5f;
  75428. *stackPos++ = (m4x + m5x) * 0.5f;
  75429. *stackPos++ = m4y;
  75430. *stackPos++ = m4x;
  75431. *stackPos++ = m1y;
  75432. *stackPos++ = m1x;
  75433. *stackPos++ = Path::cubicMarker;
  75434. }
  75435. else
  75436. {
  75437. *stackPos++ = y4;
  75438. *stackPos++ = x4;
  75439. *stackPos++ = Path::lineMarker;
  75440. *stackPos++ = m5y;
  75441. *stackPos++ = m5x;
  75442. *stackPos++ = Path::lineMarker;
  75443. *stackPos++ = m4y;
  75444. *stackPos++ = m4x;
  75445. *stackPos++ = Path::lineMarker;
  75446. }
  75447. }
  75448. else if (type == Path::closeSubPathMarker)
  75449. {
  75450. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75451. {
  75452. x1 = x2;
  75453. y1 = y2;
  75454. x2 = subPathCloseX;
  75455. y2 = subPathCloseY;
  75456. closesSubPath = true;
  75457. return true;
  75458. }
  75459. }
  75460. else
  75461. {
  75462. jassert (type == Path::moveMarker);
  75463. subPathIndex = -1;
  75464. subPathCloseX = x1 = x2;
  75465. subPathCloseY = y1 = y2;
  75466. }
  75467. }
  75468. }
  75469. #if JUCE_MSVC && JUCE_DEBUG
  75470. #pragma optimize ("", on) // resets optimisations to the project defaults
  75471. #endif
  75472. END_JUCE_NAMESPACE
  75473. /*** End of inlined file: juce_PathIterator.cpp ***/
  75474. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75475. BEGIN_JUCE_NAMESPACE
  75476. PathStrokeType::PathStrokeType (const float strokeThickness,
  75477. const JointStyle jointStyle_,
  75478. const EndCapStyle endStyle_) throw()
  75479. : thickness (strokeThickness),
  75480. jointStyle (jointStyle_),
  75481. endStyle (endStyle_)
  75482. {
  75483. }
  75484. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75485. : thickness (other.thickness),
  75486. jointStyle (other.jointStyle),
  75487. endStyle (other.endStyle)
  75488. {
  75489. }
  75490. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75491. {
  75492. thickness = other.thickness;
  75493. jointStyle = other.jointStyle;
  75494. endStyle = other.endStyle;
  75495. return *this;
  75496. }
  75497. PathStrokeType::~PathStrokeType() throw()
  75498. {
  75499. }
  75500. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75501. {
  75502. return thickness == other.thickness
  75503. && jointStyle == other.jointStyle
  75504. && endStyle == other.endStyle;
  75505. }
  75506. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75507. {
  75508. return ! operator== (other);
  75509. }
  75510. namespace PathStrokeHelpers
  75511. {
  75512. bool lineIntersection (const float x1, const float y1,
  75513. const float x2, const float y2,
  75514. const float x3, const float y3,
  75515. const float x4, const float y4,
  75516. float& intersectionX,
  75517. float& intersectionY,
  75518. float& distanceBeyondLine1EndSquared) throw()
  75519. {
  75520. if (x2 != x3 || y2 != y3)
  75521. {
  75522. const float dx1 = x2 - x1;
  75523. const float dy1 = y2 - y1;
  75524. const float dx2 = x4 - x3;
  75525. const float dy2 = y4 - y3;
  75526. const float divisor = dx1 * dy2 - dx2 * dy1;
  75527. if (divisor == 0)
  75528. {
  75529. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75530. {
  75531. if (dy1 == 0 && dy2 != 0)
  75532. {
  75533. const float along = (y1 - y3) / dy2;
  75534. intersectionX = x3 + along * dx2;
  75535. intersectionY = y1;
  75536. distanceBeyondLine1EndSquared = intersectionX - x2;
  75537. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75538. if ((x2 > x1) == (intersectionX < x2))
  75539. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75540. return along >= 0 && along <= 1.0f;
  75541. }
  75542. else if (dy2 == 0 && dy1 != 0)
  75543. {
  75544. const float along = (y3 - y1) / dy1;
  75545. intersectionX = x1 + along * dx1;
  75546. intersectionY = y3;
  75547. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75548. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75549. if (along < 1.0f)
  75550. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75551. return along >= 0 && along <= 1.0f;
  75552. }
  75553. else if (dx1 == 0 && dx2 != 0)
  75554. {
  75555. const float along = (x1 - x3) / dx2;
  75556. intersectionX = x1;
  75557. intersectionY = y3 + along * dy2;
  75558. distanceBeyondLine1EndSquared = intersectionY - y2;
  75559. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75560. if ((y2 > y1) == (intersectionY < y2))
  75561. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75562. return along >= 0 && along <= 1.0f;
  75563. }
  75564. else if (dx2 == 0 && dx1 != 0)
  75565. {
  75566. const float along = (x3 - x1) / dx1;
  75567. intersectionX = x3;
  75568. intersectionY = y1 + along * dy1;
  75569. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75570. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75571. if (along < 1.0f)
  75572. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75573. return along >= 0 && along <= 1.0f;
  75574. }
  75575. }
  75576. intersectionX = 0.5f * (x2 + x3);
  75577. intersectionY = 0.5f * (y2 + y3);
  75578. distanceBeyondLine1EndSquared = 0.0f;
  75579. return false;
  75580. }
  75581. else
  75582. {
  75583. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75584. intersectionX = x1 + along1 * dx1;
  75585. intersectionY = y1 + along1 * dy1;
  75586. if (along1 >= 0 && along1 <= 1.0f)
  75587. {
  75588. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75589. if (along2 >= 0 && along2 <= divisor)
  75590. {
  75591. distanceBeyondLine1EndSquared = 0.0f;
  75592. return true;
  75593. }
  75594. }
  75595. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75596. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75597. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75598. if (along1 < 1.0f)
  75599. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75600. return false;
  75601. }
  75602. }
  75603. intersectionX = x2;
  75604. intersectionY = y2;
  75605. distanceBeyondLine1EndSquared = 0.0f;
  75606. return true;
  75607. }
  75608. void addEdgeAndJoint (Path& destPath,
  75609. const PathStrokeType::JointStyle style,
  75610. const float maxMiterExtensionSquared, const float width,
  75611. const float x1, const float y1,
  75612. const float x2, const float y2,
  75613. const float x3, const float y3,
  75614. const float x4, const float y4,
  75615. const float midX, const float midY)
  75616. {
  75617. if (style == PathStrokeType::beveled
  75618. || (x3 == x4 && y3 == y4)
  75619. || (x1 == x2 && y1 == y2))
  75620. {
  75621. destPath.lineTo (x2, y2);
  75622. destPath.lineTo (x3, y3);
  75623. }
  75624. else
  75625. {
  75626. float jx, jy, distanceBeyondLine1EndSquared;
  75627. // if they intersect, use this point..
  75628. if (lineIntersection (x1, y1, x2, y2,
  75629. x3, y3, x4, y4,
  75630. jx, jy, distanceBeyondLine1EndSquared))
  75631. {
  75632. destPath.lineTo (jx, jy);
  75633. }
  75634. else
  75635. {
  75636. if (style == PathStrokeType::mitered)
  75637. {
  75638. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75639. && distanceBeyondLine1EndSquared > 0.0f)
  75640. {
  75641. destPath.lineTo (jx, jy);
  75642. }
  75643. else
  75644. {
  75645. // the end sticks out too far, so just use a blunt joint
  75646. destPath.lineTo (x2, y2);
  75647. destPath.lineTo (x3, y3);
  75648. }
  75649. }
  75650. else
  75651. {
  75652. // curved joints
  75653. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75654. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75655. const float angleIncrement = 0.1f;
  75656. destPath.lineTo (x2, y2);
  75657. if (std::abs (angle1 - angle2) > angleIncrement)
  75658. {
  75659. if (angle2 > angle1 + float_Pi
  75660. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75661. {
  75662. if (angle2 > angle1)
  75663. angle2 -= float_Pi * 2.0f;
  75664. jassert (angle1 <= angle2 + float_Pi);
  75665. angle1 -= angleIncrement;
  75666. while (angle1 > angle2)
  75667. {
  75668. destPath.lineTo (midX + width * std::sin (angle1),
  75669. midY + width * std::cos (angle1));
  75670. angle1 -= angleIncrement;
  75671. }
  75672. }
  75673. else
  75674. {
  75675. if (angle1 > angle2)
  75676. angle1 -= float_Pi * 2.0f;
  75677. jassert (angle1 >= angle2 - float_Pi);
  75678. angle1 += angleIncrement;
  75679. while (angle1 < angle2)
  75680. {
  75681. destPath.lineTo (midX + width * std::sin (angle1),
  75682. midY + width * std::cos (angle1));
  75683. angle1 += angleIncrement;
  75684. }
  75685. }
  75686. }
  75687. destPath.lineTo (x3, y3);
  75688. }
  75689. }
  75690. }
  75691. }
  75692. void addLineEnd (Path& destPath,
  75693. const PathStrokeType::EndCapStyle style,
  75694. const float x1, const float y1,
  75695. const float x2, const float y2,
  75696. const float width)
  75697. {
  75698. if (style == PathStrokeType::butt)
  75699. {
  75700. destPath.lineTo (x2, y2);
  75701. }
  75702. else
  75703. {
  75704. float offx1, offy1, offx2, offy2;
  75705. float dx = x2 - x1;
  75706. float dy = y2 - y1;
  75707. const float len = juce_hypot (dx, dy);
  75708. if (len == 0)
  75709. {
  75710. offx1 = offx2 = x1;
  75711. offy1 = offy2 = y1;
  75712. }
  75713. else
  75714. {
  75715. const float offset = width / len;
  75716. dx *= offset;
  75717. dy *= offset;
  75718. offx1 = x1 + dy;
  75719. offy1 = y1 - dx;
  75720. offx2 = x2 + dy;
  75721. offy2 = y2 - dx;
  75722. }
  75723. if (style == PathStrokeType::square)
  75724. {
  75725. // sqaure ends
  75726. destPath.lineTo (offx1, offy1);
  75727. destPath.lineTo (offx2, offy2);
  75728. destPath.lineTo (x2, y2);
  75729. }
  75730. else
  75731. {
  75732. // rounded ends
  75733. const float midx = (offx1 + offx2) * 0.5f;
  75734. const float midy = (offy1 + offy2) * 0.5f;
  75735. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75736. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75737. midx, midy);
  75738. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75739. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75740. x2, y2);
  75741. }
  75742. }
  75743. }
  75744. struct Arrowhead
  75745. {
  75746. float startWidth, startLength;
  75747. float endWidth, endLength;
  75748. };
  75749. void addArrowhead (Path& destPath,
  75750. const float x1, const float y1,
  75751. const float x2, const float y2,
  75752. const float tipX, const float tipY,
  75753. const float width,
  75754. const float arrowheadWidth)
  75755. {
  75756. Line<float> line (x1, y1, x2, y2);
  75757. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75758. destPath.lineTo (tipX, tipY);
  75759. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75760. destPath.lineTo (x2, y2);
  75761. }
  75762. struct LineSection
  75763. {
  75764. float x1, y1, x2, y2; // original line
  75765. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75766. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75767. };
  75768. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75769. {
  75770. while (amountAtEnd > 0 && subPath.size() > 0)
  75771. {
  75772. LineSection& l = subPath.getReference (subPath.size() - 1);
  75773. float dx = l.rx2 - l.rx1;
  75774. float dy = l.ry2 - l.ry1;
  75775. const float len = juce_hypot (dx, dy);
  75776. if (len <= amountAtEnd && subPath.size() > 1)
  75777. {
  75778. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75779. prev.x2 = l.x2;
  75780. prev.y2 = l.y2;
  75781. subPath.removeLast();
  75782. amountAtEnd -= len;
  75783. }
  75784. else
  75785. {
  75786. const float prop = jmin (0.9999f, amountAtEnd / len);
  75787. dx *= prop;
  75788. dy *= prop;
  75789. l.rx1 += dx;
  75790. l.ry1 += dy;
  75791. l.lx2 += dx;
  75792. l.ly2 += dy;
  75793. break;
  75794. }
  75795. }
  75796. while (amountAtStart > 0 && subPath.size() > 0)
  75797. {
  75798. LineSection& l = subPath.getReference (0);
  75799. float dx = l.rx2 - l.rx1;
  75800. float dy = l.ry2 - l.ry1;
  75801. const float len = juce_hypot (dx, dy);
  75802. if (len <= amountAtStart && subPath.size() > 1)
  75803. {
  75804. LineSection& next = subPath.getReference (1);
  75805. next.x1 = l.x1;
  75806. next.y1 = l.y1;
  75807. subPath.remove (0);
  75808. amountAtStart -= len;
  75809. }
  75810. else
  75811. {
  75812. const float prop = jmin (0.9999f, amountAtStart / len);
  75813. dx *= prop;
  75814. dy *= prop;
  75815. l.rx2 -= dx;
  75816. l.ry2 -= dy;
  75817. l.lx1 -= dx;
  75818. l.ly1 -= dy;
  75819. break;
  75820. }
  75821. }
  75822. }
  75823. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75824. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75825. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75826. const Arrowhead* const arrowhead)
  75827. {
  75828. jassert (subPath.size() > 0);
  75829. if (arrowhead != 0)
  75830. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75831. const LineSection& firstLine = subPath.getReference (0);
  75832. float lastX1 = firstLine.lx1;
  75833. float lastY1 = firstLine.ly1;
  75834. float lastX2 = firstLine.lx2;
  75835. float lastY2 = firstLine.ly2;
  75836. if (isClosed)
  75837. {
  75838. destPath.startNewSubPath (lastX1, lastY1);
  75839. }
  75840. else
  75841. {
  75842. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75843. if (arrowhead != 0)
  75844. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75845. width, arrowhead->startWidth);
  75846. else
  75847. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75848. }
  75849. int i;
  75850. for (i = 1; i < subPath.size(); ++i)
  75851. {
  75852. const LineSection& l = subPath.getReference (i);
  75853. addEdgeAndJoint (destPath, jointStyle,
  75854. maxMiterExtensionSquared, width,
  75855. lastX1, lastY1, lastX2, lastY2,
  75856. l.lx1, l.ly1, l.lx2, l.ly2,
  75857. l.x1, l.y1);
  75858. lastX1 = l.lx1;
  75859. lastY1 = l.ly1;
  75860. lastX2 = l.lx2;
  75861. lastY2 = l.ly2;
  75862. }
  75863. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75864. if (isClosed)
  75865. {
  75866. const LineSection& l = subPath.getReference (0);
  75867. addEdgeAndJoint (destPath, jointStyle,
  75868. maxMiterExtensionSquared, width,
  75869. lastX1, lastY1, lastX2, lastY2,
  75870. l.lx1, l.ly1, l.lx2, l.ly2,
  75871. l.x1, l.y1);
  75872. destPath.closeSubPath();
  75873. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75874. }
  75875. else
  75876. {
  75877. destPath.lineTo (lastX2, lastY2);
  75878. if (arrowhead != 0)
  75879. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75880. width, arrowhead->endWidth);
  75881. else
  75882. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75883. }
  75884. lastX1 = lastLine.rx1;
  75885. lastY1 = lastLine.ry1;
  75886. lastX2 = lastLine.rx2;
  75887. lastY2 = lastLine.ry2;
  75888. for (i = subPath.size() - 1; --i >= 0;)
  75889. {
  75890. const LineSection& l = subPath.getReference (i);
  75891. addEdgeAndJoint (destPath, jointStyle,
  75892. maxMiterExtensionSquared, width,
  75893. lastX1, lastY1, lastX2, lastY2,
  75894. l.rx1, l.ry1, l.rx2, l.ry2,
  75895. l.x2, l.y2);
  75896. lastX1 = l.rx1;
  75897. lastY1 = l.ry1;
  75898. lastX2 = l.rx2;
  75899. lastY2 = l.ry2;
  75900. }
  75901. if (isClosed)
  75902. {
  75903. addEdgeAndJoint (destPath, jointStyle,
  75904. maxMiterExtensionSquared, width,
  75905. lastX1, lastY1, lastX2, lastY2,
  75906. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75907. lastLine.x2, lastLine.y2);
  75908. }
  75909. else
  75910. {
  75911. // do the last line
  75912. destPath.lineTo (lastX2, lastY2);
  75913. }
  75914. destPath.closeSubPath();
  75915. }
  75916. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75917. const PathStrokeType::EndCapStyle endStyle,
  75918. Path& destPath, const Path& source,
  75919. const AffineTransform& transform,
  75920. const float extraAccuracy, const Arrowhead* const arrowhead)
  75921. {
  75922. jassert (extraAccuracy > 0);
  75923. if (thickness <= 0)
  75924. {
  75925. destPath.clear();
  75926. return;
  75927. }
  75928. const Path* sourcePath = &source;
  75929. Path temp;
  75930. if (sourcePath == &destPath)
  75931. {
  75932. destPath.swapWithPath (temp);
  75933. sourcePath = &temp;
  75934. }
  75935. else
  75936. {
  75937. destPath.clear();
  75938. }
  75939. destPath.setUsingNonZeroWinding (true);
  75940. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75941. const float width = 0.5f * thickness;
  75942. // Iterate the path, creating a list of the
  75943. // left/right-hand lines along either side of it...
  75944. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  75945. Array <LineSection> subPath;
  75946. subPath.ensureStorageAllocated (512);
  75947. LineSection l;
  75948. l.x1 = 0;
  75949. l.y1 = 0;
  75950. const float minSegmentLength = 0.0001f;
  75951. while (it.next())
  75952. {
  75953. if (it.subPathIndex == 0)
  75954. {
  75955. if (subPath.size() > 0)
  75956. {
  75957. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75958. subPath.clearQuick();
  75959. }
  75960. l.x1 = it.x1;
  75961. l.y1 = it.y1;
  75962. }
  75963. l.x2 = it.x2;
  75964. l.y2 = it.y2;
  75965. float dx = l.x2 - l.x1;
  75966. float dy = l.y2 - l.y1;
  75967. const float hypotSquared = dx*dx + dy*dy;
  75968. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75969. {
  75970. const float len = std::sqrt (hypotSquared);
  75971. if (len == 0)
  75972. {
  75973. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75974. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75975. }
  75976. else
  75977. {
  75978. const float offset = width / len;
  75979. dx *= offset;
  75980. dy *= offset;
  75981. l.rx2 = l.x1 - dy;
  75982. l.ry2 = l.y1 + dx;
  75983. l.lx1 = l.x1 + dy;
  75984. l.ly1 = l.y1 - dx;
  75985. l.lx2 = l.x2 + dy;
  75986. l.ly2 = l.y2 - dx;
  75987. l.rx1 = l.x2 - dy;
  75988. l.ry1 = l.y2 + dx;
  75989. }
  75990. subPath.add (l);
  75991. if (it.closesSubPath)
  75992. {
  75993. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75994. subPath.clearQuick();
  75995. }
  75996. else
  75997. {
  75998. l.x1 = it.x2;
  75999. l.y1 = it.y2;
  76000. }
  76001. }
  76002. }
  76003. if (subPath.size() > 0)
  76004. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76005. }
  76006. }
  76007. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76008. const AffineTransform& transform, const float extraAccuracy) const
  76009. {
  76010. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76011. transform, extraAccuracy, 0);
  76012. }
  76013. void PathStrokeType::createDashedStroke (Path& destPath,
  76014. const Path& sourcePath,
  76015. const float* dashLengths,
  76016. int numDashLengths,
  76017. const AffineTransform& transform,
  76018. const float extraAccuracy) const
  76019. {
  76020. jassert (extraAccuracy > 0);
  76021. if (thickness <= 0)
  76022. return;
  76023. // this should really be an even number..
  76024. jassert ((numDashLengths & 1) == 0);
  76025. Path newDestPath;
  76026. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76027. bool first = true;
  76028. int dashNum = 0;
  76029. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76030. float dx = 0.0f, dy = 0.0f;
  76031. for (;;)
  76032. {
  76033. const bool isSolid = ((dashNum & 1) == 0);
  76034. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76035. jassert (dashLen > 0); // must be a positive increment!
  76036. if (dashLen <= 0)
  76037. break;
  76038. pos += dashLen;
  76039. while (pos > lineEndPos)
  76040. {
  76041. if (! it.next())
  76042. {
  76043. if (isSolid && ! first)
  76044. newDestPath.lineTo (it.x2, it.y2);
  76045. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76046. return;
  76047. }
  76048. if (isSolid && ! first)
  76049. newDestPath.lineTo (it.x1, it.y1);
  76050. else
  76051. newDestPath.startNewSubPath (it.x1, it.y1);
  76052. dx = it.x2 - it.x1;
  76053. dy = it.y2 - it.y1;
  76054. lineLen = juce_hypot (dx, dy);
  76055. lineEndPos += lineLen;
  76056. first = it.closesSubPath;
  76057. }
  76058. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76059. if (isSolid)
  76060. newDestPath.lineTo (it.x1 + dx * alpha,
  76061. it.y1 + dy * alpha);
  76062. else
  76063. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76064. it.y1 + dy * alpha);
  76065. }
  76066. }
  76067. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76068. const Path& sourcePath,
  76069. const float arrowheadStartWidth, const float arrowheadStartLength,
  76070. const float arrowheadEndWidth, const float arrowheadEndLength,
  76071. const AffineTransform& transform,
  76072. const float extraAccuracy) const
  76073. {
  76074. PathStrokeHelpers::Arrowhead head;
  76075. head.startWidth = arrowheadStartWidth;
  76076. head.startLength = arrowheadStartLength;
  76077. head.endWidth = arrowheadEndWidth;
  76078. head.endLength = arrowheadEndLength;
  76079. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76080. destPath, sourcePath, transform, extraAccuracy, &head);
  76081. }
  76082. END_JUCE_NAMESPACE
  76083. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76084. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76085. BEGIN_JUCE_NAMESPACE
  76086. RectangleList::RectangleList() throw()
  76087. {
  76088. }
  76089. RectangleList::RectangleList (const Rectangle<int>& rect)
  76090. {
  76091. if (! rect.isEmpty())
  76092. rects.add (rect);
  76093. }
  76094. RectangleList::RectangleList (const RectangleList& other)
  76095. : rects (other.rects)
  76096. {
  76097. }
  76098. RectangleList& RectangleList::operator= (const RectangleList& other)
  76099. {
  76100. rects = other.rects;
  76101. return *this;
  76102. }
  76103. RectangleList::~RectangleList()
  76104. {
  76105. }
  76106. void RectangleList::clear()
  76107. {
  76108. rects.clearQuick();
  76109. }
  76110. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76111. {
  76112. if (isPositiveAndBelow (index, rects.size()))
  76113. return rects.getReference (index);
  76114. return Rectangle<int>();
  76115. }
  76116. bool RectangleList::isEmpty() const throw()
  76117. {
  76118. return rects.size() == 0;
  76119. }
  76120. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76121. : current (0),
  76122. owner (list),
  76123. index (list.rects.size())
  76124. {
  76125. }
  76126. RectangleList::Iterator::~Iterator()
  76127. {
  76128. }
  76129. bool RectangleList::Iterator::next() throw()
  76130. {
  76131. if (--index >= 0)
  76132. {
  76133. current = & (owner.rects.getReference (index));
  76134. return true;
  76135. }
  76136. return false;
  76137. }
  76138. void RectangleList::add (const Rectangle<int>& rect)
  76139. {
  76140. if (! rect.isEmpty())
  76141. {
  76142. if (rects.size() == 0)
  76143. {
  76144. rects.add (rect);
  76145. }
  76146. else
  76147. {
  76148. bool anyOverlaps = false;
  76149. int i;
  76150. for (i = rects.size(); --i >= 0;)
  76151. {
  76152. Rectangle<int>& ourRect = rects.getReference (i);
  76153. if (rect.intersects (ourRect))
  76154. {
  76155. if (rect.contains (ourRect))
  76156. rects.remove (i);
  76157. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76158. anyOverlaps = true;
  76159. }
  76160. }
  76161. if (anyOverlaps && rects.size() > 0)
  76162. {
  76163. RectangleList r (rect);
  76164. for (i = rects.size(); --i >= 0;)
  76165. {
  76166. const Rectangle<int>& ourRect = rects.getReference (i);
  76167. if (rect.intersects (ourRect))
  76168. {
  76169. r.subtract (ourRect);
  76170. if (r.rects.size() == 0)
  76171. return;
  76172. }
  76173. }
  76174. for (i = r.getNumRectangles(); --i >= 0;)
  76175. rects.add (r.rects.getReference (i));
  76176. }
  76177. else
  76178. {
  76179. rects.add (rect);
  76180. }
  76181. }
  76182. }
  76183. }
  76184. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76185. {
  76186. if (! rect.isEmpty())
  76187. rects.add (rect);
  76188. }
  76189. void RectangleList::add (const int x, const int y, const int w, const int h)
  76190. {
  76191. if (rects.size() == 0)
  76192. {
  76193. if (w > 0 && h > 0)
  76194. rects.add (Rectangle<int> (x, y, w, h));
  76195. }
  76196. else
  76197. {
  76198. add (Rectangle<int> (x, y, w, h));
  76199. }
  76200. }
  76201. void RectangleList::add (const RectangleList& other)
  76202. {
  76203. for (int i = 0; i < other.rects.size(); ++i)
  76204. add (other.rects.getReference (i));
  76205. }
  76206. void RectangleList::subtract (const Rectangle<int>& rect)
  76207. {
  76208. const int originalNumRects = rects.size();
  76209. if (originalNumRects > 0)
  76210. {
  76211. const int x1 = rect.x;
  76212. const int y1 = rect.y;
  76213. const int x2 = x1 + rect.w;
  76214. const int y2 = y1 + rect.h;
  76215. for (int i = getNumRectangles(); --i >= 0;)
  76216. {
  76217. Rectangle<int>& r = rects.getReference (i);
  76218. const int rx1 = r.x;
  76219. const int ry1 = r.y;
  76220. const int rx2 = rx1 + r.w;
  76221. const int ry2 = ry1 + r.h;
  76222. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76223. {
  76224. if (x1 > rx1 && x1 < rx2)
  76225. {
  76226. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76227. {
  76228. r.w = x1 - rx1;
  76229. }
  76230. else
  76231. {
  76232. r.x = x1;
  76233. r.w = rx2 - x1;
  76234. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76235. i += 2;
  76236. }
  76237. }
  76238. else if (x2 > rx1 && x2 < rx2)
  76239. {
  76240. r.x = x2;
  76241. r.w = rx2 - x2;
  76242. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76243. {
  76244. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76245. i += 2;
  76246. }
  76247. }
  76248. else if (y1 > ry1 && y1 < ry2)
  76249. {
  76250. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76251. {
  76252. r.h = y1 - ry1;
  76253. }
  76254. else
  76255. {
  76256. r.y = y1;
  76257. r.h = ry2 - y1;
  76258. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76259. i += 2;
  76260. }
  76261. }
  76262. else if (y2 > ry1 && y2 < ry2)
  76263. {
  76264. r.y = y2;
  76265. r.h = ry2 - y2;
  76266. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76267. {
  76268. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76269. i += 2;
  76270. }
  76271. }
  76272. else
  76273. {
  76274. rects.remove (i);
  76275. }
  76276. }
  76277. }
  76278. }
  76279. }
  76280. bool RectangleList::subtract (const RectangleList& otherList)
  76281. {
  76282. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76283. subtract (otherList.rects.getReference (i));
  76284. return rects.size() > 0;
  76285. }
  76286. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76287. {
  76288. bool notEmpty = false;
  76289. if (rect.isEmpty())
  76290. {
  76291. clear();
  76292. }
  76293. else
  76294. {
  76295. for (int i = rects.size(); --i >= 0;)
  76296. {
  76297. Rectangle<int>& r = rects.getReference (i);
  76298. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76299. rects.remove (i);
  76300. else
  76301. notEmpty = true;
  76302. }
  76303. }
  76304. return notEmpty;
  76305. }
  76306. bool RectangleList::clipTo (const RectangleList& other)
  76307. {
  76308. if (rects.size() == 0)
  76309. return false;
  76310. RectangleList result;
  76311. for (int j = 0; j < rects.size(); ++j)
  76312. {
  76313. const Rectangle<int>& rect = rects.getReference (j);
  76314. for (int i = other.rects.size(); --i >= 0;)
  76315. {
  76316. Rectangle<int> r (other.rects.getReference (i));
  76317. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76318. result.rects.add (r);
  76319. }
  76320. }
  76321. swapWith (result);
  76322. return ! isEmpty();
  76323. }
  76324. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76325. {
  76326. destRegion.clear();
  76327. if (! rect.isEmpty())
  76328. {
  76329. for (int i = rects.size(); --i >= 0;)
  76330. {
  76331. Rectangle<int> r (rects.getReference (i));
  76332. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76333. destRegion.rects.add (r);
  76334. }
  76335. }
  76336. return destRegion.rects.size() > 0;
  76337. }
  76338. void RectangleList::swapWith (RectangleList& otherList) throw()
  76339. {
  76340. rects.swapWithArray (otherList.rects);
  76341. }
  76342. void RectangleList::consolidate()
  76343. {
  76344. int i;
  76345. for (i = 0; i < getNumRectangles() - 1; ++i)
  76346. {
  76347. Rectangle<int>& r = rects.getReference (i);
  76348. const int rx1 = r.x;
  76349. const int ry1 = r.y;
  76350. const int rx2 = rx1 + r.w;
  76351. const int ry2 = ry1 + r.h;
  76352. for (int j = rects.size(); --j > i;)
  76353. {
  76354. Rectangle<int>& r2 = rects.getReference (j);
  76355. const int jrx1 = r2.x;
  76356. const int jry1 = r2.y;
  76357. const int jrx2 = jrx1 + r2.w;
  76358. const int jry2 = jry1 + r2.h;
  76359. // if the vertical edges of any blocks are touching and their horizontals don't
  76360. // line up, split them horizontally..
  76361. if (jrx1 == rx2 || jrx2 == rx1)
  76362. {
  76363. if (jry1 > ry1 && jry1 < ry2)
  76364. {
  76365. r.h = jry1 - ry1;
  76366. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76367. i = -1;
  76368. break;
  76369. }
  76370. if (jry2 > ry1 && jry2 < ry2)
  76371. {
  76372. r.h = jry2 - ry1;
  76373. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76374. i = -1;
  76375. break;
  76376. }
  76377. else if (ry1 > jry1 && ry1 < jry2)
  76378. {
  76379. r2.h = ry1 - jry1;
  76380. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76381. i = -1;
  76382. break;
  76383. }
  76384. else if (ry2 > jry1 && ry2 < jry2)
  76385. {
  76386. r2.h = ry2 - jry1;
  76387. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76388. i = -1;
  76389. break;
  76390. }
  76391. }
  76392. }
  76393. }
  76394. for (i = 0; i < rects.size() - 1; ++i)
  76395. {
  76396. Rectangle<int>& r = rects.getReference (i);
  76397. for (int j = rects.size(); --j > i;)
  76398. {
  76399. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76400. {
  76401. rects.remove (j);
  76402. i = -1;
  76403. break;
  76404. }
  76405. }
  76406. }
  76407. }
  76408. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76409. {
  76410. for (int i = getNumRectangles(); --i >= 0;)
  76411. if (rects.getReference (i).contains (x, y))
  76412. return true;
  76413. return false;
  76414. }
  76415. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76416. {
  76417. if (rects.size() > 1)
  76418. {
  76419. RectangleList r (rectangleToCheck);
  76420. for (int i = rects.size(); --i >= 0;)
  76421. {
  76422. r.subtract (rects.getReference (i));
  76423. if (r.rects.size() == 0)
  76424. return true;
  76425. }
  76426. }
  76427. else if (rects.size() > 0)
  76428. {
  76429. return rects.getReference (0).contains (rectangleToCheck);
  76430. }
  76431. return false;
  76432. }
  76433. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76434. {
  76435. for (int i = rects.size(); --i >= 0;)
  76436. if (rects.getReference (i).intersects (rectangleToCheck))
  76437. return true;
  76438. return false;
  76439. }
  76440. bool RectangleList::intersects (const RectangleList& other) const throw()
  76441. {
  76442. for (int i = rects.size(); --i >= 0;)
  76443. if (other.intersectsRectangle (rects.getReference (i)))
  76444. return true;
  76445. return false;
  76446. }
  76447. const Rectangle<int> RectangleList::getBounds() const throw()
  76448. {
  76449. if (rects.size() <= 1)
  76450. {
  76451. if (rects.size() == 0)
  76452. return Rectangle<int>();
  76453. else
  76454. return rects.getReference (0);
  76455. }
  76456. else
  76457. {
  76458. const Rectangle<int>& r = rects.getReference (0);
  76459. int minX = r.x;
  76460. int minY = r.y;
  76461. int maxX = minX + r.w;
  76462. int maxY = minY + r.h;
  76463. for (int i = rects.size(); --i > 0;)
  76464. {
  76465. const Rectangle<int>& r2 = rects.getReference (i);
  76466. minX = jmin (minX, r2.x);
  76467. minY = jmin (minY, r2.y);
  76468. maxX = jmax (maxX, r2.getRight());
  76469. maxY = jmax (maxY, r2.getBottom());
  76470. }
  76471. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76472. }
  76473. }
  76474. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76475. {
  76476. for (int i = rects.size(); --i >= 0;)
  76477. {
  76478. Rectangle<int>& r = rects.getReference (i);
  76479. r.x += dx;
  76480. r.y += dy;
  76481. }
  76482. }
  76483. const Path RectangleList::toPath() const
  76484. {
  76485. Path p;
  76486. for (int i = rects.size(); --i >= 0;)
  76487. {
  76488. const Rectangle<int>& r = rects.getReference (i);
  76489. p.addRectangle ((float) r.x,
  76490. (float) r.y,
  76491. (float) r.w,
  76492. (float) r.h);
  76493. }
  76494. return p;
  76495. }
  76496. END_JUCE_NAMESPACE
  76497. /*** End of inlined file: juce_RectangleList.cpp ***/
  76498. /*** Start of inlined file: juce_Image.cpp ***/
  76499. BEGIN_JUCE_NAMESPACE
  76500. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76501. : format (format_), width (width_), height (height_)
  76502. {
  76503. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76504. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76505. }
  76506. Image::SharedImage::~SharedImage()
  76507. {
  76508. }
  76509. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76510. {
  76511. return imageData + lineStride * y + pixelStride * x;
  76512. }
  76513. class SoftwareSharedImage : public Image::SharedImage
  76514. {
  76515. public:
  76516. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76517. : Image::SharedImage (format_, width_, height_)
  76518. {
  76519. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76520. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76521. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76522. imageData = imageDataAllocated;
  76523. }
  76524. Image::ImageType getType() const
  76525. {
  76526. return Image::SoftwareImage;
  76527. }
  76528. LowLevelGraphicsContext* createLowLevelContext()
  76529. {
  76530. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76531. }
  76532. Image::SharedImage* clone()
  76533. {
  76534. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76535. memcpy (s->imageData, imageData, lineStride * height);
  76536. return s;
  76537. }
  76538. private:
  76539. HeapBlock<uint8> imageDataAllocated;
  76540. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76541. };
  76542. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76543. {
  76544. return new SoftwareSharedImage (format, width, height, clearImage);
  76545. }
  76546. class SubsectionSharedImage : public Image::SharedImage
  76547. {
  76548. public:
  76549. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76550. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76551. image (image_), area (area_)
  76552. {
  76553. pixelStride = image_->getPixelStride();
  76554. lineStride = image_->getLineStride();
  76555. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76556. }
  76557. Image::ImageType getType() const
  76558. {
  76559. return Image::SoftwareImage;
  76560. }
  76561. LowLevelGraphicsContext* createLowLevelContext()
  76562. {
  76563. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76564. g->clipToRectangle (area);
  76565. g->setOrigin (area.getX(), area.getY());
  76566. return g;
  76567. }
  76568. Image::SharedImage* clone()
  76569. {
  76570. return new SubsectionSharedImage (image->clone(), area);
  76571. }
  76572. private:
  76573. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76574. const Rectangle<int> area;
  76575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76576. };
  76577. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76578. {
  76579. if (area.contains (getBounds()))
  76580. return *this;
  76581. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76582. if (validArea.isEmpty())
  76583. return Image::null;
  76584. return Image (new SubsectionSharedImage (image, validArea));
  76585. }
  76586. Image::Image()
  76587. {
  76588. }
  76589. Image::Image (SharedImage* const instance)
  76590. : image (instance)
  76591. {
  76592. }
  76593. Image::Image (const PixelFormat format,
  76594. const int width, const int height,
  76595. const bool clearImage, const ImageType type)
  76596. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76597. : new SoftwareSharedImage (format, width, height, clearImage))
  76598. {
  76599. }
  76600. Image::Image (const Image& other)
  76601. : image (other.image)
  76602. {
  76603. }
  76604. Image& Image::operator= (const Image& other)
  76605. {
  76606. image = other.image;
  76607. return *this;
  76608. }
  76609. Image::~Image()
  76610. {
  76611. }
  76612. const Image Image::null;
  76613. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76614. {
  76615. return image == 0 ? 0 : image->createLowLevelContext();
  76616. }
  76617. void Image::duplicateIfShared()
  76618. {
  76619. if (image != 0 && image->getReferenceCount() > 1)
  76620. image = image->clone();
  76621. }
  76622. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76623. {
  76624. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76625. return *this;
  76626. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76627. Graphics g (newImage);
  76628. g.setImageResamplingQuality (quality);
  76629. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76630. return newImage;
  76631. }
  76632. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76633. {
  76634. if (image == 0 || newFormat == image->format)
  76635. return *this;
  76636. const int w = image->width, h = image->height;
  76637. Image newImage (newFormat, w, h, false, image->getType());
  76638. if (newFormat == SingleChannel)
  76639. {
  76640. if (! hasAlphaChannel())
  76641. {
  76642. newImage.clear (getBounds(), Colours::black);
  76643. }
  76644. else
  76645. {
  76646. const BitmapData destData (newImage, 0, 0, w, h, true);
  76647. const BitmapData srcData (*this, 0, 0, w, h);
  76648. for (int y = 0; y < h; ++y)
  76649. {
  76650. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76651. uint8* dst = destData.getLinePointer (y);
  76652. for (int x = w; --x >= 0;)
  76653. {
  76654. *dst++ = src->getAlpha();
  76655. ++src;
  76656. }
  76657. }
  76658. }
  76659. }
  76660. else
  76661. {
  76662. if (hasAlphaChannel())
  76663. newImage.clear (getBounds());
  76664. Graphics g (newImage);
  76665. g.drawImageAt (*this, 0, 0);
  76666. }
  76667. return newImage;
  76668. }
  76669. NamedValueSet* Image::getProperties() const
  76670. {
  76671. return image == 0 ? 0 : &(image->userData);
  76672. }
  76673. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76674. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76675. pixelFormat (image.getFormat()),
  76676. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76677. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76678. width (w),
  76679. height (h)
  76680. {
  76681. jassert (data != 0);
  76682. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76683. }
  76684. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76685. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76686. pixelFormat (image.getFormat()),
  76687. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76688. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76689. width (w),
  76690. height (h)
  76691. {
  76692. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76693. }
  76694. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76695. : data (image.image == 0 ? 0 : image.image->imageData),
  76696. pixelFormat (image.getFormat()),
  76697. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76698. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76699. width (image.getWidth()),
  76700. height (image.getHeight())
  76701. {
  76702. }
  76703. Image::BitmapData::~BitmapData()
  76704. {
  76705. }
  76706. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76707. {
  76708. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76709. const uint8* const pixel = getPixelPointer (x, y);
  76710. switch (pixelFormat)
  76711. {
  76712. case Image::ARGB:
  76713. {
  76714. PixelARGB p (*(const PixelARGB*) pixel);
  76715. p.unpremultiply();
  76716. return Colour (p.getARGB());
  76717. }
  76718. case Image::RGB:
  76719. return Colour (((const PixelRGB*) pixel)->getARGB());
  76720. case Image::SingleChannel:
  76721. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76722. default:
  76723. jassertfalse;
  76724. break;
  76725. }
  76726. return Colour();
  76727. }
  76728. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76729. {
  76730. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76731. uint8* const pixel = getPixelPointer (x, y);
  76732. const PixelARGB col (colour.getPixelARGB());
  76733. switch (pixelFormat)
  76734. {
  76735. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76736. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76737. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76738. default: jassertfalse; break;
  76739. }
  76740. }
  76741. void Image::setPixelData (int x, int y, int w, int h,
  76742. const uint8* const sourcePixelData, const int sourceLineStride)
  76743. {
  76744. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76745. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76746. {
  76747. const BitmapData dest (*this, x, y, w, h, true);
  76748. for (int i = 0; i < h; ++i)
  76749. {
  76750. memcpy (dest.getLinePointer(i),
  76751. sourcePixelData + sourceLineStride * i,
  76752. w * dest.pixelStride);
  76753. }
  76754. }
  76755. }
  76756. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76757. {
  76758. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76759. if (! clipped.isEmpty())
  76760. {
  76761. const PixelARGB col (colourToClearTo.getPixelARGB());
  76762. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76763. uint8* dest = destData.data;
  76764. int dh = clipped.getHeight();
  76765. while (--dh >= 0)
  76766. {
  76767. uint8* line = dest;
  76768. dest += destData.lineStride;
  76769. if (isARGB())
  76770. {
  76771. for (int x = clipped.getWidth(); --x >= 0;)
  76772. {
  76773. ((PixelARGB*) line)->set (col);
  76774. line += destData.pixelStride;
  76775. }
  76776. }
  76777. else if (isRGB())
  76778. {
  76779. for (int x = clipped.getWidth(); --x >= 0;)
  76780. {
  76781. ((PixelRGB*) line)->set (col);
  76782. line += destData.pixelStride;
  76783. }
  76784. }
  76785. else
  76786. {
  76787. for (int x = clipped.getWidth(); --x >= 0;)
  76788. {
  76789. *line = col.getAlpha();
  76790. line += destData.pixelStride;
  76791. }
  76792. }
  76793. }
  76794. }
  76795. }
  76796. const Colour Image::getPixelAt (const int x, const int y) const
  76797. {
  76798. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76799. {
  76800. const BitmapData srcData (*this, x, y, 1, 1);
  76801. return srcData.getPixelColour (0, 0);
  76802. }
  76803. return Colour();
  76804. }
  76805. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76806. {
  76807. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76808. {
  76809. const BitmapData destData (*this, x, y, 1, 1, true);
  76810. destData.setPixelColour (0, 0, colour);
  76811. }
  76812. }
  76813. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76814. {
  76815. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  76816. && hasAlphaChannel())
  76817. {
  76818. const BitmapData destData (*this, x, y, 1, 1, true);
  76819. if (isARGB())
  76820. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76821. else
  76822. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76823. }
  76824. }
  76825. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76826. {
  76827. if (hasAlphaChannel())
  76828. {
  76829. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76830. if (isARGB())
  76831. {
  76832. for (int y = 0; y < destData.height; ++y)
  76833. {
  76834. uint8* p = destData.getLinePointer (y);
  76835. for (int x = 0; x < destData.width; ++x)
  76836. {
  76837. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76838. p += destData.pixelStride;
  76839. }
  76840. }
  76841. }
  76842. else
  76843. {
  76844. for (int y = 0; y < destData.height; ++y)
  76845. {
  76846. uint8* p = destData.getLinePointer (y);
  76847. for (int x = 0; x < destData.width; ++x)
  76848. {
  76849. *p = (uint8) (*p * amountToMultiplyBy);
  76850. p += destData.pixelStride;
  76851. }
  76852. }
  76853. }
  76854. }
  76855. else
  76856. {
  76857. jassertfalse; // can't do this without an alpha-channel!
  76858. }
  76859. }
  76860. void Image::desaturate()
  76861. {
  76862. if (isARGB() || isRGB())
  76863. {
  76864. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76865. if (isARGB())
  76866. {
  76867. for (int y = 0; y < destData.height; ++y)
  76868. {
  76869. uint8* p = destData.getLinePointer (y);
  76870. for (int x = 0; x < destData.width; ++x)
  76871. {
  76872. ((PixelARGB*) p)->desaturate();
  76873. p += destData.pixelStride;
  76874. }
  76875. }
  76876. }
  76877. else
  76878. {
  76879. for (int y = 0; y < destData.height; ++y)
  76880. {
  76881. uint8* p = destData.getLinePointer (y);
  76882. for (int x = 0; x < destData.width; ++x)
  76883. {
  76884. ((PixelRGB*) p)->desaturate();
  76885. p += destData.pixelStride;
  76886. }
  76887. }
  76888. }
  76889. }
  76890. }
  76891. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76892. {
  76893. if (hasAlphaChannel())
  76894. {
  76895. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76896. SparseSet<int> pixelsOnRow;
  76897. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76898. for (int y = 0; y < srcData.height; ++y)
  76899. {
  76900. pixelsOnRow.clear();
  76901. const uint8* lineData = srcData.getLinePointer (y);
  76902. if (isARGB())
  76903. {
  76904. for (int x = 0; x < srcData.width; ++x)
  76905. {
  76906. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76907. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76908. lineData += srcData.pixelStride;
  76909. }
  76910. }
  76911. else
  76912. {
  76913. for (int x = 0; x < srcData.width; ++x)
  76914. {
  76915. if (*lineData >= threshold)
  76916. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76917. lineData += srcData.pixelStride;
  76918. }
  76919. }
  76920. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76921. {
  76922. const Range<int> range (pixelsOnRow.getRange (i));
  76923. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76924. }
  76925. result.consolidate();
  76926. }
  76927. }
  76928. else
  76929. {
  76930. result.add (0, 0, getWidth(), getHeight());
  76931. }
  76932. }
  76933. void Image::moveImageSection (int dx, int dy,
  76934. int sx, int sy,
  76935. int w, int h)
  76936. {
  76937. if (dx < 0)
  76938. {
  76939. w += dx;
  76940. sx -= dx;
  76941. dx = 0;
  76942. }
  76943. if (dy < 0)
  76944. {
  76945. h += dy;
  76946. sy -= dy;
  76947. dy = 0;
  76948. }
  76949. if (sx < 0)
  76950. {
  76951. w += sx;
  76952. dx -= sx;
  76953. sx = 0;
  76954. }
  76955. if (sy < 0)
  76956. {
  76957. h += sy;
  76958. dy -= sy;
  76959. sy = 0;
  76960. }
  76961. const int minX = jmin (dx, sx);
  76962. const int minY = jmin (dy, sy);
  76963. w = jmin (w, getWidth() - jmax (sx, dx));
  76964. h = jmin (h, getHeight() - jmax (sy, dy));
  76965. if (w > 0 && h > 0)
  76966. {
  76967. const int maxX = jmax (dx, sx) + w;
  76968. const int maxY = jmax (dy, sy) + h;
  76969. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76970. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76971. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76972. const int lineSize = destData.pixelStride * w;
  76973. if (dy > sy)
  76974. {
  76975. while (--h >= 0)
  76976. {
  76977. const int offset = h * destData.lineStride;
  76978. memmove (dst + offset, src + offset, lineSize);
  76979. }
  76980. }
  76981. else if (dst != src)
  76982. {
  76983. while (--h >= 0)
  76984. {
  76985. memmove (dst, src, lineSize);
  76986. dst += destData.lineStride;
  76987. src += destData.lineStride;
  76988. }
  76989. }
  76990. }
  76991. }
  76992. END_JUCE_NAMESPACE
  76993. /*** End of inlined file: juce_Image.cpp ***/
  76994. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76995. BEGIN_JUCE_NAMESPACE
  76996. class ImageCache::Pimpl : public Timer,
  76997. public DeletedAtShutdown
  76998. {
  76999. public:
  77000. Pimpl()
  77001. : cacheTimeout (5000)
  77002. {
  77003. }
  77004. ~Pimpl()
  77005. {
  77006. clearSingletonInstance();
  77007. }
  77008. const Image getFromHashCode (const int64 hashCode)
  77009. {
  77010. const ScopedLock sl (lock);
  77011. for (int i = images.size(); --i >= 0;)
  77012. {
  77013. Item* const item = images.getUnchecked(i);
  77014. if (item->hashCode == hashCode)
  77015. return item->image;
  77016. }
  77017. return Image::null;
  77018. }
  77019. void addImageToCache (const Image& image, const int64 hashCode)
  77020. {
  77021. if (image.isValid())
  77022. {
  77023. if (! isTimerRunning())
  77024. startTimer (2000);
  77025. Item* const item = new Item();
  77026. item->hashCode = hashCode;
  77027. item->image = image;
  77028. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77029. const ScopedLock sl (lock);
  77030. images.add (item);
  77031. }
  77032. }
  77033. void timerCallback()
  77034. {
  77035. const uint32 now = Time::getApproximateMillisecondCounter();
  77036. const ScopedLock sl (lock);
  77037. for (int i = images.size(); --i >= 0;)
  77038. {
  77039. Item* const item = images.getUnchecked(i);
  77040. if (item->image.getReferenceCount() <= 1)
  77041. {
  77042. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77043. images.remove (i);
  77044. }
  77045. else
  77046. {
  77047. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77048. }
  77049. }
  77050. if (images.size() == 0)
  77051. stopTimer();
  77052. }
  77053. struct Item
  77054. {
  77055. Image image;
  77056. int64 hashCode;
  77057. uint32 lastUseTime;
  77058. };
  77059. int cacheTimeout;
  77060. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77061. private:
  77062. OwnedArray<Item> images;
  77063. CriticalSection lock;
  77064. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77065. };
  77066. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77067. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77068. {
  77069. if (Pimpl::getInstanceWithoutCreating() != 0)
  77070. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77071. return Image::null;
  77072. }
  77073. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77074. {
  77075. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77076. }
  77077. const Image ImageCache::getFromFile (const File& file)
  77078. {
  77079. const int64 hashCode = file.hashCode64();
  77080. Image image (getFromHashCode (hashCode));
  77081. if (image.isNull())
  77082. {
  77083. image = ImageFileFormat::loadFrom (file);
  77084. addImageToCache (image, hashCode);
  77085. }
  77086. return image;
  77087. }
  77088. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77089. {
  77090. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77091. Image image (getFromHashCode (hashCode));
  77092. if (image.isNull())
  77093. {
  77094. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77095. addImageToCache (image, hashCode);
  77096. }
  77097. return image;
  77098. }
  77099. void ImageCache::setCacheTimeout (const int millisecs)
  77100. {
  77101. Pimpl::getInstance()->cacheTimeout = millisecs;
  77102. }
  77103. END_JUCE_NAMESPACE
  77104. /*** End of inlined file: juce_ImageCache.cpp ***/
  77105. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77106. BEGIN_JUCE_NAMESPACE
  77107. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77108. : values (size_ * size_),
  77109. size (size_)
  77110. {
  77111. clear();
  77112. }
  77113. ImageConvolutionKernel::~ImageConvolutionKernel()
  77114. {
  77115. }
  77116. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77117. {
  77118. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77119. return values [x + y * size];
  77120. jassertfalse;
  77121. return 0;
  77122. }
  77123. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77124. {
  77125. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77126. {
  77127. values [x + y * size] = value;
  77128. }
  77129. else
  77130. {
  77131. jassertfalse;
  77132. }
  77133. }
  77134. void ImageConvolutionKernel::clear()
  77135. {
  77136. for (int i = size * size; --i >= 0;)
  77137. values[i] = 0;
  77138. }
  77139. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77140. {
  77141. double currentTotal = 0.0;
  77142. for (int i = size * size; --i >= 0;)
  77143. currentTotal += values[i];
  77144. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77145. }
  77146. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77147. {
  77148. for (int i = size * size; --i >= 0;)
  77149. values[i] *= multiplier;
  77150. }
  77151. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77152. {
  77153. const double radiusFactor = -1.0 / (radius * radius * 2);
  77154. const int centre = size >> 1;
  77155. for (int y = size; --y >= 0;)
  77156. {
  77157. for (int x = size; --x >= 0;)
  77158. {
  77159. const int cx = x - centre;
  77160. const int cy = y - centre;
  77161. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77162. }
  77163. }
  77164. setOverallSum (1.0f);
  77165. }
  77166. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77167. const Image& sourceImage,
  77168. const Rectangle<int>& destinationArea) const
  77169. {
  77170. if (sourceImage == destImage)
  77171. {
  77172. destImage.duplicateIfShared();
  77173. }
  77174. else
  77175. {
  77176. if (sourceImage.getWidth() != destImage.getWidth()
  77177. || sourceImage.getHeight() != destImage.getHeight()
  77178. || sourceImage.getFormat() != destImage.getFormat())
  77179. {
  77180. jassertfalse;
  77181. return;
  77182. }
  77183. }
  77184. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77185. if (area.isEmpty())
  77186. return;
  77187. const int right = area.getRight();
  77188. const int bottom = area.getBottom();
  77189. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77190. uint8* line = destData.data;
  77191. const Image::BitmapData srcData (sourceImage, false);
  77192. if (destData.pixelStride == 4)
  77193. {
  77194. for (int y = area.getY(); y < bottom; ++y)
  77195. {
  77196. uint8* dest = line;
  77197. line += destData.lineStride;
  77198. for (int x = area.getX(); x < right; ++x)
  77199. {
  77200. float c1 = 0;
  77201. float c2 = 0;
  77202. float c3 = 0;
  77203. float c4 = 0;
  77204. for (int yy = 0; yy < size; ++yy)
  77205. {
  77206. const int sy = y + yy - (size >> 1);
  77207. if (sy >= srcData.height)
  77208. break;
  77209. if (sy >= 0)
  77210. {
  77211. int sx = x - (size >> 1);
  77212. const uint8* src = srcData.getPixelPointer (sx, sy);
  77213. for (int xx = 0; xx < size; ++xx)
  77214. {
  77215. if (sx >= srcData.width)
  77216. break;
  77217. if (sx >= 0)
  77218. {
  77219. const float kernelMult = values [xx + yy * size];
  77220. c1 += kernelMult * *src++;
  77221. c2 += kernelMult * *src++;
  77222. c3 += kernelMult * *src++;
  77223. c4 += kernelMult * *src++;
  77224. }
  77225. else
  77226. {
  77227. src += 4;
  77228. }
  77229. ++sx;
  77230. }
  77231. }
  77232. }
  77233. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77234. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77235. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77236. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77237. }
  77238. }
  77239. }
  77240. else if (destData.pixelStride == 3)
  77241. {
  77242. for (int y = area.getY(); y < bottom; ++y)
  77243. {
  77244. uint8* dest = line;
  77245. line += destData.lineStride;
  77246. for (int x = area.getX(); x < right; ++x)
  77247. {
  77248. float c1 = 0;
  77249. float c2 = 0;
  77250. float c3 = 0;
  77251. for (int yy = 0; yy < size; ++yy)
  77252. {
  77253. const int sy = y + yy - (size >> 1);
  77254. if (sy >= srcData.height)
  77255. break;
  77256. if (sy >= 0)
  77257. {
  77258. int sx = x - (size >> 1);
  77259. const uint8* src = srcData.getPixelPointer (sx, sy);
  77260. for (int xx = 0; xx < size; ++xx)
  77261. {
  77262. if (sx >= srcData.width)
  77263. break;
  77264. if (sx >= 0)
  77265. {
  77266. const float kernelMult = values [xx + yy * size];
  77267. c1 += kernelMult * *src++;
  77268. c2 += kernelMult * *src++;
  77269. c3 += kernelMult * *src++;
  77270. }
  77271. else
  77272. {
  77273. src += 3;
  77274. }
  77275. ++sx;
  77276. }
  77277. }
  77278. }
  77279. *dest++ = (uint8) roundToInt (c1);
  77280. *dest++ = (uint8) roundToInt (c2);
  77281. *dest++ = (uint8) roundToInt (c3);
  77282. }
  77283. }
  77284. }
  77285. }
  77286. END_JUCE_NAMESPACE
  77287. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77288. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77289. BEGIN_JUCE_NAMESPACE
  77290. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77291. {
  77292. static PNGImageFormat png;
  77293. static JPEGImageFormat jpg;
  77294. static GIFImageFormat gif;
  77295. ImageFileFormat* formats[4];
  77296. int numFormats = 0;
  77297. formats [numFormats++] = &png;
  77298. formats [numFormats++] = &jpg;
  77299. formats [numFormats++] = &gif;
  77300. const int64 streamPos = input.getPosition();
  77301. for (int i = 0; i < numFormats; ++i)
  77302. {
  77303. const bool found = formats[i]->canUnderstand (input);
  77304. input.setPosition (streamPos);
  77305. if (found)
  77306. return formats[i];
  77307. }
  77308. return 0;
  77309. }
  77310. const Image ImageFileFormat::loadFrom (InputStream& input)
  77311. {
  77312. ImageFileFormat* const format = findImageFormatForStream (input);
  77313. if (format != 0)
  77314. return format->decodeImage (input);
  77315. return Image::null;
  77316. }
  77317. const Image ImageFileFormat::loadFrom (const File& file)
  77318. {
  77319. InputStream* const in = file.createInputStream();
  77320. if (in != 0)
  77321. {
  77322. BufferedInputStream b (in, 8192, true);
  77323. return loadFrom (b);
  77324. }
  77325. return Image::null;
  77326. }
  77327. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77328. {
  77329. if (rawData != 0 && numBytes > 4)
  77330. {
  77331. MemoryInputStream stream (rawData, numBytes, false);
  77332. return loadFrom (stream);
  77333. }
  77334. return Image::null;
  77335. }
  77336. END_JUCE_NAMESPACE
  77337. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77338. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77339. BEGIN_JUCE_NAMESPACE
  77340. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77341. const Image juce_loadWithCoreImage (InputStream& input);
  77342. #else
  77343. class GIFLoader
  77344. {
  77345. public:
  77346. GIFLoader (InputStream& in)
  77347. : input (in),
  77348. dataBlockIsZero (false),
  77349. fresh (false),
  77350. finished (false)
  77351. {
  77352. currentBit = lastBit = lastByteIndex = 0;
  77353. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77354. firstcode = oldcode = 0;
  77355. clearCode = end_code = 0;
  77356. int imageWidth, imageHeight;
  77357. int transparent = -1;
  77358. if (! getSizeFromHeader (imageWidth, imageHeight))
  77359. return;
  77360. if ((imageWidth <= 0) || (imageHeight <= 0))
  77361. return;
  77362. unsigned char buf [16];
  77363. if (in.read (buf, 3) != 3)
  77364. return;
  77365. int numColours = 2 << (buf[0] & 7);
  77366. if ((buf[0] & 0x80) != 0)
  77367. readPalette (numColours);
  77368. for (;;)
  77369. {
  77370. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77371. break;
  77372. if (buf[0] == '!')
  77373. {
  77374. if (input.read (buf, 1) != 1)
  77375. break;
  77376. if (processExtension (buf[0], transparent) < 0)
  77377. break;
  77378. continue;
  77379. }
  77380. if (buf[0] != ',')
  77381. continue;
  77382. if (input.read (buf, 9) != 9)
  77383. break;
  77384. imageWidth = makeWord (buf[4], buf[5]);
  77385. imageHeight = makeWord (buf[6], buf[7]);
  77386. numColours = 2 << (buf[8] & 7);
  77387. if ((buf[8] & 0x80) != 0)
  77388. if (! readPalette (numColours))
  77389. break;
  77390. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77391. imageWidth, imageHeight, (transparent >= 0));
  77392. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77393. readImage ((buf[8] & 0x40) != 0, transparent);
  77394. break;
  77395. }
  77396. }
  77397. ~GIFLoader() {}
  77398. Image image;
  77399. private:
  77400. InputStream& input;
  77401. uint8 buffer [300];
  77402. uint8 palette [256][4];
  77403. bool dataBlockIsZero, fresh, finished;
  77404. int currentBit, lastBit, lastByteIndex;
  77405. int codeSize, setCodeSize;
  77406. int maxCode, maxCodeSize;
  77407. int firstcode, oldcode;
  77408. int clearCode, end_code;
  77409. enum { maxGifCode = 1 << 12 };
  77410. int table [2] [maxGifCode];
  77411. int stack [2 * maxGifCode];
  77412. int *sp;
  77413. bool getSizeFromHeader (int& w, int& h)
  77414. {
  77415. char b[8];
  77416. if (input.read (b, 6) == 6)
  77417. {
  77418. if ((strncmp ("GIF87a", b, 6) == 0)
  77419. || (strncmp ("GIF89a", b, 6) == 0))
  77420. {
  77421. if (input.read (b, 4) == 4)
  77422. {
  77423. w = makeWord (b[0], b[1]);
  77424. h = makeWord (b[2], b[3]);
  77425. return true;
  77426. }
  77427. }
  77428. }
  77429. return false;
  77430. }
  77431. bool readPalette (const int numCols)
  77432. {
  77433. unsigned char rgb[4];
  77434. for (int i = 0; i < numCols; ++i)
  77435. {
  77436. input.read (rgb, 3);
  77437. palette [i][0] = rgb[0];
  77438. palette [i][1] = rgb[1];
  77439. palette [i][2] = rgb[2];
  77440. palette [i][3] = 0xff;
  77441. }
  77442. return true;
  77443. }
  77444. int readDataBlock (unsigned char* dest)
  77445. {
  77446. unsigned char n;
  77447. if (input.read (&n, 1) == 1)
  77448. {
  77449. dataBlockIsZero = (n == 0);
  77450. if (dataBlockIsZero || (input.read (dest, n) == n))
  77451. return n;
  77452. }
  77453. return -1;
  77454. }
  77455. int processExtension (const int type, int& transparent)
  77456. {
  77457. unsigned char b [300];
  77458. int n = 0;
  77459. if (type == 0xf9)
  77460. {
  77461. n = readDataBlock (b);
  77462. if (n < 0)
  77463. return 1;
  77464. if ((b[0] & 0x1) != 0)
  77465. transparent = b[3];
  77466. }
  77467. do
  77468. {
  77469. n = readDataBlock (b);
  77470. }
  77471. while (n > 0);
  77472. return n;
  77473. }
  77474. int readLZWByte (const bool initialise, const int inputCodeSize)
  77475. {
  77476. int code, incode, i;
  77477. if (initialise)
  77478. {
  77479. setCodeSize = inputCodeSize;
  77480. codeSize = setCodeSize + 1;
  77481. clearCode = 1 << setCodeSize;
  77482. end_code = clearCode + 1;
  77483. maxCodeSize = 2 * clearCode;
  77484. maxCode = clearCode + 2;
  77485. getCode (0, true);
  77486. fresh = true;
  77487. for (i = 0; i < clearCode; ++i)
  77488. {
  77489. table[0][i] = 0;
  77490. table[1][i] = i;
  77491. }
  77492. for (; i < maxGifCode; ++i)
  77493. {
  77494. table[0][i] = 0;
  77495. table[1][i] = 0;
  77496. }
  77497. sp = stack;
  77498. return 0;
  77499. }
  77500. else if (fresh)
  77501. {
  77502. fresh = false;
  77503. do
  77504. {
  77505. firstcode = oldcode
  77506. = getCode (codeSize, false);
  77507. }
  77508. while (firstcode == clearCode);
  77509. return firstcode;
  77510. }
  77511. if (sp > stack)
  77512. return *--sp;
  77513. while ((code = getCode (codeSize, false)) >= 0)
  77514. {
  77515. if (code == clearCode)
  77516. {
  77517. for (i = 0; i < clearCode; ++i)
  77518. {
  77519. table[0][i] = 0;
  77520. table[1][i] = i;
  77521. }
  77522. for (; i < maxGifCode; ++i)
  77523. {
  77524. table[0][i] = 0;
  77525. table[1][i] = 0;
  77526. }
  77527. codeSize = setCodeSize + 1;
  77528. maxCodeSize = 2 * clearCode;
  77529. maxCode = clearCode + 2;
  77530. sp = stack;
  77531. firstcode = oldcode = getCode (codeSize, false);
  77532. return firstcode;
  77533. }
  77534. else if (code == end_code)
  77535. {
  77536. if (dataBlockIsZero)
  77537. return -2;
  77538. unsigned char buf [260];
  77539. int n;
  77540. while ((n = readDataBlock (buf)) > 0)
  77541. {}
  77542. if (n != 0)
  77543. return -2;
  77544. }
  77545. incode = code;
  77546. if (code >= maxCode)
  77547. {
  77548. *sp++ = firstcode;
  77549. code = oldcode;
  77550. }
  77551. while (code >= clearCode)
  77552. {
  77553. *sp++ = table[1][code];
  77554. if (code == table[0][code])
  77555. return -2;
  77556. code = table[0][code];
  77557. }
  77558. *sp++ = firstcode = table[1][code];
  77559. if ((code = maxCode) < maxGifCode)
  77560. {
  77561. table[0][code] = oldcode;
  77562. table[1][code] = firstcode;
  77563. ++maxCode;
  77564. if ((maxCode >= maxCodeSize)
  77565. && (maxCodeSize < maxGifCode))
  77566. {
  77567. maxCodeSize <<= 1;
  77568. ++codeSize;
  77569. }
  77570. }
  77571. oldcode = incode;
  77572. if (sp > stack)
  77573. return *--sp;
  77574. }
  77575. return code;
  77576. }
  77577. int getCode (const int codeSize_, const bool initialise)
  77578. {
  77579. if (initialise)
  77580. {
  77581. currentBit = 0;
  77582. lastBit = 0;
  77583. finished = false;
  77584. return 0;
  77585. }
  77586. if ((currentBit + codeSize_) >= lastBit)
  77587. {
  77588. if (finished)
  77589. return -1;
  77590. buffer[0] = buffer [lastByteIndex - 2];
  77591. buffer[1] = buffer [lastByteIndex - 1];
  77592. const int n = readDataBlock (&buffer[2]);
  77593. if (n == 0)
  77594. finished = true;
  77595. lastByteIndex = 2 + n;
  77596. currentBit = (currentBit - lastBit) + 16;
  77597. lastBit = (2 + n) * 8 ;
  77598. }
  77599. int result = 0;
  77600. int i = currentBit;
  77601. for (int j = 0; j < codeSize_; ++j)
  77602. {
  77603. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77604. ++i;
  77605. }
  77606. currentBit += codeSize_;
  77607. return result;
  77608. }
  77609. bool readImage (const int interlace, const int transparent)
  77610. {
  77611. unsigned char c;
  77612. if (input.read (&c, 1) != 1
  77613. || readLZWByte (true, c) < 0)
  77614. return false;
  77615. if (transparent >= 0)
  77616. {
  77617. palette [transparent][0] = 0;
  77618. palette [transparent][1] = 0;
  77619. palette [transparent][2] = 0;
  77620. palette [transparent][3] = 0;
  77621. }
  77622. int index;
  77623. int xpos = 0, ypos = 0, pass = 0;
  77624. const Image::BitmapData destData (image, true);
  77625. uint8* p = destData.data;
  77626. const bool hasAlpha = image.hasAlphaChannel();
  77627. while ((index = readLZWByte (false, c)) >= 0)
  77628. {
  77629. const uint8* const paletteEntry = palette [index];
  77630. if (hasAlpha)
  77631. {
  77632. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77633. paletteEntry[0],
  77634. paletteEntry[1],
  77635. paletteEntry[2]);
  77636. ((PixelARGB*) p)->premultiply();
  77637. }
  77638. else
  77639. {
  77640. ((PixelRGB*) p)->setARGB (0,
  77641. paletteEntry[0],
  77642. paletteEntry[1],
  77643. paletteEntry[2]);
  77644. }
  77645. p += destData.pixelStride;
  77646. ++xpos;
  77647. if (xpos == destData.width)
  77648. {
  77649. xpos = 0;
  77650. if (interlace)
  77651. {
  77652. switch (pass)
  77653. {
  77654. case 0:
  77655. case 1: ypos += 8; break;
  77656. case 2: ypos += 4; break;
  77657. case 3: ypos += 2; break;
  77658. }
  77659. while (ypos >= destData.height)
  77660. {
  77661. ++pass;
  77662. switch (pass)
  77663. {
  77664. case 1: ypos = 4; break;
  77665. case 2: ypos = 2; break;
  77666. case 3: ypos = 1; break;
  77667. default: return true;
  77668. }
  77669. }
  77670. }
  77671. else
  77672. {
  77673. ++ypos;
  77674. }
  77675. p = destData.getPixelPointer (xpos, ypos);
  77676. }
  77677. if (ypos >= destData.height)
  77678. break;
  77679. }
  77680. return true;
  77681. }
  77682. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77683. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77684. };
  77685. #endif
  77686. GIFImageFormat::GIFImageFormat() {}
  77687. GIFImageFormat::~GIFImageFormat() {}
  77688. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77689. bool GIFImageFormat::canUnderstand (InputStream& in)
  77690. {
  77691. char header [4];
  77692. return (in.read (header, sizeof (header)) == sizeof (header))
  77693. && header[0] == 'G'
  77694. && header[1] == 'I'
  77695. && header[2] == 'F';
  77696. }
  77697. const Image GIFImageFormat::decodeImage (InputStream& in)
  77698. {
  77699. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77700. return juce_loadWithCoreImage (in);
  77701. #else
  77702. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77703. return loader->image;
  77704. #endif
  77705. }
  77706. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77707. {
  77708. jassertfalse; // writing isn't implemented for GIFs!
  77709. return false;
  77710. }
  77711. END_JUCE_NAMESPACE
  77712. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77713. #endif
  77714. //==============================================================================
  77715. // some files include lots of library code, so leave them to the end to avoid cluttering
  77716. // up the build for the clean files.
  77717. #if JUCE_BUILD_CORE
  77718. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77719. namespace zlibNamespace
  77720. {
  77721. #if JUCE_INCLUDE_ZLIB_CODE
  77722. #undef OS_CODE
  77723. #undef fdopen
  77724. /*** Start of inlined file: zlib.h ***/
  77725. #ifndef ZLIB_H
  77726. #define ZLIB_H
  77727. /*** Start of inlined file: zconf.h ***/
  77728. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77729. #ifndef ZCONF_H
  77730. #define ZCONF_H
  77731. // *** Just a few hacks here to make it compile nicely with Juce..
  77732. #define Z_PREFIX 1
  77733. #undef __MACTYPES__
  77734. #ifdef _MSC_VER
  77735. #pragma warning (disable : 4131 4127 4244 4267)
  77736. #endif
  77737. /*
  77738. * If you *really* need a unique prefix for all types and library functions,
  77739. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77740. */
  77741. #ifdef Z_PREFIX
  77742. # define deflateInit_ z_deflateInit_
  77743. # define deflate z_deflate
  77744. # define deflateEnd z_deflateEnd
  77745. # define inflateInit_ z_inflateInit_
  77746. # define inflate z_inflate
  77747. # define inflateEnd z_inflateEnd
  77748. # define inflatePrime z_inflatePrime
  77749. # define inflateGetHeader z_inflateGetHeader
  77750. # define adler32_combine z_adler32_combine
  77751. # define crc32_combine z_crc32_combine
  77752. # define deflateInit2_ z_deflateInit2_
  77753. # define deflateSetDictionary z_deflateSetDictionary
  77754. # define deflateCopy z_deflateCopy
  77755. # define deflateReset z_deflateReset
  77756. # define deflateParams z_deflateParams
  77757. # define deflateBound z_deflateBound
  77758. # define deflatePrime z_deflatePrime
  77759. # define inflateInit2_ z_inflateInit2_
  77760. # define inflateSetDictionary z_inflateSetDictionary
  77761. # define inflateSync z_inflateSync
  77762. # define inflateSyncPoint z_inflateSyncPoint
  77763. # define inflateCopy z_inflateCopy
  77764. # define inflateReset z_inflateReset
  77765. # define inflateBack z_inflateBack
  77766. # define inflateBackEnd z_inflateBackEnd
  77767. # define compress z_compress
  77768. # define compress2 z_compress2
  77769. # define compressBound z_compressBound
  77770. # define uncompress z_uncompress
  77771. # define adler32 z_adler32
  77772. # define crc32 z_crc32
  77773. # define get_crc_table z_get_crc_table
  77774. # define zError z_zError
  77775. # define alloc_func z_alloc_func
  77776. # define free_func z_free_func
  77777. # define in_func z_in_func
  77778. # define out_func z_out_func
  77779. # define Byte z_Byte
  77780. # define uInt z_uInt
  77781. # define uLong z_uLong
  77782. # define Bytef z_Bytef
  77783. # define charf z_charf
  77784. # define intf z_intf
  77785. # define uIntf z_uIntf
  77786. # define uLongf z_uLongf
  77787. # define voidpf z_voidpf
  77788. # define voidp z_voidp
  77789. #endif
  77790. #if defined(__MSDOS__) && !defined(MSDOS)
  77791. # define MSDOS
  77792. #endif
  77793. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77794. # define OS2
  77795. #endif
  77796. #if defined(_WINDOWS) && !defined(WINDOWS)
  77797. # define WINDOWS
  77798. #endif
  77799. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77800. # ifndef WIN32
  77801. # define WIN32
  77802. # endif
  77803. #endif
  77804. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77805. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77806. # ifndef SYS16BIT
  77807. # define SYS16BIT
  77808. # endif
  77809. # endif
  77810. #endif
  77811. /*
  77812. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77813. * than 64k bytes at a time (needed on systems with 16-bit int).
  77814. */
  77815. #ifdef SYS16BIT
  77816. # define MAXSEG_64K
  77817. #endif
  77818. #ifdef MSDOS
  77819. # define UNALIGNED_OK
  77820. #endif
  77821. #ifdef __STDC_VERSION__
  77822. # ifndef STDC
  77823. # define STDC
  77824. # endif
  77825. # if __STDC_VERSION__ >= 199901L
  77826. # ifndef STDC99
  77827. # define STDC99
  77828. # endif
  77829. # endif
  77830. #endif
  77831. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77832. # define STDC
  77833. #endif
  77834. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77835. # define STDC
  77836. #endif
  77837. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77838. # define STDC
  77839. #endif
  77840. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77841. # define STDC
  77842. #endif
  77843. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77844. # define STDC
  77845. #endif
  77846. #ifndef STDC
  77847. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77848. # define const /* note: need a more gentle solution here */
  77849. # endif
  77850. #endif
  77851. /* Some Mac compilers merge all .h files incorrectly: */
  77852. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77853. # define NO_DUMMY_DECL
  77854. #endif
  77855. /* Maximum value for memLevel in deflateInit2 */
  77856. #ifndef MAX_MEM_LEVEL
  77857. # ifdef MAXSEG_64K
  77858. # define MAX_MEM_LEVEL 8
  77859. # else
  77860. # define MAX_MEM_LEVEL 9
  77861. # endif
  77862. #endif
  77863. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77864. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77865. * created by gzip. (Files created by minigzip can still be extracted by
  77866. * gzip.)
  77867. */
  77868. #ifndef MAX_WBITS
  77869. # define MAX_WBITS 15 /* 32K LZ77 window */
  77870. #endif
  77871. /* The memory requirements for deflate are (in bytes):
  77872. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77873. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77874. plus a few kilobytes for small objects. For example, if you want to reduce
  77875. the default memory requirements from 256K to 128K, compile with
  77876. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77877. Of course this will generally degrade compression (there's no free lunch).
  77878. The memory requirements for inflate are (in bytes) 1 << windowBits
  77879. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77880. for small objects.
  77881. */
  77882. /* Type declarations */
  77883. #ifndef OF /* function prototypes */
  77884. # ifdef STDC
  77885. # define OF(args) args
  77886. # else
  77887. # define OF(args) ()
  77888. # endif
  77889. #endif
  77890. /* The following definitions for FAR are needed only for MSDOS mixed
  77891. * model programming (small or medium model with some far allocations).
  77892. * This was tested only with MSC; for other MSDOS compilers you may have
  77893. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77894. * just define FAR to be empty.
  77895. */
  77896. #ifdef SYS16BIT
  77897. # if defined(M_I86SM) || defined(M_I86MM)
  77898. /* MSC small or medium model */
  77899. # define SMALL_MEDIUM
  77900. # ifdef _MSC_VER
  77901. # define FAR _far
  77902. # else
  77903. # define FAR far
  77904. # endif
  77905. # endif
  77906. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77907. /* Turbo C small or medium model */
  77908. # define SMALL_MEDIUM
  77909. # ifdef __BORLANDC__
  77910. # define FAR _far
  77911. # else
  77912. # define FAR far
  77913. # endif
  77914. # endif
  77915. #endif
  77916. #if defined(WINDOWS) || defined(WIN32)
  77917. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77918. * This is not mandatory, but it offers a little performance increase.
  77919. */
  77920. # ifdef ZLIB_DLL
  77921. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77922. # ifdef ZLIB_INTERNAL
  77923. # define ZEXTERN extern __declspec(dllexport)
  77924. # else
  77925. # define ZEXTERN extern __declspec(dllimport)
  77926. # endif
  77927. # endif
  77928. # endif /* ZLIB_DLL */
  77929. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77930. * define ZLIB_WINAPI.
  77931. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77932. */
  77933. # ifdef ZLIB_WINAPI
  77934. # ifdef FAR
  77935. # undef FAR
  77936. # endif
  77937. # include <windows.h>
  77938. /* No need for _export, use ZLIB.DEF instead. */
  77939. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77940. # define ZEXPORT WINAPI
  77941. # ifdef WIN32
  77942. # define ZEXPORTVA WINAPIV
  77943. # else
  77944. # define ZEXPORTVA FAR CDECL
  77945. # endif
  77946. # endif
  77947. #endif
  77948. #if defined (__BEOS__)
  77949. # ifdef ZLIB_DLL
  77950. # ifdef ZLIB_INTERNAL
  77951. # define ZEXPORT __declspec(dllexport)
  77952. # define ZEXPORTVA __declspec(dllexport)
  77953. # else
  77954. # define ZEXPORT __declspec(dllimport)
  77955. # define ZEXPORTVA __declspec(dllimport)
  77956. # endif
  77957. # endif
  77958. #endif
  77959. #ifndef ZEXTERN
  77960. # define ZEXTERN extern
  77961. #endif
  77962. #ifndef ZEXPORT
  77963. # define ZEXPORT
  77964. #endif
  77965. #ifndef ZEXPORTVA
  77966. # define ZEXPORTVA
  77967. #endif
  77968. #ifndef FAR
  77969. # define FAR
  77970. #endif
  77971. #if !defined(__MACTYPES__)
  77972. typedef unsigned char Byte; /* 8 bits */
  77973. #endif
  77974. typedef unsigned int uInt; /* 16 bits or more */
  77975. typedef unsigned long uLong; /* 32 bits or more */
  77976. #ifdef SMALL_MEDIUM
  77977. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77978. # define Bytef Byte FAR
  77979. #else
  77980. typedef Byte FAR Bytef;
  77981. #endif
  77982. typedef char FAR charf;
  77983. typedef int FAR intf;
  77984. typedef uInt FAR uIntf;
  77985. typedef uLong FAR uLongf;
  77986. #ifdef STDC
  77987. typedef void const *voidpc;
  77988. typedef void FAR *voidpf;
  77989. typedef void *voidp;
  77990. #else
  77991. typedef Byte const *voidpc;
  77992. typedef Byte FAR *voidpf;
  77993. typedef Byte *voidp;
  77994. #endif
  77995. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77996. # include <sys/types.h> /* for off_t */
  77997. # include <unistd.h> /* for SEEK_* and off_t */
  77998. # ifdef VMS
  77999. # include <unixio.h> /* for off_t */
  78000. # endif
  78001. # define z_off_t off_t
  78002. #endif
  78003. #ifndef SEEK_SET
  78004. # define SEEK_SET 0 /* Seek from beginning of file. */
  78005. # define SEEK_CUR 1 /* Seek from current position. */
  78006. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78007. #endif
  78008. #ifndef z_off_t
  78009. # define z_off_t long
  78010. #endif
  78011. #if defined(__OS400__)
  78012. # define NO_vsnprintf
  78013. #endif
  78014. #if defined(__MVS__)
  78015. # define NO_vsnprintf
  78016. # ifdef FAR
  78017. # undef FAR
  78018. # endif
  78019. #endif
  78020. /* MVS linker does not support external names larger than 8 bytes */
  78021. #if defined(__MVS__)
  78022. # pragma map(deflateInit_,"DEIN")
  78023. # pragma map(deflateInit2_,"DEIN2")
  78024. # pragma map(deflateEnd,"DEEND")
  78025. # pragma map(deflateBound,"DEBND")
  78026. # pragma map(inflateInit_,"ININ")
  78027. # pragma map(inflateInit2_,"ININ2")
  78028. # pragma map(inflateEnd,"INEND")
  78029. # pragma map(inflateSync,"INSY")
  78030. # pragma map(inflateSetDictionary,"INSEDI")
  78031. # pragma map(compressBound,"CMBND")
  78032. # pragma map(inflate_table,"INTABL")
  78033. # pragma map(inflate_fast,"INFA")
  78034. # pragma map(inflate_copyright,"INCOPY")
  78035. #endif
  78036. #endif /* ZCONF_H */
  78037. /*** End of inlined file: zconf.h ***/
  78038. #ifdef __cplusplus
  78039. //extern "C" {
  78040. #endif
  78041. #define ZLIB_VERSION "1.2.3"
  78042. #define ZLIB_VERNUM 0x1230
  78043. /*
  78044. The 'zlib' compression library provides in-memory compression and
  78045. decompression functions, including integrity checks of the uncompressed
  78046. data. This version of the library supports only one compression method
  78047. (deflation) but other algorithms will be added later and will have the same
  78048. stream interface.
  78049. Compression can be done in a single step if the buffers are large
  78050. enough (for example if an input file is mmap'ed), or can be done by
  78051. repeated calls of the compression function. In the latter case, the
  78052. application must provide more input and/or consume the output
  78053. (providing more output space) before each call.
  78054. The compressed data format used by default by the in-memory functions is
  78055. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78056. around a deflate stream, which is itself documented in RFC 1951.
  78057. The library also supports reading and writing files in gzip (.gz) format
  78058. with an interface similar to that of stdio using the functions that start
  78059. with "gz". The gzip format is different from the zlib format. gzip is a
  78060. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78061. This library can optionally read and write gzip streams in memory as well.
  78062. The zlib format was designed to be compact and fast for use in memory
  78063. and on communications channels. The gzip format was designed for single-
  78064. file compression on file systems, has a larger header than zlib to maintain
  78065. directory information, and uses a different, slower check method than zlib.
  78066. The library does not install any signal handler. The decoder checks
  78067. the consistency of the compressed data, so the library should never
  78068. crash even in case of corrupted input.
  78069. */
  78070. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78071. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78072. struct internal_state;
  78073. typedef struct z_stream_s {
  78074. Bytef *next_in; /* next input byte */
  78075. uInt avail_in; /* number of bytes available at next_in */
  78076. uLong total_in; /* total nb of input bytes read so far */
  78077. Bytef *next_out; /* next output byte should be put there */
  78078. uInt avail_out; /* remaining free space at next_out */
  78079. uLong total_out; /* total nb of bytes output so far */
  78080. char *msg; /* last error message, NULL if no error */
  78081. struct internal_state FAR *state; /* not visible by applications */
  78082. alloc_func zalloc; /* used to allocate the internal state */
  78083. free_func zfree; /* used to free the internal state */
  78084. voidpf opaque; /* private data object passed to zalloc and zfree */
  78085. int data_type; /* best guess about the data type: binary or text */
  78086. uLong adler; /* adler32 value of the uncompressed data */
  78087. uLong reserved; /* reserved for future use */
  78088. } z_stream;
  78089. typedef z_stream FAR *z_streamp;
  78090. /*
  78091. gzip header information passed to and from zlib routines. See RFC 1952
  78092. for more details on the meanings of these fields.
  78093. */
  78094. typedef struct gz_header_s {
  78095. int text; /* true if compressed data believed to be text */
  78096. uLong time; /* modification time */
  78097. int xflags; /* extra flags (not used when writing a gzip file) */
  78098. int os; /* operating system */
  78099. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78100. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78101. uInt extra_max; /* space at extra (only when reading header) */
  78102. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78103. uInt name_max; /* space at name (only when reading header) */
  78104. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78105. uInt comm_max; /* space at comment (only when reading header) */
  78106. int hcrc; /* true if there was or will be a header crc */
  78107. int done; /* true when done reading gzip header (not used
  78108. when writing a gzip file) */
  78109. } gz_header;
  78110. typedef gz_header FAR *gz_headerp;
  78111. /*
  78112. The application must update next_in and avail_in when avail_in has
  78113. dropped to zero. It must update next_out and avail_out when avail_out
  78114. has dropped to zero. The application must initialize zalloc, zfree and
  78115. opaque before calling the init function. All other fields are set by the
  78116. compression library and must not be updated by the application.
  78117. The opaque value provided by the application will be passed as the first
  78118. parameter for calls of zalloc and zfree. This can be useful for custom
  78119. memory management. The compression library attaches no meaning to the
  78120. opaque value.
  78121. zalloc must return Z_NULL if there is not enough memory for the object.
  78122. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78123. thread safe.
  78124. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78125. exactly 65536 bytes, but will not be required to allocate more than this
  78126. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78127. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78128. have their offset normalized to zero. The default allocation function
  78129. provided by this library ensures this (see zutil.c). To reduce memory
  78130. requirements and avoid any allocation of 64K objects, at the expense of
  78131. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78132. The fields total_in and total_out can be used for statistics or
  78133. progress reports. After compression, total_in holds the total size of
  78134. the uncompressed data and may be saved for use in the decompressor
  78135. (particularly if the decompressor wants to decompress everything in
  78136. a single step).
  78137. */
  78138. /* constants */
  78139. #define Z_NO_FLUSH 0
  78140. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78141. #define Z_SYNC_FLUSH 2
  78142. #define Z_FULL_FLUSH 3
  78143. #define Z_FINISH 4
  78144. #define Z_BLOCK 5
  78145. /* Allowed flush values; see deflate() and inflate() below for details */
  78146. #define Z_OK 0
  78147. #define Z_STREAM_END 1
  78148. #define Z_NEED_DICT 2
  78149. #define Z_ERRNO (-1)
  78150. #define Z_STREAM_ERROR (-2)
  78151. #define Z_DATA_ERROR (-3)
  78152. #define Z_MEM_ERROR (-4)
  78153. #define Z_BUF_ERROR (-5)
  78154. #define Z_VERSION_ERROR (-6)
  78155. /* Return codes for the compression/decompression functions. Negative
  78156. * values are errors, positive values are used for special but normal events.
  78157. */
  78158. #define Z_NO_COMPRESSION 0
  78159. #define Z_BEST_SPEED 1
  78160. #define Z_BEST_COMPRESSION 9
  78161. #define Z_DEFAULT_COMPRESSION (-1)
  78162. /* compression levels */
  78163. #define Z_FILTERED 1
  78164. #define Z_HUFFMAN_ONLY 2
  78165. #define Z_RLE 3
  78166. #define Z_FIXED 4
  78167. #define Z_DEFAULT_STRATEGY 0
  78168. /* compression strategy; see deflateInit2() below for details */
  78169. #define Z_BINARY 0
  78170. #define Z_TEXT 1
  78171. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78172. #define Z_UNKNOWN 2
  78173. /* Possible values of the data_type field (though see inflate()) */
  78174. #define Z_DEFLATED 8
  78175. /* The deflate compression method (the only one supported in this version) */
  78176. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78177. #define zlib_version zlibVersion()
  78178. /* for compatibility with versions < 1.0.2 */
  78179. /* basic functions */
  78180. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78181. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78182. If the first character differs, the library code actually used is
  78183. not compatible with the zlib.h header file used by the application.
  78184. This check is automatically made by deflateInit and inflateInit.
  78185. */
  78186. /*
  78187. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78188. Initializes the internal stream state for compression. The fields
  78189. zalloc, zfree and opaque must be initialized before by the caller.
  78190. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78191. use default allocation functions.
  78192. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78193. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78194. all (the input data is simply copied a block at a time).
  78195. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78196. compression (currently equivalent to level 6).
  78197. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78198. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78199. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78200. with the version assumed by the caller (ZLIB_VERSION).
  78201. msg is set to null if there is no error message. deflateInit does not
  78202. perform any compression: this will be done by deflate().
  78203. */
  78204. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78205. /*
  78206. deflate compresses as much data as possible, and stops when the input
  78207. buffer becomes empty or the output buffer becomes full. It may introduce some
  78208. output latency (reading input without producing any output) except when
  78209. forced to flush.
  78210. The detailed semantics are as follows. deflate performs one or both of the
  78211. following actions:
  78212. - Compress more input starting at next_in and update next_in and avail_in
  78213. accordingly. If not all input can be processed (because there is not
  78214. enough room in the output buffer), next_in and avail_in are updated and
  78215. processing will resume at this point for the next call of deflate().
  78216. - Provide more output starting at next_out and update next_out and avail_out
  78217. accordingly. This action is forced if the parameter flush is non zero.
  78218. Forcing flush frequently degrades the compression ratio, so this parameter
  78219. should be set only when necessary (in interactive applications).
  78220. Some output may be provided even if flush is not set.
  78221. Before the call of deflate(), the application should ensure that at least
  78222. one of the actions is possible, by providing more input and/or consuming
  78223. more output, and updating avail_in or avail_out accordingly; avail_out
  78224. should never be zero before the call. The application can consume the
  78225. compressed output when it wants, for example when the output buffer is full
  78226. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78227. and with zero avail_out, it must be called again after making room in the
  78228. output buffer because there might be more output pending.
  78229. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78230. decide how much data to accumualte before producing output, in order to
  78231. maximize compression.
  78232. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78233. flushed to the output buffer and the output is aligned on a byte boundary, so
  78234. that the decompressor can get all input data available so far. (In particular
  78235. avail_in is zero after the call if enough output space has been provided
  78236. before the call.) Flushing may degrade compression for some compression
  78237. algorithms and so it should be used only when necessary.
  78238. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78239. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78240. restart from this point if previous compressed data has been damaged or if
  78241. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78242. compression.
  78243. If deflate returns with avail_out == 0, this function must be called again
  78244. with the same value of the flush parameter and more output space (updated
  78245. avail_out), until the flush is complete (deflate returns with non-zero
  78246. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78247. avail_out is greater than six to avoid repeated flush markers due to
  78248. avail_out == 0 on return.
  78249. If the parameter flush is set to Z_FINISH, pending input is processed,
  78250. pending output is flushed and deflate returns with Z_STREAM_END if there
  78251. was enough output space; if deflate returns with Z_OK, this function must be
  78252. called again with Z_FINISH and more output space (updated avail_out) but no
  78253. more input data, until it returns with Z_STREAM_END or an error. After
  78254. deflate has returned Z_STREAM_END, the only possible operations on the
  78255. stream are deflateReset or deflateEnd.
  78256. Z_FINISH can be used immediately after deflateInit if all the compression
  78257. is to be done in a single step. In this case, avail_out must be at least
  78258. the value returned by deflateBound (see below). If deflate does not return
  78259. Z_STREAM_END, then it must be called again as described above.
  78260. deflate() sets strm->adler to the adler32 checksum of all input read
  78261. so far (that is, total_in bytes).
  78262. deflate() may update strm->data_type if it can make a good guess about
  78263. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78264. binary. This field is only for information purposes and does not affect
  78265. the compression algorithm in any manner.
  78266. deflate() returns Z_OK if some progress has been made (more input
  78267. processed or more output produced), Z_STREAM_END if all input has been
  78268. consumed and all output has been produced (only when flush is set to
  78269. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78270. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78271. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78272. fatal, and deflate() can be called again with more input and more output
  78273. space to continue compressing.
  78274. */
  78275. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78276. /*
  78277. All dynamically allocated data structures for this stream are freed.
  78278. This function discards any unprocessed input and does not flush any
  78279. pending output.
  78280. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78281. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78282. prematurely (some input or output was discarded). In the error case,
  78283. msg may be set but then points to a static string (which must not be
  78284. deallocated).
  78285. */
  78286. /*
  78287. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78288. Initializes the internal stream state for decompression. The fields
  78289. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78290. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78291. value depends on the compression method), inflateInit determines the
  78292. compression method from the zlib header and allocates all data structures
  78293. accordingly; otherwise the allocation will be deferred to the first call of
  78294. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78295. use default allocation functions.
  78296. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78297. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78298. version assumed by the caller. msg is set to null if there is no error
  78299. message. inflateInit does not perform any decompression apart from reading
  78300. the zlib header if present: this will be done by inflate(). (So next_in and
  78301. avail_in may be modified, but next_out and avail_out are unchanged.)
  78302. */
  78303. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78304. /*
  78305. inflate decompresses as much data as possible, and stops when the input
  78306. buffer becomes empty or the output buffer becomes full. It may introduce
  78307. some output latency (reading input without producing any output) except when
  78308. forced to flush.
  78309. The detailed semantics are as follows. inflate performs one or both of the
  78310. following actions:
  78311. - Decompress more input starting at next_in and update next_in and avail_in
  78312. accordingly. If not all input can be processed (because there is not
  78313. enough room in the output buffer), next_in is updated and processing
  78314. will resume at this point for the next call of inflate().
  78315. - Provide more output starting at next_out and update next_out and avail_out
  78316. accordingly. inflate() provides as much output as possible, until there
  78317. is no more input data or no more space in the output buffer (see below
  78318. about the flush parameter).
  78319. Before the call of inflate(), the application should ensure that at least
  78320. one of the actions is possible, by providing more input and/or consuming
  78321. more output, and updating the next_* and avail_* values accordingly.
  78322. The application can consume the uncompressed output when it wants, for
  78323. example when the output buffer is full (avail_out == 0), or after each
  78324. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78325. must be called again after making room in the output buffer because there
  78326. might be more output pending.
  78327. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78328. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78329. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78330. if and when it gets to the next deflate block boundary. When decoding the
  78331. zlib or gzip format, this will cause inflate() to return immediately after
  78332. the header and before the first block. When doing a raw inflate, inflate()
  78333. will go ahead and process the first block, and will return when it gets to
  78334. the end of that block, or when it runs out of data.
  78335. The Z_BLOCK option assists in appending to or combining deflate streams.
  78336. Also to assist in this, on return inflate() will set strm->data_type to the
  78337. number of unused bits in the last byte taken from strm->next_in, plus 64
  78338. if inflate() is currently decoding the last block in the deflate stream,
  78339. plus 128 if inflate() returned immediately after decoding an end-of-block
  78340. code or decoding the complete header up to just before the first byte of the
  78341. deflate stream. The end-of-block will not be indicated until all of the
  78342. uncompressed data from that block has been written to strm->next_out. The
  78343. number of unused bits may in general be greater than seven, except when
  78344. bit 7 of data_type is set, in which case the number of unused bits will be
  78345. less than eight.
  78346. inflate() should normally be called until it returns Z_STREAM_END or an
  78347. error. However if all decompression is to be performed in a single step
  78348. (a single call of inflate), the parameter flush should be set to
  78349. Z_FINISH. In this case all pending input is processed and all pending
  78350. output is flushed; avail_out must be large enough to hold all the
  78351. uncompressed data. (The size of the uncompressed data may have been saved
  78352. by the compressor for this purpose.) The next operation on this stream must
  78353. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78354. is never required, but can be used to inform inflate that a faster approach
  78355. may be used for the single inflate() call.
  78356. In this implementation, inflate() always flushes as much output as
  78357. possible to the output buffer, and always uses the faster approach on the
  78358. first call. So the only effect of the flush parameter in this implementation
  78359. is on the return value of inflate(), as noted below, or when it returns early
  78360. because Z_BLOCK is used.
  78361. If a preset dictionary is needed after this call (see inflateSetDictionary
  78362. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78363. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78364. strm->adler to the adler32 checksum of all output produced so far (that is,
  78365. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78366. below. At the end of the stream, inflate() checks that its computed adler32
  78367. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78368. only if the checksum is correct.
  78369. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78370. deflate data. The header type is detected automatically. Any information
  78371. contained in the gzip header is not retained, so applications that need that
  78372. information should instead use raw inflate, see inflateInit2() below, or
  78373. inflateBack() and perform their own processing of the gzip header and
  78374. trailer.
  78375. inflate() returns Z_OK if some progress has been made (more input processed
  78376. or more output produced), Z_STREAM_END if the end of the compressed data has
  78377. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78378. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78379. corrupted (input stream not conforming to the zlib format or incorrect check
  78380. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78381. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78382. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78383. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78384. inflate() can be called again with more input and more output space to
  78385. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78386. call inflateSync() to look for a good compression block if a partial recovery
  78387. of the data is desired.
  78388. */
  78389. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78390. /*
  78391. All dynamically allocated data structures for this stream are freed.
  78392. This function discards any unprocessed input and does not flush any
  78393. pending output.
  78394. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78395. was inconsistent. In the error case, msg may be set but then points to a
  78396. static string (which must not be deallocated).
  78397. */
  78398. /* Advanced functions */
  78399. /*
  78400. The following functions are needed only in some special applications.
  78401. */
  78402. /*
  78403. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78404. int level,
  78405. int method,
  78406. int windowBits,
  78407. int memLevel,
  78408. int strategy));
  78409. This is another version of deflateInit with more compression options. The
  78410. fields next_in, zalloc, zfree and opaque must be initialized before by
  78411. the caller.
  78412. The method parameter is the compression method. It must be Z_DEFLATED in
  78413. this version of the library.
  78414. The windowBits parameter is the base two logarithm of the window size
  78415. (the size of the history buffer). It should be in the range 8..15 for this
  78416. version of the library. Larger values of this parameter result in better
  78417. compression at the expense of memory usage. The default value is 15 if
  78418. deflateInit is used instead.
  78419. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78420. determines the window size. deflate() will then generate raw deflate data
  78421. with no zlib header or trailer, and will not compute an adler32 check value.
  78422. windowBits can also be greater than 15 for optional gzip encoding. Add
  78423. 16 to windowBits to write a simple gzip header and trailer around the
  78424. compressed data instead of a zlib wrapper. The gzip header will have no
  78425. file name, no extra data, no comment, no modification time (set to zero),
  78426. no header crc, and the operating system will be set to 255 (unknown). If a
  78427. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78428. The memLevel parameter specifies how much memory should be allocated
  78429. for the internal compression state. memLevel=1 uses minimum memory but
  78430. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78431. for optimal speed. The default value is 8. See zconf.h for total memory
  78432. usage as a function of windowBits and memLevel.
  78433. The strategy parameter is used to tune the compression algorithm. Use the
  78434. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78435. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78436. string match), or Z_RLE to limit match distances to one (run-length
  78437. encoding). Filtered data consists mostly of small values with a somewhat
  78438. random distribution. In this case, the compression algorithm is tuned to
  78439. compress them better. The effect of Z_FILTERED is to force more Huffman
  78440. coding and less string matching; it is somewhat intermediate between
  78441. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78442. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78443. parameter only affects the compression ratio but not the correctness of the
  78444. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78445. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78446. applications.
  78447. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78448. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78449. method). msg is set to null if there is no error message. deflateInit2 does
  78450. not perform any compression: this will be done by deflate().
  78451. */
  78452. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78453. const Bytef *dictionary,
  78454. uInt dictLength));
  78455. /*
  78456. Initializes the compression dictionary from the given byte sequence
  78457. without producing any compressed output. This function must be called
  78458. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78459. call of deflate. The compressor and decompressor must use exactly the same
  78460. dictionary (see inflateSetDictionary).
  78461. The dictionary should consist of strings (byte sequences) that are likely
  78462. to be encountered later in the data to be compressed, with the most commonly
  78463. used strings preferably put towards the end of the dictionary. Using a
  78464. dictionary is most useful when the data to be compressed is short and can be
  78465. predicted with good accuracy; the data can then be compressed better than
  78466. with the default empty dictionary.
  78467. Depending on the size of the compression data structures selected by
  78468. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78469. discarded, for example if the dictionary is larger than the window size in
  78470. deflate or deflate2. Thus the strings most likely to be useful should be
  78471. put at the end of the dictionary, not at the front. In addition, the
  78472. current implementation of deflate will use at most the window size minus
  78473. 262 bytes of the provided dictionary.
  78474. Upon return of this function, strm->adler is set to the adler32 value
  78475. of the dictionary; the decompressor may later use this value to determine
  78476. which dictionary has been used by the compressor. (The adler32 value
  78477. applies to the whole dictionary even if only a subset of the dictionary is
  78478. actually used by the compressor.) If a raw deflate was requested, then the
  78479. adler32 value is not computed and strm->adler is not set.
  78480. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78481. parameter is invalid (such as NULL dictionary) or the stream state is
  78482. inconsistent (for example if deflate has already been called for this stream
  78483. or if the compression method is bsort). deflateSetDictionary does not
  78484. perform any compression: this will be done by deflate().
  78485. */
  78486. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78487. z_streamp source));
  78488. /*
  78489. Sets the destination stream as a complete copy of the source stream.
  78490. This function can be useful when several compression strategies will be
  78491. tried, for example when there are several ways of pre-processing the input
  78492. data with a filter. The streams that will be discarded should then be freed
  78493. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78494. compression state which can be quite large, so this strategy is slow and
  78495. can consume lots of memory.
  78496. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78497. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78498. (such as zalloc being NULL). msg is left unchanged in both source and
  78499. destination.
  78500. */
  78501. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78502. /*
  78503. This function is equivalent to deflateEnd followed by deflateInit,
  78504. but does not free and reallocate all the internal compression state.
  78505. The stream will keep the same compression level and any other attributes
  78506. that may have been set by deflateInit2.
  78507. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78508. stream state was inconsistent (such as zalloc or state being NULL).
  78509. */
  78510. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78511. int level,
  78512. int strategy));
  78513. /*
  78514. Dynamically update the compression level and compression strategy. The
  78515. interpretation of level and strategy is as in deflateInit2. This can be
  78516. used to switch between compression and straight copy of the input data, or
  78517. to switch to a different kind of input data requiring a different
  78518. strategy. If the compression level is changed, the input available so far
  78519. is compressed with the old level (and may be flushed); the new level will
  78520. take effect only at the next call of deflate().
  78521. Before the call of deflateParams, the stream state must be set as for
  78522. a call of deflate(), since the currently available input may have to
  78523. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78524. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78525. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78526. if strm->avail_out was zero.
  78527. */
  78528. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78529. int good_length,
  78530. int max_lazy,
  78531. int nice_length,
  78532. int max_chain));
  78533. /*
  78534. Fine tune deflate's internal compression parameters. This should only be
  78535. used by someone who understands the algorithm used by zlib's deflate for
  78536. searching for the best matching string, and even then only by the most
  78537. fanatic optimizer trying to squeeze out the last compressed bit for their
  78538. specific input data. Read the deflate.c source code for the meaning of the
  78539. max_lazy, good_length, nice_length, and max_chain parameters.
  78540. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78541. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78542. */
  78543. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78544. uLong sourceLen));
  78545. /*
  78546. deflateBound() returns an upper bound on the compressed size after
  78547. deflation of sourceLen bytes. It must be called after deflateInit()
  78548. or deflateInit2(). This would be used to allocate an output buffer
  78549. for deflation in a single pass, and so would be called before deflate().
  78550. */
  78551. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78552. int bits,
  78553. int value));
  78554. /*
  78555. deflatePrime() inserts bits in the deflate output stream. The intent
  78556. is that this function is used to start off the deflate output with the
  78557. bits leftover from a previous deflate stream when appending to it. As such,
  78558. this function can only be used for raw deflate, and must be used before the
  78559. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78560. less than or equal to 16, and that many of the least significant bits of
  78561. value will be inserted in the output.
  78562. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78563. stream state was inconsistent.
  78564. */
  78565. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78566. gz_headerp head));
  78567. /*
  78568. deflateSetHeader() provides gzip header information for when a gzip
  78569. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78570. after deflateInit2() or deflateReset() and before the first call of
  78571. deflate(). The text, time, os, extra field, name, and comment information
  78572. in the provided gz_header structure are written to the gzip header (xflag is
  78573. ignored -- the extra flags are set according to the compression level). The
  78574. caller must assure that, if not Z_NULL, name and comment are terminated with
  78575. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78576. available there. If hcrc is true, a gzip header crc is included. Note that
  78577. the current versions of the command-line version of gzip (up through version
  78578. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78579. gzip file" and give up.
  78580. If deflateSetHeader is not used, the default gzip header has text false,
  78581. the time set to zero, and os set to 255, with no extra, name, or comment
  78582. fields. The gzip header is returned to the default state by deflateReset().
  78583. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78584. stream state was inconsistent.
  78585. */
  78586. /*
  78587. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78588. int windowBits));
  78589. This is another version of inflateInit with an extra parameter. The
  78590. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78591. before by the caller.
  78592. The windowBits parameter is the base two logarithm of the maximum window
  78593. size (the size of the history buffer). It should be in the range 8..15 for
  78594. this version of the library. The default value is 15 if inflateInit is used
  78595. instead. windowBits must be greater than or equal to the windowBits value
  78596. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78597. deflateInit2() was not used. If a compressed stream with a larger window
  78598. size is given as input, inflate() will return with the error code
  78599. Z_DATA_ERROR instead of trying to allocate a larger window.
  78600. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78601. determines the window size. inflate() will then process raw deflate data,
  78602. not looking for a zlib or gzip header, not generating a check value, and not
  78603. looking for any check values for comparison at the end of the stream. This
  78604. is for use with other formats that use the deflate compressed data format
  78605. such as zip. Those formats provide their own check values. If a custom
  78606. format is developed using the raw deflate format for compressed data, it is
  78607. recommended that a check value such as an adler32 or a crc32 be applied to
  78608. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78609. most applications, the zlib format should be used as is. Note that comments
  78610. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78611. windowBits can also be greater than 15 for optional gzip decoding. Add
  78612. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78613. detection, or add 16 to decode only the gzip format (the zlib format will
  78614. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78615. a crc32 instead of an adler32.
  78616. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78617. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78618. is set to null if there is no error message. inflateInit2 does not perform
  78619. any decompression apart from reading the zlib header if present: this will
  78620. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78621. and avail_out are unchanged.)
  78622. */
  78623. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78624. const Bytef *dictionary,
  78625. uInt dictLength));
  78626. /*
  78627. Initializes the decompression dictionary from the given uncompressed byte
  78628. sequence. This function must be called immediately after a call of inflate,
  78629. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78630. can be determined from the adler32 value returned by that call of inflate.
  78631. The compressor and decompressor must use exactly the same dictionary (see
  78632. deflateSetDictionary). For raw inflate, this function can be called
  78633. immediately after inflateInit2() or inflateReset() and before any call of
  78634. inflate() to set the dictionary. The application must insure that the
  78635. dictionary that was used for compression is provided.
  78636. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78637. parameter is invalid (such as NULL dictionary) or the stream state is
  78638. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78639. expected one (incorrect adler32 value). inflateSetDictionary does not
  78640. perform any decompression: this will be done by subsequent calls of
  78641. inflate().
  78642. */
  78643. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78644. /*
  78645. Skips invalid compressed data until a full flush point (see above the
  78646. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78647. available input is skipped. No output is provided.
  78648. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78649. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78650. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78651. case, the application may save the current current value of total_in which
  78652. indicates where valid compressed data was found. In the error case, the
  78653. application may repeatedly call inflateSync, providing more input each time,
  78654. until success or end of the input data.
  78655. */
  78656. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78657. z_streamp source));
  78658. /*
  78659. Sets the destination stream as a complete copy of the source stream.
  78660. This function can be useful when randomly accessing a large stream. The
  78661. first pass through the stream can periodically record the inflate state,
  78662. allowing restarting inflate at those points when randomly accessing the
  78663. stream.
  78664. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78665. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78666. (such as zalloc being NULL). msg is left unchanged in both source and
  78667. destination.
  78668. */
  78669. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78670. /*
  78671. This function is equivalent to inflateEnd followed by inflateInit,
  78672. but does not free and reallocate all the internal decompression state.
  78673. The stream will keep attributes that may have been set by inflateInit2.
  78674. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78675. stream state was inconsistent (such as zalloc or state being NULL).
  78676. */
  78677. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78678. int bits,
  78679. int value));
  78680. /*
  78681. This function inserts bits in the inflate input stream. The intent is
  78682. that this function is used to start inflating at a bit position in the
  78683. middle of a byte. The provided bits will be used before any bytes are used
  78684. from next_in. This function should only be used with raw inflate, and
  78685. should be used before the first inflate() call after inflateInit2() or
  78686. inflateReset(). bits must be less than or equal to 16, and that many of the
  78687. least significant bits of value will be inserted in the input.
  78688. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78689. stream state was inconsistent.
  78690. */
  78691. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78692. gz_headerp head));
  78693. /*
  78694. inflateGetHeader() requests that gzip header information be stored in the
  78695. provided gz_header structure. inflateGetHeader() may be called after
  78696. inflateInit2() or inflateReset(), and before the first call of inflate().
  78697. As inflate() processes the gzip stream, head->done is zero until the header
  78698. is completed, at which time head->done is set to one. If a zlib stream is
  78699. being decoded, then head->done is set to -1 to indicate that there will be
  78700. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78701. force inflate() to return immediately after header processing is complete
  78702. and before any actual data is decompressed.
  78703. The text, time, xflags, and os fields are filled in with the gzip header
  78704. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78705. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78706. contains the maximum number of bytes to write to extra. Once done is true,
  78707. extra_len contains the actual extra field length, and extra contains the
  78708. extra field, or that field truncated if extra_max is less than extra_len.
  78709. If name is not Z_NULL, then up to name_max characters are written there,
  78710. terminated with a zero unless the length is greater than name_max. If
  78711. comment is not Z_NULL, then up to comm_max characters are written there,
  78712. terminated with a zero unless the length is greater than comm_max. When
  78713. any of extra, name, or comment are not Z_NULL and the respective field is
  78714. not present in the header, then that field is set to Z_NULL to signal its
  78715. absence. This allows the use of deflateSetHeader() with the returned
  78716. structure to duplicate the header. However if those fields are set to
  78717. allocated memory, then the application will need to save those pointers
  78718. elsewhere so that they can be eventually freed.
  78719. If inflateGetHeader is not used, then the header information is simply
  78720. discarded. The header is always checked for validity, including the header
  78721. CRC if present. inflateReset() will reset the process to discard the header
  78722. information. The application would need to call inflateGetHeader() again to
  78723. retrieve the header from the next gzip stream.
  78724. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78725. stream state was inconsistent.
  78726. */
  78727. /*
  78728. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78729. unsigned char FAR *window));
  78730. Initialize the internal stream state for decompression using inflateBack()
  78731. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78732. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78733. derived memory allocation routines are used. windowBits is the base two
  78734. logarithm of the window size, in the range 8..15. window is a caller
  78735. supplied buffer of that size. Except for special applications where it is
  78736. assured that deflate was used with small window sizes, windowBits must be 15
  78737. and a 32K byte window must be supplied to be able to decompress general
  78738. deflate streams.
  78739. See inflateBack() for the usage of these routines.
  78740. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78741. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78742. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78743. match the version of the header file.
  78744. */
  78745. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78746. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78747. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78748. in_func in, void FAR *in_desc,
  78749. out_func out, void FAR *out_desc));
  78750. /*
  78751. inflateBack() does a raw inflate with a single call using a call-back
  78752. interface for input and output. This is more efficient than inflate() for
  78753. file i/o applications in that it avoids copying between the output and the
  78754. sliding window by simply making the window itself the output buffer. This
  78755. function trusts the application to not change the output buffer passed by
  78756. the output function, at least until inflateBack() returns.
  78757. inflateBackInit() must be called first to allocate the internal state
  78758. and to initialize the state with the user-provided window buffer.
  78759. inflateBack() may then be used multiple times to inflate a complete, raw
  78760. deflate stream with each call. inflateBackEnd() is then called to free
  78761. the allocated state.
  78762. A raw deflate stream is one with no zlib or gzip header or trailer.
  78763. This routine would normally be used in a utility that reads zip or gzip
  78764. files and writes out uncompressed files. The utility would decode the
  78765. header and process the trailer on its own, hence this routine expects
  78766. only the raw deflate stream to decompress. This is different from the
  78767. normal behavior of inflate(), which expects either a zlib or gzip header and
  78768. trailer around the deflate stream.
  78769. inflateBack() uses two subroutines supplied by the caller that are then
  78770. called by inflateBack() for input and output. inflateBack() calls those
  78771. routines until it reads a complete deflate stream and writes out all of the
  78772. uncompressed data, or until it encounters an error. The function's
  78773. parameters and return types are defined above in the in_func and out_func
  78774. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78775. number of bytes of provided input, and a pointer to that input in buf. If
  78776. there is no input available, in() must return zero--buf is ignored in that
  78777. case--and inflateBack() will return a buffer error. inflateBack() will call
  78778. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78779. should return zero on success, or non-zero on failure. If out() returns
  78780. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78781. are permitted to change the contents of the window provided to
  78782. inflateBackInit(), which is also the buffer that out() uses to write from.
  78783. The length written by out() will be at most the window size. Any non-zero
  78784. amount of input may be provided by in().
  78785. For convenience, inflateBack() can be provided input on the first call by
  78786. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78787. in() will be called. Therefore strm->next_in must be initialized before
  78788. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78789. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78790. must also be initialized, and then if strm->avail_in is not zero, input will
  78791. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78792. The in_desc and out_desc parameters of inflateBack() is passed as the
  78793. first parameter of in() and out() respectively when they are called. These
  78794. descriptors can be optionally used to pass any information that the caller-
  78795. supplied in() and out() functions need to do their job.
  78796. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78797. pass back any unused input that was provided by the last in() call. The
  78798. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78799. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78800. error in the deflate stream (in which case strm->msg is set to indicate the
  78801. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78802. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78803. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78804. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78805. out() returning non-zero. (in() will always be called before out(), so
  78806. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78807. that inflateBack() cannot return Z_OK.
  78808. */
  78809. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78810. /*
  78811. All memory allocated by inflateBackInit() is freed.
  78812. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78813. state was inconsistent.
  78814. */
  78815. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78816. /* Return flags indicating compile-time options.
  78817. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78818. 1.0: size of uInt
  78819. 3.2: size of uLong
  78820. 5.4: size of voidpf (pointer)
  78821. 7.6: size of z_off_t
  78822. Compiler, assembler, and debug options:
  78823. 8: DEBUG
  78824. 9: ASMV or ASMINF -- use ASM code
  78825. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78826. 11: 0 (reserved)
  78827. One-time table building (smaller code, but not thread-safe if true):
  78828. 12: BUILDFIXED -- build static block decoding tables when needed
  78829. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78830. 14,15: 0 (reserved)
  78831. Library content (indicates missing functionality):
  78832. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78833. deflate code when not needed)
  78834. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78835. and decode gzip streams (to avoid linking crc code)
  78836. 18-19: 0 (reserved)
  78837. Operation variations (changes in library functionality):
  78838. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78839. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78840. 22,23: 0 (reserved)
  78841. The sprintf variant used by gzprintf (zero is best):
  78842. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78843. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78844. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78845. Remainder:
  78846. 27-31: 0 (reserved)
  78847. */
  78848. /* utility functions */
  78849. /*
  78850. The following utility functions are implemented on top of the
  78851. basic stream-oriented functions. To simplify the interface, some
  78852. default options are assumed (compression level and memory usage,
  78853. standard memory allocation functions). The source code of these
  78854. utility functions can easily be modified if you need special options.
  78855. */
  78856. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78857. const Bytef *source, uLong sourceLen));
  78858. /*
  78859. Compresses the source buffer into the destination buffer. sourceLen is
  78860. the byte length of the source buffer. Upon entry, destLen is the total
  78861. size of the destination buffer, which must be at least the value returned
  78862. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78863. compressed buffer.
  78864. This function can be used to compress a whole file at once if the
  78865. input file is mmap'ed.
  78866. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78867. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78868. buffer.
  78869. */
  78870. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78871. const Bytef *source, uLong sourceLen,
  78872. int level));
  78873. /*
  78874. Compresses the source buffer into the destination buffer. The level
  78875. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78876. length of the source buffer. Upon entry, destLen is the total size of the
  78877. destination buffer, which must be at least the value returned by
  78878. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78879. compressed buffer.
  78880. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78881. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78882. Z_STREAM_ERROR if the level parameter is invalid.
  78883. */
  78884. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78885. /*
  78886. compressBound() returns an upper bound on the compressed size after
  78887. compress() or compress2() on sourceLen bytes. It would be used before
  78888. a compress() or compress2() call to allocate the destination buffer.
  78889. */
  78890. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78891. const Bytef *source, uLong sourceLen));
  78892. /*
  78893. Decompresses the source buffer into the destination buffer. sourceLen is
  78894. the byte length of the source buffer. Upon entry, destLen is the total
  78895. size of the destination buffer, which must be large enough to hold the
  78896. entire uncompressed data. (The size of the uncompressed data must have
  78897. been saved previously by the compressor and transmitted to the decompressor
  78898. by some mechanism outside the scope of this compression library.)
  78899. Upon exit, destLen is the actual size of the compressed buffer.
  78900. This function can be used to decompress a whole file at once if the
  78901. input file is mmap'ed.
  78902. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78903. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78904. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78905. */
  78906. typedef voidp gzFile;
  78907. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78908. /*
  78909. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78910. is as in fopen ("rb" or "wb") but can also include a compression level
  78911. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78912. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78913. as in "wb1R". (See the description of deflateInit2 for more information
  78914. about the strategy parameter.)
  78915. gzopen can be used to read a file which is not in gzip format; in this
  78916. case gzread will directly read from the file without decompression.
  78917. gzopen returns NULL if the file could not be opened or if there was
  78918. insufficient memory to allocate the (de)compression state; errno
  78919. can be checked to distinguish the two cases (if errno is zero, the
  78920. zlib error is Z_MEM_ERROR). */
  78921. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78922. /*
  78923. gzdopen() associates a gzFile with the file descriptor fd. File
  78924. descriptors are obtained from calls like open, dup, creat, pipe or
  78925. fileno (in the file has been previously opened with fopen).
  78926. The mode parameter is as in gzopen.
  78927. The next call of gzclose on the returned gzFile will also close the
  78928. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78929. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78930. gzdopen returns NULL if there was insufficient memory to allocate
  78931. the (de)compression state.
  78932. */
  78933. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78934. /*
  78935. Dynamically update the compression level or strategy. See the description
  78936. of deflateInit2 for the meaning of these parameters.
  78937. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78938. opened for writing.
  78939. */
  78940. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78941. /*
  78942. Reads the given number of uncompressed bytes from the compressed file.
  78943. If the input file was not in gzip format, gzread copies the given number
  78944. of bytes into the buffer.
  78945. gzread returns the number of uncompressed bytes actually read (0 for
  78946. end of file, -1 for error). */
  78947. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78948. voidpc buf, unsigned len));
  78949. /*
  78950. Writes the given number of uncompressed bytes into the compressed file.
  78951. gzwrite returns the number of uncompressed bytes actually written
  78952. (0 in case of error).
  78953. */
  78954. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78955. /*
  78956. Converts, formats, and writes the args to the compressed file under
  78957. control of the format string, as in fprintf. gzprintf returns the number of
  78958. uncompressed bytes actually written (0 in case of error). The number of
  78959. uncompressed bytes written is limited to 4095. The caller should assure that
  78960. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78961. return an error (0) with nothing written. In this case, there may also be a
  78962. buffer overflow with unpredictable consequences, which is possible only if
  78963. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78964. because the secure snprintf() or vsnprintf() functions were not available.
  78965. */
  78966. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78967. /*
  78968. Writes the given null-terminated string to the compressed file, excluding
  78969. the terminating null character.
  78970. gzputs returns the number of characters written, or -1 in case of error.
  78971. */
  78972. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78973. /*
  78974. Reads bytes from the compressed file until len-1 characters are read, or
  78975. a newline character is read and transferred to buf, or an end-of-file
  78976. condition is encountered. The string is then terminated with a null
  78977. character.
  78978. gzgets returns buf, or Z_NULL in case of error.
  78979. */
  78980. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78981. /*
  78982. Writes c, converted to an unsigned char, into the compressed file.
  78983. gzputc returns the value that was written, or -1 in case of error.
  78984. */
  78985. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78986. /*
  78987. Reads one byte from the compressed file. gzgetc returns this byte
  78988. or -1 in case of end of file or error.
  78989. */
  78990. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78991. /*
  78992. Push one character back onto the stream to be read again later.
  78993. Only one character of push-back is allowed. gzungetc() returns the
  78994. character pushed, or -1 on failure. gzungetc() will fail if a
  78995. character has been pushed but not read yet, or if c is -1. The pushed
  78996. character will be discarded if the stream is repositioned with gzseek()
  78997. or gzrewind().
  78998. */
  78999. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79000. /*
  79001. Flushes all pending output into the compressed file. The parameter
  79002. flush is as in the deflate() function. The return value is the zlib
  79003. error number (see function gzerror below). gzflush returns Z_OK if
  79004. the flush parameter is Z_FINISH and all output could be flushed.
  79005. gzflush should be called only when strictly necessary because it can
  79006. degrade compression.
  79007. */
  79008. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79009. z_off_t offset, int whence));
  79010. /*
  79011. Sets the starting position for the next gzread or gzwrite on the
  79012. given compressed file. The offset represents a number of bytes in the
  79013. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79014. the value SEEK_END is not supported.
  79015. If the file is opened for reading, this function is emulated but can be
  79016. extremely slow. If the file is opened for writing, only forward seeks are
  79017. supported; gzseek then compresses a sequence of zeroes up to the new
  79018. starting position.
  79019. gzseek returns the resulting offset location as measured in bytes from
  79020. the beginning of the uncompressed stream, or -1 in case of error, in
  79021. particular if the file is opened for writing and the new starting position
  79022. would be before the current position.
  79023. */
  79024. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79025. /*
  79026. Rewinds the given file. This function is supported only for reading.
  79027. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79028. */
  79029. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79030. /*
  79031. Returns the starting position for the next gzread or gzwrite on the
  79032. given compressed file. This position represents a number of bytes in the
  79033. uncompressed data stream.
  79034. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79035. */
  79036. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79037. /*
  79038. Returns 1 when EOF has previously been detected reading the given
  79039. input stream, otherwise zero.
  79040. */
  79041. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79042. /*
  79043. Returns 1 if file is being read directly without decompression, otherwise
  79044. zero.
  79045. */
  79046. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79047. /*
  79048. Flushes all pending output if necessary, closes the compressed file
  79049. and deallocates all the (de)compression state. The return value is the zlib
  79050. error number (see function gzerror below).
  79051. */
  79052. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79053. /*
  79054. Returns the error message for the last error which occurred on the
  79055. given compressed file. errnum is set to zlib error number. If an
  79056. error occurred in the file system and not in the compression library,
  79057. errnum is set to Z_ERRNO and the application may consult errno
  79058. to get the exact error code.
  79059. */
  79060. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79061. /*
  79062. Clears the error and end-of-file flags for file. This is analogous to the
  79063. clearerr() function in stdio. This is useful for continuing to read a gzip
  79064. file that is being written concurrently.
  79065. */
  79066. /* checksum functions */
  79067. /*
  79068. These functions are not related to compression but are exported
  79069. anyway because they might be useful in applications using the
  79070. compression library.
  79071. */
  79072. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79073. /*
  79074. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79075. return the updated checksum. If buf is NULL, this function returns
  79076. the required initial value for the checksum.
  79077. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79078. much faster. Usage example:
  79079. uLong adler = adler32(0L, Z_NULL, 0);
  79080. while (read_buffer(buffer, length) != EOF) {
  79081. adler = adler32(adler, buffer, length);
  79082. }
  79083. if (adler != original_adler) error();
  79084. */
  79085. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79086. z_off_t len2));
  79087. /*
  79088. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79089. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79090. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79091. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79092. */
  79093. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79094. /*
  79095. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79096. updated CRC-32. If buf is NULL, this function returns the required initial
  79097. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79098. performed within this function so it shouldn't be done by the application.
  79099. Usage example:
  79100. uLong crc = crc32(0L, Z_NULL, 0);
  79101. while (read_buffer(buffer, length) != EOF) {
  79102. crc = crc32(crc, buffer, length);
  79103. }
  79104. if (crc != original_crc) error();
  79105. */
  79106. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79107. /*
  79108. Combine two CRC-32 check values into one. For two sequences of bytes,
  79109. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79110. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79111. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79112. len2.
  79113. */
  79114. /* various hacks, don't look :) */
  79115. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79116. * and the compiler's view of z_stream:
  79117. */
  79118. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79119. const char *version, int stream_size));
  79120. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79121. const char *version, int stream_size));
  79122. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79123. int windowBits, int memLevel,
  79124. int strategy, const char *version,
  79125. int stream_size));
  79126. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79127. const char *version, int stream_size));
  79128. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79129. unsigned char FAR *window,
  79130. const char *version,
  79131. int stream_size));
  79132. #define deflateInit(strm, level) \
  79133. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79134. #define inflateInit(strm) \
  79135. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79136. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79137. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79138. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79139. #define inflateInit2(strm, windowBits) \
  79140. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79141. #define inflateBackInit(strm, windowBits, window) \
  79142. inflateBackInit_((strm), (windowBits), (window), \
  79143. ZLIB_VERSION, sizeof(z_stream))
  79144. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79145. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79146. #endif
  79147. ZEXTERN const char * ZEXPORT zError OF((int));
  79148. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79149. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79150. #ifdef __cplusplus
  79151. //}
  79152. #endif
  79153. #endif /* ZLIB_H */
  79154. /*** End of inlined file: zlib.h ***/
  79155. #undef OS_CODE
  79156. #else
  79157. #include <zlib.h>
  79158. #endif
  79159. }
  79160. BEGIN_JUCE_NAMESPACE
  79161. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79162. {
  79163. public:
  79164. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79165. : data (0),
  79166. dataSize (0),
  79167. compLevel (compressionLevel),
  79168. strategy (0),
  79169. setParams (true),
  79170. streamIsValid (false),
  79171. finished (false),
  79172. shouldFinish (false)
  79173. {
  79174. using namespace zlibNamespace;
  79175. zerostruct (stream);
  79176. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79177. windowBits != 0 ? windowBits : MAX_WBITS,
  79178. 8, strategy) == Z_OK);
  79179. }
  79180. ~GZIPCompressorHelper()
  79181. {
  79182. using namespace zlibNamespace;
  79183. if (streamIsValid)
  79184. deflateEnd (&stream);
  79185. }
  79186. bool needsInput() const throw()
  79187. {
  79188. return dataSize <= 0;
  79189. }
  79190. void setInput (const uint8* const newData, const int size) throw()
  79191. {
  79192. data = newData;
  79193. dataSize = size;
  79194. }
  79195. int doNextBlock (uint8* const dest, const int destSize) throw()
  79196. {
  79197. using namespace zlibNamespace;
  79198. if (streamIsValid)
  79199. {
  79200. stream.next_in = const_cast <uint8*> (data);
  79201. stream.next_out = dest;
  79202. stream.avail_in = dataSize;
  79203. stream.avail_out = destSize;
  79204. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79205. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79206. setParams = false;
  79207. switch (result)
  79208. {
  79209. case Z_STREAM_END:
  79210. finished = true;
  79211. // Deliberate fall-through..
  79212. case Z_OK:
  79213. data += dataSize - stream.avail_in;
  79214. dataSize = stream.avail_in;
  79215. return destSize - stream.avail_out;
  79216. default:
  79217. break;
  79218. }
  79219. }
  79220. return 0;
  79221. }
  79222. enum { gzipCompBufferSize = 32768 };
  79223. private:
  79224. zlibNamespace::z_stream stream;
  79225. const uint8* data;
  79226. int dataSize, compLevel, strategy;
  79227. bool setParams, streamIsValid;
  79228. public:
  79229. bool finished, shouldFinish;
  79230. };
  79231. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79232. int compressionLevel,
  79233. const bool deleteDestStream,
  79234. const int windowBits)
  79235. : destStream (destStream_),
  79236. streamToDelete (deleteDestStream ? destStream_ : 0),
  79237. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79238. {
  79239. if (compressionLevel < 1 || compressionLevel > 9)
  79240. compressionLevel = -1;
  79241. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79242. }
  79243. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79244. {
  79245. flush();
  79246. }
  79247. void GZIPCompressorOutputStream::flush()
  79248. {
  79249. if (! helper->finished)
  79250. {
  79251. helper->shouldFinish = true;
  79252. while (! helper->finished)
  79253. doNextBlock();
  79254. }
  79255. destStream->flush();
  79256. }
  79257. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79258. {
  79259. if (! helper->finished)
  79260. {
  79261. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79262. while (! helper->needsInput())
  79263. {
  79264. if (! doNextBlock())
  79265. return false;
  79266. }
  79267. }
  79268. return true;
  79269. }
  79270. bool GZIPCompressorOutputStream::doNextBlock()
  79271. {
  79272. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79273. return len <= 0 || destStream->write (buffer, len);
  79274. }
  79275. int64 GZIPCompressorOutputStream::getPosition()
  79276. {
  79277. return destStream->getPosition();
  79278. }
  79279. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79280. {
  79281. jassertfalse; // can't do it!
  79282. return false;
  79283. }
  79284. END_JUCE_NAMESPACE
  79285. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79286. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79287. #if JUCE_MSVC
  79288. #pragma warning (push)
  79289. #pragma warning (disable: 4309 4305)
  79290. #endif
  79291. namespace zlibNamespace
  79292. {
  79293. #if JUCE_INCLUDE_ZLIB_CODE
  79294. #undef OS_CODE
  79295. #undef fdopen
  79296. #define ZLIB_INTERNAL
  79297. #define NO_DUMMY_DECL
  79298. /*** Start of inlined file: adler32.c ***/
  79299. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79300. #define ZLIB_INTERNAL
  79301. #define BASE 65521UL /* largest prime smaller than 65536 */
  79302. #define NMAX 5552
  79303. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79304. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79305. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79306. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79307. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79308. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79309. /* use NO_DIVIDE if your processor does not do division in hardware */
  79310. #ifdef NO_DIVIDE
  79311. # define MOD(a) \
  79312. do { \
  79313. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79314. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79315. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79316. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79317. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79318. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79319. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79320. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79321. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79322. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79323. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79324. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79325. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79326. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79327. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79328. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79329. if (a >= BASE) a -= BASE; \
  79330. } while (0)
  79331. # define MOD4(a) \
  79332. do { \
  79333. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79334. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79335. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79336. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79337. if (a >= BASE) a -= BASE; \
  79338. } while (0)
  79339. #else
  79340. # define MOD(a) a %= BASE
  79341. # define MOD4(a) a %= BASE
  79342. #endif
  79343. /* ========================================================================= */
  79344. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79345. {
  79346. unsigned long sum2;
  79347. unsigned n;
  79348. /* split Adler-32 into component sums */
  79349. sum2 = (adler >> 16) & 0xffff;
  79350. adler &= 0xffff;
  79351. /* in case user likes doing a byte at a time, keep it fast */
  79352. if (len == 1) {
  79353. adler += buf[0];
  79354. if (adler >= BASE)
  79355. adler -= BASE;
  79356. sum2 += adler;
  79357. if (sum2 >= BASE)
  79358. sum2 -= BASE;
  79359. return adler | (sum2 << 16);
  79360. }
  79361. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79362. if (buf == Z_NULL)
  79363. return 1L;
  79364. /* in case short lengths are provided, keep it somewhat fast */
  79365. if (len < 16) {
  79366. while (len--) {
  79367. adler += *buf++;
  79368. sum2 += adler;
  79369. }
  79370. if (adler >= BASE)
  79371. adler -= BASE;
  79372. MOD4(sum2); /* only added so many BASE's */
  79373. return adler | (sum2 << 16);
  79374. }
  79375. /* do length NMAX blocks -- requires just one modulo operation */
  79376. while (len >= NMAX) {
  79377. len -= NMAX;
  79378. n = NMAX / 16; /* NMAX is divisible by 16 */
  79379. do {
  79380. DO16(buf); /* 16 sums unrolled */
  79381. buf += 16;
  79382. } while (--n);
  79383. MOD(adler);
  79384. MOD(sum2);
  79385. }
  79386. /* do remaining bytes (less than NMAX, still just one modulo) */
  79387. if (len) { /* avoid modulos if none remaining */
  79388. while (len >= 16) {
  79389. len -= 16;
  79390. DO16(buf);
  79391. buf += 16;
  79392. }
  79393. while (len--) {
  79394. adler += *buf++;
  79395. sum2 += adler;
  79396. }
  79397. MOD(adler);
  79398. MOD(sum2);
  79399. }
  79400. /* return recombined sums */
  79401. return adler | (sum2 << 16);
  79402. }
  79403. /* ========================================================================= */
  79404. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79405. {
  79406. unsigned long sum1;
  79407. unsigned long sum2;
  79408. unsigned rem;
  79409. /* the derivation of this formula is left as an exercise for the reader */
  79410. rem = (unsigned)(len2 % BASE);
  79411. sum1 = adler1 & 0xffff;
  79412. sum2 = rem * sum1;
  79413. MOD(sum2);
  79414. sum1 += (adler2 & 0xffff) + BASE - 1;
  79415. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79416. if (sum1 > BASE) sum1 -= BASE;
  79417. if (sum1 > BASE) sum1 -= BASE;
  79418. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79419. if (sum2 > BASE) sum2 -= BASE;
  79420. return sum1 | (sum2 << 16);
  79421. }
  79422. /*** End of inlined file: adler32.c ***/
  79423. /*** Start of inlined file: compress.c ***/
  79424. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79425. #define ZLIB_INTERNAL
  79426. /* ===========================================================================
  79427. Compresses the source buffer into the destination buffer. The level
  79428. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79429. length of the source buffer. Upon entry, destLen is the total size of the
  79430. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79431. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79432. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79433. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79434. Z_STREAM_ERROR if the level parameter is invalid.
  79435. */
  79436. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79437. uLong sourceLen, int level)
  79438. {
  79439. z_stream stream;
  79440. int err;
  79441. stream.next_in = (Bytef*)source;
  79442. stream.avail_in = (uInt)sourceLen;
  79443. #ifdef MAXSEG_64K
  79444. /* Check for source > 64K on 16-bit machine: */
  79445. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79446. #endif
  79447. stream.next_out = dest;
  79448. stream.avail_out = (uInt)*destLen;
  79449. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79450. stream.zalloc = (alloc_func)0;
  79451. stream.zfree = (free_func)0;
  79452. stream.opaque = (voidpf)0;
  79453. err = deflateInit(&stream, level);
  79454. if (err != Z_OK) return err;
  79455. err = deflate(&stream, Z_FINISH);
  79456. if (err != Z_STREAM_END) {
  79457. deflateEnd(&stream);
  79458. return err == Z_OK ? Z_BUF_ERROR : err;
  79459. }
  79460. *destLen = stream.total_out;
  79461. err = deflateEnd(&stream);
  79462. return err;
  79463. }
  79464. /* ===========================================================================
  79465. */
  79466. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79467. {
  79468. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79469. }
  79470. /* ===========================================================================
  79471. If the default memLevel or windowBits for deflateInit() is changed, then
  79472. this function needs to be updated.
  79473. */
  79474. uLong ZEXPORT compressBound (uLong sourceLen)
  79475. {
  79476. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79477. }
  79478. /*** End of inlined file: compress.c ***/
  79479. #undef DO1
  79480. #undef DO8
  79481. /*** Start of inlined file: crc32.c ***/
  79482. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79483. /*
  79484. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79485. protection on the static variables used to control the first-use generation
  79486. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79487. first call get_crc_table() to initialize the tables before allowing more than
  79488. one thread to use crc32().
  79489. */
  79490. #ifdef MAKECRCH
  79491. # include <stdio.h>
  79492. # ifndef DYNAMIC_CRC_TABLE
  79493. # define DYNAMIC_CRC_TABLE
  79494. # endif /* !DYNAMIC_CRC_TABLE */
  79495. #endif /* MAKECRCH */
  79496. /*** Start of inlined file: zutil.h ***/
  79497. /* WARNING: this file should *not* be used by applications. It is
  79498. part of the implementation of the compression library and is
  79499. subject to change. Applications should only use zlib.h.
  79500. */
  79501. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79502. #ifndef ZUTIL_H
  79503. #define ZUTIL_H
  79504. #define ZLIB_INTERNAL
  79505. #ifdef STDC
  79506. # ifndef _WIN32_WCE
  79507. # include <stddef.h>
  79508. # endif
  79509. # include <string.h>
  79510. # include <stdlib.h>
  79511. #endif
  79512. #ifdef NO_ERRNO_H
  79513. # ifdef _WIN32_WCE
  79514. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79515. * errno. We define it as a global variable to simplify porting.
  79516. * Its value is always 0 and should not be used. We rename it to
  79517. * avoid conflict with other libraries that use the same workaround.
  79518. */
  79519. # define errno z_errno
  79520. # endif
  79521. extern int errno;
  79522. #else
  79523. # ifndef _WIN32_WCE
  79524. # include <errno.h>
  79525. # endif
  79526. #endif
  79527. #ifndef local
  79528. # define local static
  79529. #endif
  79530. /* compile with -Dlocal if your debugger can't find static symbols */
  79531. typedef unsigned char uch;
  79532. typedef uch FAR uchf;
  79533. typedef unsigned short ush;
  79534. typedef ush FAR ushf;
  79535. typedef unsigned long ulg;
  79536. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79537. /* (size given to avoid silly warnings with Visual C++) */
  79538. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79539. #define ERR_RETURN(strm,err) \
  79540. return (strm->msg = (char*)ERR_MSG(err), (err))
  79541. /* To be used only when the state is known to be valid */
  79542. /* common constants */
  79543. #ifndef DEF_WBITS
  79544. # define DEF_WBITS MAX_WBITS
  79545. #endif
  79546. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79547. #if MAX_MEM_LEVEL >= 8
  79548. # define DEF_MEM_LEVEL 8
  79549. #else
  79550. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79551. #endif
  79552. /* default memLevel */
  79553. #define STORED_BLOCK 0
  79554. #define STATIC_TREES 1
  79555. #define DYN_TREES 2
  79556. /* The three kinds of block type */
  79557. #define MIN_MATCH 3
  79558. #define MAX_MATCH 258
  79559. /* The minimum and maximum match lengths */
  79560. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79561. /* target dependencies */
  79562. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79563. # define OS_CODE 0x00
  79564. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79565. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79566. /* Allow compilation with ANSI keywords only enabled */
  79567. void _Cdecl farfree( void *block );
  79568. void *_Cdecl farmalloc( unsigned long nbytes );
  79569. # else
  79570. # include <alloc.h>
  79571. # endif
  79572. # else /* MSC or DJGPP */
  79573. # include <malloc.h>
  79574. # endif
  79575. #endif
  79576. #ifdef AMIGA
  79577. # define OS_CODE 0x01
  79578. #endif
  79579. #if defined(VAXC) || defined(VMS)
  79580. # define OS_CODE 0x02
  79581. # define F_OPEN(name, mode) \
  79582. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79583. #endif
  79584. #if defined(ATARI) || defined(atarist)
  79585. # define OS_CODE 0x05
  79586. #endif
  79587. #ifdef OS2
  79588. # define OS_CODE 0x06
  79589. # ifdef M_I86
  79590. #include <malloc.h>
  79591. # endif
  79592. #endif
  79593. #if defined(MACOS) || TARGET_OS_MAC
  79594. # define OS_CODE 0x07
  79595. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79596. # include <unix.h> /* for fdopen */
  79597. # else
  79598. # ifndef fdopen
  79599. # define fdopen(fd,mode) NULL /* No fdopen() */
  79600. # endif
  79601. # endif
  79602. #endif
  79603. #ifdef TOPS20
  79604. # define OS_CODE 0x0a
  79605. #endif
  79606. #ifdef WIN32
  79607. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79608. # define OS_CODE 0x0b
  79609. # endif
  79610. #endif
  79611. #ifdef __50SERIES /* Prime/PRIMOS */
  79612. # define OS_CODE 0x0f
  79613. #endif
  79614. #if defined(_BEOS_) || defined(RISCOS)
  79615. # define fdopen(fd,mode) NULL /* No fdopen() */
  79616. #endif
  79617. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79618. # if defined(_WIN32_WCE)
  79619. # define fdopen(fd,mode) NULL /* No fdopen() */
  79620. # ifndef _PTRDIFF_T_DEFINED
  79621. typedef int ptrdiff_t;
  79622. # define _PTRDIFF_T_DEFINED
  79623. # endif
  79624. # else
  79625. # define fdopen(fd,type) _fdopen(fd,type)
  79626. # endif
  79627. #endif
  79628. /* common defaults */
  79629. #ifndef OS_CODE
  79630. # define OS_CODE 0x03 /* assume Unix */
  79631. #endif
  79632. #ifndef F_OPEN
  79633. # define F_OPEN(name, mode) fopen((name), (mode))
  79634. #endif
  79635. /* functions */
  79636. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79637. # ifndef HAVE_VSNPRINTF
  79638. # define HAVE_VSNPRINTF
  79639. # endif
  79640. #endif
  79641. #if defined(__CYGWIN__)
  79642. # ifndef HAVE_VSNPRINTF
  79643. # define HAVE_VSNPRINTF
  79644. # endif
  79645. #endif
  79646. #ifndef HAVE_VSNPRINTF
  79647. # ifdef MSDOS
  79648. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79649. but for now we just assume it doesn't. */
  79650. # define NO_vsnprintf
  79651. # endif
  79652. # ifdef __TURBOC__
  79653. # define NO_vsnprintf
  79654. # endif
  79655. # ifdef WIN32
  79656. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79657. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79658. # define vsnprintf _vsnprintf
  79659. # endif
  79660. # endif
  79661. # ifdef __SASC
  79662. # define NO_vsnprintf
  79663. # endif
  79664. #endif
  79665. #ifdef VMS
  79666. # define NO_vsnprintf
  79667. #endif
  79668. #if defined(pyr)
  79669. # define NO_MEMCPY
  79670. #endif
  79671. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79672. /* Use our own functions for small and medium model with MSC <= 5.0.
  79673. * You may have to use the same strategy for Borland C (untested).
  79674. * The __SC__ check is for Symantec.
  79675. */
  79676. # define NO_MEMCPY
  79677. #endif
  79678. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79679. # define HAVE_MEMCPY
  79680. #endif
  79681. #ifdef HAVE_MEMCPY
  79682. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79683. # define zmemcpy _fmemcpy
  79684. # define zmemcmp _fmemcmp
  79685. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79686. # else
  79687. # define zmemcpy memcpy
  79688. # define zmemcmp memcmp
  79689. # define zmemzero(dest, len) memset(dest, 0, len)
  79690. # endif
  79691. #else
  79692. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79693. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79694. extern void zmemzero OF((Bytef* dest, uInt len));
  79695. #endif
  79696. /* Diagnostic functions */
  79697. #ifdef DEBUG
  79698. # include <stdio.h>
  79699. extern int z_verbose;
  79700. extern void z_error OF((const char *m));
  79701. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79702. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79703. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79704. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79705. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79706. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79707. #else
  79708. # define Assert(cond,msg)
  79709. # define Trace(x)
  79710. # define Tracev(x)
  79711. # define Tracevv(x)
  79712. # define Tracec(c,x)
  79713. # define Tracecv(c,x)
  79714. #endif
  79715. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79716. void zcfree OF((voidpf opaque, voidpf ptr));
  79717. #define ZALLOC(strm, items, size) \
  79718. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79719. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79720. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79721. #endif /* ZUTIL_H */
  79722. /*** End of inlined file: zutil.h ***/
  79723. /* for STDC and FAR definitions */
  79724. #define local static
  79725. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79726. #ifndef NOBYFOUR
  79727. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79728. # include <limits.h>
  79729. # define BYFOUR
  79730. # if (UINT_MAX == 0xffffffffUL)
  79731. typedef unsigned int u4;
  79732. # else
  79733. # if (ULONG_MAX == 0xffffffffUL)
  79734. typedef unsigned long u4;
  79735. # else
  79736. # if (USHRT_MAX == 0xffffffffUL)
  79737. typedef unsigned short u4;
  79738. # else
  79739. # undef BYFOUR /* can't find a four-byte integer type! */
  79740. # endif
  79741. # endif
  79742. # endif
  79743. # endif /* STDC */
  79744. #endif /* !NOBYFOUR */
  79745. /* Definitions for doing the crc four data bytes at a time. */
  79746. #ifdef BYFOUR
  79747. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79748. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79749. local unsigned long crc32_little OF((unsigned long,
  79750. const unsigned char FAR *, unsigned));
  79751. local unsigned long crc32_big OF((unsigned long,
  79752. const unsigned char FAR *, unsigned));
  79753. # define TBLS 8
  79754. #else
  79755. # define TBLS 1
  79756. #endif /* BYFOUR */
  79757. /* Local functions for crc concatenation */
  79758. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79759. unsigned long vec));
  79760. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79761. #ifdef DYNAMIC_CRC_TABLE
  79762. local volatile int crc_table_empty = 1;
  79763. local unsigned long FAR crc_table[TBLS][256];
  79764. local void make_crc_table OF((void));
  79765. #ifdef MAKECRCH
  79766. local void write_table OF((FILE *, const unsigned long FAR *));
  79767. #endif /* MAKECRCH */
  79768. /*
  79769. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79770. 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.
  79771. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79772. with the lowest powers in the most significant bit. Then adding polynomials
  79773. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79774. one. If we call the above polynomial p, and represent a byte as the
  79775. polynomial q, also with the lowest power in the most significant bit (so the
  79776. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79777. where a mod b means the remainder after dividing a by b.
  79778. This calculation is done using the shift-register method of multiplying and
  79779. taking the remainder. The register is initialized to zero, and for each
  79780. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79781. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79782. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79783. out is a one). We start with the highest power (least significant bit) of
  79784. q and repeat for all eight bits of q.
  79785. The first table is simply the CRC of all possible eight bit values. This is
  79786. all the information needed to generate CRCs on data a byte at a time for all
  79787. combinations of CRC register values and incoming bytes. The remaining tables
  79788. allow for word-at-a-time CRC calculation for both big-endian and little-
  79789. endian machines, where a word is four bytes.
  79790. */
  79791. local void make_crc_table()
  79792. {
  79793. unsigned long c;
  79794. int n, k;
  79795. unsigned long poly; /* polynomial exclusive-or pattern */
  79796. /* terms of polynomial defining this crc (except x^32): */
  79797. static volatile int first = 1; /* flag to limit concurrent making */
  79798. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79799. /* See if another task is already doing this (not thread-safe, but better
  79800. than nothing -- significantly reduces duration of vulnerability in
  79801. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79802. if (first) {
  79803. first = 0;
  79804. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79805. poly = 0UL;
  79806. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79807. poly |= 1UL << (31 - p[n]);
  79808. /* generate a crc for every 8-bit value */
  79809. for (n = 0; n < 256; n++) {
  79810. c = (unsigned long)n;
  79811. for (k = 0; k < 8; k++)
  79812. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79813. crc_table[0][n] = c;
  79814. }
  79815. #ifdef BYFOUR
  79816. /* generate crc for each value followed by one, two, and three zeros,
  79817. and then the byte reversal of those as well as the first table */
  79818. for (n = 0; n < 256; n++) {
  79819. c = crc_table[0][n];
  79820. crc_table[4][n] = REV(c);
  79821. for (k = 1; k < 4; k++) {
  79822. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79823. crc_table[k][n] = c;
  79824. crc_table[k + 4][n] = REV(c);
  79825. }
  79826. }
  79827. #endif /* BYFOUR */
  79828. crc_table_empty = 0;
  79829. }
  79830. else { /* not first */
  79831. /* wait for the other guy to finish (not efficient, but rare) */
  79832. while (crc_table_empty)
  79833. ;
  79834. }
  79835. #ifdef MAKECRCH
  79836. /* write out CRC tables to crc32.h */
  79837. {
  79838. FILE *out;
  79839. out = fopen("crc32.h", "w");
  79840. if (out == NULL) return;
  79841. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79842. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79843. fprintf(out, "local const unsigned long FAR ");
  79844. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79845. write_table(out, crc_table[0]);
  79846. # ifdef BYFOUR
  79847. fprintf(out, "#ifdef BYFOUR\n");
  79848. for (k = 1; k < 8; k++) {
  79849. fprintf(out, " },\n {\n");
  79850. write_table(out, crc_table[k]);
  79851. }
  79852. fprintf(out, "#endif\n");
  79853. # endif /* BYFOUR */
  79854. fprintf(out, " }\n};\n");
  79855. fclose(out);
  79856. }
  79857. #endif /* MAKECRCH */
  79858. }
  79859. #ifdef MAKECRCH
  79860. local void write_table(out, table)
  79861. FILE *out;
  79862. const unsigned long FAR *table;
  79863. {
  79864. int n;
  79865. for (n = 0; n < 256; n++)
  79866. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79867. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79868. }
  79869. #endif /* MAKECRCH */
  79870. #else /* !DYNAMIC_CRC_TABLE */
  79871. /* ========================================================================
  79872. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79873. */
  79874. /*** Start of inlined file: crc32.h ***/
  79875. local const unsigned long FAR crc_table[TBLS][256] =
  79876. {
  79877. {
  79878. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79879. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79880. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79881. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79882. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79883. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79884. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79885. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79886. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79887. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79888. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79889. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79890. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79891. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79892. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79893. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79894. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79895. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79896. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79897. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79898. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79899. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79900. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79901. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79902. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79903. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79904. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79905. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79906. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79907. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79908. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79909. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79910. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79911. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79912. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79913. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79914. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79915. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79916. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79917. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79918. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79919. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79920. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79921. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79922. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79923. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79924. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79925. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79926. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79927. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79928. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79929. 0x2d02ef8dUL
  79930. #ifdef BYFOUR
  79931. },
  79932. {
  79933. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79934. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79935. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79936. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79937. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79938. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79939. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79940. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79941. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79942. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79943. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79944. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79945. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79946. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79947. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79948. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79949. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79950. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79951. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79952. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79953. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79954. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79955. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79956. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79957. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79958. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79959. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79960. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79961. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79962. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79963. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79964. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79965. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79966. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79967. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79968. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79969. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79970. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79971. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79972. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79973. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79974. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79975. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79976. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79977. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79978. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79979. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79980. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79981. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79982. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79983. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79984. 0x9324fd72UL
  79985. },
  79986. {
  79987. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79988. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79989. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79990. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79991. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79992. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79993. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79994. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79995. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79996. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79997. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79998. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79999. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80000. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80001. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80002. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80003. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80004. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80005. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80006. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80007. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80008. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80009. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80010. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80011. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80012. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80013. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80014. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80015. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80016. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80017. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80018. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80019. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80020. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80021. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80022. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80023. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80024. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80025. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80026. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80027. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80028. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80029. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80030. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80031. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80032. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80033. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80034. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80035. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80036. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80037. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80038. 0xbe9834edUL
  80039. },
  80040. {
  80041. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80042. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80043. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80044. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80045. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80046. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80047. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80048. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80049. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80050. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80051. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80052. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80053. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80054. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80055. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80056. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80057. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80058. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80059. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80060. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80061. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80062. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80063. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80064. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80065. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80066. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80067. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80068. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80069. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80070. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80071. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80072. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80073. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80074. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80075. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80076. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80077. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80078. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80079. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80080. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80081. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80082. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80083. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80084. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80085. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80086. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80087. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80088. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80089. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80090. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80091. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80092. 0xde0506f1UL
  80093. },
  80094. {
  80095. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80096. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80097. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80098. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80099. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80100. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80101. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80102. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80103. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80104. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80105. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80106. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80107. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80108. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80109. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80110. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80111. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80112. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80113. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80114. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80115. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80116. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80117. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80118. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80119. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80120. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80121. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80122. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80123. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80124. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80125. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80126. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80127. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80128. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80129. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80130. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80131. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80132. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80133. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80134. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80135. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80136. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80137. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80138. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80139. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80140. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80141. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80142. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80143. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80144. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80145. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80146. 0x8def022dUL
  80147. },
  80148. {
  80149. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80150. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80151. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80152. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80153. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80154. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80155. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80156. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80157. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80158. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80159. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80160. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80161. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80162. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80163. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80164. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80165. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80166. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80167. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80168. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80169. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80170. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80171. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80172. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80173. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80174. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80175. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80176. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80177. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80178. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80179. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80180. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80181. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80182. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80183. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80184. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80185. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80186. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80187. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80188. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80189. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80190. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80191. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80192. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80193. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80194. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80195. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80196. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80197. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80198. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80199. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80200. 0x72fd2493UL
  80201. },
  80202. {
  80203. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80204. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80205. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80206. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80207. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80208. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80209. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80210. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80211. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80212. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80213. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80214. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80215. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80216. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80217. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80218. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80219. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80220. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80221. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80222. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80223. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80224. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80225. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80226. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80227. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80228. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80229. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80230. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80231. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80232. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80233. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80234. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80235. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80236. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80237. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80238. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80239. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80240. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80241. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80242. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80243. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80244. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80245. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80246. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80247. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80248. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80249. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80250. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80251. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80252. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80253. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80254. 0xed3498beUL
  80255. },
  80256. {
  80257. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80258. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80259. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80260. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80261. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80262. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80263. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80264. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80265. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80266. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80267. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80268. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80269. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80270. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80271. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80272. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80273. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80274. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80275. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80276. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80277. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80278. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80279. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80280. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80281. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80282. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80283. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80284. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80285. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80286. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80287. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80288. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80289. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80290. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80291. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80292. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80293. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80294. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80295. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80296. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80297. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80298. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80299. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80300. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80301. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80302. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80303. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80304. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80305. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80306. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80307. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80308. 0xf10605deUL
  80309. #endif
  80310. }
  80311. };
  80312. /*** End of inlined file: crc32.h ***/
  80313. #endif /* DYNAMIC_CRC_TABLE */
  80314. /* =========================================================================
  80315. * This function can be used by asm versions of crc32()
  80316. */
  80317. const unsigned long FAR * ZEXPORT get_crc_table()
  80318. {
  80319. #ifdef DYNAMIC_CRC_TABLE
  80320. if (crc_table_empty)
  80321. make_crc_table();
  80322. #endif /* DYNAMIC_CRC_TABLE */
  80323. return (const unsigned long FAR *)crc_table;
  80324. }
  80325. /* ========================================================================= */
  80326. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80327. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80328. /* ========================================================================= */
  80329. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80330. {
  80331. if (buf == Z_NULL) return 0UL;
  80332. #ifdef DYNAMIC_CRC_TABLE
  80333. if (crc_table_empty)
  80334. make_crc_table();
  80335. #endif /* DYNAMIC_CRC_TABLE */
  80336. #ifdef BYFOUR
  80337. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80338. u4 endian;
  80339. endian = 1;
  80340. if (*((unsigned char *)(&endian)))
  80341. return crc32_little(crc, buf, len);
  80342. else
  80343. return crc32_big(crc, buf, len);
  80344. }
  80345. #endif /* BYFOUR */
  80346. crc = crc ^ 0xffffffffUL;
  80347. while (len >= 8) {
  80348. DO8;
  80349. len -= 8;
  80350. }
  80351. if (len) do {
  80352. DO1;
  80353. } while (--len);
  80354. return crc ^ 0xffffffffUL;
  80355. }
  80356. #ifdef BYFOUR
  80357. /* ========================================================================= */
  80358. #define DOLIT4 c ^= *buf4++; \
  80359. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80360. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80361. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80362. /* ========================================================================= */
  80363. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80364. {
  80365. register u4 c;
  80366. register const u4 FAR *buf4;
  80367. c = (u4)crc;
  80368. c = ~c;
  80369. while (len && ((ptrdiff_t)buf & 3)) {
  80370. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80371. len--;
  80372. }
  80373. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80374. while (len >= 32) {
  80375. DOLIT32;
  80376. len -= 32;
  80377. }
  80378. while (len >= 4) {
  80379. DOLIT4;
  80380. len -= 4;
  80381. }
  80382. buf = (const unsigned char FAR *)buf4;
  80383. if (len) do {
  80384. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80385. } while (--len);
  80386. c = ~c;
  80387. return (unsigned long)c;
  80388. }
  80389. /* ========================================================================= */
  80390. #define DOBIG4 c ^= *++buf4; \
  80391. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80392. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80393. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80394. /* ========================================================================= */
  80395. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80396. {
  80397. register u4 c;
  80398. register const u4 FAR *buf4;
  80399. c = REV((u4)crc);
  80400. c = ~c;
  80401. while (len && ((ptrdiff_t)buf & 3)) {
  80402. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80403. len--;
  80404. }
  80405. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80406. buf4--;
  80407. while (len >= 32) {
  80408. DOBIG32;
  80409. len -= 32;
  80410. }
  80411. while (len >= 4) {
  80412. DOBIG4;
  80413. len -= 4;
  80414. }
  80415. buf4++;
  80416. buf = (const unsigned char FAR *)buf4;
  80417. if (len) do {
  80418. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80419. } while (--len);
  80420. c = ~c;
  80421. return (unsigned long)(REV(c));
  80422. }
  80423. #endif /* BYFOUR */
  80424. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80425. /* ========================================================================= */
  80426. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80427. {
  80428. unsigned long sum;
  80429. sum = 0;
  80430. while (vec) {
  80431. if (vec & 1)
  80432. sum ^= *mat;
  80433. vec >>= 1;
  80434. mat++;
  80435. }
  80436. return sum;
  80437. }
  80438. /* ========================================================================= */
  80439. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80440. {
  80441. int n;
  80442. for (n = 0; n < GF2_DIM; n++)
  80443. square[n] = gf2_matrix_times(mat, mat[n]);
  80444. }
  80445. /* ========================================================================= */
  80446. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80447. {
  80448. int n;
  80449. unsigned long row;
  80450. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80451. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80452. /* degenerate case */
  80453. if (len2 == 0)
  80454. return crc1;
  80455. /* put operator for one zero bit in odd */
  80456. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80457. row = 1;
  80458. for (n = 1; n < GF2_DIM; n++) {
  80459. odd[n] = row;
  80460. row <<= 1;
  80461. }
  80462. /* put operator for two zero bits in even */
  80463. gf2_matrix_square(even, odd);
  80464. /* put operator for four zero bits in odd */
  80465. gf2_matrix_square(odd, even);
  80466. /* apply len2 zeros to crc1 (first square will put the operator for one
  80467. zero byte, eight zero bits, in even) */
  80468. do {
  80469. /* apply zeros operator for this bit of len2 */
  80470. gf2_matrix_square(even, odd);
  80471. if (len2 & 1)
  80472. crc1 = gf2_matrix_times(even, crc1);
  80473. len2 >>= 1;
  80474. /* if no more bits set, then done */
  80475. if (len2 == 0)
  80476. break;
  80477. /* another iteration of the loop with odd and even swapped */
  80478. gf2_matrix_square(odd, even);
  80479. if (len2 & 1)
  80480. crc1 = gf2_matrix_times(odd, crc1);
  80481. len2 >>= 1;
  80482. /* if no more bits set, then done */
  80483. } while (len2 != 0);
  80484. /* return combined crc */
  80485. crc1 ^= crc2;
  80486. return crc1;
  80487. }
  80488. /*** End of inlined file: crc32.c ***/
  80489. /*** Start of inlined file: deflate.c ***/
  80490. /*
  80491. * ALGORITHM
  80492. *
  80493. * The "deflation" process depends on being able to identify portions
  80494. * of the input text which are identical to earlier input (within a
  80495. * sliding window trailing behind the input currently being processed).
  80496. *
  80497. * The most straightforward technique turns out to be the fastest for
  80498. * most input files: try all possible matches and select the longest.
  80499. * The key feature of this algorithm is that insertions into the string
  80500. * dictionary are very simple and thus fast, and deletions are avoided
  80501. * completely. Insertions are performed at each input character, whereas
  80502. * string matches are performed only when the previous match ends. So it
  80503. * is preferable to spend more time in matches to allow very fast string
  80504. * insertions and avoid deletions. The matching algorithm for small
  80505. * strings is inspired from that of Rabin & Karp. A brute force approach
  80506. * is used to find longer strings when a small match has been found.
  80507. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80508. * (by Leonid Broukhis).
  80509. * A previous version of this file used a more sophisticated algorithm
  80510. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80511. * time, but has a larger average cost, uses more memory and is patented.
  80512. * However the F&G algorithm may be faster for some highly redundant
  80513. * files if the parameter max_chain_length (described below) is too large.
  80514. *
  80515. * ACKNOWLEDGEMENTS
  80516. *
  80517. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80518. * I found it in 'freeze' written by Leonid Broukhis.
  80519. * Thanks to many people for bug reports and testing.
  80520. *
  80521. * REFERENCES
  80522. *
  80523. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80524. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80525. *
  80526. * A description of the Rabin and Karp algorithm is given in the book
  80527. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80528. *
  80529. * Fiala,E.R., and Greene,D.H.
  80530. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80531. *
  80532. */
  80533. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80534. /*** Start of inlined file: deflate.h ***/
  80535. /* WARNING: this file should *not* be used by applications. It is
  80536. part of the implementation of the compression library and is
  80537. subject to change. Applications should only use zlib.h.
  80538. */
  80539. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80540. #ifndef DEFLATE_H
  80541. #define DEFLATE_H
  80542. /* define NO_GZIP when compiling if you want to disable gzip header and
  80543. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80544. the crc code when it is not needed. For shared libraries, gzip encoding
  80545. should be left enabled. */
  80546. #ifndef NO_GZIP
  80547. # define GZIP
  80548. #endif
  80549. #define NO_DUMMY_DECL
  80550. /* ===========================================================================
  80551. * Internal compression state.
  80552. */
  80553. #define LENGTH_CODES 29
  80554. /* number of length codes, not counting the special END_BLOCK code */
  80555. #define LITERALS 256
  80556. /* number of literal bytes 0..255 */
  80557. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80558. /* number of Literal or Length codes, including the END_BLOCK code */
  80559. #define D_CODES 30
  80560. /* number of distance codes */
  80561. #define BL_CODES 19
  80562. /* number of codes used to transfer the bit lengths */
  80563. #define HEAP_SIZE (2*L_CODES+1)
  80564. /* maximum heap size */
  80565. #define MAX_BITS 15
  80566. /* All codes must not exceed MAX_BITS bits */
  80567. #define INIT_STATE 42
  80568. #define EXTRA_STATE 69
  80569. #define NAME_STATE 73
  80570. #define COMMENT_STATE 91
  80571. #define HCRC_STATE 103
  80572. #define BUSY_STATE 113
  80573. #define FINISH_STATE 666
  80574. /* Stream status */
  80575. /* Data structure describing a single value and its code string. */
  80576. typedef struct ct_data_s {
  80577. union {
  80578. ush freq; /* frequency count */
  80579. ush code; /* bit string */
  80580. } fc;
  80581. union {
  80582. ush dad; /* father node in Huffman tree */
  80583. ush len; /* length of bit string */
  80584. } dl;
  80585. } FAR ct_data;
  80586. #define Freq fc.freq
  80587. #define Code fc.code
  80588. #define Dad dl.dad
  80589. #define Len dl.len
  80590. typedef struct static_tree_desc_s static_tree_desc;
  80591. typedef struct tree_desc_s {
  80592. ct_data *dyn_tree; /* the dynamic tree */
  80593. int max_code; /* largest code with non zero frequency */
  80594. static_tree_desc *stat_desc; /* the corresponding static tree */
  80595. } FAR tree_desc;
  80596. typedef ush Pos;
  80597. typedef Pos FAR Posf;
  80598. typedef unsigned IPos;
  80599. /* A Pos is an index in the character window. We use short instead of int to
  80600. * save space in the various tables. IPos is used only for parameter passing.
  80601. */
  80602. typedef struct internal_state {
  80603. z_streamp strm; /* pointer back to this zlib stream */
  80604. int status; /* as the name implies */
  80605. Bytef *pending_buf; /* output still pending */
  80606. ulg pending_buf_size; /* size of pending_buf */
  80607. Bytef *pending_out; /* next pending byte to output to the stream */
  80608. uInt pending; /* nb of bytes in the pending buffer */
  80609. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80610. gz_headerp gzhead; /* gzip header information to write */
  80611. uInt gzindex; /* where in extra, name, or comment */
  80612. Byte method; /* STORED (for zip only) or DEFLATED */
  80613. int last_flush; /* value of flush param for previous deflate call */
  80614. /* used by deflate.c: */
  80615. uInt w_size; /* LZ77 window size (32K by default) */
  80616. uInt w_bits; /* log2(w_size) (8..16) */
  80617. uInt w_mask; /* w_size - 1 */
  80618. Bytef *window;
  80619. /* Sliding window. Input bytes are read into the second half of the window,
  80620. * and move to the first half later to keep a dictionary of at least wSize
  80621. * bytes. With this organization, matches are limited to a distance of
  80622. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80623. * performed with a length multiple of the block size. Also, it limits
  80624. * the window size to 64K, which is quite useful on MSDOS.
  80625. * To do: use the user input buffer as sliding window.
  80626. */
  80627. ulg window_size;
  80628. /* Actual size of window: 2*wSize, except when the user input buffer
  80629. * is directly used as sliding window.
  80630. */
  80631. Posf *prev;
  80632. /* Link to older string with same hash index. To limit the size of this
  80633. * array to 64K, this link is maintained only for the last 32K strings.
  80634. * An index in this array is thus a window index modulo 32K.
  80635. */
  80636. Posf *head; /* Heads of the hash chains or NIL. */
  80637. uInt ins_h; /* hash index of string to be inserted */
  80638. uInt hash_size; /* number of elements in hash table */
  80639. uInt hash_bits; /* log2(hash_size) */
  80640. uInt hash_mask; /* hash_size-1 */
  80641. uInt hash_shift;
  80642. /* Number of bits by which ins_h must be shifted at each input
  80643. * step. It must be such that after MIN_MATCH steps, the oldest
  80644. * byte no longer takes part in the hash key, that is:
  80645. * hash_shift * MIN_MATCH >= hash_bits
  80646. */
  80647. long block_start;
  80648. /* Window position at the beginning of the current output block. Gets
  80649. * negative when the window is moved backwards.
  80650. */
  80651. uInt match_length; /* length of best match */
  80652. IPos prev_match; /* previous match */
  80653. int match_available; /* set if previous match exists */
  80654. uInt strstart; /* start of string to insert */
  80655. uInt match_start; /* start of matching string */
  80656. uInt lookahead; /* number of valid bytes ahead in window */
  80657. uInt prev_length;
  80658. /* Length of the best match at previous step. Matches not greater than this
  80659. * are discarded. This is used in the lazy match evaluation.
  80660. */
  80661. uInt max_chain_length;
  80662. /* To speed up deflation, hash chains are never searched beyond this
  80663. * length. A higher limit improves compression ratio but degrades the
  80664. * speed.
  80665. */
  80666. uInt max_lazy_match;
  80667. /* Attempt to find a better match only when the current match is strictly
  80668. * smaller than this value. This mechanism is used only for compression
  80669. * levels >= 4.
  80670. */
  80671. # define max_insert_length max_lazy_match
  80672. /* Insert new strings in the hash table only if the match length is not
  80673. * greater than this length. This saves time but degrades compression.
  80674. * max_insert_length is used only for compression levels <= 3.
  80675. */
  80676. int level; /* compression level (1..9) */
  80677. int strategy; /* favor or force Huffman coding*/
  80678. uInt good_match;
  80679. /* Use a faster search when the previous match is longer than this */
  80680. int nice_match; /* Stop searching when current match exceeds this */
  80681. /* used by trees.c: */
  80682. /* Didn't use ct_data typedef below to supress compiler warning */
  80683. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80684. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80685. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80686. struct tree_desc_s l_desc; /* desc. for literal tree */
  80687. struct tree_desc_s d_desc; /* desc. for distance tree */
  80688. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80689. ush bl_count[MAX_BITS+1];
  80690. /* number of codes at each bit length for an optimal tree */
  80691. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80692. int heap_len; /* number of elements in the heap */
  80693. int heap_max; /* element of largest frequency */
  80694. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80695. * The same heap array is used to build all trees.
  80696. */
  80697. uch depth[2*L_CODES+1];
  80698. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80699. */
  80700. uchf *l_buf; /* buffer for literals or lengths */
  80701. uInt lit_bufsize;
  80702. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80703. * limiting lit_bufsize to 64K:
  80704. * - frequencies can be kept in 16 bit counters
  80705. * - if compression is not successful for the first block, all input
  80706. * data is still in the window so we can still emit a stored block even
  80707. * when input comes from standard input. (This can also be done for
  80708. * all blocks if lit_bufsize is not greater than 32K.)
  80709. * - if compression is not successful for a file smaller than 64K, we can
  80710. * even emit a stored file instead of a stored block (saving 5 bytes).
  80711. * This is applicable only for zip (not gzip or zlib).
  80712. * - creating new Huffman trees less frequently may not provide fast
  80713. * adaptation to changes in the input data statistics. (Take for
  80714. * example a binary file with poorly compressible code followed by
  80715. * a highly compressible string table.) Smaller buffer sizes give
  80716. * fast adaptation but have of course the overhead of transmitting
  80717. * trees more frequently.
  80718. * - I can't count above 4
  80719. */
  80720. uInt last_lit; /* running index in l_buf */
  80721. ushf *d_buf;
  80722. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80723. * the same number of elements. To use different lengths, an extra flag
  80724. * array would be necessary.
  80725. */
  80726. ulg opt_len; /* bit length of current block with optimal trees */
  80727. ulg static_len; /* bit length of current block with static trees */
  80728. uInt matches; /* number of string matches in current block */
  80729. int last_eob_len; /* bit length of EOB code for last block */
  80730. #ifdef DEBUG
  80731. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80732. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80733. #endif
  80734. ush bi_buf;
  80735. /* Output buffer. bits are inserted starting at the bottom (least
  80736. * significant bits).
  80737. */
  80738. int bi_valid;
  80739. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80740. * are always zero.
  80741. */
  80742. } FAR deflate_state;
  80743. /* Output a byte on the stream.
  80744. * IN assertion: there is enough room in pending_buf.
  80745. */
  80746. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80747. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80748. /* Minimum amount of lookahead, except at the end of the input file.
  80749. * See deflate.c for comments about the MIN_MATCH+1.
  80750. */
  80751. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80752. /* In order to simplify the code, particularly on 16 bit machines, match
  80753. * distances are limited to MAX_DIST instead of WSIZE.
  80754. */
  80755. /* in trees.c */
  80756. void _tr_init OF((deflate_state *s));
  80757. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80758. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80759. int eof));
  80760. void _tr_align OF((deflate_state *s));
  80761. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80762. int eof));
  80763. #define d_code(dist) \
  80764. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80765. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80766. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80767. * used.
  80768. */
  80769. #ifndef DEBUG
  80770. /* Inline versions of _tr_tally for speed: */
  80771. #if defined(GEN_TREES_H) || !defined(STDC)
  80772. extern uch _length_code[];
  80773. extern uch _dist_code[];
  80774. #else
  80775. extern const uch _length_code[];
  80776. extern const uch _dist_code[];
  80777. #endif
  80778. # define _tr_tally_lit(s, c, flush) \
  80779. { uch cc = (c); \
  80780. s->d_buf[s->last_lit] = 0; \
  80781. s->l_buf[s->last_lit++] = cc; \
  80782. s->dyn_ltree[cc].Freq++; \
  80783. flush = (s->last_lit == s->lit_bufsize-1); \
  80784. }
  80785. # define _tr_tally_dist(s, distance, length, flush) \
  80786. { uch len = (length); \
  80787. ush dist = (distance); \
  80788. s->d_buf[s->last_lit] = dist; \
  80789. s->l_buf[s->last_lit++] = len; \
  80790. dist--; \
  80791. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80792. s->dyn_dtree[d_code(dist)].Freq++; \
  80793. flush = (s->last_lit == s->lit_bufsize-1); \
  80794. }
  80795. #else
  80796. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80797. # define _tr_tally_dist(s, distance, length, flush) \
  80798. flush = _tr_tally(s, distance, length)
  80799. #endif
  80800. #endif /* DEFLATE_H */
  80801. /*** End of inlined file: deflate.h ***/
  80802. const char deflate_copyright[] =
  80803. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80804. /*
  80805. If you use the zlib library in a product, an acknowledgment is welcome
  80806. in the documentation of your product. If for some reason you cannot
  80807. include such an acknowledgment, I would appreciate that you keep this
  80808. copyright string in the executable of your product.
  80809. */
  80810. /* ===========================================================================
  80811. * Function prototypes.
  80812. */
  80813. typedef enum {
  80814. need_more, /* block not completed, need more input or more output */
  80815. block_done, /* block flush performed */
  80816. finish_started, /* finish started, need only more output at next deflate */
  80817. finish_done /* finish done, accept no more input or output */
  80818. } block_state;
  80819. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80820. /* Compression function. Returns the block state after the call. */
  80821. local void fill_window OF((deflate_state *s));
  80822. local block_state deflate_stored OF((deflate_state *s, int flush));
  80823. local block_state deflate_fast OF((deflate_state *s, int flush));
  80824. #ifndef FASTEST
  80825. local block_state deflate_slow OF((deflate_state *s, int flush));
  80826. #endif
  80827. local void lm_init OF((deflate_state *s));
  80828. local void putShortMSB OF((deflate_state *s, uInt b));
  80829. local void flush_pending OF((z_streamp strm));
  80830. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80831. #ifndef FASTEST
  80832. #ifdef ASMV
  80833. void match_init OF((void)); /* asm code initialization */
  80834. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80835. #else
  80836. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80837. #endif
  80838. #endif
  80839. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80840. #ifdef DEBUG
  80841. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80842. int length));
  80843. #endif
  80844. /* ===========================================================================
  80845. * Local data
  80846. */
  80847. #define NIL 0
  80848. /* Tail of hash chains */
  80849. #ifndef TOO_FAR
  80850. # define TOO_FAR 4096
  80851. #endif
  80852. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80853. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80854. /* Minimum amount of lookahead, except at the end of the input file.
  80855. * See deflate.c for comments about the MIN_MATCH+1.
  80856. */
  80857. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80858. * the desired pack level (0..9). The values given below have been tuned to
  80859. * exclude worst case performance for pathological files. Better values may be
  80860. * found for specific files.
  80861. */
  80862. typedef struct config_s {
  80863. ush good_length; /* reduce lazy search above this match length */
  80864. ush max_lazy; /* do not perform lazy search above this match length */
  80865. ush nice_length; /* quit search above this match length */
  80866. ush max_chain;
  80867. compress_func func;
  80868. } config;
  80869. #ifdef FASTEST
  80870. local const config configuration_table[2] = {
  80871. /* good lazy nice chain */
  80872. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80873. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80874. #else
  80875. local const config configuration_table[10] = {
  80876. /* good lazy nice chain */
  80877. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80878. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80879. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80880. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80881. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80882. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80883. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80884. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80885. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80886. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80887. #endif
  80888. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80889. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80890. * meaning.
  80891. */
  80892. #define EQUAL 0
  80893. /* result of memcmp for equal strings */
  80894. #ifndef NO_DUMMY_DECL
  80895. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80896. #endif
  80897. /* ===========================================================================
  80898. * Update a hash value with the given input byte
  80899. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80900. * input characters, so that a running hash key can be computed from the
  80901. * previous key instead of complete recalculation each time.
  80902. */
  80903. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80904. /* ===========================================================================
  80905. * Insert string str in the dictionary and set match_head to the previous head
  80906. * of the hash chain (the most recent string with same hash key). Return
  80907. * the previous length of the hash chain.
  80908. * If this file is compiled with -DFASTEST, the compression level is forced
  80909. * to 1, and no hash chains are maintained.
  80910. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80911. * input characters and the first MIN_MATCH bytes of str are valid
  80912. * (except for the last MIN_MATCH-1 bytes of the input file).
  80913. */
  80914. #ifdef FASTEST
  80915. #define INSERT_STRING(s, str, match_head) \
  80916. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80917. match_head = s->head[s->ins_h], \
  80918. s->head[s->ins_h] = (Pos)(str))
  80919. #else
  80920. #define INSERT_STRING(s, str, match_head) \
  80921. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80922. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80923. s->head[s->ins_h] = (Pos)(str))
  80924. #endif
  80925. /* ===========================================================================
  80926. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80927. * prev[] will be initialized on the fly.
  80928. */
  80929. #define CLEAR_HASH(s) \
  80930. s->head[s->hash_size-1] = NIL; \
  80931. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80932. /* ========================================================================= */
  80933. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80934. {
  80935. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80936. Z_DEFAULT_STRATEGY, version, stream_size);
  80937. /* To do: ignore strm->next_in if we use it as window */
  80938. }
  80939. /* ========================================================================= */
  80940. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80941. {
  80942. deflate_state *s;
  80943. int wrap = 1;
  80944. static const char my_version[] = ZLIB_VERSION;
  80945. ushf *overlay;
  80946. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80947. * output size for (length,distance) codes is <= 24 bits.
  80948. */
  80949. if (version == Z_NULL || version[0] != my_version[0] ||
  80950. stream_size != sizeof(z_stream)) {
  80951. return Z_VERSION_ERROR;
  80952. }
  80953. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80954. strm->msg = Z_NULL;
  80955. if (strm->zalloc == (alloc_func)0) {
  80956. strm->zalloc = zcalloc;
  80957. strm->opaque = (voidpf)0;
  80958. }
  80959. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80960. #ifdef FASTEST
  80961. if (level != 0) level = 1;
  80962. #else
  80963. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80964. #endif
  80965. if (windowBits < 0) { /* suppress zlib wrapper */
  80966. wrap = 0;
  80967. windowBits = -windowBits;
  80968. }
  80969. #ifdef GZIP
  80970. else if (windowBits > 15) {
  80971. wrap = 2; /* write gzip wrapper instead */
  80972. windowBits -= 16;
  80973. }
  80974. #endif
  80975. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80976. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80977. strategy < 0 || strategy > Z_FIXED) {
  80978. return Z_STREAM_ERROR;
  80979. }
  80980. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80981. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80982. if (s == Z_NULL) return Z_MEM_ERROR;
  80983. strm->state = (struct internal_state FAR *)s;
  80984. s->strm = strm;
  80985. s->wrap = wrap;
  80986. s->gzhead = Z_NULL;
  80987. s->w_bits = windowBits;
  80988. s->w_size = 1 << s->w_bits;
  80989. s->w_mask = s->w_size - 1;
  80990. s->hash_bits = memLevel + 7;
  80991. s->hash_size = 1 << s->hash_bits;
  80992. s->hash_mask = s->hash_size - 1;
  80993. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80994. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80995. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80996. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80997. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80998. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80999. s->pending_buf = (uchf *) overlay;
  81000. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81001. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81002. s->pending_buf == Z_NULL) {
  81003. s->status = FINISH_STATE;
  81004. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81005. deflateEnd (strm);
  81006. return Z_MEM_ERROR;
  81007. }
  81008. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81009. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81010. s->level = level;
  81011. s->strategy = strategy;
  81012. s->method = (Byte)method;
  81013. return deflateReset(strm);
  81014. }
  81015. /* ========================================================================= */
  81016. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81017. {
  81018. deflate_state *s;
  81019. uInt length = dictLength;
  81020. uInt n;
  81021. IPos hash_head = 0;
  81022. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81023. strm->state->wrap == 2 ||
  81024. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81025. return Z_STREAM_ERROR;
  81026. s = strm->state;
  81027. if (s->wrap)
  81028. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81029. if (length < MIN_MATCH) return Z_OK;
  81030. if (length > MAX_DIST(s)) {
  81031. length = MAX_DIST(s);
  81032. dictionary += dictLength - length; /* use the tail of the dictionary */
  81033. }
  81034. zmemcpy(s->window, dictionary, length);
  81035. s->strstart = length;
  81036. s->block_start = (long)length;
  81037. /* Insert all strings in the hash table (except for the last two bytes).
  81038. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81039. * call of fill_window.
  81040. */
  81041. s->ins_h = s->window[0];
  81042. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81043. for (n = 0; n <= length - MIN_MATCH; n++) {
  81044. INSERT_STRING(s, n, hash_head);
  81045. }
  81046. if (hash_head) hash_head = 0; /* to make compiler happy */
  81047. return Z_OK;
  81048. }
  81049. /* ========================================================================= */
  81050. int ZEXPORT deflateReset (z_streamp strm)
  81051. {
  81052. deflate_state *s;
  81053. if (strm == Z_NULL || strm->state == Z_NULL ||
  81054. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81055. return Z_STREAM_ERROR;
  81056. }
  81057. strm->total_in = strm->total_out = 0;
  81058. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81059. strm->data_type = Z_UNKNOWN;
  81060. s = (deflate_state *)strm->state;
  81061. s->pending = 0;
  81062. s->pending_out = s->pending_buf;
  81063. if (s->wrap < 0) {
  81064. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81065. }
  81066. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81067. strm->adler =
  81068. #ifdef GZIP
  81069. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81070. #endif
  81071. adler32(0L, Z_NULL, 0);
  81072. s->last_flush = Z_NO_FLUSH;
  81073. _tr_init(s);
  81074. lm_init(s);
  81075. return Z_OK;
  81076. }
  81077. /* ========================================================================= */
  81078. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81079. {
  81080. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81081. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81082. strm->state->gzhead = head;
  81083. return Z_OK;
  81084. }
  81085. /* ========================================================================= */
  81086. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81087. {
  81088. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81089. strm->state->bi_valid = bits;
  81090. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81091. return Z_OK;
  81092. }
  81093. /* ========================================================================= */
  81094. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81095. {
  81096. deflate_state *s;
  81097. compress_func func;
  81098. int err = Z_OK;
  81099. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81100. s = strm->state;
  81101. #ifdef FASTEST
  81102. if (level != 0) level = 1;
  81103. #else
  81104. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81105. #endif
  81106. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81107. return Z_STREAM_ERROR;
  81108. }
  81109. func = configuration_table[s->level].func;
  81110. if (func != configuration_table[level].func && strm->total_in != 0) {
  81111. /* Flush the last buffer: */
  81112. err = deflate(strm, Z_PARTIAL_FLUSH);
  81113. }
  81114. if (s->level != level) {
  81115. s->level = level;
  81116. s->max_lazy_match = configuration_table[level].max_lazy;
  81117. s->good_match = configuration_table[level].good_length;
  81118. s->nice_match = configuration_table[level].nice_length;
  81119. s->max_chain_length = configuration_table[level].max_chain;
  81120. }
  81121. s->strategy = strategy;
  81122. return err;
  81123. }
  81124. /* ========================================================================= */
  81125. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81126. {
  81127. deflate_state *s;
  81128. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81129. s = strm->state;
  81130. s->good_match = good_length;
  81131. s->max_lazy_match = max_lazy;
  81132. s->nice_match = nice_length;
  81133. s->max_chain_length = max_chain;
  81134. return Z_OK;
  81135. }
  81136. /* =========================================================================
  81137. * For the default windowBits of 15 and memLevel of 8, this function returns
  81138. * a close to exact, as well as small, upper bound on the compressed size.
  81139. * They are coded as constants here for a reason--if the #define's are
  81140. * changed, then this function needs to be changed as well. The return
  81141. * value for 15 and 8 only works for those exact settings.
  81142. *
  81143. * For any setting other than those defaults for windowBits and memLevel,
  81144. * the value returned is a conservative worst case for the maximum expansion
  81145. * resulting from using fixed blocks instead of stored blocks, which deflate
  81146. * can emit on compressed data for some combinations of the parameters.
  81147. *
  81148. * This function could be more sophisticated to provide closer upper bounds
  81149. * for every combination of windowBits and memLevel, as well as wrap.
  81150. * But even the conservative upper bound of about 14% expansion does not
  81151. * seem onerous for output buffer allocation.
  81152. */
  81153. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81154. {
  81155. deflate_state *s;
  81156. uLong destLen;
  81157. /* conservative upper bound */
  81158. destLen = sourceLen +
  81159. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81160. /* if can't get parameters, return conservative bound */
  81161. if (strm == Z_NULL || strm->state == Z_NULL)
  81162. return destLen;
  81163. /* if not default parameters, return conservative bound */
  81164. s = strm->state;
  81165. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81166. return destLen;
  81167. /* default settings: return tight bound for that case */
  81168. return compressBound(sourceLen);
  81169. }
  81170. /* =========================================================================
  81171. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81172. * IN assertion: the stream state is correct and there is enough room in
  81173. * pending_buf.
  81174. */
  81175. local void putShortMSB (deflate_state *s, uInt b)
  81176. {
  81177. put_byte(s, (Byte)(b >> 8));
  81178. put_byte(s, (Byte)(b & 0xff));
  81179. }
  81180. /* =========================================================================
  81181. * Flush as much pending output as possible. All deflate() output goes
  81182. * through this function so some applications may wish to modify it
  81183. * to avoid allocating a large strm->next_out buffer and copying into it.
  81184. * (See also read_buf()).
  81185. */
  81186. local void flush_pending (z_streamp strm)
  81187. {
  81188. unsigned len = strm->state->pending;
  81189. if (len > strm->avail_out) len = strm->avail_out;
  81190. if (len == 0) return;
  81191. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81192. strm->next_out += len;
  81193. strm->state->pending_out += len;
  81194. strm->total_out += len;
  81195. strm->avail_out -= len;
  81196. strm->state->pending -= len;
  81197. if (strm->state->pending == 0) {
  81198. strm->state->pending_out = strm->state->pending_buf;
  81199. }
  81200. }
  81201. /* ========================================================================= */
  81202. int ZEXPORT deflate (z_streamp strm, int flush)
  81203. {
  81204. int old_flush; /* value of flush param for previous deflate call */
  81205. deflate_state *s;
  81206. if (strm == Z_NULL || strm->state == Z_NULL ||
  81207. flush > Z_FINISH || flush < 0) {
  81208. return Z_STREAM_ERROR;
  81209. }
  81210. s = strm->state;
  81211. if (strm->next_out == Z_NULL ||
  81212. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81213. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81214. ERR_RETURN(strm, Z_STREAM_ERROR);
  81215. }
  81216. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81217. s->strm = strm; /* just in case */
  81218. old_flush = s->last_flush;
  81219. s->last_flush = flush;
  81220. /* Write the header */
  81221. if (s->status == INIT_STATE) {
  81222. #ifdef GZIP
  81223. if (s->wrap == 2) {
  81224. strm->adler = crc32(0L, Z_NULL, 0);
  81225. put_byte(s, 31);
  81226. put_byte(s, 139);
  81227. put_byte(s, 8);
  81228. if (s->gzhead == NULL) {
  81229. put_byte(s, 0);
  81230. put_byte(s, 0);
  81231. put_byte(s, 0);
  81232. put_byte(s, 0);
  81233. put_byte(s, 0);
  81234. put_byte(s, s->level == 9 ? 2 :
  81235. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81236. 4 : 0));
  81237. put_byte(s, OS_CODE);
  81238. s->status = BUSY_STATE;
  81239. }
  81240. else {
  81241. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81242. (s->gzhead->hcrc ? 2 : 0) +
  81243. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81244. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81245. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81246. );
  81247. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81248. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81249. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81250. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81251. put_byte(s, s->level == 9 ? 2 :
  81252. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81253. 4 : 0));
  81254. put_byte(s, s->gzhead->os & 0xff);
  81255. if (s->gzhead->extra != NULL) {
  81256. put_byte(s, s->gzhead->extra_len & 0xff);
  81257. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81258. }
  81259. if (s->gzhead->hcrc)
  81260. strm->adler = crc32(strm->adler, s->pending_buf,
  81261. s->pending);
  81262. s->gzindex = 0;
  81263. s->status = EXTRA_STATE;
  81264. }
  81265. }
  81266. else
  81267. #endif
  81268. {
  81269. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81270. uInt level_flags;
  81271. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81272. level_flags = 0;
  81273. else if (s->level < 6)
  81274. level_flags = 1;
  81275. else if (s->level == 6)
  81276. level_flags = 2;
  81277. else
  81278. level_flags = 3;
  81279. header |= (level_flags << 6);
  81280. if (s->strstart != 0) header |= PRESET_DICT;
  81281. header += 31 - (header % 31);
  81282. s->status = BUSY_STATE;
  81283. putShortMSB(s, header);
  81284. /* Save the adler32 of the preset dictionary: */
  81285. if (s->strstart != 0) {
  81286. putShortMSB(s, (uInt)(strm->adler >> 16));
  81287. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81288. }
  81289. strm->adler = adler32(0L, Z_NULL, 0);
  81290. }
  81291. }
  81292. #ifdef GZIP
  81293. if (s->status == EXTRA_STATE) {
  81294. if (s->gzhead->extra != NULL) {
  81295. uInt beg = s->pending; /* start of bytes to update crc */
  81296. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81297. if (s->pending == s->pending_buf_size) {
  81298. if (s->gzhead->hcrc && s->pending > beg)
  81299. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81300. s->pending - beg);
  81301. flush_pending(strm);
  81302. beg = s->pending;
  81303. if (s->pending == s->pending_buf_size)
  81304. break;
  81305. }
  81306. put_byte(s, s->gzhead->extra[s->gzindex]);
  81307. s->gzindex++;
  81308. }
  81309. if (s->gzhead->hcrc && s->pending > beg)
  81310. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81311. s->pending - beg);
  81312. if (s->gzindex == s->gzhead->extra_len) {
  81313. s->gzindex = 0;
  81314. s->status = NAME_STATE;
  81315. }
  81316. }
  81317. else
  81318. s->status = NAME_STATE;
  81319. }
  81320. if (s->status == NAME_STATE) {
  81321. if (s->gzhead->name != NULL) {
  81322. uInt beg = s->pending; /* start of bytes to update crc */
  81323. int val;
  81324. do {
  81325. if (s->pending == s->pending_buf_size) {
  81326. if (s->gzhead->hcrc && s->pending > beg)
  81327. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81328. s->pending - beg);
  81329. flush_pending(strm);
  81330. beg = s->pending;
  81331. if (s->pending == s->pending_buf_size) {
  81332. val = 1;
  81333. break;
  81334. }
  81335. }
  81336. val = s->gzhead->name[s->gzindex++];
  81337. put_byte(s, val);
  81338. } while (val != 0);
  81339. if (s->gzhead->hcrc && s->pending > beg)
  81340. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81341. s->pending - beg);
  81342. if (val == 0) {
  81343. s->gzindex = 0;
  81344. s->status = COMMENT_STATE;
  81345. }
  81346. }
  81347. else
  81348. s->status = COMMENT_STATE;
  81349. }
  81350. if (s->status == COMMENT_STATE) {
  81351. if (s->gzhead->comment != NULL) {
  81352. uInt beg = s->pending; /* start of bytes to update crc */
  81353. int val;
  81354. do {
  81355. if (s->pending == s->pending_buf_size) {
  81356. if (s->gzhead->hcrc && s->pending > beg)
  81357. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81358. s->pending - beg);
  81359. flush_pending(strm);
  81360. beg = s->pending;
  81361. if (s->pending == s->pending_buf_size) {
  81362. val = 1;
  81363. break;
  81364. }
  81365. }
  81366. val = s->gzhead->comment[s->gzindex++];
  81367. put_byte(s, val);
  81368. } while (val != 0);
  81369. if (s->gzhead->hcrc && s->pending > beg)
  81370. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81371. s->pending - beg);
  81372. if (val == 0)
  81373. s->status = HCRC_STATE;
  81374. }
  81375. else
  81376. s->status = HCRC_STATE;
  81377. }
  81378. if (s->status == HCRC_STATE) {
  81379. if (s->gzhead->hcrc) {
  81380. if (s->pending + 2 > s->pending_buf_size)
  81381. flush_pending(strm);
  81382. if (s->pending + 2 <= s->pending_buf_size) {
  81383. put_byte(s, (Byte)(strm->adler & 0xff));
  81384. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81385. strm->adler = crc32(0L, Z_NULL, 0);
  81386. s->status = BUSY_STATE;
  81387. }
  81388. }
  81389. else
  81390. s->status = BUSY_STATE;
  81391. }
  81392. #endif
  81393. /* Flush as much pending output as possible */
  81394. if (s->pending != 0) {
  81395. flush_pending(strm);
  81396. if (strm->avail_out == 0) {
  81397. /* Since avail_out is 0, deflate will be called again with
  81398. * more output space, but possibly with both pending and
  81399. * avail_in equal to zero. There won't be anything to do,
  81400. * but this is not an error situation so make sure we
  81401. * return OK instead of BUF_ERROR at next call of deflate:
  81402. */
  81403. s->last_flush = -1;
  81404. return Z_OK;
  81405. }
  81406. /* Make sure there is something to do and avoid duplicate consecutive
  81407. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81408. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81409. */
  81410. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81411. flush != Z_FINISH) {
  81412. ERR_RETURN(strm, Z_BUF_ERROR);
  81413. }
  81414. /* User must not provide more input after the first FINISH: */
  81415. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81416. ERR_RETURN(strm, Z_BUF_ERROR);
  81417. }
  81418. /* Start a new block or continue the current one.
  81419. */
  81420. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81421. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81422. block_state bstate;
  81423. bstate = (*(configuration_table[s->level].func))(s, flush);
  81424. if (bstate == finish_started || bstate == finish_done) {
  81425. s->status = FINISH_STATE;
  81426. }
  81427. if (bstate == need_more || bstate == finish_started) {
  81428. if (strm->avail_out == 0) {
  81429. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81430. }
  81431. return Z_OK;
  81432. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81433. * of deflate should use the same flush parameter to make sure
  81434. * that the flush is complete. So we don't have to output an
  81435. * empty block here, this will be done at next call. This also
  81436. * ensures that for a very small output buffer, we emit at most
  81437. * one empty block.
  81438. */
  81439. }
  81440. if (bstate == block_done) {
  81441. if (flush == Z_PARTIAL_FLUSH) {
  81442. _tr_align(s);
  81443. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81444. _tr_stored_block(s, (char*)0, 0L, 0);
  81445. /* For a full flush, this empty block will be recognized
  81446. * as a special marker by inflate_sync().
  81447. */
  81448. if (flush == Z_FULL_FLUSH) {
  81449. CLEAR_HASH(s); /* forget history */
  81450. }
  81451. }
  81452. flush_pending(strm);
  81453. if (strm->avail_out == 0) {
  81454. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81455. return Z_OK;
  81456. }
  81457. }
  81458. }
  81459. Assert(strm->avail_out > 0, "bug2");
  81460. if (flush != Z_FINISH) return Z_OK;
  81461. if (s->wrap <= 0) return Z_STREAM_END;
  81462. /* Write the trailer */
  81463. #ifdef GZIP
  81464. if (s->wrap == 2) {
  81465. put_byte(s, (Byte)(strm->adler & 0xff));
  81466. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81467. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81468. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81469. put_byte(s, (Byte)(strm->total_in & 0xff));
  81470. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81471. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81472. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81473. }
  81474. else
  81475. #endif
  81476. {
  81477. putShortMSB(s, (uInt)(strm->adler >> 16));
  81478. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81479. }
  81480. flush_pending(strm);
  81481. /* If avail_out is zero, the application will call deflate again
  81482. * to flush the rest.
  81483. */
  81484. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81485. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81486. }
  81487. /* ========================================================================= */
  81488. int ZEXPORT deflateEnd (z_streamp strm)
  81489. {
  81490. int status;
  81491. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81492. status = strm->state->status;
  81493. if (status != INIT_STATE &&
  81494. status != EXTRA_STATE &&
  81495. status != NAME_STATE &&
  81496. status != COMMENT_STATE &&
  81497. status != HCRC_STATE &&
  81498. status != BUSY_STATE &&
  81499. status != FINISH_STATE) {
  81500. return Z_STREAM_ERROR;
  81501. }
  81502. /* Deallocate in reverse order of allocations: */
  81503. TRY_FREE(strm, strm->state->pending_buf);
  81504. TRY_FREE(strm, strm->state->head);
  81505. TRY_FREE(strm, strm->state->prev);
  81506. TRY_FREE(strm, strm->state->window);
  81507. ZFREE(strm, strm->state);
  81508. strm->state = Z_NULL;
  81509. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81510. }
  81511. /* =========================================================================
  81512. * Copy the source state to the destination state.
  81513. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81514. * doesn't have enough memory anyway to duplicate compression states).
  81515. */
  81516. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81517. {
  81518. #ifdef MAXSEG_64K
  81519. return Z_STREAM_ERROR;
  81520. #else
  81521. deflate_state *ds;
  81522. deflate_state *ss;
  81523. ushf *overlay;
  81524. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81525. return Z_STREAM_ERROR;
  81526. }
  81527. ss = source->state;
  81528. zmemcpy(dest, source, sizeof(z_stream));
  81529. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81530. if (ds == Z_NULL) return Z_MEM_ERROR;
  81531. dest->state = (struct internal_state FAR *) ds;
  81532. zmemcpy(ds, ss, sizeof(deflate_state));
  81533. ds->strm = dest;
  81534. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81535. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81536. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81537. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81538. ds->pending_buf = (uchf *) overlay;
  81539. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81540. ds->pending_buf == Z_NULL) {
  81541. deflateEnd (dest);
  81542. return Z_MEM_ERROR;
  81543. }
  81544. /* following zmemcpy do not work for 16-bit MSDOS */
  81545. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81546. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81547. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81548. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81549. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81550. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81551. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81552. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81553. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81554. ds->bl_desc.dyn_tree = ds->bl_tree;
  81555. return Z_OK;
  81556. #endif /* MAXSEG_64K */
  81557. }
  81558. /* ===========================================================================
  81559. * Read a new buffer from the current input stream, update the adler32
  81560. * and total number of bytes read. All deflate() input goes through
  81561. * this function so some applications may wish to modify it to avoid
  81562. * allocating a large strm->next_in buffer and copying from it.
  81563. * (See also flush_pending()).
  81564. */
  81565. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81566. {
  81567. unsigned len = strm->avail_in;
  81568. if (len > size) len = size;
  81569. if (len == 0) return 0;
  81570. strm->avail_in -= len;
  81571. if (strm->state->wrap == 1) {
  81572. strm->adler = adler32(strm->adler, strm->next_in, len);
  81573. }
  81574. #ifdef GZIP
  81575. else if (strm->state->wrap == 2) {
  81576. strm->adler = crc32(strm->adler, strm->next_in, len);
  81577. }
  81578. #endif
  81579. zmemcpy(buf, strm->next_in, len);
  81580. strm->next_in += len;
  81581. strm->total_in += len;
  81582. return (int)len;
  81583. }
  81584. /* ===========================================================================
  81585. * Initialize the "longest match" routines for a new zlib stream
  81586. */
  81587. local void lm_init (deflate_state *s)
  81588. {
  81589. s->window_size = (ulg)2L*s->w_size;
  81590. CLEAR_HASH(s);
  81591. /* Set the default configuration parameters:
  81592. */
  81593. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81594. s->good_match = configuration_table[s->level].good_length;
  81595. s->nice_match = configuration_table[s->level].nice_length;
  81596. s->max_chain_length = configuration_table[s->level].max_chain;
  81597. s->strstart = 0;
  81598. s->block_start = 0L;
  81599. s->lookahead = 0;
  81600. s->match_length = s->prev_length = MIN_MATCH-1;
  81601. s->match_available = 0;
  81602. s->ins_h = 0;
  81603. #ifndef FASTEST
  81604. #ifdef ASMV
  81605. match_init(); /* initialize the asm code */
  81606. #endif
  81607. #endif
  81608. }
  81609. #ifndef FASTEST
  81610. /* ===========================================================================
  81611. * Set match_start to the longest match starting at the given string and
  81612. * return its length. Matches shorter or equal to prev_length are discarded,
  81613. * in which case the result is equal to prev_length and match_start is
  81614. * garbage.
  81615. * IN assertions: cur_match is the head of the hash chain for the current
  81616. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81617. * OUT assertion: the match length is not greater than s->lookahead.
  81618. */
  81619. #ifndef ASMV
  81620. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81621. * match.S. The code will be functionally equivalent.
  81622. */
  81623. local uInt longest_match(deflate_state *s, IPos cur_match)
  81624. {
  81625. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81626. register Bytef *scan = s->window + s->strstart; /* current string */
  81627. register Bytef *match; /* matched string */
  81628. register int len; /* length of current match */
  81629. int best_len = s->prev_length; /* best match length so far */
  81630. int nice_match = s->nice_match; /* stop if match long enough */
  81631. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81632. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81633. /* Stop when cur_match becomes <= limit. To simplify the code,
  81634. * we prevent matches with the string of window index 0.
  81635. */
  81636. Posf *prev = s->prev;
  81637. uInt wmask = s->w_mask;
  81638. #ifdef UNALIGNED_OK
  81639. /* Compare two bytes at a time. Note: this is not always beneficial.
  81640. * Try with and without -DUNALIGNED_OK to check.
  81641. */
  81642. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81643. register ush scan_start = *(ushf*)scan;
  81644. register ush scan_end = *(ushf*)(scan+best_len-1);
  81645. #else
  81646. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81647. register Byte scan_end1 = scan[best_len-1];
  81648. register Byte scan_end = scan[best_len];
  81649. #endif
  81650. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81651. * It is easy to get rid of this optimization if necessary.
  81652. */
  81653. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81654. /* Do not waste too much time if we already have a good match: */
  81655. if (s->prev_length >= s->good_match) {
  81656. chain_length >>= 2;
  81657. }
  81658. /* Do not look for matches beyond the end of the input. This is necessary
  81659. * to make deflate deterministic.
  81660. */
  81661. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81662. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81663. do {
  81664. Assert(cur_match < s->strstart, "no future");
  81665. match = s->window + cur_match;
  81666. /* Skip to next match if the match length cannot increase
  81667. * or if the match length is less than 2. Note that the checks below
  81668. * for insufficient lookahead only occur occasionally for performance
  81669. * reasons. Therefore uninitialized memory will be accessed, and
  81670. * conditional jumps will be made that depend on those values.
  81671. * However the length of the match is limited to the lookahead, so
  81672. * the output of deflate is not affected by the uninitialized values.
  81673. */
  81674. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81675. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81676. * UNALIGNED_OK if your compiler uses a different size.
  81677. */
  81678. if (*(ushf*)(match+best_len-1) != scan_end ||
  81679. *(ushf*)match != scan_start) continue;
  81680. /* It is not necessary to compare scan[2] and match[2] since they are
  81681. * always equal when the other bytes match, given that the hash keys
  81682. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81683. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81684. * lookahead only every 4th comparison; the 128th check will be made
  81685. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81686. * necessary to put more guard bytes at the end of the window, or
  81687. * to check more often for insufficient lookahead.
  81688. */
  81689. Assert(scan[2] == match[2], "scan[2]?");
  81690. scan++, match++;
  81691. do {
  81692. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81693. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81694. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81695. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81696. scan < strend);
  81697. /* The funny "do {}" generates better code on most compilers */
  81698. /* Here, scan <= window+strstart+257 */
  81699. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81700. if (*scan == *match) scan++;
  81701. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81702. scan = strend - (MAX_MATCH-1);
  81703. #else /* UNALIGNED_OK */
  81704. if (match[best_len] != scan_end ||
  81705. match[best_len-1] != scan_end1 ||
  81706. *match != *scan ||
  81707. *++match != scan[1]) continue;
  81708. /* The check at best_len-1 can be removed because it will be made
  81709. * again later. (This heuristic is not always a win.)
  81710. * It is not necessary to compare scan[2] and match[2] since they
  81711. * are always equal when the other bytes match, given that
  81712. * the hash keys are equal and that HASH_BITS >= 8.
  81713. */
  81714. scan += 2, match++;
  81715. Assert(*scan == *match, "match[2]?");
  81716. /* We check for insufficient lookahead only every 8th comparison;
  81717. * the 256th check will be made at strstart+258.
  81718. */
  81719. do {
  81720. } while (*++scan == *++match && *++scan == *++match &&
  81721. *++scan == *++match && *++scan == *++match &&
  81722. *++scan == *++match && *++scan == *++match &&
  81723. *++scan == *++match && *++scan == *++match &&
  81724. scan < strend);
  81725. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81726. len = MAX_MATCH - (int)(strend - scan);
  81727. scan = strend - MAX_MATCH;
  81728. #endif /* UNALIGNED_OK */
  81729. if (len > best_len) {
  81730. s->match_start = cur_match;
  81731. best_len = len;
  81732. if (len >= nice_match) break;
  81733. #ifdef UNALIGNED_OK
  81734. scan_end = *(ushf*)(scan+best_len-1);
  81735. #else
  81736. scan_end1 = scan[best_len-1];
  81737. scan_end = scan[best_len];
  81738. #endif
  81739. }
  81740. } while ((cur_match = prev[cur_match & wmask]) > limit
  81741. && --chain_length != 0);
  81742. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81743. return s->lookahead;
  81744. }
  81745. #endif /* ASMV */
  81746. #endif /* FASTEST */
  81747. /* ---------------------------------------------------------------------------
  81748. * Optimized version for level == 1 or strategy == Z_RLE only
  81749. */
  81750. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81751. {
  81752. register Bytef *scan = s->window + s->strstart; /* current string */
  81753. register Bytef *match; /* matched string */
  81754. register int len; /* length of current match */
  81755. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81756. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81757. * It is easy to get rid of this optimization if necessary.
  81758. */
  81759. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81760. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81761. Assert(cur_match < s->strstart, "no future");
  81762. match = s->window + cur_match;
  81763. /* Return failure if the match length is less than 2:
  81764. */
  81765. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81766. /* The check at best_len-1 can be removed because it will be made
  81767. * again later. (This heuristic is not always a win.)
  81768. * It is not necessary to compare scan[2] and match[2] since they
  81769. * are always equal when the other bytes match, given that
  81770. * the hash keys are equal and that HASH_BITS >= 8.
  81771. */
  81772. scan += 2, match += 2;
  81773. Assert(*scan == *match, "match[2]?");
  81774. /* We check for insufficient lookahead only every 8th comparison;
  81775. * the 256th check will be made at strstart+258.
  81776. */
  81777. do {
  81778. } while (*++scan == *++match && *++scan == *++match &&
  81779. *++scan == *++match && *++scan == *++match &&
  81780. *++scan == *++match && *++scan == *++match &&
  81781. *++scan == *++match && *++scan == *++match &&
  81782. scan < strend);
  81783. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81784. len = MAX_MATCH - (int)(strend - scan);
  81785. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81786. s->match_start = cur_match;
  81787. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81788. }
  81789. #ifdef DEBUG
  81790. /* ===========================================================================
  81791. * Check that the match at match_start is indeed a match.
  81792. */
  81793. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81794. {
  81795. /* check that the match is indeed a match */
  81796. if (zmemcmp(s->window + match,
  81797. s->window + start, length) != EQUAL) {
  81798. fprintf(stderr, " start %u, match %u, length %d\n",
  81799. start, match, length);
  81800. do {
  81801. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81802. } while (--length != 0);
  81803. z_error("invalid match");
  81804. }
  81805. if (z_verbose > 1) {
  81806. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81807. do { putc(s->window[start++], stderr); } while (--length != 0);
  81808. }
  81809. }
  81810. #else
  81811. # define check_match(s, start, match, length)
  81812. #endif /* DEBUG */
  81813. /* ===========================================================================
  81814. * Fill the window when the lookahead becomes insufficient.
  81815. * Updates strstart and lookahead.
  81816. *
  81817. * IN assertion: lookahead < MIN_LOOKAHEAD
  81818. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81819. * At least one byte has been read, or avail_in == 0; reads are
  81820. * performed for at least two bytes (required for the zip translate_eol
  81821. * option -- not supported here).
  81822. */
  81823. local void fill_window (deflate_state *s)
  81824. {
  81825. register unsigned n, m;
  81826. register Posf *p;
  81827. unsigned more; /* Amount of free space at the end of the window. */
  81828. uInt wsize = s->w_size;
  81829. do {
  81830. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81831. /* Deal with !@#$% 64K limit: */
  81832. if (sizeof(int) <= 2) {
  81833. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81834. more = wsize;
  81835. } else if (more == (unsigned)(-1)) {
  81836. /* Very unlikely, but possible on 16 bit machine if
  81837. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81838. */
  81839. more--;
  81840. }
  81841. }
  81842. /* If the window is almost full and there is insufficient lookahead,
  81843. * move the upper half to the lower one to make room in the upper half.
  81844. */
  81845. if (s->strstart >= wsize+MAX_DIST(s)) {
  81846. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81847. s->match_start -= wsize;
  81848. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81849. s->block_start -= (long) wsize;
  81850. /* Slide the hash table (could be avoided with 32 bit values
  81851. at the expense of memory usage). We slide even when level == 0
  81852. to keep the hash table consistent if we switch back to level > 0
  81853. later. (Using level 0 permanently is not an optimal usage of
  81854. zlib, so we don't care about this pathological case.)
  81855. */
  81856. /* %%% avoid this when Z_RLE */
  81857. n = s->hash_size;
  81858. p = &s->head[n];
  81859. do {
  81860. m = *--p;
  81861. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81862. } while (--n);
  81863. n = wsize;
  81864. #ifndef FASTEST
  81865. p = &s->prev[n];
  81866. do {
  81867. m = *--p;
  81868. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81869. /* If n is not on any hash chain, prev[n] is garbage but
  81870. * its value will never be used.
  81871. */
  81872. } while (--n);
  81873. #endif
  81874. more += wsize;
  81875. }
  81876. if (s->strm->avail_in == 0) return;
  81877. /* If there was no sliding:
  81878. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81879. * more == window_size - lookahead - strstart
  81880. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81881. * => more >= window_size - 2*WSIZE + 2
  81882. * In the BIG_MEM or MMAP case (not yet supported),
  81883. * window_size == input_size + MIN_LOOKAHEAD &&
  81884. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81885. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81886. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81887. */
  81888. Assert(more >= 2, "more < 2");
  81889. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81890. s->lookahead += n;
  81891. /* Initialize the hash value now that we have some input: */
  81892. if (s->lookahead >= MIN_MATCH) {
  81893. s->ins_h = s->window[s->strstart];
  81894. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81895. #if MIN_MATCH != 3
  81896. Call UPDATE_HASH() MIN_MATCH-3 more times
  81897. #endif
  81898. }
  81899. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81900. * but this is not important since only literal bytes will be emitted.
  81901. */
  81902. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81903. }
  81904. /* ===========================================================================
  81905. * Flush the current block, with given end-of-file flag.
  81906. * IN assertion: strstart is set to the end of the current match.
  81907. */
  81908. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81909. _tr_flush_block(s, (s->block_start >= 0L ? \
  81910. (charf *)&s->window[(unsigned)s->block_start] : \
  81911. (charf *)Z_NULL), \
  81912. (ulg)((long)s->strstart - s->block_start), \
  81913. (eof)); \
  81914. s->block_start = s->strstart; \
  81915. flush_pending(s->strm); \
  81916. Tracev((stderr,"[FLUSH]")); \
  81917. }
  81918. /* Same but force premature exit if necessary. */
  81919. #define FLUSH_BLOCK(s, eof) { \
  81920. FLUSH_BLOCK_ONLY(s, eof); \
  81921. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81922. }
  81923. /* ===========================================================================
  81924. * Copy without compression as much as possible from the input stream, return
  81925. * the current block state.
  81926. * This function does not insert new strings in the dictionary since
  81927. * uncompressible data is probably not useful. This function is used
  81928. * only for the level=0 compression option.
  81929. * NOTE: this function should be optimized to avoid extra copying from
  81930. * window to pending_buf.
  81931. */
  81932. local block_state deflate_stored(deflate_state *s, int flush)
  81933. {
  81934. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81935. * to pending_buf_size, and each stored block has a 5 byte header:
  81936. */
  81937. ulg max_block_size = 0xffff;
  81938. ulg max_start;
  81939. if (max_block_size > s->pending_buf_size - 5) {
  81940. max_block_size = s->pending_buf_size - 5;
  81941. }
  81942. /* Copy as much as possible from input to output: */
  81943. for (;;) {
  81944. /* Fill the window as much as possible: */
  81945. if (s->lookahead <= 1) {
  81946. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81947. s->block_start >= (long)s->w_size, "slide too late");
  81948. fill_window(s);
  81949. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81950. if (s->lookahead == 0) break; /* flush the current block */
  81951. }
  81952. Assert(s->block_start >= 0L, "block gone");
  81953. s->strstart += s->lookahead;
  81954. s->lookahead = 0;
  81955. /* Emit a stored block if pending_buf will be full: */
  81956. max_start = s->block_start + max_block_size;
  81957. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81958. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81959. s->lookahead = (uInt)(s->strstart - max_start);
  81960. s->strstart = (uInt)max_start;
  81961. FLUSH_BLOCK(s, 0);
  81962. }
  81963. /* Flush if we may have to slide, otherwise block_start may become
  81964. * negative and the data will be gone:
  81965. */
  81966. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81967. FLUSH_BLOCK(s, 0);
  81968. }
  81969. }
  81970. FLUSH_BLOCK(s, flush == Z_FINISH);
  81971. return flush == Z_FINISH ? finish_done : block_done;
  81972. }
  81973. /* ===========================================================================
  81974. * Compress as much as possible from the input stream, return the current
  81975. * block state.
  81976. * This function does not perform lazy evaluation of matches and inserts
  81977. * new strings in the dictionary only for unmatched strings or for short
  81978. * matches. It is used only for the fast compression options.
  81979. */
  81980. local block_state deflate_fast(deflate_state *s, int flush)
  81981. {
  81982. IPos hash_head = NIL; /* head of the hash chain */
  81983. int bflush; /* set if current block must be flushed */
  81984. for (;;) {
  81985. /* Make sure that we always have enough lookahead, except
  81986. * at the end of the input file. We need MAX_MATCH bytes
  81987. * for the next match, plus MIN_MATCH bytes to insert the
  81988. * string following the next match.
  81989. */
  81990. if (s->lookahead < MIN_LOOKAHEAD) {
  81991. fill_window(s);
  81992. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81993. return need_more;
  81994. }
  81995. if (s->lookahead == 0) break; /* flush the current block */
  81996. }
  81997. /* Insert the string window[strstart .. strstart+2] in the
  81998. * dictionary, and set hash_head to the head of the hash chain:
  81999. */
  82000. if (s->lookahead >= MIN_MATCH) {
  82001. INSERT_STRING(s, s->strstart, hash_head);
  82002. }
  82003. /* Find the longest match, discarding those <= prev_length.
  82004. * At this point we have always match_length < MIN_MATCH
  82005. */
  82006. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82007. /* To simplify the code, we prevent matches with the string
  82008. * of window index 0 (in particular we have to avoid a match
  82009. * of the string with itself at the start of the input file).
  82010. */
  82011. #ifdef FASTEST
  82012. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82013. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82014. s->match_length = longest_match_fast (s, hash_head);
  82015. }
  82016. #else
  82017. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82018. s->match_length = longest_match (s, hash_head);
  82019. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82020. s->match_length = longest_match_fast (s, hash_head);
  82021. }
  82022. #endif
  82023. /* longest_match() or longest_match_fast() sets match_start */
  82024. }
  82025. if (s->match_length >= MIN_MATCH) {
  82026. check_match(s, s->strstart, s->match_start, s->match_length);
  82027. _tr_tally_dist(s, s->strstart - s->match_start,
  82028. s->match_length - MIN_MATCH, bflush);
  82029. s->lookahead -= s->match_length;
  82030. /* Insert new strings in the hash table only if the match length
  82031. * is not too large. This saves time but degrades compression.
  82032. */
  82033. #ifndef FASTEST
  82034. if (s->match_length <= s->max_insert_length &&
  82035. s->lookahead >= MIN_MATCH) {
  82036. s->match_length--; /* string at strstart already in table */
  82037. do {
  82038. s->strstart++;
  82039. INSERT_STRING(s, s->strstart, hash_head);
  82040. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82041. * always MIN_MATCH bytes ahead.
  82042. */
  82043. } while (--s->match_length != 0);
  82044. s->strstart++;
  82045. } else
  82046. #endif
  82047. {
  82048. s->strstart += s->match_length;
  82049. s->match_length = 0;
  82050. s->ins_h = s->window[s->strstart];
  82051. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82052. #if MIN_MATCH != 3
  82053. Call UPDATE_HASH() MIN_MATCH-3 more times
  82054. #endif
  82055. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82056. * matter since it will be recomputed at next deflate call.
  82057. */
  82058. }
  82059. } else {
  82060. /* No match, output a literal byte */
  82061. Tracevv((stderr,"%c", s->window[s->strstart]));
  82062. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82063. s->lookahead--;
  82064. s->strstart++;
  82065. }
  82066. if (bflush) FLUSH_BLOCK(s, 0);
  82067. }
  82068. FLUSH_BLOCK(s, flush == Z_FINISH);
  82069. return flush == Z_FINISH ? finish_done : block_done;
  82070. }
  82071. #ifndef FASTEST
  82072. /* ===========================================================================
  82073. * Same as above, but achieves better compression. We use a lazy
  82074. * evaluation for matches: a match is finally adopted only if there is
  82075. * no better match at the next window position.
  82076. */
  82077. local block_state deflate_slow(deflate_state *s, int flush)
  82078. {
  82079. IPos hash_head = NIL; /* head of hash chain */
  82080. int bflush; /* set if current block must be flushed */
  82081. /* Process the input block. */
  82082. for (;;) {
  82083. /* Make sure that we always have enough lookahead, except
  82084. * at the end of the input file. We need MAX_MATCH bytes
  82085. * for the next match, plus MIN_MATCH bytes to insert the
  82086. * string following the next match.
  82087. */
  82088. if (s->lookahead < MIN_LOOKAHEAD) {
  82089. fill_window(s);
  82090. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82091. return need_more;
  82092. }
  82093. if (s->lookahead == 0) break; /* flush the current block */
  82094. }
  82095. /* Insert the string window[strstart .. strstart+2] in the
  82096. * dictionary, and set hash_head to the head of the hash chain:
  82097. */
  82098. if (s->lookahead >= MIN_MATCH) {
  82099. INSERT_STRING(s, s->strstart, hash_head);
  82100. }
  82101. /* Find the longest match, discarding those <= prev_length.
  82102. */
  82103. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82104. s->match_length = MIN_MATCH-1;
  82105. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82106. s->strstart - hash_head <= MAX_DIST(s)) {
  82107. /* To simplify the code, we prevent matches with the string
  82108. * of window index 0 (in particular we have to avoid a match
  82109. * of the string with itself at the start of the input file).
  82110. */
  82111. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82112. s->match_length = longest_match (s, hash_head);
  82113. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82114. s->match_length = longest_match_fast (s, hash_head);
  82115. }
  82116. /* longest_match() or longest_match_fast() sets match_start */
  82117. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82118. #if TOO_FAR <= 32767
  82119. || (s->match_length == MIN_MATCH &&
  82120. s->strstart - s->match_start > TOO_FAR)
  82121. #endif
  82122. )) {
  82123. /* If prev_match is also MIN_MATCH, match_start is garbage
  82124. * but we will ignore the current match anyway.
  82125. */
  82126. s->match_length = MIN_MATCH-1;
  82127. }
  82128. }
  82129. /* If there was a match at the previous step and the current
  82130. * match is not better, output the previous match:
  82131. */
  82132. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82133. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82134. /* Do not insert strings in hash table beyond this. */
  82135. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82136. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82137. s->prev_length - MIN_MATCH, bflush);
  82138. /* Insert in hash table all strings up to the end of the match.
  82139. * strstart-1 and strstart are already inserted. If there is not
  82140. * enough lookahead, the last two strings are not inserted in
  82141. * the hash table.
  82142. */
  82143. s->lookahead -= s->prev_length-1;
  82144. s->prev_length -= 2;
  82145. do {
  82146. if (++s->strstart <= max_insert) {
  82147. INSERT_STRING(s, s->strstart, hash_head);
  82148. }
  82149. } while (--s->prev_length != 0);
  82150. s->match_available = 0;
  82151. s->match_length = MIN_MATCH-1;
  82152. s->strstart++;
  82153. if (bflush) FLUSH_BLOCK(s, 0);
  82154. } else if (s->match_available) {
  82155. /* If there was no match at the previous position, output a
  82156. * single literal. If there was a match but the current match
  82157. * is longer, truncate the previous match to a single literal.
  82158. */
  82159. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82160. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82161. if (bflush) {
  82162. FLUSH_BLOCK_ONLY(s, 0);
  82163. }
  82164. s->strstart++;
  82165. s->lookahead--;
  82166. if (s->strm->avail_out == 0) return need_more;
  82167. } else {
  82168. /* There is no previous match to compare with, wait for
  82169. * the next step to decide.
  82170. */
  82171. s->match_available = 1;
  82172. s->strstart++;
  82173. s->lookahead--;
  82174. }
  82175. }
  82176. Assert (flush != Z_NO_FLUSH, "no flush?");
  82177. if (s->match_available) {
  82178. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82179. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82180. s->match_available = 0;
  82181. }
  82182. FLUSH_BLOCK(s, flush == Z_FINISH);
  82183. return flush == Z_FINISH ? finish_done : block_done;
  82184. }
  82185. #endif /* FASTEST */
  82186. #if 0
  82187. /* ===========================================================================
  82188. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82189. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82190. * deflate switches away from Z_RLE.)
  82191. */
  82192. local block_state deflate_rle(s, flush)
  82193. deflate_state *s;
  82194. int flush;
  82195. {
  82196. int bflush; /* set if current block must be flushed */
  82197. uInt run; /* length of run */
  82198. uInt max; /* maximum length of run */
  82199. uInt prev; /* byte at distance one to match */
  82200. Bytef *scan; /* scan for end of run */
  82201. for (;;) {
  82202. /* Make sure that we always have enough lookahead, except
  82203. * at the end of the input file. We need MAX_MATCH bytes
  82204. * for the longest encodable run.
  82205. */
  82206. if (s->lookahead < MAX_MATCH) {
  82207. fill_window(s);
  82208. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82209. return need_more;
  82210. }
  82211. if (s->lookahead == 0) break; /* flush the current block */
  82212. }
  82213. /* See how many times the previous byte repeats */
  82214. run = 0;
  82215. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82216. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82217. scan = s->window + s->strstart - 1;
  82218. prev = *scan++;
  82219. do {
  82220. if (*scan++ != prev)
  82221. break;
  82222. } while (++run < max);
  82223. }
  82224. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82225. if (run >= MIN_MATCH) {
  82226. check_match(s, s->strstart, s->strstart - 1, run);
  82227. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82228. s->lookahead -= run;
  82229. s->strstart += run;
  82230. } else {
  82231. /* No match, output a literal byte */
  82232. Tracevv((stderr,"%c", s->window[s->strstart]));
  82233. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82234. s->lookahead--;
  82235. s->strstart++;
  82236. }
  82237. if (bflush) FLUSH_BLOCK(s, 0);
  82238. }
  82239. FLUSH_BLOCK(s, flush == Z_FINISH);
  82240. return flush == Z_FINISH ? finish_done : block_done;
  82241. }
  82242. #endif
  82243. /*** End of inlined file: deflate.c ***/
  82244. /*** Start of inlined file: inffast.c ***/
  82245. /*** Start of inlined file: inftrees.h ***/
  82246. /* WARNING: this file should *not* be used by applications. It is
  82247. part of the implementation of the compression library and is
  82248. subject to change. Applications should only use zlib.h.
  82249. */
  82250. #ifndef _INFTREES_H_
  82251. #define _INFTREES_H_
  82252. /* Structure for decoding tables. Each entry provides either the
  82253. information needed to do the operation requested by the code that
  82254. indexed that table entry, or it provides a pointer to another
  82255. table that indexes more bits of the code. op indicates whether
  82256. the entry is a pointer to another table, a literal, a length or
  82257. distance, an end-of-block, or an invalid code. For a table
  82258. pointer, the low four bits of op is the number of index bits of
  82259. that table. For a length or distance, the low four bits of op
  82260. is the number of extra bits to get after the code. bits is
  82261. the number of bits in this code or part of the code to drop off
  82262. of the bit buffer. val is the actual byte to output in the case
  82263. of a literal, the base length or distance, or the offset from
  82264. the current table to the next table. Each entry is four bytes. */
  82265. typedef struct {
  82266. unsigned char op; /* operation, extra bits, table bits */
  82267. unsigned char bits; /* bits in this part of the code */
  82268. unsigned short val; /* offset in table or code value */
  82269. } code;
  82270. /* op values as set by inflate_table():
  82271. 00000000 - literal
  82272. 0000tttt - table link, tttt != 0 is the number of table index bits
  82273. 0001eeee - length or distance, eeee is the number of extra bits
  82274. 01100000 - end of block
  82275. 01000000 - invalid code
  82276. */
  82277. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82278. exhaustive search was 1444 code structures (852 for length/literals
  82279. and 592 for distances, the latter actually the result of an
  82280. exhaustive search). The true maximum is not known, but the value
  82281. below is more than safe. */
  82282. #define ENOUGH 2048
  82283. #define MAXD 592
  82284. /* Type of code to build for inftable() */
  82285. typedef enum {
  82286. CODES,
  82287. LENS,
  82288. DISTS
  82289. } codetype;
  82290. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82291. unsigned codes, code FAR * FAR *table,
  82292. unsigned FAR *bits, unsigned short FAR *work));
  82293. #endif
  82294. /*** End of inlined file: inftrees.h ***/
  82295. /*** Start of inlined file: inflate.h ***/
  82296. /* WARNING: this file should *not* be used by applications. It is
  82297. part of the implementation of the compression library and is
  82298. subject to change. Applications should only use zlib.h.
  82299. */
  82300. #ifndef _INFLATE_H_
  82301. #define _INFLATE_H_
  82302. /* define NO_GZIP when compiling if you want to disable gzip header and
  82303. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82304. the crc code when it is not needed. For shared libraries, gzip decoding
  82305. should be left enabled. */
  82306. #ifndef NO_GZIP
  82307. # define GUNZIP
  82308. #endif
  82309. /* Possible inflate modes between inflate() calls */
  82310. typedef enum {
  82311. HEAD, /* i: waiting for magic header */
  82312. FLAGS, /* i: waiting for method and flags (gzip) */
  82313. TIME, /* i: waiting for modification time (gzip) */
  82314. OS, /* i: waiting for extra flags and operating system (gzip) */
  82315. EXLEN, /* i: waiting for extra length (gzip) */
  82316. EXTRA, /* i: waiting for extra bytes (gzip) */
  82317. NAME, /* i: waiting for end of file name (gzip) */
  82318. COMMENT, /* i: waiting for end of comment (gzip) */
  82319. HCRC, /* i: waiting for header crc (gzip) */
  82320. DICTID, /* i: waiting for dictionary check value */
  82321. DICT, /* waiting for inflateSetDictionary() call */
  82322. TYPE, /* i: waiting for type bits, including last-flag bit */
  82323. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82324. STORED, /* i: waiting for stored size (length and complement) */
  82325. COPY, /* i/o: waiting for input or output to copy stored block */
  82326. TABLE, /* i: waiting for dynamic block table lengths */
  82327. LENLENS, /* i: waiting for code length code lengths */
  82328. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82329. LEN, /* i: waiting for length/lit code */
  82330. LENEXT, /* i: waiting for length extra bits */
  82331. DIST, /* i: waiting for distance code */
  82332. DISTEXT, /* i: waiting for distance extra bits */
  82333. MATCH, /* o: waiting for output space to copy string */
  82334. LIT, /* o: waiting for output space to write literal */
  82335. CHECK, /* i: waiting for 32-bit check value */
  82336. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82337. DONE, /* finished check, done -- remain here until reset */
  82338. BAD, /* got a data error -- remain here until reset */
  82339. MEM, /* got an inflate() memory error -- remain here until reset */
  82340. SYNC /* looking for synchronization bytes to restart inflate() */
  82341. } inflate_mode;
  82342. /*
  82343. State transitions between above modes -
  82344. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82345. Process header:
  82346. HEAD -> (gzip) or (zlib)
  82347. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82348. NAME -> COMMENT -> HCRC -> TYPE
  82349. (zlib) -> DICTID or TYPE
  82350. DICTID -> DICT -> TYPE
  82351. Read deflate blocks:
  82352. TYPE -> STORED or TABLE or LEN or CHECK
  82353. STORED -> COPY -> TYPE
  82354. TABLE -> LENLENS -> CODELENS -> LEN
  82355. Read deflate codes:
  82356. LEN -> LENEXT or LIT or TYPE
  82357. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82358. LIT -> LEN
  82359. Process trailer:
  82360. CHECK -> LENGTH -> DONE
  82361. */
  82362. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82363. struct inflate_state {
  82364. inflate_mode mode; /* current inflate mode */
  82365. int last; /* true if processing last block */
  82366. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82367. int havedict; /* true if dictionary provided */
  82368. int flags; /* gzip header method and flags (0 if zlib) */
  82369. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82370. unsigned long check; /* protected copy of check value */
  82371. unsigned long total; /* protected copy of output count */
  82372. gz_headerp head; /* where to save gzip header information */
  82373. /* sliding window */
  82374. unsigned wbits; /* log base 2 of requested window size */
  82375. unsigned wsize; /* window size or zero if not using window */
  82376. unsigned whave; /* valid bytes in the window */
  82377. unsigned write; /* window write index */
  82378. unsigned char FAR *window; /* allocated sliding window, if needed */
  82379. /* bit accumulator */
  82380. unsigned long hold; /* input bit accumulator */
  82381. unsigned bits; /* number of bits in "in" */
  82382. /* for string and stored block copying */
  82383. unsigned length; /* literal or length of data to copy */
  82384. unsigned offset; /* distance back to copy string from */
  82385. /* for table and code decoding */
  82386. unsigned extra; /* extra bits needed */
  82387. /* fixed and dynamic code tables */
  82388. code const FAR *lencode; /* starting table for length/literal codes */
  82389. code const FAR *distcode; /* starting table for distance codes */
  82390. unsigned lenbits; /* index bits for lencode */
  82391. unsigned distbits; /* index bits for distcode */
  82392. /* dynamic table building */
  82393. unsigned ncode; /* number of code length code lengths */
  82394. unsigned nlen; /* number of length code lengths */
  82395. unsigned ndist; /* number of distance code lengths */
  82396. unsigned have; /* number of code lengths in lens[] */
  82397. code FAR *next; /* next available space in codes[] */
  82398. unsigned short lens[320]; /* temporary storage for code lengths */
  82399. unsigned short work[288]; /* work area for code table building */
  82400. code codes[ENOUGH]; /* space for code tables */
  82401. };
  82402. #endif
  82403. /*** End of inlined file: inflate.h ***/
  82404. /*** Start of inlined file: inffast.h ***/
  82405. /* WARNING: this file should *not* be used by applications. It is
  82406. part of the implementation of the compression library and is
  82407. subject to change. Applications should only use zlib.h.
  82408. */
  82409. void inflate_fast OF((z_streamp strm, unsigned start));
  82410. /*** End of inlined file: inffast.h ***/
  82411. #ifndef ASMINF
  82412. /* Allow machine dependent optimization for post-increment or pre-increment.
  82413. Based on testing to date,
  82414. Pre-increment preferred for:
  82415. - PowerPC G3 (Adler)
  82416. - MIPS R5000 (Randers-Pehrson)
  82417. Post-increment preferred for:
  82418. - none
  82419. No measurable difference:
  82420. - Pentium III (Anderson)
  82421. - M68060 (Nikl)
  82422. */
  82423. #ifdef POSTINC
  82424. # define OFF 0
  82425. # define PUP(a) *(a)++
  82426. #else
  82427. # define OFF 1
  82428. # define PUP(a) *++(a)
  82429. #endif
  82430. /*
  82431. Decode literal, length, and distance codes and write out the resulting
  82432. literal and match bytes until either not enough input or output is
  82433. available, an end-of-block is encountered, or a data error is encountered.
  82434. When large enough input and output buffers are supplied to inflate(), for
  82435. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82436. inflate execution time is spent in this routine.
  82437. Entry assumptions:
  82438. state->mode == LEN
  82439. strm->avail_in >= 6
  82440. strm->avail_out >= 258
  82441. start >= strm->avail_out
  82442. state->bits < 8
  82443. On return, state->mode is one of:
  82444. LEN -- ran out of enough output space or enough available input
  82445. TYPE -- reached end of block code, inflate() to interpret next block
  82446. BAD -- error in block data
  82447. Notes:
  82448. - The maximum input bits used by a length/distance pair is 15 bits for the
  82449. length code, 5 bits for the length extra, 15 bits for the distance code,
  82450. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82451. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82452. checking for available input while decoding.
  82453. - The maximum bytes that a single length/distance pair can output is 258
  82454. bytes, which is the maximum length that can be coded. inflate_fast()
  82455. requires strm->avail_out >= 258 for each loop to avoid checking for
  82456. output space.
  82457. */
  82458. void inflate_fast (z_streamp strm, unsigned start)
  82459. {
  82460. struct inflate_state FAR *state;
  82461. unsigned char FAR *in; /* local strm->next_in */
  82462. unsigned char FAR *last; /* while in < last, enough input available */
  82463. unsigned char FAR *out; /* local strm->next_out */
  82464. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82465. unsigned char FAR *end; /* while out < end, enough space available */
  82466. #ifdef INFLATE_STRICT
  82467. unsigned dmax; /* maximum distance from zlib header */
  82468. #endif
  82469. unsigned wsize; /* window size or zero if not using window */
  82470. unsigned whave; /* valid bytes in the window */
  82471. unsigned write; /* window write index */
  82472. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82473. unsigned long hold; /* local strm->hold */
  82474. unsigned bits; /* local strm->bits */
  82475. code const FAR *lcode; /* local strm->lencode */
  82476. code const FAR *dcode; /* local strm->distcode */
  82477. unsigned lmask; /* mask for first level of length codes */
  82478. unsigned dmask; /* mask for first level of distance codes */
  82479. code thisx; /* retrieved table entry */
  82480. unsigned op; /* code bits, operation, extra bits, or */
  82481. /* window position, window bytes to copy */
  82482. unsigned len; /* match length, unused bytes */
  82483. unsigned dist; /* match distance */
  82484. unsigned char FAR *from; /* where to copy match from */
  82485. /* copy state to local variables */
  82486. state = (struct inflate_state FAR *)strm->state;
  82487. in = strm->next_in - OFF;
  82488. last = in + (strm->avail_in - 5);
  82489. out = strm->next_out - OFF;
  82490. beg = out - (start - strm->avail_out);
  82491. end = out + (strm->avail_out - 257);
  82492. #ifdef INFLATE_STRICT
  82493. dmax = state->dmax;
  82494. #endif
  82495. wsize = state->wsize;
  82496. whave = state->whave;
  82497. write = state->write;
  82498. window = state->window;
  82499. hold = state->hold;
  82500. bits = state->bits;
  82501. lcode = state->lencode;
  82502. dcode = state->distcode;
  82503. lmask = (1U << state->lenbits) - 1;
  82504. dmask = (1U << state->distbits) - 1;
  82505. /* decode literals and length/distances until end-of-block or not enough
  82506. input data or output space */
  82507. do {
  82508. if (bits < 15) {
  82509. hold += (unsigned long)(PUP(in)) << bits;
  82510. bits += 8;
  82511. hold += (unsigned long)(PUP(in)) << bits;
  82512. bits += 8;
  82513. }
  82514. thisx = lcode[hold & lmask];
  82515. dolen:
  82516. op = (unsigned)(thisx.bits);
  82517. hold >>= op;
  82518. bits -= op;
  82519. op = (unsigned)(thisx.op);
  82520. if (op == 0) { /* literal */
  82521. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82522. "inflate: literal '%c'\n" :
  82523. "inflate: literal 0x%02x\n", thisx.val));
  82524. PUP(out) = (unsigned char)(thisx.val);
  82525. }
  82526. else if (op & 16) { /* length base */
  82527. len = (unsigned)(thisx.val);
  82528. op &= 15; /* number of extra bits */
  82529. if (op) {
  82530. if (bits < op) {
  82531. hold += (unsigned long)(PUP(in)) << bits;
  82532. bits += 8;
  82533. }
  82534. len += (unsigned)hold & ((1U << op) - 1);
  82535. hold >>= op;
  82536. bits -= op;
  82537. }
  82538. Tracevv((stderr, "inflate: length %u\n", len));
  82539. if (bits < 15) {
  82540. hold += (unsigned long)(PUP(in)) << bits;
  82541. bits += 8;
  82542. hold += (unsigned long)(PUP(in)) << bits;
  82543. bits += 8;
  82544. }
  82545. thisx = dcode[hold & dmask];
  82546. dodist:
  82547. op = (unsigned)(thisx.bits);
  82548. hold >>= op;
  82549. bits -= op;
  82550. op = (unsigned)(thisx.op);
  82551. if (op & 16) { /* distance base */
  82552. dist = (unsigned)(thisx.val);
  82553. op &= 15; /* number of extra bits */
  82554. if (bits < op) {
  82555. hold += (unsigned long)(PUP(in)) << bits;
  82556. bits += 8;
  82557. if (bits < op) {
  82558. hold += (unsigned long)(PUP(in)) << bits;
  82559. bits += 8;
  82560. }
  82561. }
  82562. dist += (unsigned)hold & ((1U << op) - 1);
  82563. #ifdef INFLATE_STRICT
  82564. if (dist > dmax) {
  82565. strm->msg = (char *)"invalid distance too far back";
  82566. state->mode = BAD;
  82567. break;
  82568. }
  82569. #endif
  82570. hold >>= op;
  82571. bits -= op;
  82572. Tracevv((stderr, "inflate: distance %u\n", dist));
  82573. op = (unsigned)(out - beg); /* max distance in output */
  82574. if (dist > op) { /* see if copy from window */
  82575. op = dist - op; /* distance back in window */
  82576. if (op > whave) {
  82577. strm->msg = (char *)"invalid distance too far back";
  82578. state->mode = BAD;
  82579. break;
  82580. }
  82581. from = window - OFF;
  82582. if (write == 0) { /* very common case */
  82583. from += wsize - op;
  82584. if (op < len) { /* some from window */
  82585. len -= op;
  82586. do {
  82587. PUP(out) = PUP(from);
  82588. } while (--op);
  82589. from = out - dist; /* rest from output */
  82590. }
  82591. }
  82592. else if (write < op) { /* wrap around window */
  82593. from += wsize + write - op;
  82594. op -= write;
  82595. if (op < len) { /* some from end of window */
  82596. len -= op;
  82597. do {
  82598. PUP(out) = PUP(from);
  82599. } while (--op);
  82600. from = window - OFF;
  82601. if (write < len) { /* some from start of window */
  82602. op = write;
  82603. len -= op;
  82604. do {
  82605. PUP(out) = PUP(from);
  82606. } while (--op);
  82607. from = out - dist; /* rest from output */
  82608. }
  82609. }
  82610. }
  82611. else { /* contiguous in window */
  82612. from += write - op;
  82613. if (op < len) { /* some from window */
  82614. len -= op;
  82615. do {
  82616. PUP(out) = PUP(from);
  82617. } while (--op);
  82618. from = out - dist; /* rest from output */
  82619. }
  82620. }
  82621. while (len > 2) {
  82622. PUP(out) = PUP(from);
  82623. PUP(out) = PUP(from);
  82624. PUP(out) = PUP(from);
  82625. len -= 3;
  82626. }
  82627. if (len) {
  82628. PUP(out) = PUP(from);
  82629. if (len > 1)
  82630. PUP(out) = PUP(from);
  82631. }
  82632. }
  82633. else {
  82634. from = out - dist; /* copy direct from output */
  82635. do { /* minimum length is three */
  82636. PUP(out) = PUP(from);
  82637. PUP(out) = PUP(from);
  82638. PUP(out) = PUP(from);
  82639. len -= 3;
  82640. } while (len > 2);
  82641. if (len) {
  82642. PUP(out) = PUP(from);
  82643. if (len > 1)
  82644. PUP(out) = PUP(from);
  82645. }
  82646. }
  82647. }
  82648. else if ((op & 64) == 0) { /* 2nd level distance code */
  82649. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82650. goto dodist;
  82651. }
  82652. else {
  82653. strm->msg = (char *)"invalid distance code";
  82654. state->mode = BAD;
  82655. break;
  82656. }
  82657. }
  82658. else if ((op & 64) == 0) { /* 2nd level length code */
  82659. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82660. goto dolen;
  82661. }
  82662. else if (op & 32) { /* end-of-block */
  82663. Tracevv((stderr, "inflate: end of block\n"));
  82664. state->mode = TYPE;
  82665. break;
  82666. }
  82667. else {
  82668. strm->msg = (char *)"invalid literal/length code";
  82669. state->mode = BAD;
  82670. break;
  82671. }
  82672. } while (in < last && out < end);
  82673. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82674. len = bits >> 3;
  82675. in -= len;
  82676. bits -= len << 3;
  82677. hold &= (1U << bits) - 1;
  82678. /* update state and return */
  82679. strm->next_in = in + OFF;
  82680. strm->next_out = out + OFF;
  82681. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82682. strm->avail_out = (unsigned)(out < end ?
  82683. 257 + (end - out) : 257 - (out - end));
  82684. state->hold = hold;
  82685. state->bits = bits;
  82686. return;
  82687. }
  82688. /*
  82689. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82690. - Using bit fields for code structure
  82691. - Different op definition to avoid & for extra bits (do & for table bits)
  82692. - Three separate decoding do-loops for direct, window, and write == 0
  82693. - Special case for distance > 1 copies to do overlapped load and store copy
  82694. - Explicit branch predictions (based on measured branch probabilities)
  82695. - Deferring match copy and interspersed it with decoding subsequent codes
  82696. - Swapping literal/length else
  82697. - Swapping window/direct else
  82698. - Larger unrolled copy loops (three is about right)
  82699. - Moving len -= 3 statement into middle of loop
  82700. */
  82701. #endif /* !ASMINF */
  82702. /*** End of inlined file: inffast.c ***/
  82703. #undef PULLBYTE
  82704. #undef LOAD
  82705. #undef RESTORE
  82706. #undef INITBITS
  82707. #undef NEEDBITS
  82708. #undef DROPBITS
  82709. #undef BYTEBITS
  82710. /*** Start of inlined file: inflate.c ***/
  82711. /*
  82712. * Change history:
  82713. *
  82714. * 1.2.beta0 24 Nov 2002
  82715. * - First version -- complete rewrite of inflate to simplify code, avoid
  82716. * creation of window when not needed, minimize use of window when it is
  82717. * needed, make inffast.c even faster, implement gzip decoding, and to
  82718. * improve code readability and style over the previous zlib inflate code
  82719. *
  82720. * 1.2.beta1 25 Nov 2002
  82721. * - Use pointers for available input and output checking in inffast.c
  82722. * - Remove input and output counters in inffast.c
  82723. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82724. * - Remove unnecessary second byte pull from length extra in inffast.c
  82725. * - Unroll direct copy to three copies per loop in inffast.c
  82726. *
  82727. * 1.2.beta2 4 Dec 2002
  82728. * - Change external routine names to reduce potential conflicts
  82729. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82730. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82731. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82732. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82733. *
  82734. * 1.2.beta3 22 Dec 2002
  82735. * - Add comments on state->bits assertion in inffast.c
  82736. * - Add comments on op field in inftrees.h
  82737. * - Fix bug in reuse of allocated window after inflateReset()
  82738. * - Remove bit fields--back to byte structure for speed
  82739. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82740. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82741. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82742. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82743. * - Use local copies of stream next and avail values, as well as local bit
  82744. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82745. *
  82746. * 1.2.beta4 1 Jan 2003
  82747. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82748. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82749. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82750. * - Rearrange window copies in inflate_fast() for speed and simplification
  82751. * - Unroll last copy for window match in inflate_fast()
  82752. * - Use local copies of window variables in inflate_fast() for speed
  82753. * - Pull out common write == 0 case for speed in inflate_fast()
  82754. * - Make op and len in inflate_fast() unsigned for consistency
  82755. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82756. * - Simplified bad distance check in inflate_fast()
  82757. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82758. * source file infback.c to provide a call-back interface to inflate for
  82759. * programs like gzip and unzip -- uses window as output buffer to avoid
  82760. * window copying
  82761. *
  82762. * 1.2.beta5 1 Jan 2003
  82763. * - Improved inflateBack() interface to allow the caller to provide initial
  82764. * input in strm.
  82765. * - Fixed stored blocks bug in inflateBack()
  82766. *
  82767. * 1.2.beta6 4 Jan 2003
  82768. * - Added comments in inffast.c on effectiveness of POSTINC
  82769. * - Typecasting all around to reduce compiler warnings
  82770. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82771. * make compilers happy
  82772. * - Changed type of window in inflateBackInit() to unsigned char *
  82773. *
  82774. * 1.2.beta7 27 Jan 2003
  82775. * - Changed many types to unsigned or unsigned short to avoid warnings
  82776. * - Added inflateCopy() function
  82777. *
  82778. * 1.2.0 9 Mar 2003
  82779. * - Changed inflateBack() interface to provide separate opaque descriptors
  82780. * for the in() and out() functions
  82781. * - Changed inflateBack() argument and in_func typedef to swap the length
  82782. * and buffer address return values for the input function
  82783. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82784. *
  82785. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82786. */
  82787. /*** Start of inlined file: inffast.h ***/
  82788. /* WARNING: this file should *not* be used by applications. It is
  82789. part of the implementation of the compression library and is
  82790. subject to change. Applications should only use zlib.h.
  82791. */
  82792. void inflate_fast OF((z_streamp strm, unsigned start));
  82793. /*** End of inlined file: inffast.h ***/
  82794. #ifdef MAKEFIXED
  82795. # ifndef BUILDFIXED
  82796. # define BUILDFIXED
  82797. # endif
  82798. #endif
  82799. /* function prototypes */
  82800. local void fixedtables OF((struct inflate_state FAR *state));
  82801. local int updatewindow OF((z_streamp strm, unsigned out));
  82802. #ifdef BUILDFIXED
  82803. void makefixed OF((void));
  82804. #endif
  82805. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82806. unsigned len));
  82807. int ZEXPORT inflateReset (z_streamp strm)
  82808. {
  82809. struct inflate_state FAR *state;
  82810. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82811. state = (struct inflate_state FAR *)strm->state;
  82812. strm->total_in = strm->total_out = state->total = 0;
  82813. strm->msg = Z_NULL;
  82814. strm->adler = 1; /* to support ill-conceived Java test suite */
  82815. state->mode = HEAD;
  82816. state->last = 0;
  82817. state->havedict = 0;
  82818. state->dmax = 32768U;
  82819. state->head = Z_NULL;
  82820. state->wsize = 0;
  82821. state->whave = 0;
  82822. state->write = 0;
  82823. state->hold = 0;
  82824. state->bits = 0;
  82825. state->lencode = state->distcode = state->next = state->codes;
  82826. Tracev((stderr, "inflate: reset\n"));
  82827. return Z_OK;
  82828. }
  82829. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82830. {
  82831. struct inflate_state FAR *state;
  82832. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82833. state = (struct inflate_state FAR *)strm->state;
  82834. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82835. value &= (1L << bits) - 1;
  82836. state->hold += value << state->bits;
  82837. state->bits += bits;
  82838. return Z_OK;
  82839. }
  82840. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82841. {
  82842. struct inflate_state FAR *state;
  82843. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82844. stream_size != (int)(sizeof(z_stream)))
  82845. return Z_VERSION_ERROR;
  82846. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82847. strm->msg = Z_NULL; /* in case we return an error */
  82848. if (strm->zalloc == (alloc_func)0) {
  82849. strm->zalloc = zcalloc;
  82850. strm->opaque = (voidpf)0;
  82851. }
  82852. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82853. state = (struct inflate_state FAR *)
  82854. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82855. if (state == Z_NULL) return Z_MEM_ERROR;
  82856. Tracev((stderr, "inflate: allocated\n"));
  82857. strm->state = (struct internal_state FAR *)state;
  82858. if (windowBits < 0) {
  82859. state->wrap = 0;
  82860. windowBits = -windowBits;
  82861. }
  82862. else {
  82863. state->wrap = (windowBits >> 4) + 1;
  82864. #ifdef GUNZIP
  82865. if (windowBits < 48) windowBits &= 15;
  82866. #endif
  82867. }
  82868. if (windowBits < 8 || windowBits > 15) {
  82869. ZFREE(strm, state);
  82870. strm->state = Z_NULL;
  82871. return Z_STREAM_ERROR;
  82872. }
  82873. state->wbits = (unsigned)windowBits;
  82874. state->window = Z_NULL;
  82875. return inflateReset(strm);
  82876. }
  82877. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82878. {
  82879. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82880. }
  82881. /*
  82882. Return state with length and distance decoding tables and index sizes set to
  82883. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82884. If BUILDFIXED is defined, then instead this routine builds the tables the
  82885. first time it's called, and returns those tables the first time and
  82886. thereafter. This reduces the size of the code by about 2K bytes, in
  82887. exchange for a little execution time. However, BUILDFIXED should not be
  82888. used for threaded applications, since the rewriting of the tables and virgin
  82889. may not be thread-safe.
  82890. */
  82891. local void fixedtables (struct inflate_state FAR *state)
  82892. {
  82893. #ifdef BUILDFIXED
  82894. static int virgin = 1;
  82895. static code *lenfix, *distfix;
  82896. static code fixed[544];
  82897. /* build fixed huffman tables if first call (may not be thread safe) */
  82898. if (virgin) {
  82899. unsigned sym, bits;
  82900. static code *next;
  82901. /* literal/length table */
  82902. sym = 0;
  82903. while (sym < 144) state->lens[sym++] = 8;
  82904. while (sym < 256) state->lens[sym++] = 9;
  82905. while (sym < 280) state->lens[sym++] = 7;
  82906. while (sym < 288) state->lens[sym++] = 8;
  82907. next = fixed;
  82908. lenfix = next;
  82909. bits = 9;
  82910. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82911. /* distance table */
  82912. sym = 0;
  82913. while (sym < 32) state->lens[sym++] = 5;
  82914. distfix = next;
  82915. bits = 5;
  82916. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82917. /* do this just once */
  82918. virgin = 0;
  82919. }
  82920. #else /* !BUILDFIXED */
  82921. /*** Start of inlined file: inffixed.h ***/
  82922. /* WARNING: this file should *not* be used by applications. It
  82923. is part of the implementation of the compression library and
  82924. is subject to change. Applications should only use zlib.h.
  82925. */
  82926. static const code lenfix[512] = {
  82927. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82928. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82929. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82930. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82931. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82932. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82933. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82934. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82935. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82936. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82937. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82938. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82939. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82940. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82941. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82942. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82943. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82944. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82945. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82946. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82947. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82948. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82949. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82950. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82951. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82952. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82953. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82954. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82955. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82956. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82957. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82958. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82959. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82960. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82961. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82962. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82963. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82964. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82965. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82966. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82967. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82968. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82969. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82970. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82971. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82972. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82973. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82974. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82975. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82976. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82977. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82978. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82979. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82980. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82981. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82982. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82983. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82984. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82985. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82986. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82987. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82988. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82989. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82990. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82991. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82992. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82993. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82994. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82995. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82996. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82997. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82998. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82999. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83000. {0,9,255}
  83001. };
  83002. static const code distfix[32] = {
  83003. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83004. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83005. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83006. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83007. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83008. {22,5,193},{64,5,0}
  83009. };
  83010. /*** End of inlined file: inffixed.h ***/
  83011. #endif /* BUILDFIXED */
  83012. state->lencode = lenfix;
  83013. state->lenbits = 9;
  83014. state->distcode = distfix;
  83015. state->distbits = 5;
  83016. }
  83017. #ifdef MAKEFIXED
  83018. #include <stdio.h>
  83019. /*
  83020. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83021. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83022. those tables to stdout, which would be piped to inffixed.h. A small program
  83023. can simply call makefixed to do this:
  83024. void makefixed(void);
  83025. int main(void)
  83026. {
  83027. makefixed();
  83028. return 0;
  83029. }
  83030. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83031. a.out > inffixed.h
  83032. */
  83033. void makefixed()
  83034. {
  83035. unsigned low, size;
  83036. struct inflate_state state;
  83037. fixedtables(&state);
  83038. puts(" /* inffixed.h -- table for decoding fixed codes");
  83039. puts(" * Generated automatically by makefixed().");
  83040. puts(" */");
  83041. puts("");
  83042. puts(" /* WARNING: this file should *not* be used by applications.");
  83043. puts(" It is part of the implementation of this library and is");
  83044. puts(" subject to change. Applications should only use zlib.h.");
  83045. puts(" */");
  83046. puts("");
  83047. size = 1U << 9;
  83048. printf(" static const code lenfix[%u] = {", size);
  83049. low = 0;
  83050. for (;;) {
  83051. if ((low % 7) == 0) printf("\n ");
  83052. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83053. state.lencode[low].val);
  83054. if (++low == size) break;
  83055. putchar(',');
  83056. }
  83057. puts("\n };");
  83058. size = 1U << 5;
  83059. printf("\n static const code distfix[%u] = {", size);
  83060. low = 0;
  83061. for (;;) {
  83062. if ((low % 6) == 0) printf("\n ");
  83063. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83064. state.distcode[low].val);
  83065. if (++low == size) break;
  83066. putchar(',');
  83067. }
  83068. puts("\n };");
  83069. }
  83070. #endif /* MAKEFIXED */
  83071. /*
  83072. Update the window with the last wsize (normally 32K) bytes written before
  83073. returning. If window does not exist yet, create it. This is only called
  83074. when a window is already in use, or when output has been written during this
  83075. inflate call, but the end of the deflate stream has not been reached yet.
  83076. It is also called to create a window for dictionary data when a dictionary
  83077. is loaded.
  83078. Providing output buffers larger than 32K to inflate() should provide a speed
  83079. advantage, since only the last 32K of output is copied to the sliding window
  83080. upon return from inflate(), and since all distances after the first 32K of
  83081. output will fall in the output data, making match copies simpler and faster.
  83082. The advantage may be dependent on the size of the processor's data caches.
  83083. */
  83084. local int updatewindow (z_streamp strm, unsigned out)
  83085. {
  83086. struct inflate_state FAR *state;
  83087. unsigned copy, dist;
  83088. state = (struct inflate_state FAR *)strm->state;
  83089. /* if it hasn't been done already, allocate space for the window */
  83090. if (state->window == Z_NULL) {
  83091. state->window = (unsigned char FAR *)
  83092. ZALLOC(strm, 1U << state->wbits,
  83093. sizeof(unsigned char));
  83094. if (state->window == Z_NULL) return 1;
  83095. }
  83096. /* if window not in use yet, initialize */
  83097. if (state->wsize == 0) {
  83098. state->wsize = 1U << state->wbits;
  83099. state->write = 0;
  83100. state->whave = 0;
  83101. }
  83102. /* copy state->wsize or less output bytes into the circular window */
  83103. copy = out - strm->avail_out;
  83104. if (copy >= state->wsize) {
  83105. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83106. state->write = 0;
  83107. state->whave = state->wsize;
  83108. }
  83109. else {
  83110. dist = state->wsize - state->write;
  83111. if (dist > copy) dist = copy;
  83112. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83113. copy -= dist;
  83114. if (copy) {
  83115. zmemcpy(state->window, strm->next_out - copy, copy);
  83116. state->write = copy;
  83117. state->whave = state->wsize;
  83118. }
  83119. else {
  83120. state->write += dist;
  83121. if (state->write == state->wsize) state->write = 0;
  83122. if (state->whave < state->wsize) state->whave += dist;
  83123. }
  83124. }
  83125. return 0;
  83126. }
  83127. /* Macros for inflate(): */
  83128. /* check function to use adler32() for zlib or crc32() for gzip */
  83129. #ifdef GUNZIP
  83130. # define UPDATE(check, buf, len) \
  83131. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83132. #else
  83133. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83134. #endif
  83135. /* check macros for header crc */
  83136. #ifdef GUNZIP
  83137. # define CRC2(check, word) \
  83138. do { \
  83139. hbuf[0] = (unsigned char)(word); \
  83140. hbuf[1] = (unsigned char)((word) >> 8); \
  83141. check = crc32(check, hbuf, 2); \
  83142. } while (0)
  83143. # define CRC4(check, word) \
  83144. do { \
  83145. hbuf[0] = (unsigned char)(word); \
  83146. hbuf[1] = (unsigned char)((word) >> 8); \
  83147. hbuf[2] = (unsigned char)((word) >> 16); \
  83148. hbuf[3] = (unsigned char)((word) >> 24); \
  83149. check = crc32(check, hbuf, 4); \
  83150. } while (0)
  83151. #endif
  83152. /* Load registers with state in inflate() for speed */
  83153. #define LOAD() \
  83154. do { \
  83155. put = strm->next_out; \
  83156. left = strm->avail_out; \
  83157. next = strm->next_in; \
  83158. have = strm->avail_in; \
  83159. hold = state->hold; \
  83160. bits = state->bits; \
  83161. } while (0)
  83162. /* Restore state from registers in inflate() */
  83163. #define RESTORE() \
  83164. do { \
  83165. strm->next_out = put; \
  83166. strm->avail_out = left; \
  83167. strm->next_in = next; \
  83168. strm->avail_in = have; \
  83169. state->hold = hold; \
  83170. state->bits = bits; \
  83171. } while (0)
  83172. /* Clear the input bit accumulator */
  83173. #define INITBITS() \
  83174. do { \
  83175. hold = 0; \
  83176. bits = 0; \
  83177. } while (0)
  83178. /* Get a byte of input into the bit accumulator, or return from inflate()
  83179. if there is no input available. */
  83180. #define PULLBYTE() \
  83181. do { \
  83182. if (have == 0) goto inf_leave; \
  83183. have--; \
  83184. hold += (unsigned long)(*next++) << bits; \
  83185. bits += 8; \
  83186. } while (0)
  83187. /* Assure that there are at least n bits in the bit accumulator. If there is
  83188. not enough available input to do that, then return from inflate(). */
  83189. #define NEEDBITS(n) \
  83190. do { \
  83191. while (bits < (unsigned)(n)) \
  83192. PULLBYTE(); \
  83193. } while (0)
  83194. /* Return the low n bits of the bit accumulator (n < 16) */
  83195. #define BITS(n) \
  83196. ((unsigned)hold & ((1U << (n)) - 1))
  83197. /* Remove n bits from the bit accumulator */
  83198. #define DROPBITS(n) \
  83199. do { \
  83200. hold >>= (n); \
  83201. bits -= (unsigned)(n); \
  83202. } while (0)
  83203. /* Remove zero to seven bits as needed to go to a byte boundary */
  83204. #define BYTEBITS() \
  83205. do { \
  83206. hold >>= bits & 7; \
  83207. bits -= bits & 7; \
  83208. } while (0)
  83209. /* Reverse the bytes in a 32-bit value */
  83210. #define REVERSE(q) \
  83211. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83212. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83213. /*
  83214. inflate() uses a state machine to process as much input data and generate as
  83215. much output data as possible before returning. The state machine is
  83216. structured roughly as follows:
  83217. for (;;) switch (state) {
  83218. ...
  83219. case STATEn:
  83220. if (not enough input data or output space to make progress)
  83221. return;
  83222. ... make progress ...
  83223. state = STATEm;
  83224. break;
  83225. ...
  83226. }
  83227. so when inflate() is called again, the same case is attempted again, and
  83228. if the appropriate resources are provided, the machine proceeds to the
  83229. next state. The NEEDBITS() macro is usually the way the state evaluates
  83230. whether it can proceed or should return. NEEDBITS() does the return if
  83231. the requested bits are not available. The typical use of the BITS macros
  83232. is:
  83233. NEEDBITS(n);
  83234. ... do something with BITS(n) ...
  83235. DROPBITS(n);
  83236. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83237. input left to load n bits into the accumulator, or it continues. BITS(n)
  83238. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83239. the low n bits off the accumulator. INITBITS() clears the accumulator
  83240. and sets the number of available bits to zero. BYTEBITS() discards just
  83241. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83242. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83243. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83244. if there is no input available. The decoding of variable length codes uses
  83245. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83246. code, and no more.
  83247. Some states loop until they get enough input, making sure that enough
  83248. state information is maintained to continue the loop where it left off
  83249. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83250. would all have to actually be part of the saved state in case NEEDBITS()
  83251. returns:
  83252. case STATEw:
  83253. while (want < need) {
  83254. NEEDBITS(n);
  83255. keep[want++] = BITS(n);
  83256. DROPBITS(n);
  83257. }
  83258. state = STATEx;
  83259. case STATEx:
  83260. As shown above, if the next state is also the next case, then the break
  83261. is omitted.
  83262. A state may also return if there is not enough output space available to
  83263. complete that state. Those states are copying stored data, writing a
  83264. literal byte, and copying a matching string.
  83265. When returning, a "goto inf_leave" is used to update the total counters,
  83266. update the check value, and determine whether any progress has been made
  83267. during that inflate() call in order to return the proper return code.
  83268. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83269. When there is a window, goto inf_leave will update the window with the last
  83270. output written. If a goto inf_leave occurs in the middle of decompression
  83271. and there is no window currently, goto inf_leave will create one and copy
  83272. output to the window for the next call of inflate().
  83273. In this implementation, the flush parameter of inflate() only affects the
  83274. return code (per zlib.h). inflate() always writes as much as possible to
  83275. strm->next_out, given the space available and the provided input--the effect
  83276. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83277. the allocation of and copying into a sliding window until necessary, which
  83278. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83279. stream available. So the only thing the flush parameter actually does is:
  83280. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83281. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83282. */
  83283. int ZEXPORT inflate (z_streamp strm, int flush)
  83284. {
  83285. struct inflate_state FAR *state;
  83286. unsigned char FAR *next; /* next input */
  83287. unsigned char FAR *put; /* next output */
  83288. unsigned have, left; /* available input and output */
  83289. unsigned long hold; /* bit buffer */
  83290. unsigned bits; /* bits in bit buffer */
  83291. unsigned in, out; /* save starting available input and output */
  83292. unsigned copy; /* number of stored or match bytes to copy */
  83293. unsigned char FAR *from; /* where to copy match bytes from */
  83294. code thisx; /* current decoding table entry */
  83295. code last; /* parent table entry */
  83296. unsigned len; /* length to copy for repeats, bits to drop */
  83297. int ret; /* return code */
  83298. #ifdef GUNZIP
  83299. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83300. #endif
  83301. static const unsigned short order[19] = /* permutation of code lengths */
  83302. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83303. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83304. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83305. return Z_STREAM_ERROR;
  83306. state = (struct inflate_state FAR *)strm->state;
  83307. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83308. LOAD();
  83309. in = have;
  83310. out = left;
  83311. ret = Z_OK;
  83312. for (;;)
  83313. switch (state->mode) {
  83314. case HEAD:
  83315. if (state->wrap == 0) {
  83316. state->mode = TYPEDO;
  83317. break;
  83318. }
  83319. NEEDBITS(16);
  83320. #ifdef GUNZIP
  83321. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83322. state->check = crc32(0L, Z_NULL, 0);
  83323. CRC2(state->check, hold);
  83324. INITBITS();
  83325. state->mode = FLAGS;
  83326. break;
  83327. }
  83328. state->flags = 0; /* expect zlib header */
  83329. if (state->head != Z_NULL)
  83330. state->head->done = -1;
  83331. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83332. #else
  83333. if (
  83334. #endif
  83335. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83336. strm->msg = (char *)"incorrect header check";
  83337. state->mode = BAD;
  83338. break;
  83339. }
  83340. if (BITS(4) != Z_DEFLATED) {
  83341. strm->msg = (char *)"unknown compression method";
  83342. state->mode = BAD;
  83343. break;
  83344. }
  83345. DROPBITS(4);
  83346. len = BITS(4) + 8;
  83347. if (len > state->wbits) {
  83348. strm->msg = (char *)"invalid window size";
  83349. state->mode = BAD;
  83350. break;
  83351. }
  83352. state->dmax = 1U << len;
  83353. Tracev((stderr, "inflate: zlib header ok\n"));
  83354. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83355. state->mode = hold & 0x200 ? DICTID : TYPE;
  83356. INITBITS();
  83357. break;
  83358. #ifdef GUNZIP
  83359. case FLAGS:
  83360. NEEDBITS(16);
  83361. state->flags = (int)(hold);
  83362. if ((state->flags & 0xff) != Z_DEFLATED) {
  83363. strm->msg = (char *)"unknown compression method";
  83364. state->mode = BAD;
  83365. break;
  83366. }
  83367. if (state->flags & 0xe000) {
  83368. strm->msg = (char *)"unknown header flags set";
  83369. state->mode = BAD;
  83370. break;
  83371. }
  83372. if (state->head != Z_NULL)
  83373. state->head->text = (int)((hold >> 8) & 1);
  83374. if (state->flags & 0x0200) CRC2(state->check, hold);
  83375. INITBITS();
  83376. state->mode = TIME;
  83377. case TIME:
  83378. NEEDBITS(32);
  83379. if (state->head != Z_NULL)
  83380. state->head->time = hold;
  83381. if (state->flags & 0x0200) CRC4(state->check, hold);
  83382. INITBITS();
  83383. state->mode = OS;
  83384. case OS:
  83385. NEEDBITS(16);
  83386. if (state->head != Z_NULL) {
  83387. state->head->xflags = (int)(hold & 0xff);
  83388. state->head->os = (int)(hold >> 8);
  83389. }
  83390. if (state->flags & 0x0200) CRC2(state->check, hold);
  83391. INITBITS();
  83392. state->mode = EXLEN;
  83393. case EXLEN:
  83394. if (state->flags & 0x0400) {
  83395. NEEDBITS(16);
  83396. state->length = (unsigned)(hold);
  83397. if (state->head != Z_NULL)
  83398. state->head->extra_len = (unsigned)hold;
  83399. if (state->flags & 0x0200) CRC2(state->check, hold);
  83400. INITBITS();
  83401. }
  83402. else if (state->head != Z_NULL)
  83403. state->head->extra = Z_NULL;
  83404. state->mode = EXTRA;
  83405. case EXTRA:
  83406. if (state->flags & 0x0400) {
  83407. copy = state->length;
  83408. if (copy > have) copy = have;
  83409. if (copy) {
  83410. if (state->head != Z_NULL &&
  83411. state->head->extra != Z_NULL) {
  83412. len = state->head->extra_len - state->length;
  83413. zmemcpy(state->head->extra + len, next,
  83414. len + copy > state->head->extra_max ?
  83415. state->head->extra_max - len : copy);
  83416. }
  83417. if (state->flags & 0x0200)
  83418. state->check = crc32(state->check, next, copy);
  83419. have -= copy;
  83420. next += copy;
  83421. state->length -= copy;
  83422. }
  83423. if (state->length) goto inf_leave;
  83424. }
  83425. state->length = 0;
  83426. state->mode = NAME;
  83427. case NAME:
  83428. if (state->flags & 0x0800) {
  83429. if (have == 0) goto inf_leave;
  83430. copy = 0;
  83431. do {
  83432. len = (unsigned)(next[copy++]);
  83433. if (state->head != Z_NULL &&
  83434. state->head->name != Z_NULL &&
  83435. state->length < state->head->name_max)
  83436. state->head->name[state->length++] = len;
  83437. } while (len && copy < have);
  83438. if (state->flags & 0x0200)
  83439. state->check = crc32(state->check, next, copy);
  83440. have -= copy;
  83441. next += copy;
  83442. if (len) goto inf_leave;
  83443. }
  83444. else if (state->head != Z_NULL)
  83445. state->head->name = Z_NULL;
  83446. state->length = 0;
  83447. state->mode = COMMENT;
  83448. case COMMENT:
  83449. if (state->flags & 0x1000) {
  83450. if (have == 0) goto inf_leave;
  83451. copy = 0;
  83452. do {
  83453. len = (unsigned)(next[copy++]);
  83454. if (state->head != Z_NULL &&
  83455. state->head->comment != Z_NULL &&
  83456. state->length < state->head->comm_max)
  83457. state->head->comment[state->length++] = len;
  83458. } while (len && copy < have);
  83459. if (state->flags & 0x0200)
  83460. state->check = crc32(state->check, next, copy);
  83461. have -= copy;
  83462. next += copy;
  83463. if (len) goto inf_leave;
  83464. }
  83465. else if (state->head != Z_NULL)
  83466. state->head->comment = Z_NULL;
  83467. state->mode = HCRC;
  83468. case HCRC:
  83469. if (state->flags & 0x0200) {
  83470. NEEDBITS(16);
  83471. if (hold != (state->check & 0xffff)) {
  83472. strm->msg = (char *)"header crc mismatch";
  83473. state->mode = BAD;
  83474. break;
  83475. }
  83476. INITBITS();
  83477. }
  83478. if (state->head != Z_NULL) {
  83479. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83480. state->head->done = 1;
  83481. }
  83482. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83483. state->mode = TYPE;
  83484. break;
  83485. #endif
  83486. case DICTID:
  83487. NEEDBITS(32);
  83488. strm->adler = state->check = REVERSE(hold);
  83489. INITBITS();
  83490. state->mode = DICT;
  83491. case DICT:
  83492. if (state->havedict == 0) {
  83493. RESTORE();
  83494. return Z_NEED_DICT;
  83495. }
  83496. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83497. state->mode = TYPE;
  83498. case TYPE:
  83499. if (flush == Z_BLOCK) goto inf_leave;
  83500. case TYPEDO:
  83501. if (state->last) {
  83502. BYTEBITS();
  83503. state->mode = CHECK;
  83504. break;
  83505. }
  83506. NEEDBITS(3);
  83507. state->last = BITS(1);
  83508. DROPBITS(1);
  83509. switch (BITS(2)) {
  83510. case 0: /* stored block */
  83511. Tracev((stderr, "inflate: stored block%s\n",
  83512. state->last ? " (last)" : ""));
  83513. state->mode = STORED;
  83514. break;
  83515. case 1: /* fixed block */
  83516. fixedtables(state);
  83517. Tracev((stderr, "inflate: fixed codes block%s\n",
  83518. state->last ? " (last)" : ""));
  83519. state->mode = LEN; /* decode codes */
  83520. break;
  83521. case 2: /* dynamic block */
  83522. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83523. state->last ? " (last)" : ""));
  83524. state->mode = TABLE;
  83525. break;
  83526. case 3:
  83527. strm->msg = (char *)"invalid block type";
  83528. state->mode = BAD;
  83529. }
  83530. DROPBITS(2);
  83531. break;
  83532. case STORED:
  83533. BYTEBITS(); /* go to byte boundary */
  83534. NEEDBITS(32);
  83535. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83536. strm->msg = (char *)"invalid stored block lengths";
  83537. state->mode = BAD;
  83538. break;
  83539. }
  83540. state->length = (unsigned)hold & 0xffff;
  83541. Tracev((stderr, "inflate: stored length %u\n",
  83542. state->length));
  83543. INITBITS();
  83544. state->mode = COPY;
  83545. case COPY:
  83546. copy = state->length;
  83547. if (copy) {
  83548. if (copy > have) copy = have;
  83549. if (copy > left) copy = left;
  83550. if (copy == 0) goto inf_leave;
  83551. zmemcpy(put, next, copy);
  83552. have -= copy;
  83553. next += copy;
  83554. left -= copy;
  83555. put += copy;
  83556. state->length -= copy;
  83557. break;
  83558. }
  83559. Tracev((stderr, "inflate: stored end\n"));
  83560. state->mode = TYPE;
  83561. break;
  83562. case TABLE:
  83563. NEEDBITS(14);
  83564. state->nlen = BITS(5) + 257;
  83565. DROPBITS(5);
  83566. state->ndist = BITS(5) + 1;
  83567. DROPBITS(5);
  83568. state->ncode = BITS(4) + 4;
  83569. DROPBITS(4);
  83570. #ifndef PKZIP_BUG_WORKAROUND
  83571. if (state->nlen > 286 || state->ndist > 30) {
  83572. strm->msg = (char *)"too many length or distance symbols";
  83573. state->mode = BAD;
  83574. break;
  83575. }
  83576. #endif
  83577. Tracev((stderr, "inflate: table sizes ok\n"));
  83578. state->have = 0;
  83579. state->mode = LENLENS;
  83580. case LENLENS:
  83581. while (state->have < state->ncode) {
  83582. NEEDBITS(3);
  83583. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83584. DROPBITS(3);
  83585. }
  83586. while (state->have < 19)
  83587. state->lens[order[state->have++]] = 0;
  83588. state->next = state->codes;
  83589. state->lencode = (code const FAR *)(state->next);
  83590. state->lenbits = 7;
  83591. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83592. &(state->lenbits), state->work);
  83593. if (ret) {
  83594. strm->msg = (char *)"invalid code lengths set";
  83595. state->mode = BAD;
  83596. break;
  83597. }
  83598. Tracev((stderr, "inflate: code lengths ok\n"));
  83599. state->have = 0;
  83600. state->mode = CODELENS;
  83601. case CODELENS:
  83602. while (state->have < state->nlen + state->ndist) {
  83603. for (;;) {
  83604. thisx = state->lencode[BITS(state->lenbits)];
  83605. if ((unsigned)(thisx.bits) <= bits) break;
  83606. PULLBYTE();
  83607. }
  83608. if (thisx.val < 16) {
  83609. NEEDBITS(thisx.bits);
  83610. DROPBITS(thisx.bits);
  83611. state->lens[state->have++] = thisx.val;
  83612. }
  83613. else {
  83614. if (thisx.val == 16) {
  83615. NEEDBITS(thisx.bits + 2);
  83616. DROPBITS(thisx.bits);
  83617. if (state->have == 0) {
  83618. strm->msg = (char *)"invalid bit length repeat";
  83619. state->mode = BAD;
  83620. break;
  83621. }
  83622. len = state->lens[state->have - 1];
  83623. copy = 3 + BITS(2);
  83624. DROPBITS(2);
  83625. }
  83626. else if (thisx.val == 17) {
  83627. NEEDBITS(thisx.bits + 3);
  83628. DROPBITS(thisx.bits);
  83629. len = 0;
  83630. copy = 3 + BITS(3);
  83631. DROPBITS(3);
  83632. }
  83633. else {
  83634. NEEDBITS(thisx.bits + 7);
  83635. DROPBITS(thisx.bits);
  83636. len = 0;
  83637. copy = 11 + BITS(7);
  83638. DROPBITS(7);
  83639. }
  83640. if (state->have + copy > state->nlen + state->ndist) {
  83641. strm->msg = (char *)"invalid bit length repeat";
  83642. state->mode = BAD;
  83643. break;
  83644. }
  83645. while (copy--)
  83646. state->lens[state->have++] = (unsigned short)len;
  83647. }
  83648. }
  83649. /* handle error breaks in while */
  83650. if (state->mode == BAD) break;
  83651. /* build code tables */
  83652. state->next = state->codes;
  83653. state->lencode = (code const FAR *)(state->next);
  83654. state->lenbits = 9;
  83655. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83656. &(state->lenbits), state->work);
  83657. if (ret) {
  83658. strm->msg = (char *)"invalid literal/lengths set";
  83659. state->mode = BAD;
  83660. break;
  83661. }
  83662. state->distcode = (code const FAR *)(state->next);
  83663. state->distbits = 6;
  83664. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83665. &(state->next), &(state->distbits), state->work);
  83666. if (ret) {
  83667. strm->msg = (char *)"invalid distances set";
  83668. state->mode = BAD;
  83669. break;
  83670. }
  83671. Tracev((stderr, "inflate: codes ok\n"));
  83672. state->mode = LEN;
  83673. case LEN:
  83674. if (have >= 6 && left >= 258) {
  83675. RESTORE();
  83676. inflate_fast(strm, out);
  83677. LOAD();
  83678. break;
  83679. }
  83680. for (;;) {
  83681. thisx = state->lencode[BITS(state->lenbits)];
  83682. if ((unsigned)(thisx.bits) <= bits) break;
  83683. PULLBYTE();
  83684. }
  83685. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83686. last = thisx;
  83687. for (;;) {
  83688. thisx = state->lencode[last.val +
  83689. (BITS(last.bits + last.op) >> last.bits)];
  83690. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83691. PULLBYTE();
  83692. }
  83693. DROPBITS(last.bits);
  83694. }
  83695. DROPBITS(thisx.bits);
  83696. state->length = (unsigned)thisx.val;
  83697. if ((int)(thisx.op) == 0) {
  83698. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83699. "inflate: literal '%c'\n" :
  83700. "inflate: literal 0x%02x\n", thisx.val));
  83701. state->mode = LIT;
  83702. break;
  83703. }
  83704. if (thisx.op & 32) {
  83705. Tracevv((stderr, "inflate: end of block\n"));
  83706. state->mode = TYPE;
  83707. break;
  83708. }
  83709. if (thisx.op & 64) {
  83710. strm->msg = (char *)"invalid literal/length code";
  83711. state->mode = BAD;
  83712. break;
  83713. }
  83714. state->extra = (unsigned)(thisx.op) & 15;
  83715. state->mode = LENEXT;
  83716. case LENEXT:
  83717. if (state->extra) {
  83718. NEEDBITS(state->extra);
  83719. state->length += BITS(state->extra);
  83720. DROPBITS(state->extra);
  83721. }
  83722. Tracevv((stderr, "inflate: length %u\n", state->length));
  83723. state->mode = DIST;
  83724. case DIST:
  83725. for (;;) {
  83726. thisx = state->distcode[BITS(state->distbits)];
  83727. if ((unsigned)(thisx.bits) <= bits) break;
  83728. PULLBYTE();
  83729. }
  83730. if ((thisx.op & 0xf0) == 0) {
  83731. last = thisx;
  83732. for (;;) {
  83733. thisx = state->distcode[last.val +
  83734. (BITS(last.bits + last.op) >> last.bits)];
  83735. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83736. PULLBYTE();
  83737. }
  83738. DROPBITS(last.bits);
  83739. }
  83740. DROPBITS(thisx.bits);
  83741. if (thisx.op & 64) {
  83742. strm->msg = (char *)"invalid distance code";
  83743. state->mode = BAD;
  83744. break;
  83745. }
  83746. state->offset = (unsigned)thisx.val;
  83747. state->extra = (unsigned)(thisx.op) & 15;
  83748. state->mode = DISTEXT;
  83749. case DISTEXT:
  83750. if (state->extra) {
  83751. NEEDBITS(state->extra);
  83752. state->offset += BITS(state->extra);
  83753. DROPBITS(state->extra);
  83754. }
  83755. #ifdef INFLATE_STRICT
  83756. if (state->offset > state->dmax) {
  83757. strm->msg = (char *)"invalid distance too far back";
  83758. state->mode = BAD;
  83759. break;
  83760. }
  83761. #endif
  83762. if (state->offset > state->whave + out - left) {
  83763. strm->msg = (char *)"invalid distance too far back";
  83764. state->mode = BAD;
  83765. break;
  83766. }
  83767. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83768. state->mode = MATCH;
  83769. case MATCH:
  83770. if (left == 0) goto inf_leave;
  83771. copy = out - left;
  83772. if (state->offset > copy) { /* copy from window */
  83773. copy = state->offset - copy;
  83774. if (copy > state->write) {
  83775. copy -= state->write;
  83776. from = state->window + (state->wsize - copy);
  83777. }
  83778. else
  83779. from = state->window + (state->write - copy);
  83780. if (copy > state->length) copy = state->length;
  83781. }
  83782. else { /* copy from output */
  83783. from = put - state->offset;
  83784. copy = state->length;
  83785. }
  83786. if (copy > left) copy = left;
  83787. left -= copy;
  83788. state->length -= copy;
  83789. do {
  83790. *put++ = *from++;
  83791. } while (--copy);
  83792. if (state->length == 0) state->mode = LEN;
  83793. break;
  83794. case LIT:
  83795. if (left == 0) goto inf_leave;
  83796. *put++ = (unsigned char)(state->length);
  83797. left--;
  83798. state->mode = LEN;
  83799. break;
  83800. case CHECK:
  83801. if (state->wrap) {
  83802. NEEDBITS(32);
  83803. out -= left;
  83804. strm->total_out += out;
  83805. state->total += out;
  83806. if (out)
  83807. strm->adler = state->check =
  83808. UPDATE(state->check, put - out, out);
  83809. out = left;
  83810. if ((
  83811. #ifdef GUNZIP
  83812. state->flags ? hold :
  83813. #endif
  83814. REVERSE(hold)) != state->check) {
  83815. strm->msg = (char *)"incorrect data check";
  83816. state->mode = BAD;
  83817. break;
  83818. }
  83819. INITBITS();
  83820. Tracev((stderr, "inflate: check matches trailer\n"));
  83821. }
  83822. #ifdef GUNZIP
  83823. state->mode = LENGTH;
  83824. case LENGTH:
  83825. if (state->wrap && state->flags) {
  83826. NEEDBITS(32);
  83827. if (hold != (state->total & 0xffffffffUL)) {
  83828. strm->msg = (char *)"incorrect length check";
  83829. state->mode = BAD;
  83830. break;
  83831. }
  83832. INITBITS();
  83833. Tracev((stderr, "inflate: length matches trailer\n"));
  83834. }
  83835. #endif
  83836. state->mode = DONE;
  83837. case DONE:
  83838. ret = Z_STREAM_END;
  83839. goto inf_leave;
  83840. case BAD:
  83841. ret = Z_DATA_ERROR;
  83842. goto inf_leave;
  83843. case MEM:
  83844. return Z_MEM_ERROR;
  83845. case SYNC:
  83846. default:
  83847. return Z_STREAM_ERROR;
  83848. }
  83849. /*
  83850. Return from inflate(), updating the total counts and the check value.
  83851. If there was no progress during the inflate() call, return a buffer
  83852. error. Call updatewindow() to create and/or update the window state.
  83853. Note: a memory error from inflate() is non-recoverable.
  83854. */
  83855. inf_leave:
  83856. RESTORE();
  83857. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83858. if (updatewindow(strm, out)) {
  83859. state->mode = MEM;
  83860. return Z_MEM_ERROR;
  83861. }
  83862. in -= strm->avail_in;
  83863. out -= strm->avail_out;
  83864. strm->total_in += in;
  83865. strm->total_out += out;
  83866. state->total += out;
  83867. if (state->wrap && out)
  83868. strm->adler = state->check =
  83869. UPDATE(state->check, strm->next_out - out, out);
  83870. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83871. (state->mode == TYPE ? 128 : 0);
  83872. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83873. ret = Z_BUF_ERROR;
  83874. return ret;
  83875. }
  83876. int ZEXPORT inflateEnd (z_streamp strm)
  83877. {
  83878. struct inflate_state FAR *state;
  83879. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83880. return Z_STREAM_ERROR;
  83881. state = (struct inflate_state FAR *)strm->state;
  83882. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83883. ZFREE(strm, strm->state);
  83884. strm->state = Z_NULL;
  83885. Tracev((stderr, "inflate: end\n"));
  83886. return Z_OK;
  83887. }
  83888. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83889. {
  83890. struct inflate_state FAR *state;
  83891. unsigned long id_;
  83892. /* check state */
  83893. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83894. state = (struct inflate_state FAR *)strm->state;
  83895. if (state->wrap != 0 && state->mode != DICT)
  83896. return Z_STREAM_ERROR;
  83897. /* check for correct dictionary id */
  83898. if (state->mode == DICT) {
  83899. id_ = adler32(0L, Z_NULL, 0);
  83900. id_ = adler32(id_, dictionary, dictLength);
  83901. if (id_ != state->check)
  83902. return Z_DATA_ERROR;
  83903. }
  83904. /* copy dictionary to window */
  83905. if (updatewindow(strm, strm->avail_out)) {
  83906. state->mode = MEM;
  83907. return Z_MEM_ERROR;
  83908. }
  83909. if (dictLength > state->wsize) {
  83910. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83911. state->wsize);
  83912. state->whave = state->wsize;
  83913. }
  83914. else {
  83915. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83916. dictLength);
  83917. state->whave = dictLength;
  83918. }
  83919. state->havedict = 1;
  83920. Tracev((stderr, "inflate: dictionary set\n"));
  83921. return Z_OK;
  83922. }
  83923. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83924. {
  83925. struct inflate_state FAR *state;
  83926. /* check state */
  83927. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83928. state = (struct inflate_state FAR *)strm->state;
  83929. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83930. /* save header structure */
  83931. state->head = head;
  83932. head->done = 0;
  83933. return Z_OK;
  83934. }
  83935. /*
  83936. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83937. or when out of input. When called, *have is the number of pattern bytes
  83938. found in order so far, in 0..3. On return *have is updated to the new
  83939. state. If on return *have equals four, then the pattern was found and the
  83940. return value is how many bytes were read including the last byte of the
  83941. pattern. If *have is less than four, then the pattern has not been found
  83942. yet and the return value is len. In the latter case, syncsearch() can be
  83943. called again with more data and the *have state. *have is initialized to
  83944. zero for the first call.
  83945. */
  83946. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83947. {
  83948. unsigned got;
  83949. unsigned next;
  83950. got = *have;
  83951. next = 0;
  83952. while (next < len && got < 4) {
  83953. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83954. got++;
  83955. else if (buf[next])
  83956. got = 0;
  83957. else
  83958. got = 4 - got;
  83959. next++;
  83960. }
  83961. *have = got;
  83962. return next;
  83963. }
  83964. int ZEXPORT inflateSync (z_streamp strm)
  83965. {
  83966. unsigned len; /* number of bytes to look at or looked at */
  83967. unsigned long in, out; /* temporary to save total_in and total_out */
  83968. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83969. struct inflate_state FAR *state;
  83970. /* check parameters */
  83971. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83972. state = (struct inflate_state FAR *)strm->state;
  83973. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83974. /* if first time, start search in bit buffer */
  83975. if (state->mode != SYNC) {
  83976. state->mode = SYNC;
  83977. state->hold <<= state->bits & 7;
  83978. state->bits -= state->bits & 7;
  83979. len = 0;
  83980. while (state->bits >= 8) {
  83981. buf[len++] = (unsigned char)(state->hold);
  83982. state->hold >>= 8;
  83983. state->bits -= 8;
  83984. }
  83985. state->have = 0;
  83986. syncsearch(&(state->have), buf, len);
  83987. }
  83988. /* search available input */
  83989. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83990. strm->avail_in -= len;
  83991. strm->next_in += len;
  83992. strm->total_in += len;
  83993. /* return no joy or set up to restart inflate() on a new block */
  83994. if (state->have != 4) return Z_DATA_ERROR;
  83995. in = strm->total_in; out = strm->total_out;
  83996. inflateReset(strm);
  83997. strm->total_in = in; strm->total_out = out;
  83998. state->mode = TYPE;
  83999. return Z_OK;
  84000. }
  84001. /*
  84002. Returns true if inflate is currently at the end of a block generated by
  84003. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84004. implementation to provide an additional safety check. PPP uses
  84005. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84006. block. When decompressing, PPP checks that at the end of input packet,
  84007. inflate is waiting for these length bytes.
  84008. */
  84009. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84010. {
  84011. struct inflate_state FAR *state;
  84012. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84013. state = (struct inflate_state FAR *)strm->state;
  84014. return state->mode == STORED && state->bits == 0;
  84015. }
  84016. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84017. {
  84018. struct inflate_state FAR *state;
  84019. struct inflate_state FAR *copy;
  84020. unsigned char FAR *window;
  84021. unsigned wsize;
  84022. /* check input */
  84023. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84024. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84025. return Z_STREAM_ERROR;
  84026. state = (struct inflate_state FAR *)source->state;
  84027. /* allocate space */
  84028. copy = (struct inflate_state FAR *)
  84029. ZALLOC(source, 1, sizeof(struct inflate_state));
  84030. if (copy == Z_NULL) return Z_MEM_ERROR;
  84031. window = Z_NULL;
  84032. if (state->window != Z_NULL) {
  84033. window = (unsigned char FAR *)
  84034. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84035. if (window == Z_NULL) {
  84036. ZFREE(source, copy);
  84037. return Z_MEM_ERROR;
  84038. }
  84039. }
  84040. /* copy state */
  84041. zmemcpy(dest, source, sizeof(z_stream));
  84042. zmemcpy(copy, state, sizeof(struct inflate_state));
  84043. if (state->lencode >= state->codes &&
  84044. state->lencode <= state->codes + ENOUGH - 1) {
  84045. copy->lencode = copy->codes + (state->lencode - state->codes);
  84046. copy->distcode = copy->codes + (state->distcode - state->codes);
  84047. }
  84048. copy->next = copy->codes + (state->next - state->codes);
  84049. if (window != Z_NULL) {
  84050. wsize = 1U << state->wbits;
  84051. zmemcpy(window, state->window, wsize);
  84052. }
  84053. copy->window = window;
  84054. dest->state = (struct internal_state FAR *)copy;
  84055. return Z_OK;
  84056. }
  84057. /*** End of inlined file: inflate.c ***/
  84058. /*** Start of inlined file: inftrees.c ***/
  84059. #define MAXBITS 15
  84060. const char inflate_copyright[] =
  84061. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84062. /*
  84063. If you use the zlib library in a product, an acknowledgment is welcome
  84064. in the documentation of your product. If for some reason you cannot
  84065. include such an acknowledgment, I would appreciate that you keep this
  84066. copyright string in the executable of your product.
  84067. */
  84068. /*
  84069. Build a set of tables to decode the provided canonical Huffman code.
  84070. The code lengths are lens[0..codes-1]. The result starts at *table,
  84071. whose indices are 0..2^bits-1. work is a writable array of at least
  84072. lens shorts, which is used as a work area. type is the type of code
  84073. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84074. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84075. on return points to the next available entry's address. bits is the
  84076. requested root table index bits, and on return it is the actual root
  84077. table index bits. It will differ if the request is greater than the
  84078. longest code or if it is less than the shortest code.
  84079. */
  84080. int inflate_table (codetype type,
  84081. unsigned short FAR *lens,
  84082. unsigned codes,
  84083. code FAR * FAR *table,
  84084. unsigned FAR *bits,
  84085. unsigned short FAR *work)
  84086. {
  84087. unsigned len; /* a code's length in bits */
  84088. unsigned sym; /* index of code symbols */
  84089. unsigned min, max; /* minimum and maximum code lengths */
  84090. unsigned root; /* number of index bits for root table */
  84091. unsigned curr; /* number of index bits for current table */
  84092. unsigned drop; /* code bits to drop for sub-table */
  84093. int left; /* number of prefix codes available */
  84094. unsigned used; /* code entries in table used */
  84095. unsigned huff; /* Huffman code */
  84096. unsigned incr; /* for incrementing code, index */
  84097. unsigned fill; /* index for replicating entries */
  84098. unsigned low; /* low bits for current root entry */
  84099. unsigned mask; /* mask for low root bits */
  84100. code thisx; /* table entry for duplication */
  84101. code FAR *next; /* next available space in table */
  84102. const unsigned short FAR *base; /* base value table to use */
  84103. const unsigned short FAR *extra; /* extra bits table to use */
  84104. int end; /* use base and extra for symbol > end */
  84105. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84106. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84107. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84108. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84109. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84110. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84111. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84112. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84113. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84114. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84115. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84116. 8193, 12289, 16385, 24577, 0, 0};
  84117. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84118. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84119. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84120. 28, 28, 29, 29, 64, 64};
  84121. /*
  84122. Process a set of code lengths to create a canonical Huffman code. The
  84123. code lengths are lens[0..codes-1]. Each length corresponds to the
  84124. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84125. symbols by length from short to long, and retaining the symbol order
  84126. for codes with equal lengths. Then the code starts with all zero bits
  84127. for the first code of the shortest length, and the codes are integer
  84128. increments for the same length, and zeros are appended as the length
  84129. increases. For the deflate format, these bits are stored backwards
  84130. from their more natural integer increment ordering, and so when the
  84131. decoding tables are built in the large loop below, the integer codes
  84132. are incremented backwards.
  84133. This routine assumes, but does not check, that all of the entries in
  84134. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84135. 1..MAXBITS is interpreted as that code length. zero means that that
  84136. symbol does not occur in this code.
  84137. The codes are sorted by computing a count of codes for each length,
  84138. creating from that a table of starting indices for each length in the
  84139. sorted table, and then entering the symbols in order in the sorted
  84140. table. The sorted table is work[], with that space being provided by
  84141. the caller.
  84142. The length counts are used for other purposes as well, i.e. finding
  84143. the minimum and maximum length codes, determining if there are any
  84144. codes at all, checking for a valid set of lengths, and looking ahead
  84145. at length counts to determine sub-table sizes when building the
  84146. decoding tables.
  84147. */
  84148. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84149. for (len = 0; len <= MAXBITS; len++)
  84150. count[len] = 0;
  84151. for (sym = 0; sym < codes; sym++)
  84152. count[lens[sym]]++;
  84153. /* bound code lengths, force root to be within code lengths */
  84154. root = *bits;
  84155. for (max = MAXBITS; max >= 1; max--)
  84156. if (count[max] != 0) break;
  84157. if (root > max) root = max;
  84158. if (max == 0) { /* no symbols to code at all */
  84159. thisx.op = (unsigned char)64; /* invalid code marker */
  84160. thisx.bits = (unsigned char)1;
  84161. thisx.val = (unsigned short)0;
  84162. *(*table)++ = thisx; /* make a table to force an error */
  84163. *(*table)++ = thisx;
  84164. *bits = 1;
  84165. return 0; /* no symbols, but wait for decoding to report error */
  84166. }
  84167. for (min = 1; min <= MAXBITS; min++)
  84168. if (count[min] != 0) break;
  84169. if (root < min) root = min;
  84170. /* check for an over-subscribed or incomplete set of lengths */
  84171. left = 1;
  84172. for (len = 1; len <= MAXBITS; len++) {
  84173. left <<= 1;
  84174. left -= count[len];
  84175. if (left < 0) return -1; /* over-subscribed */
  84176. }
  84177. if (left > 0 && (type == CODES || max != 1))
  84178. return -1; /* incomplete set */
  84179. /* generate offsets into symbol table for each length for sorting */
  84180. offs[1] = 0;
  84181. for (len = 1; len < MAXBITS; len++)
  84182. offs[len + 1] = offs[len] + count[len];
  84183. /* sort symbols by length, by symbol order within each length */
  84184. for (sym = 0; sym < codes; sym++)
  84185. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84186. /*
  84187. Create and fill in decoding tables. In this loop, the table being
  84188. filled is at next and has curr index bits. The code being used is huff
  84189. with length len. That code is converted to an index by dropping drop
  84190. bits off of the bottom. For codes where len is less than drop + curr,
  84191. those top drop + curr - len bits are incremented through all values to
  84192. fill the table with replicated entries.
  84193. root is the number of index bits for the root table. When len exceeds
  84194. root, sub-tables are created pointed to by the root entry with an index
  84195. of the low root bits of huff. This is saved in low to check for when a
  84196. new sub-table should be started. drop is zero when the root table is
  84197. being filled, and drop is root when sub-tables are being filled.
  84198. When a new sub-table is needed, it is necessary to look ahead in the
  84199. code lengths to determine what size sub-table is needed. The length
  84200. counts are used for this, and so count[] is decremented as codes are
  84201. entered in the tables.
  84202. used keeps track of how many table entries have been allocated from the
  84203. provided *table space. It is checked when a LENS table is being made
  84204. against the space in *table, ENOUGH, minus the maximum space needed by
  84205. the worst case distance code, MAXD. This should never happen, but the
  84206. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84207. This assumes that when type == LENS, bits == 9.
  84208. sym increments through all symbols, and the loop terminates when
  84209. all codes of length max, i.e. all codes, have been processed. This
  84210. routine permits incomplete codes, so another loop after this one fills
  84211. in the rest of the decoding tables with invalid code markers.
  84212. */
  84213. /* set up for code type */
  84214. switch (type) {
  84215. case CODES:
  84216. base = extra = work; /* dummy value--not used */
  84217. end = 19;
  84218. break;
  84219. case LENS:
  84220. base = lbase;
  84221. base -= 257;
  84222. extra = lext;
  84223. extra -= 257;
  84224. end = 256;
  84225. break;
  84226. default: /* DISTS */
  84227. base = dbase;
  84228. extra = dext;
  84229. end = -1;
  84230. }
  84231. /* initialize state for loop */
  84232. huff = 0; /* starting code */
  84233. sym = 0; /* starting code symbol */
  84234. len = min; /* starting code length */
  84235. next = *table; /* current table to fill in */
  84236. curr = root; /* current table index bits */
  84237. drop = 0; /* current bits to drop from code for index */
  84238. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84239. used = 1U << root; /* use root table entries */
  84240. mask = used - 1; /* mask for comparing low */
  84241. /* check available table space */
  84242. if (type == LENS && used >= ENOUGH - MAXD)
  84243. return 1;
  84244. /* process all codes and make table entries */
  84245. for (;;) {
  84246. /* create table entry */
  84247. thisx.bits = (unsigned char)(len - drop);
  84248. if ((int)(work[sym]) < end) {
  84249. thisx.op = (unsigned char)0;
  84250. thisx.val = work[sym];
  84251. }
  84252. else if ((int)(work[sym]) > end) {
  84253. thisx.op = (unsigned char)(extra[work[sym]]);
  84254. thisx.val = base[work[sym]];
  84255. }
  84256. else {
  84257. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84258. thisx.val = 0;
  84259. }
  84260. /* replicate for those indices with low len bits equal to huff */
  84261. incr = 1U << (len - drop);
  84262. fill = 1U << curr;
  84263. min = fill; /* save offset to next table */
  84264. do {
  84265. fill -= incr;
  84266. next[(huff >> drop) + fill] = thisx;
  84267. } while (fill != 0);
  84268. /* backwards increment the len-bit code huff */
  84269. incr = 1U << (len - 1);
  84270. while (huff & incr)
  84271. incr >>= 1;
  84272. if (incr != 0) {
  84273. huff &= incr - 1;
  84274. huff += incr;
  84275. }
  84276. else
  84277. huff = 0;
  84278. /* go to next symbol, update count, len */
  84279. sym++;
  84280. if (--(count[len]) == 0) {
  84281. if (len == max) break;
  84282. len = lens[work[sym]];
  84283. }
  84284. /* create new sub-table if needed */
  84285. if (len > root && (huff & mask) != low) {
  84286. /* if first time, transition to sub-tables */
  84287. if (drop == 0)
  84288. drop = root;
  84289. /* increment past last table */
  84290. next += min; /* here min is 1 << curr */
  84291. /* determine length of next table */
  84292. curr = len - drop;
  84293. left = (int)(1 << curr);
  84294. while (curr + drop < max) {
  84295. left -= count[curr + drop];
  84296. if (left <= 0) break;
  84297. curr++;
  84298. left <<= 1;
  84299. }
  84300. /* check for enough space */
  84301. used += 1U << curr;
  84302. if (type == LENS && used >= ENOUGH - MAXD)
  84303. return 1;
  84304. /* point entry in root table to sub-table */
  84305. low = huff & mask;
  84306. (*table)[low].op = (unsigned char)curr;
  84307. (*table)[low].bits = (unsigned char)root;
  84308. (*table)[low].val = (unsigned short)(next - *table);
  84309. }
  84310. }
  84311. /*
  84312. Fill in rest of table for incomplete codes. This loop is similar to the
  84313. loop above in incrementing huff for table indices. It is assumed that
  84314. len is equal to curr + drop, so there is no loop needed to increment
  84315. through high index bits. When the current sub-table is filled, the loop
  84316. drops back to the root table to fill in any remaining entries there.
  84317. */
  84318. thisx.op = (unsigned char)64; /* invalid code marker */
  84319. thisx.bits = (unsigned char)(len - drop);
  84320. thisx.val = (unsigned short)0;
  84321. while (huff != 0) {
  84322. /* when done with sub-table, drop back to root table */
  84323. if (drop != 0 && (huff & mask) != low) {
  84324. drop = 0;
  84325. len = root;
  84326. next = *table;
  84327. thisx.bits = (unsigned char)len;
  84328. }
  84329. /* put invalid code marker in table */
  84330. next[huff >> drop] = thisx;
  84331. /* backwards increment the len-bit code huff */
  84332. incr = 1U << (len - 1);
  84333. while (huff & incr)
  84334. incr >>= 1;
  84335. if (incr != 0) {
  84336. huff &= incr - 1;
  84337. huff += incr;
  84338. }
  84339. else
  84340. huff = 0;
  84341. }
  84342. /* set return parameters */
  84343. *table += used;
  84344. *bits = root;
  84345. return 0;
  84346. }
  84347. /*** End of inlined file: inftrees.c ***/
  84348. /*** Start of inlined file: trees.c ***/
  84349. /*
  84350. * ALGORITHM
  84351. *
  84352. * The "deflation" process uses several Huffman trees. The more
  84353. * common source values are represented by shorter bit sequences.
  84354. *
  84355. * Each code tree is stored in a compressed form which is itself
  84356. * a Huffman encoding of the lengths of all the code strings (in
  84357. * ascending order by source values). The actual code strings are
  84358. * reconstructed from the lengths in the inflate process, as described
  84359. * in the deflate specification.
  84360. *
  84361. * REFERENCES
  84362. *
  84363. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84364. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84365. *
  84366. * Storer, James A.
  84367. * Data Compression: Methods and Theory, pp. 49-50.
  84368. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84369. *
  84370. * Sedgewick, R.
  84371. * Algorithms, p290.
  84372. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84373. */
  84374. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84375. /* #define GEN_TREES_H */
  84376. #ifdef DEBUG
  84377. # include <ctype.h>
  84378. #endif
  84379. /* ===========================================================================
  84380. * Constants
  84381. */
  84382. #define MAX_BL_BITS 7
  84383. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84384. #define END_BLOCK 256
  84385. /* end of block literal code */
  84386. #define REP_3_6 16
  84387. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84388. #define REPZ_3_10 17
  84389. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84390. #define REPZ_11_138 18
  84391. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84392. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84393. = {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};
  84394. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84395. = {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};
  84396. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84397. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84398. local const uch bl_order[BL_CODES]
  84399. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84400. /* The lengths of the bit length codes are sent in order of decreasing
  84401. * probability, to avoid transmitting the lengths for unused bit length codes.
  84402. */
  84403. #define Buf_size (8 * 2*sizeof(char))
  84404. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84405. * more than 16 bits on some systems.)
  84406. */
  84407. /* ===========================================================================
  84408. * Local data. These are initialized only once.
  84409. */
  84410. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84411. #if defined(GEN_TREES_H) || !defined(STDC)
  84412. /* non ANSI compilers may not accept trees.h */
  84413. local ct_data static_ltree[L_CODES+2];
  84414. /* The static literal tree. Since the bit lengths are imposed, there is no
  84415. * need for the L_CODES extra codes used during heap construction. However
  84416. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84417. * below).
  84418. */
  84419. local ct_data static_dtree[D_CODES];
  84420. /* The static distance tree. (Actually a trivial tree since all codes use
  84421. * 5 bits.)
  84422. */
  84423. uch _dist_code[DIST_CODE_LEN];
  84424. /* Distance codes. The first 256 values correspond to the distances
  84425. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84426. * the 15 bit distances.
  84427. */
  84428. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84429. /* length code for each normalized match length (0 == MIN_MATCH) */
  84430. local int base_length[LENGTH_CODES];
  84431. /* First normalized length for each code (0 = MIN_MATCH) */
  84432. local int base_dist[D_CODES];
  84433. /* First normalized distance for each code (0 = distance of 1) */
  84434. #else
  84435. /*** Start of inlined file: trees.h ***/
  84436. local const ct_data static_ltree[L_CODES+2] = {
  84437. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84438. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84439. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84440. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84441. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84442. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84443. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84444. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84445. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84446. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84447. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84448. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84449. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84450. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84451. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84452. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84453. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84454. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84455. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84456. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84457. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84458. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84459. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84460. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84461. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84462. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84463. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84464. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84465. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84466. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84467. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84468. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84469. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84470. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84471. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84472. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84473. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84474. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84475. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84476. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84477. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84478. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84479. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84480. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84481. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84482. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84483. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84484. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84485. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84486. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84487. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84488. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84489. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84490. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84491. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84492. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84493. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84494. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84495. };
  84496. local const ct_data static_dtree[D_CODES] = {
  84497. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84498. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84499. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84500. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84501. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84502. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84503. };
  84504. const uch _dist_code[DIST_CODE_LEN] = {
  84505. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84506. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84507. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84508. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84509. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84510. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84511. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84512. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84513. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84514. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84515. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84516. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84517. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84518. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84519. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84520. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84521. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84522. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84523. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84524. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84525. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84526. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84527. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84528. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84529. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84530. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84531. };
  84532. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84533. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84534. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84535. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84536. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84537. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84538. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84539. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84540. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84541. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84542. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84543. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84544. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84545. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84546. };
  84547. local const int base_length[LENGTH_CODES] = {
  84548. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84549. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84550. };
  84551. local const int base_dist[D_CODES] = {
  84552. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84553. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84554. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84555. };
  84556. /*** End of inlined file: trees.h ***/
  84557. #endif /* GEN_TREES_H */
  84558. struct static_tree_desc_s {
  84559. const ct_data *static_tree; /* static tree or NULL */
  84560. const intf *extra_bits; /* extra bits for each code or NULL */
  84561. int extra_base; /* base index for extra_bits */
  84562. int elems; /* max number of elements in the tree */
  84563. int max_length; /* max bit length for the codes */
  84564. };
  84565. local static_tree_desc static_l_desc =
  84566. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84567. local static_tree_desc static_d_desc =
  84568. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84569. local static_tree_desc static_bl_desc =
  84570. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84571. /* ===========================================================================
  84572. * Local (static) routines in this file.
  84573. */
  84574. local void tr_static_init OF((void));
  84575. local void init_block OF((deflate_state *s));
  84576. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84577. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84578. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84579. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84580. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84581. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84582. local int build_bl_tree OF((deflate_state *s));
  84583. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84584. int blcodes));
  84585. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84586. ct_data *dtree));
  84587. local void set_data_type OF((deflate_state *s));
  84588. local unsigned bi_reverse OF((unsigned value, int length));
  84589. local void bi_windup OF((deflate_state *s));
  84590. local void bi_flush OF((deflate_state *s));
  84591. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84592. int header));
  84593. #ifdef GEN_TREES_H
  84594. local void gen_trees_header OF((void));
  84595. #endif
  84596. #ifndef DEBUG
  84597. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84598. /* Send a code of the given tree. c and tree must not have side effects */
  84599. #else /* DEBUG */
  84600. # define send_code(s, c, tree) \
  84601. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84602. send_bits(s, tree[c].Code, tree[c].Len); }
  84603. #endif
  84604. /* ===========================================================================
  84605. * Output a short LSB first on the stream.
  84606. * IN assertion: there is enough room in pendingBuf.
  84607. */
  84608. #define put_short(s, w) { \
  84609. put_byte(s, (uch)((w) & 0xff)); \
  84610. put_byte(s, (uch)((ush)(w) >> 8)); \
  84611. }
  84612. /* ===========================================================================
  84613. * Send a value on a given number of bits.
  84614. * IN assertion: length <= 16 and value fits in length bits.
  84615. */
  84616. #ifdef DEBUG
  84617. local void send_bits OF((deflate_state *s, int value, int length));
  84618. local void send_bits (deflate_state *s, int value, int length)
  84619. {
  84620. Tracevv((stderr," l %2d v %4x ", length, value));
  84621. Assert(length > 0 && length <= 15, "invalid length");
  84622. s->bits_sent += (ulg)length;
  84623. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84624. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84625. * unused bits in value.
  84626. */
  84627. if (s->bi_valid > (int)Buf_size - length) {
  84628. s->bi_buf |= (value << s->bi_valid);
  84629. put_short(s, s->bi_buf);
  84630. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84631. s->bi_valid += length - Buf_size;
  84632. } else {
  84633. s->bi_buf |= value << s->bi_valid;
  84634. s->bi_valid += length;
  84635. }
  84636. }
  84637. #else /* !DEBUG */
  84638. #define send_bits(s, value, length) \
  84639. { int len = length;\
  84640. if (s->bi_valid > (int)Buf_size - len) {\
  84641. int val = value;\
  84642. s->bi_buf |= (val << s->bi_valid);\
  84643. put_short(s, s->bi_buf);\
  84644. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84645. s->bi_valid += len - Buf_size;\
  84646. } else {\
  84647. s->bi_buf |= (value) << s->bi_valid;\
  84648. s->bi_valid += len;\
  84649. }\
  84650. }
  84651. #endif /* DEBUG */
  84652. /* the arguments must not have side effects */
  84653. /* ===========================================================================
  84654. * Initialize the various 'constant' tables.
  84655. */
  84656. local void tr_static_init()
  84657. {
  84658. #if defined(GEN_TREES_H) || !defined(STDC)
  84659. static int static_init_done = 0;
  84660. int n; /* iterates over tree elements */
  84661. int bits; /* bit counter */
  84662. int length; /* length value */
  84663. int code; /* code value */
  84664. int dist; /* distance index */
  84665. ush bl_count[MAX_BITS+1];
  84666. /* number of codes at each bit length for an optimal tree */
  84667. if (static_init_done) return;
  84668. /* For some embedded targets, global variables are not initialized: */
  84669. static_l_desc.static_tree = static_ltree;
  84670. static_l_desc.extra_bits = extra_lbits;
  84671. static_d_desc.static_tree = static_dtree;
  84672. static_d_desc.extra_bits = extra_dbits;
  84673. static_bl_desc.extra_bits = extra_blbits;
  84674. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84675. length = 0;
  84676. for (code = 0; code < LENGTH_CODES-1; code++) {
  84677. base_length[code] = length;
  84678. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84679. _length_code[length++] = (uch)code;
  84680. }
  84681. }
  84682. Assert (length == 256, "tr_static_init: length != 256");
  84683. /* Note that the length 255 (match length 258) can be represented
  84684. * in two different ways: code 284 + 5 bits or code 285, so we
  84685. * overwrite length_code[255] to use the best encoding:
  84686. */
  84687. _length_code[length-1] = (uch)code;
  84688. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84689. dist = 0;
  84690. for (code = 0 ; code < 16; code++) {
  84691. base_dist[code] = dist;
  84692. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84693. _dist_code[dist++] = (uch)code;
  84694. }
  84695. }
  84696. Assert (dist == 256, "tr_static_init: dist != 256");
  84697. dist >>= 7; /* from now on, all distances are divided by 128 */
  84698. for ( ; code < D_CODES; code++) {
  84699. base_dist[code] = dist << 7;
  84700. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84701. _dist_code[256 + dist++] = (uch)code;
  84702. }
  84703. }
  84704. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84705. /* Construct the codes of the static literal tree */
  84706. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84707. n = 0;
  84708. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84709. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84710. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84711. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84712. /* Codes 286 and 287 do not exist, but we must include them in the
  84713. * tree construction to get a canonical Huffman tree (longest code
  84714. * all ones)
  84715. */
  84716. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84717. /* The static distance tree is trivial: */
  84718. for (n = 0; n < D_CODES; n++) {
  84719. static_dtree[n].Len = 5;
  84720. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84721. }
  84722. static_init_done = 1;
  84723. # ifdef GEN_TREES_H
  84724. gen_trees_header();
  84725. # endif
  84726. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84727. }
  84728. /* ===========================================================================
  84729. * Genererate the file trees.h describing the static trees.
  84730. */
  84731. #ifdef GEN_TREES_H
  84732. # ifndef DEBUG
  84733. # include <stdio.h>
  84734. # endif
  84735. # define SEPARATOR(i, last, width) \
  84736. ((i) == (last)? "\n};\n\n" : \
  84737. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84738. void gen_trees_header()
  84739. {
  84740. FILE *header = fopen("trees.h", "w");
  84741. int i;
  84742. Assert (header != NULL, "Can't open trees.h");
  84743. fprintf(header,
  84744. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84745. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84746. for (i = 0; i < L_CODES+2; i++) {
  84747. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84748. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84749. }
  84750. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84751. for (i = 0; i < D_CODES; i++) {
  84752. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84753. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84754. }
  84755. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84756. for (i = 0; i < DIST_CODE_LEN; i++) {
  84757. fprintf(header, "%2u%s", _dist_code[i],
  84758. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84759. }
  84760. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84761. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84762. fprintf(header, "%2u%s", _length_code[i],
  84763. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84764. }
  84765. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84766. for (i = 0; i < LENGTH_CODES; i++) {
  84767. fprintf(header, "%1u%s", base_length[i],
  84768. SEPARATOR(i, LENGTH_CODES-1, 20));
  84769. }
  84770. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84771. for (i = 0; i < D_CODES; i++) {
  84772. fprintf(header, "%5u%s", base_dist[i],
  84773. SEPARATOR(i, D_CODES-1, 10));
  84774. }
  84775. fclose(header);
  84776. }
  84777. #endif /* GEN_TREES_H */
  84778. /* ===========================================================================
  84779. * Initialize the tree data structures for a new zlib stream.
  84780. */
  84781. void _tr_init(deflate_state *s)
  84782. {
  84783. tr_static_init();
  84784. s->l_desc.dyn_tree = s->dyn_ltree;
  84785. s->l_desc.stat_desc = &static_l_desc;
  84786. s->d_desc.dyn_tree = s->dyn_dtree;
  84787. s->d_desc.stat_desc = &static_d_desc;
  84788. s->bl_desc.dyn_tree = s->bl_tree;
  84789. s->bl_desc.stat_desc = &static_bl_desc;
  84790. s->bi_buf = 0;
  84791. s->bi_valid = 0;
  84792. s->last_eob_len = 8; /* enough lookahead for inflate */
  84793. #ifdef DEBUG
  84794. s->compressed_len = 0L;
  84795. s->bits_sent = 0L;
  84796. #endif
  84797. /* Initialize the first block of the first file: */
  84798. init_block(s);
  84799. }
  84800. /* ===========================================================================
  84801. * Initialize a new block.
  84802. */
  84803. local void init_block (deflate_state *s)
  84804. {
  84805. int n; /* iterates over tree elements */
  84806. /* Initialize the trees. */
  84807. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84808. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84809. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84810. s->dyn_ltree[END_BLOCK].Freq = 1;
  84811. s->opt_len = s->static_len = 0L;
  84812. s->last_lit = s->matches = 0;
  84813. }
  84814. #define SMALLEST 1
  84815. /* Index within the heap array of least frequent node in the Huffman tree */
  84816. /* ===========================================================================
  84817. * Remove the smallest element from the heap and recreate the heap with
  84818. * one less element. Updates heap and heap_len.
  84819. */
  84820. #define pqremove(s, tree, top) \
  84821. {\
  84822. top = s->heap[SMALLEST]; \
  84823. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84824. pqdownheap(s, tree, SMALLEST); \
  84825. }
  84826. /* ===========================================================================
  84827. * Compares to subtrees, using the tree depth as tie breaker when
  84828. * the subtrees have equal frequency. This minimizes the worst case length.
  84829. */
  84830. #define smaller(tree, n, m, depth) \
  84831. (tree[n].Freq < tree[m].Freq || \
  84832. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84833. /* ===========================================================================
  84834. * Restore the heap property by moving down the tree starting at node k,
  84835. * exchanging a node with the smallest of its two sons if necessary, stopping
  84836. * when the heap property is re-established (each father smaller than its
  84837. * two sons).
  84838. */
  84839. local void pqdownheap (deflate_state *s,
  84840. ct_data *tree, /* the tree to restore */
  84841. int k) /* node to move down */
  84842. {
  84843. int v = s->heap[k];
  84844. int j = k << 1; /* left son of k */
  84845. while (j <= s->heap_len) {
  84846. /* Set j to the smallest of the two sons: */
  84847. if (j < s->heap_len &&
  84848. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84849. j++;
  84850. }
  84851. /* Exit if v is smaller than both sons */
  84852. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84853. /* Exchange v with the smallest son */
  84854. s->heap[k] = s->heap[j]; k = j;
  84855. /* And continue down the tree, setting j to the left son of k */
  84856. j <<= 1;
  84857. }
  84858. s->heap[k] = v;
  84859. }
  84860. /* ===========================================================================
  84861. * Compute the optimal bit lengths for a tree and update the total bit length
  84862. * for the current block.
  84863. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84864. * above are the tree nodes sorted by increasing frequency.
  84865. * OUT assertions: the field len is set to the optimal bit length, the
  84866. * array bl_count contains the frequencies for each bit length.
  84867. * The length opt_len is updated; static_len is also updated if stree is
  84868. * not null.
  84869. */
  84870. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84871. {
  84872. ct_data *tree = desc->dyn_tree;
  84873. int max_code = desc->max_code;
  84874. const ct_data *stree = desc->stat_desc->static_tree;
  84875. const intf *extra = desc->stat_desc->extra_bits;
  84876. int base = desc->stat_desc->extra_base;
  84877. int max_length = desc->stat_desc->max_length;
  84878. int h; /* heap index */
  84879. int n, m; /* iterate over the tree elements */
  84880. int bits; /* bit length */
  84881. int xbits; /* extra bits */
  84882. ush f; /* frequency */
  84883. int overflow = 0; /* number of elements with bit length too large */
  84884. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84885. /* In a first pass, compute the optimal bit lengths (which may
  84886. * overflow in the case of the bit length tree).
  84887. */
  84888. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84889. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84890. n = s->heap[h];
  84891. bits = tree[tree[n].Dad].Len + 1;
  84892. if (bits > max_length) bits = max_length, overflow++;
  84893. tree[n].Len = (ush)bits;
  84894. /* We overwrite tree[n].Dad which is no longer needed */
  84895. if (n > max_code) continue; /* not a leaf node */
  84896. s->bl_count[bits]++;
  84897. xbits = 0;
  84898. if (n >= base) xbits = extra[n-base];
  84899. f = tree[n].Freq;
  84900. s->opt_len += (ulg)f * (bits + xbits);
  84901. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84902. }
  84903. if (overflow == 0) return;
  84904. Trace((stderr,"\nbit length overflow\n"));
  84905. /* This happens for example on obj2 and pic of the Calgary corpus */
  84906. /* Find the first bit length which could increase: */
  84907. do {
  84908. bits = max_length-1;
  84909. while (s->bl_count[bits] == 0) bits--;
  84910. s->bl_count[bits]--; /* move one leaf down the tree */
  84911. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84912. s->bl_count[max_length]--;
  84913. /* The brother of the overflow item also moves one step up,
  84914. * but this does not affect bl_count[max_length]
  84915. */
  84916. overflow -= 2;
  84917. } while (overflow > 0);
  84918. /* Now recompute all bit lengths, scanning in increasing frequency.
  84919. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84920. * lengths instead of fixing only the wrong ones. This idea is taken
  84921. * from 'ar' written by Haruhiko Okumura.)
  84922. */
  84923. for (bits = max_length; bits != 0; bits--) {
  84924. n = s->bl_count[bits];
  84925. while (n != 0) {
  84926. m = s->heap[--h];
  84927. if (m > max_code) continue;
  84928. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84929. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84930. s->opt_len += ((long)bits - (long)tree[m].Len)
  84931. *(long)tree[m].Freq;
  84932. tree[m].Len = (ush)bits;
  84933. }
  84934. n--;
  84935. }
  84936. }
  84937. }
  84938. /* ===========================================================================
  84939. * Generate the codes for a given tree and bit counts (which need not be
  84940. * optimal).
  84941. * IN assertion: the array bl_count contains the bit length statistics for
  84942. * the given tree and the field len is set for all tree elements.
  84943. * OUT assertion: the field code is set for all tree elements of non
  84944. * zero code length.
  84945. */
  84946. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84947. int max_code, /* largest code with non zero frequency */
  84948. ushf *bl_count) /* number of codes at each bit length */
  84949. {
  84950. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84951. ush code = 0; /* running code value */
  84952. int bits; /* bit index */
  84953. int n; /* code index */
  84954. /* The distribution counts are first used to generate the code values
  84955. * without bit reversal.
  84956. */
  84957. for (bits = 1; bits <= MAX_BITS; bits++) {
  84958. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84959. }
  84960. /* Check that the bit counts in bl_count are consistent. The last code
  84961. * must be all ones.
  84962. */
  84963. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84964. "inconsistent bit counts");
  84965. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84966. for (n = 0; n <= max_code; n++) {
  84967. int len = tree[n].Len;
  84968. if (len == 0) continue;
  84969. /* Now reverse the bits */
  84970. tree[n].Code = bi_reverse(next_code[len]++, len);
  84971. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84972. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84973. }
  84974. }
  84975. /* ===========================================================================
  84976. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84977. * Update the total bit length for the current block.
  84978. * IN assertion: the field freq is set for all tree elements.
  84979. * OUT assertions: the fields len and code are set to the optimal bit length
  84980. * and corresponding code. The length opt_len is updated; static_len is
  84981. * also updated if stree is not null. The field max_code is set.
  84982. */
  84983. local void build_tree (deflate_state *s,
  84984. tree_desc *desc) /* the tree descriptor */
  84985. {
  84986. ct_data *tree = desc->dyn_tree;
  84987. const ct_data *stree = desc->stat_desc->static_tree;
  84988. int elems = desc->stat_desc->elems;
  84989. int n, m; /* iterate over heap elements */
  84990. int max_code = -1; /* largest code with non zero frequency */
  84991. int node; /* new node being created */
  84992. /* Construct the initial heap, with least frequent element in
  84993. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84994. * heap[0] is not used.
  84995. */
  84996. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84997. for (n = 0; n < elems; n++) {
  84998. if (tree[n].Freq != 0) {
  84999. s->heap[++(s->heap_len)] = max_code = n;
  85000. s->depth[n] = 0;
  85001. } else {
  85002. tree[n].Len = 0;
  85003. }
  85004. }
  85005. /* The pkzip format requires that at least one distance code exists,
  85006. * and that at least one bit should be sent even if there is only one
  85007. * possible code. So to avoid special checks later on we force at least
  85008. * two codes of non zero frequency.
  85009. */
  85010. while (s->heap_len < 2) {
  85011. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85012. tree[node].Freq = 1;
  85013. s->depth[node] = 0;
  85014. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85015. /* node is 0 or 1 so it does not have extra bits */
  85016. }
  85017. desc->max_code = max_code;
  85018. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85019. * establish sub-heaps of increasing lengths:
  85020. */
  85021. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85022. /* Construct the Huffman tree by repeatedly combining the least two
  85023. * frequent nodes.
  85024. */
  85025. node = elems; /* next internal node of the tree */
  85026. do {
  85027. pqremove(s, tree, n); /* n = node of least frequency */
  85028. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85029. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85030. s->heap[--(s->heap_max)] = m;
  85031. /* Create a new node father of n and m */
  85032. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85033. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85034. s->depth[n] : s->depth[m]) + 1);
  85035. tree[n].Dad = tree[m].Dad = (ush)node;
  85036. #ifdef DUMP_BL_TREE
  85037. if (tree == s->bl_tree) {
  85038. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85039. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85040. }
  85041. #endif
  85042. /* and insert the new node in the heap */
  85043. s->heap[SMALLEST] = node++;
  85044. pqdownheap(s, tree, SMALLEST);
  85045. } while (s->heap_len >= 2);
  85046. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85047. /* At this point, the fields freq and dad are set. We can now
  85048. * generate the bit lengths.
  85049. */
  85050. gen_bitlen(s, (tree_desc *)desc);
  85051. /* The field len is now set, we can generate the bit codes */
  85052. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85053. }
  85054. /* ===========================================================================
  85055. * Scan a literal or distance tree to determine the frequencies of the codes
  85056. * in the bit length tree.
  85057. */
  85058. local void scan_tree (deflate_state *s,
  85059. ct_data *tree, /* the tree to be scanned */
  85060. int max_code) /* and its largest code of non zero frequency */
  85061. {
  85062. int n; /* iterates over all tree elements */
  85063. int prevlen = -1; /* last emitted length */
  85064. int curlen; /* length of current code */
  85065. int nextlen = tree[0].Len; /* length of next code */
  85066. int count = 0; /* repeat count of the current code */
  85067. int max_count = 7; /* max repeat count */
  85068. int min_count = 4; /* min repeat count */
  85069. if (nextlen == 0) max_count = 138, min_count = 3;
  85070. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85071. for (n = 0; n <= max_code; n++) {
  85072. curlen = nextlen; nextlen = tree[n+1].Len;
  85073. if (++count < max_count && curlen == nextlen) {
  85074. continue;
  85075. } else if (count < min_count) {
  85076. s->bl_tree[curlen].Freq += count;
  85077. } else if (curlen != 0) {
  85078. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85079. s->bl_tree[REP_3_6].Freq++;
  85080. } else if (count <= 10) {
  85081. s->bl_tree[REPZ_3_10].Freq++;
  85082. } else {
  85083. s->bl_tree[REPZ_11_138].Freq++;
  85084. }
  85085. count = 0; prevlen = curlen;
  85086. if (nextlen == 0) {
  85087. max_count = 138, min_count = 3;
  85088. } else if (curlen == nextlen) {
  85089. max_count = 6, min_count = 3;
  85090. } else {
  85091. max_count = 7, min_count = 4;
  85092. }
  85093. }
  85094. }
  85095. /* ===========================================================================
  85096. * Send a literal or distance tree in compressed form, using the codes in
  85097. * bl_tree.
  85098. */
  85099. local void send_tree (deflate_state *s,
  85100. ct_data *tree, /* the tree to be scanned */
  85101. int max_code) /* and its largest code of non zero frequency */
  85102. {
  85103. int n; /* iterates over all tree elements */
  85104. int prevlen = -1; /* last emitted length */
  85105. int curlen; /* length of current code */
  85106. int nextlen = tree[0].Len; /* length of next code */
  85107. int count = 0; /* repeat count of the current code */
  85108. int max_count = 7; /* max repeat count */
  85109. int min_count = 4; /* min repeat count */
  85110. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85111. if (nextlen == 0) max_count = 138, min_count = 3;
  85112. for (n = 0; n <= max_code; n++) {
  85113. curlen = nextlen; nextlen = tree[n+1].Len;
  85114. if (++count < max_count && curlen == nextlen) {
  85115. continue;
  85116. } else if (count < min_count) {
  85117. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85118. } else if (curlen != 0) {
  85119. if (curlen != prevlen) {
  85120. send_code(s, curlen, s->bl_tree); count--;
  85121. }
  85122. Assert(count >= 3 && count <= 6, " 3_6?");
  85123. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85124. } else if (count <= 10) {
  85125. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85126. } else {
  85127. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85128. }
  85129. count = 0; prevlen = curlen;
  85130. if (nextlen == 0) {
  85131. max_count = 138, min_count = 3;
  85132. } else if (curlen == nextlen) {
  85133. max_count = 6, min_count = 3;
  85134. } else {
  85135. max_count = 7, min_count = 4;
  85136. }
  85137. }
  85138. }
  85139. /* ===========================================================================
  85140. * Construct the Huffman tree for the bit lengths and return the index in
  85141. * bl_order of the last bit length code to send.
  85142. */
  85143. local int build_bl_tree (deflate_state *s)
  85144. {
  85145. int max_blindex; /* index of last bit length code of non zero freq */
  85146. /* Determine the bit length frequencies for literal and distance trees */
  85147. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85148. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85149. /* Build the bit length tree: */
  85150. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85151. /* opt_len now includes the length of the tree representations, except
  85152. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85153. */
  85154. /* Determine the number of bit length codes to send. The pkzip format
  85155. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85156. * 3 but the actual value used is 4.)
  85157. */
  85158. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85159. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85160. }
  85161. /* Update opt_len to include the bit length tree and counts */
  85162. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85163. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85164. s->opt_len, s->static_len));
  85165. return max_blindex;
  85166. }
  85167. /* ===========================================================================
  85168. * Send the header for a block using dynamic Huffman trees: the counts, the
  85169. * lengths of the bit length codes, the literal tree and the distance tree.
  85170. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85171. */
  85172. local void send_all_trees (deflate_state *s,
  85173. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85174. {
  85175. int rank; /* index in bl_order */
  85176. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85177. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85178. "too many codes");
  85179. Tracev((stderr, "\nbl counts: "));
  85180. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85181. send_bits(s, dcodes-1, 5);
  85182. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85183. for (rank = 0; rank < blcodes; rank++) {
  85184. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85185. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85186. }
  85187. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85188. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85189. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85190. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85191. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85192. }
  85193. /* ===========================================================================
  85194. * Send a stored block
  85195. */
  85196. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85197. {
  85198. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85199. #ifdef DEBUG
  85200. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85201. s->compressed_len += (stored_len + 4) << 3;
  85202. #endif
  85203. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85204. }
  85205. /* ===========================================================================
  85206. * Send one empty static block to give enough lookahead for inflate.
  85207. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85208. * The current inflate code requires 9 bits of lookahead. If the
  85209. * last two codes for the previous block (real code plus EOB) were coded
  85210. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85211. * the last real code. In this case we send two empty static blocks instead
  85212. * of one. (There are no problems if the previous block is stored or fixed.)
  85213. * To simplify the code, we assume the worst case of last real code encoded
  85214. * on one bit only.
  85215. */
  85216. void _tr_align (deflate_state *s)
  85217. {
  85218. send_bits(s, STATIC_TREES<<1, 3);
  85219. send_code(s, END_BLOCK, static_ltree);
  85220. #ifdef DEBUG
  85221. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85222. #endif
  85223. bi_flush(s);
  85224. /* Of the 10 bits for the empty block, we have already sent
  85225. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85226. * the EOB of the previous block) was thus at least one plus the length
  85227. * of the EOB plus what we have just sent of the empty static block.
  85228. */
  85229. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85230. send_bits(s, STATIC_TREES<<1, 3);
  85231. send_code(s, END_BLOCK, static_ltree);
  85232. #ifdef DEBUG
  85233. s->compressed_len += 10L;
  85234. #endif
  85235. bi_flush(s);
  85236. }
  85237. s->last_eob_len = 7;
  85238. }
  85239. /* ===========================================================================
  85240. * Determine the best encoding for the current block: dynamic trees, static
  85241. * trees or store, and output the encoded block to the zip file.
  85242. */
  85243. void _tr_flush_block (deflate_state *s,
  85244. charf *buf, /* input block, or NULL if too old */
  85245. ulg stored_len, /* length of input block */
  85246. int eof) /* true if this is the last block for a file */
  85247. {
  85248. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85249. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85250. /* Build the Huffman trees unless a stored block is forced */
  85251. if (s->level > 0) {
  85252. /* Check if the file is binary or text */
  85253. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85254. set_data_type(s);
  85255. /* Construct the literal and distance trees */
  85256. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85257. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85258. s->static_len));
  85259. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85260. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85261. s->static_len));
  85262. /* At this point, opt_len and static_len are the total bit lengths of
  85263. * the compressed block data, excluding the tree representations.
  85264. */
  85265. /* Build the bit length tree for the above two trees, and get the index
  85266. * in bl_order of the last bit length code to send.
  85267. */
  85268. max_blindex = build_bl_tree(s);
  85269. /* Determine the best encoding. Compute the block lengths in bytes. */
  85270. opt_lenb = (s->opt_len+3+7)>>3;
  85271. static_lenb = (s->static_len+3+7)>>3;
  85272. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85273. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85274. s->last_lit));
  85275. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85276. } else {
  85277. Assert(buf != (char*)0, "lost buf");
  85278. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85279. }
  85280. #ifdef FORCE_STORED
  85281. if (buf != (char*)0) { /* force stored block */
  85282. #else
  85283. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85284. /* 4: two words for the lengths */
  85285. #endif
  85286. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85287. * Otherwise we can't have processed more than WSIZE input bytes since
  85288. * the last block flush, because compression would have been
  85289. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85290. * transform a block into a stored block.
  85291. */
  85292. _tr_stored_block(s, buf, stored_len, eof);
  85293. #ifdef FORCE_STATIC
  85294. } else if (static_lenb >= 0) { /* force static trees */
  85295. #else
  85296. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85297. #endif
  85298. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85299. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85300. #ifdef DEBUG
  85301. s->compressed_len += 3 + s->static_len;
  85302. #endif
  85303. } else {
  85304. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85305. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85306. max_blindex+1);
  85307. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85308. #ifdef DEBUG
  85309. s->compressed_len += 3 + s->opt_len;
  85310. #endif
  85311. }
  85312. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85313. /* The above check is made mod 2^32, for files larger than 512 MB
  85314. * and uLong implemented on 32 bits.
  85315. */
  85316. init_block(s);
  85317. if (eof) {
  85318. bi_windup(s);
  85319. #ifdef DEBUG
  85320. s->compressed_len += 7; /* align on byte boundary */
  85321. #endif
  85322. }
  85323. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85324. s->compressed_len-7*eof));
  85325. }
  85326. /* ===========================================================================
  85327. * Save the match info and tally the frequency counts. Return true if
  85328. * the current block must be flushed.
  85329. */
  85330. int _tr_tally (deflate_state *s,
  85331. unsigned dist, /* distance of matched string */
  85332. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85333. {
  85334. s->d_buf[s->last_lit] = (ush)dist;
  85335. s->l_buf[s->last_lit++] = (uch)lc;
  85336. if (dist == 0) {
  85337. /* lc is the unmatched char */
  85338. s->dyn_ltree[lc].Freq++;
  85339. } else {
  85340. s->matches++;
  85341. /* Here, lc is the match length - MIN_MATCH */
  85342. dist--; /* dist = match distance - 1 */
  85343. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85344. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85345. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85346. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85347. s->dyn_dtree[d_code(dist)].Freq++;
  85348. }
  85349. #ifdef TRUNCATE_BLOCK
  85350. /* Try to guess if it is profitable to stop the current block here */
  85351. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85352. /* Compute an upper bound for the compressed length */
  85353. ulg out_length = (ulg)s->last_lit*8L;
  85354. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85355. int dcode;
  85356. for (dcode = 0; dcode < D_CODES; dcode++) {
  85357. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85358. (5L+extra_dbits[dcode]);
  85359. }
  85360. out_length >>= 3;
  85361. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85362. s->last_lit, in_length, out_length,
  85363. 100L - out_length*100L/in_length));
  85364. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85365. }
  85366. #endif
  85367. return (s->last_lit == s->lit_bufsize-1);
  85368. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85369. * on 16 bit machines and because stored blocks are restricted to
  85370. * 64K-1 bytes.
  85371. */
  85372. }
  85373. /* ===========================================================================
  85374. * Send the block data compressed using the given Huffman trees
  85375. */
  85376. local void compress_block (deflate_state *s,
  85377. ct_data *ltree, /* literal tree */
  85378. ct_data *dtree) /* distance tree */
  85379. {
  85380. unsigned dist; /* distance of matched string */
  85381. int lc; /* match length or unmatched char (if dist == 0) */
  85382. unsigned lx = 0; /* running index in l_buf */
  85383. unsigned code; /* the code to send */
  85384. int extra; /* number of extra bits to send */
  85385. if (s->last_lit != 0) do {
  85386. dist = s->d_buf[lx];
  85387. lc = s->l_buf[lx++];
  85388. if (dist == 0) {
  85389. send_code(s, lc, ltree); /* send a literal byte */
  85390. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85391. } else {
  85392. /* Here, lc is the match length - MIN_MATCH */
  85393. code = _length_code[lc];
  85394. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85395. extra = extra_lbits[code];
  85396. if (extra != 0) {
  85397. lc -= base_length[code];
  85398. send_bits(s, lc, extra); /* send the extra length bits */
  85399. }
  85400. dist--; /* dist is now the match distance - 1 */
  85401. code = d_code(dist);
  85402. Assert (code < D_CODES, "bad d_code");
  85403. send_code(s, code, dtree); /* send the distance code */
  85404. extra = extra_dbits[code];
  85405. if (extra != 0) {
  85406. dist -= base_dist[code];
  85407. send_bits(s, dist, extra); /* send the extra distance bits */
  85408. }
  85409. } /* literal or match pair ? */
  85410. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85411. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85412. "pendingBuf overflow");
  85413. } while (lx < s->last_lit);
  85414. send_code(s, END_BLOCK, ltree);
  85415. s->last_eob_len = ltree[END_BLOCK].Len;
  85416. }
  85417. /* ===========================================================================
  85418. * Set the data type to BINARY or TEXT, using a crude approximation:
  85419. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85420. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85421. * IN assertion: the fields Freq of dyn_ltree are set.
  85422. */
  85423. local void set_data_type (deflate_state *s)
  85424. {
  85425. int n;
  85426. for (n = 0; n < 9; n++)
  85427. if (s->dyn_ltree[n].Freq != 0)
  85428. break;
  85429. if (n == 9)
  85430. for (n = 14; n < 32; n++)
  85431. if (s->dyn_ltree[n].Freq != 0)
  85432. break;
  85433. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85434. }
  85435. /* ===========================================================================
  85436. * Reverse the first len bits of a code, using straightforward code (a faster
  85437. * method would use a table)
  85438. * IN assertion: 1 <= len <= 15
  85439. */
  85440. local unsigned bi_reverse (unsigned code, int len)
  85441. {
  85442. register unsigned res = 0;
  85443. do {
  85444. res |= code & 1;
  85445. code >>= 1, res <<= 1;
  85446. } while (--len > 0);
  85447. return res >> 1;
  85448. }
  85449. /* ===========================================================================
  85450. * Flush the bit buffer, keeping at most 7 bits in it.
  85451. */
  85452. local void bi_flush (deflate_state *s)
  85453. {
  85454. if (s->bi_valid == 16) {
  85455. put_short(s, s->bi_buf);
  85456. s->bi_buf = 0;
  85457. s->bi_valid = 0;
  85458. } else if (s->bi_valid >= 8) {
  85459. put_byte(s, (Byte)s->bi_buf);
  85460. s->bi_buf >>= 8;
  85461. s->bi_valid -= 8;
  85462. }
  85463. }
  85464. /* ===========================================================================
  85465. * Flush the bit buffer and align the output on a byte boundary
  85466. */
  85467. local void bi_windup (deflate_state *s)
  85468. {
  85469. if (s->bi_valid > 8) {
  85470. put_short(s, s->bi_buf);
  85471. } else if (s->bi_valid > 0) {
  85472. put_byte(s, (Byte)s->bi_buf);
  85473. }
  85474. s->bi_buf = 0;
  85475. s->bi_valid = 0;
  85476. #ifdef DEBUG
  85477. s->bits_sent = (s->bits_sent+7) & ~7;
  85478. #endif
  85479. }
  85480. /* ===========================================================================
  85481. * Copy a stored block, storing first the length and its
  85482. * one's complement if requested.
  85483. */
  85484. local void copy_block(deflate_state *s,
  85485. charf *buf, /* the input data */
  85486. unsigned len, /* its length */
  85487. int header) /* true if block header must be written */
  85488. {
  85489. bi_windup(s); /* align on byte boundary */
  85490. s->last_eob_len = 8; /* enough lookahead for inflate */
  85491. if (header) {
  85492. put_short(s, (ush)len);
  85493. put_short(s, (ush)~len);
  85494. #ifdef DEBUG
  85495. s->bits_sent += 2*16;
  85496. #endif
  85497. }
  85498. #ifdef DEBUG
  85499. s->bits_sent += (ulg)len<<3;
  85500. #endif
  85501. while (len--) {
  85502. put_byte(s, *buf++);
  85503. }
  85504. }
  85505. /*** End of inlined file: trees.c ***/
  85506. /*** Start of inlined file: zutil.c ***/
  85507. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85508. #ifndef NO_DUMMY_DECL
  85509. struct internal_state {int dummy;}; /* for buggy compilers */
  85510. #endif
  85511. const char * const z_errmsg[10] = {
  85512. "need dictionary", /* Z_NEED_DICT 2 */
  85513. "stream end", /* Z_STREAM_END 1 */
  85514. "", /* Z_OK 0 */
  85515. "file error", /* Z_ERRNO (-1) */
  85516. "stream error", /* Z_STREAM_ERROR (-2) */
  85517. "data error", /* Z_DATA_ERROR (-3) */
  85518. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85519. "buffer error", /* Z_BUF_ERROR (-5) */
  85520. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85521. ""};
  85522. /*const char * ZEXPORT zlibVersion()
  85523. {
  85524. return ZLIB_VERSION;
  85525. }
  85526. uLong ZEXPORT zlibCompileFlags()
  85527. {
  85528. uLong flags;
  85529. flags = 0;
  85530. switch (sizeof(uInt)) {
  85531. case 2: break;
  85532. case 4: flags += 1; break;
  85533. case 8: flags += 2; break;
  85534. default: flags += 3;
  85535. }
  85536. switch (sizeof(uLong)) {
  85537. case 2: break;
  85538. case 4: flags += 1 << 2; break;
  85539. case 8: flags += 2 << 2; break;
  85540. default: flags += 3 << 2;
  85541. }
  85542. switch (sizeof(voidpf)) {
  85543. case 2: break;
  85544. case 4: flags += 1 << 4; break;
  85545. case 8: flags += 2 << 4; break;
  85546. default: flags += 3 << 4;
  85547. }
  85548. switch (sizeof(z_off_t)) {
  85549. case 2: break;
  85550. case 4: flags += 1 << 6; break;
  85551. case 8: flags += 2 << 6; break;
  85552. default: flags += 3 << 6;
  85553. }
  85554. #ifdef DEBUG
  85555. flags += 1 << 8;
  85556. #endif
  85557. #if defined(ASMV) || defined(ASMINF)
  85558. flags += 1 << 9;
  85559. #endif
  85560. #ifdef ZLIB_WINAPI
  85561. flags += 1 << 10;
  85562. #endif
  85563. #ifdef BUILDFIXED
  85564. flags += 1 << 12;
  85565. #endif
  85566. #ifdef DYNAMIC_CRC_TABLE
  85567. flags += 1 << 13;
  85568. #endif
  85569. #ifdef NO_GZCOMPRESS
  85570. flags += 1L << 16;
  85571. #endif
  85572. #ifdef NO_GZIP
  85573. flags += 1L << 17;
  85574. #endif
  85575. #ifdef PKZIP_BUG_WORKAROUND
  85576. flags += 1L << 20;
  85577. #endif
  85578. #ifdef FASTEST
  85579. flags += 1L << 21;
  85580. #endif
  85581. #ifdef STDC
  85582. # ifdef NO_vsnprintf
  85583. flags += 1L << 25;
  85584. # ifdef HAS_vsprintf_void
  85585. flags += 1L << 26;
  85586. # endif
  85587. # else
  85588. # ifdef HAS_vsnprintf_void
  85589. flags += 1L << 26;
  85590. # endif
  85591. # endif
  85592. #else
  85593. flags += 1L << 24;
  85594. # ifdef NO_snprintf
  85595. flags += 1L << 25;
  85596. # ifdef HAS_sprintf_void
  85597. flags += 1L << 26;
  85598. # endif
  85599. # else
  85600. # ifdef HAS_snprintf_void
  85601. flags += 1L << 26;
  85602. # endif
  85603. # endif
  85604. #endif
  85605. return flags;
  85606. }*/
  85607. #ifdef DEBUG
  85608. # ifndef verbose
  85609. # define verbose 0
  85610. # endif
  85611. int z_verbose = verbose;
  85612. void z_error (const char *m)
  85613. {
  85614. fprintf(stderr, "%s\n", m);
  85615. exit(1);
  85616. }
  85617. #endif
  85618. /* exported to allow conversion of error code to string for compress() and
  85619. * uncompress()
  85620. */
  85621. const char * ZEXPORT zError(int err)
  85622. {
  85623. return ERR_MSG(err);
  85624. }
  85625. #if defined(_WIN32_WCE)
  85626. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85627. * errno. We define it as a global variable to simplify porting.
  85628. * Its value is always 0 and should not be used.
  85629. */
  85630. int errno = 0;
  85631. #endif
  85632. #ifndef HAVE_MEMCPY
  85633. void zmemcpy(dest, source, len)
  85634. Bytef* dest;
  85635. const Bytef* source;
  85636. uInt len;
  85637. {
  85638. if (len == 0) return;
  85639. do {
  85640. *dest++ = *source++; /* ??? to be unrolled */
  85641. } while (--len != 0);
  85642. }
  85643. int zmemcmp(s1, s2, len)
  85644. const Bytef* s1;
  85645. const Bytef* s2;
  85646. uInt len;
  85647. {
  85648. uInt j;
  85649. for (j = 0; j < len; j++) {
  85650. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85651. }
  85652. return 0;
  85653. }
  85654. void zmemzero(dest, len)
  85655. Bytef* dest;
  85656. uInt len;
  85657. {
  85658. if (len == 0) return;
  85659. do {
  85660. *dest++ = 0; /* ??? to be unrolled */
  85661. } while (--len != 0);
  85662. }
  85663. #endif
  85664. #ifdef SYS16BIT
  85665. #ifdef __TURBOC__
  85666. /* Turbo C in 16-bit mode */
  85667. # define MY_ZCALLOC
  85668. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85669. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85670. * must fix the pointer. Warning: the pointer must be put back to its
  85671. * original form in order to free it, use zcfree().
  85672. */
  85673. #define MAX_PTR 10
  85674. /* 10*64K = 640K */
  85675. local int next_ptr = 0;
  85676. typedef struct ptr_table_s {
  85677. voidpf org_ptr;
  85678. voidpf new_ptr;
  85679. } ptr_table;
  85680. local ptr_table table[MAX_PTR];
  85681. /* This table is used to remember the original form of pointers
  85682. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85683. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85684. * protected from concurrent access. This hack doesn't work anyway on
  85685. * a protected system like OS/2. Use Microsoft C instead.
  85686. */
  85687. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85688. {
  85689. voidpf buf = opaque; /* just to make some compilers happy */
  85690. ulg bsize = (ulg)items*size;
  85691. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85692. * will return a usable pointer which doesn't have to be normalized.
  85693. */
  85694. if (bsize < 65520L) {
  85695. buf = farmalloc(bsize);
  85696. if (*(ush*)&buf != 0) return buf;
  85697. } else {
  85698. buf = farmalloc(bsize + 16L);
  85699. }
  85700. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85701. table[next_ptr].org_ptr = buf;
  85702. /* Normalize the pointer to seg:0 */
  85703. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85704. *(ush*)&buf = 0;
  85705. table[next_ptr++].new_ptr = buf;
  85706. return buf;
  85707. }
  85708. void zcfree (voidpf opaque, voidpf ptr)
  85709. {
  85710. int n;
  85711. if (*(ush*)&ptr != 0) { /* object < 64K */
  85712. farfree(ptr);
  85713. return;
  85714. }
  85715. /* Find the original pointer */
  85716. for (n = 0; n < next_ptr; n++) {
  85717. if (ptr != table[n].new_ptr) continue;
  85718. farfree(table[n].org_ptr);
  85719. while (++n < next_ptr) {
  85720. table[n-1] = table[n];
  85721. }
  85722. next_ptr--;
  85723. return;
  85724. }
  85725. ptr = opaque; /* just to make some compilers happy */
  85726. Assert(0, "zcfree: ptr not found");
  85727. }
  85728. #endif /* __TURBOC__ */
  85729. #ifdef M_I86
  85730. /* Microsoft C in 16-bit mode */
  85731. # define MY_ZCALLOC
  85732. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85733. # define _halloc halloc
  85734. # define _hfree hfree
  85735. #endif
  85736. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85737. {
  85738. if (opaque) opaque = 0; /* to make compiler happy */
  85739. return _halloc((long)items, size);
  85740. }
  85741. void zcfree (voidpf opaque, voidpf ptr)
  85742. {
  85743. if (opaque) opaque = 0; /* to make compiler happy */
  85744. _hfree(ptr);
  85745. }
  85746. #endif /* M_I86 */
  85747. #endif /* SYS16BIT */
  85748. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85749. #ifndef STDC
  85750. extern voidp malloc OF((uInt size));
  85751. extern voidp calloc OF((uInt items, uInt size));
  85752. extern void free OF((voidpf ptr));
  85753. #endif
  85754. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85755. {
  85756. if (opaque) items += size - size; /* make compiler happy */
  85757. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85758. (voidpf)calloc(items, size);
  85759. }
  85760. void zcfree (voidpf opaque, voidpf ptr)
  85761. {
  85762. free(ptr);
  85763. if (opaque) return; /* make compiler happy */
  85764. }
  85765. #endif /* MY_ZCALLOC */
  85766. /*** End of inlined file: zutil.c ***/
  85767. #undef Byte
  85768. #else
  85769. #include <zlib.h>
  85770. #endif
  85771. }
  85772. #if JUCE_MSVC
  85773. #pragma warning (pop)
  85774. #endif
  85775. BEGIN_JUCE_NAMESPACE
  85776. // internal helper object that holds the zlib structures so they don't have to be
  85777. // included publicly.
  85778. class GZIPDecompressorInputStream::GZIPDecompressHelper
  85779. {
  85780. public:
  85781. GZIPDecompressHelper (const bool noWrap)
  85782. : finished (true),
  85783. needsDictionary (false),
  85784. error (true),
  85785. streamIsValid (false),
  85786. data (0),
  85787. dataSize (0)
  85788. {
  85789. using namespace zlibNamespace;
  85790. zerostruct (stream);
  85791. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85792. finished = error = ! streamIsValid;
  85793. }
  85794. ~GZIPDecompressHelper()
  85795. {
  85796. using namespace zlibNamespace;
  85797. if (streamIsValid)
  85798. inflateEnd (&stream);
  85799. }
  85800. bool needsInput() const throw() { return dataSize <= 0; }
  85801. void setInput (uint8* const data_, const int size) throw()
  85802. {
  85803. data = data_;
  85804. dataSize = size;
  85805. }
  85806. int doNextBlock (uint8* const dest, const int destSize)
  85807. {
  85808. using namespace zlibNamespace;
  85809. if (streamIsValid && data != 0 && ! finished)
  85810. {
  85811. stream.next_in = data;
  85812. stream.next_out = dest;
  85813. stream.avail_in = dataSize;
  85814. stream.avail_out = destSize;
  85815. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85816. {
  85817. case Z_STREAM_END:
  85818. finished = true;
  85819. // deliberate fall-through
  85820. case Z_OK:
  85821. data += dataSize - stream.avail_in;
  85822. dataSize = stream.avail_in;
  85823. return destSize - stream.avail_out;
  85824. case Z_NEED_DICT:
  85825. needsDictionary = true;
  85826. data += dataSize - stream.avail_in;
  85827. dataSize = stream.avail_in;
  85828. break;
  85829. case Z_DATA_ERROR:
  85830. case Z_MEM_ERROR:
  85831. error = true;
  85832. default:
  85833. break;
  85834. }
  85835. }
  85836. return 0;
  85837. }
  85838. bool finished, needsDictionary, error, streamIsValid;
  85839. enum { gzipDecompBufferSize = 32768 };
  85840. private:
  85841. zlibNamespace::z_stream stream;
  85842. uint8* data;
  85843. int dataSize;
  85844. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  85845. };
  85846. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85847. const bool deleteSourceWhenDestroyed,
  85848. const bool noWrap_,
  85849. const int64 uncompressedStreamLength_)
  85850. : sourceStream (sourceStream_),
  85851. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85852. uncompressedStreamLength (uncompressedStreamLength_),
  85853. noWrap (noWrap_),
  85854. isEof (false),
  85855. activeBufferSize (0),
  85856. originalSourcePos (sourceStream_->getPosition()),
  85857. currentPos (0),
  85858. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85859. helper (new GZIPDecompressHelper (noWrap_))
  85860. {
  85861. }
  85862. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  85863. : sourceStream (&sourceStream_),
  85864. uncompressedStreamLength (-1),
  85865. noWrap (false),
  85866. isEof (false),
  85867. activeBufferSize (0),
  85868. originalSourcePos (sourceStream_.getPosition()),
  85869. currentPos (0),
  85870. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85871. helper (new GZIPDecompressHelper (false))
  85872. {
  85873. }
  85874. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85875. {
  85876. }
  85877. int64 GZIPDecompressorInputStream::getTotalLength()
  85878. {
  85879. return uncompressedStreamLength;
  85880. }
  85881. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85882. {
  85883. if ((howMany > 0) && ! isEof)
  85884. {
  85885. jassert (destBuffer != 0);
  85886. if (destBuffer != 0)
  85887. {
  85888. int numRead = 0;
  85889. uint8* d = static_cast <uint8*> (destBuffer);
  85890. while (! helper->error)
  85891. {
  85892. const int n = helper->doNextBlock (d, howMany);
  85893. currentPos += n;
  85894. if (n == 0)
  85895. {
  85896. if (helper->finished || helper->needsDictionary)
  85897. {
  85898. isEof = true;
  85899. return numRead;
  85900. }
  85901. if (helper->needsInput())
  85902. {
  85903. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  85904. if (activeBufferSize > 0)
  85905. {
  85906. helper->setInput (buffer, activeBufferSize);
  85907. }
  85908. else
  85909. {
  85910. isEof = true;
  85911. return numRead;
  85912. }
  85913. }
  85914. }
  85915. else
  85916. {
  85917. numRead += n;
  85918. howMany -= n;
  85919. d += n;
  85920. if (howMany <= 0)
  85921. return numRead;
  85922. }
  85923. }
  85924. }
  85925. }
  85926. return 0;
  85927. }
  85928. bool GZIPDecompressorInputStream::isExhausted()
  85929. {
  85930. return helper->error || isEof;
  85931. }
  85932. int64 GZIPDecompressorInputStream::getPosition()
  85933. {
  85934. return currentPos;
  85935. }
  85936. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85937. {
  85938. if (newPos < currentPos)
  85939. {
  85940. // to go backwards, reset the stream and start again..
  85941. isEof = false;
  85942. activeBufferSize = 0;
  85943. currentPos = 0;
  85944. helper = new GZIPDecompressHelper (noWrap);
  85945. sourceStream->setPosition (originalSourcePos);
  85946. }
  85947. skipNextBytes (newPos - currentPos);
  85948. return true;
  85949. }
  85950. END_JUCE_NAMESPACE
  85951. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85952. #endif
  85953. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85954. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85955. #if JUCE_USE_FLAC
  85956. #if JUCE_WINDOWS
  85957. #include <windows.h>
  85958. #endif
  85959. namespace FlacNamespace
  85960. {
  85961. #if JUCE_INCLUDE_FLAC_CODE
  85962. #if JUCE_MSVC
  85963. #pragma warning (disable: 4505 181 111)
  85964. #endif
  85965. #define FLAC__NO_DLL 1
  85966. #if ! defined (SIZE_MAX)
  85967. #define SIZE_MAX 0xffffffff
  85968. #endif
  85969. #define __STDC_LIMIT_MACROS 1
  85970. /*** Start of inlined file: all.h ***/
  85971. #ifndef FLAC__ALL_H
  85972. #define FLAC__ALL_H
  85973. /*** Start of inlined file: export.h ***/
  85974. #ifndef FLAC__EXPORT_H
  85975. #define FLAC__EXPORT_H
  85976. /** \file include/FLAC/export.h
  85977. *
  85978. * \brief
  85979. * This module contains #defines and symbols for exporting function
  85980. * calls, and providing version information and compiled-in features.
  85981. *
  85982. * See the \link flac_export export \endlink module.
  85983. */
  85984. /** \defgroup flac_export FLAC/export.h: export symbols
  85985. * \ingroup flac
  85986. *
  85987. * \brief
  85988. * This module contains #defines and symbols for exporting function
  85989. * calls, and providing version information and compiled-in features.
  85990. *
  85991. * If you are compiling with MSVC and will link to the static library
  85992. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85993. * make sure the symbols are exported properly.
  85994. *
  85995. * \{
  85996. */
  85997. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85998. #define FLAC_API
  85999. #else
  86000. #ifdef FLAC_API_EXPORTS
  86001. #define FLAC_API _declspec(dllexport)
  86002. #else
  86003. #define FLAC_API _declspec(dllimport)
  86004. #endif
  86005. #endif
  86006. /** These #defines will mirror the libtool-based library version number, see
  86007. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86008. */
  86009. #define FLAC_API_VERSION_CURRENT 10
  86010. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86011. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86012. #ifdef __cplusplus
  86013. extern "C" {
  86014. #endif
  86015. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86016. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86017. #ifdef __cplusplus
  86018. }
  86019. #endif
  86020. /* \} */
  86021. #endif
  86022. /*** End of inlined file: export.h ***/
  86023. /*** Start of inlined file: assert.h ***/
  86024. #ifndef FLAC__ASSERT_H
  86025. #define FLAC__ASSERT_H
  86026. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86027. #ifdef DEBUG
  86028. #include <assert.h>
  86029. #define FLAC__ASSERT(x) assert(x)
  86030. #define FLAC__ASSERT_DECLARATION(x) x
  86031. #else
  86032. #define FLAC__ASSERT(x)
  86033. #define FLAC__ASSERT_DECLARATION(x)
  86034. #endif
  86035. #endif
  86036. /*** End of inlined file: assert.h ***/
  86037. /*** Start of inlined file: callback.h ***/
  86038. #ifndef FLAC__CALLBACK_H
  86039. #define FLAC__CALLBACK_H
  86040. /*** Start of inlined file: ordinals.h ***/
  86041. #ifndef FLAC__ORDINALS_H
  86042. #define FLAC__ORDINALS_H
  86043. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86044. #include <inttypes.h>
  86045. #endif
  86046. typedef signed char FLAC__int8;
  86047. typedef unsigned char FLAC__uint8;
  86048. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86049. typedef __int16 FLAC__int16;
  86050. typedef __int32 FLAC__int32;
  86051. typedef __int64 FLAC__int64;
  86052. typedef unsigned __int16 FLAC__uint16;
  86053. typedef unsigned __int32 FLAC__uint32;
  86054. typedef unsigned __int64 FLAC__uint64;
  86055. #elif defined(__EMX__)
  86056. typedef short FLAC__int16;
  86057. typedef long FLAC__int32;
  86058. typedef long long FLAC__int64;
  86059. typedef unsigned short FLAC__uint16;
  86060. typedef unsigned long FLAC__uint32;
  86061. typedef unsigned long long FLAC__uint64;
  86062. #else
  86063. typedef int16_t FLAC__int16;
  86064. typedef int32_t FLAC__int32;
  86065. typedef int64_t FLAC__int64;
  86066. typedef uint16_t FLAC__uint16;
  86067. typedef uint32_t FLAC__uint32;
  86068. typedef uint64_t FLAC__uint64;
  86069. #endif
  86070. typedef int FLAC__bool;
  86071. typedef FLAC__uint8 FLAC__byte;
  86072. #ifdef true
  86073. #undef true
  86074. #endif
  86075. #ifdef false
  86076. #undef false
  86077. #endif
  86078. #ifndef __cplusplus
  86079. #define true 1
  86080. #define false 0
  86081. #endif
  86082. #endif
  86083. /*** End of inlined file: ordinals.h ***/
  86084. #include <stdlib.h> /* for size_t */
  86085. /** \file include/FLAC/callback.h
  86086. *
  86087. * \brief
  86088. * This module defines the structures for describing I/O callbacks
  86089. * to the other FLAC interfaces.
  86090. *
  86091. * See the detailed documentation for callbacks in the
  86092. * \link flac_callbacks callbacks \endlink module.
  86093. */
  86094. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86095. * \ingroup flac
  86096. *
  86097. * \brief
  86098. * This module defines the structures for describing I/O callbacks
  86099. * to the other FLAC interfaces.
  86100. *
  86101. * The purpose of the I/O callback functions is to create a common way
  86102. * for the metadata interfaces to handle I/O.
  86103. *
  86104. * Originally the metadata interfaces required filenames as the way of
  86105. * specifying FLAC files to operate on. This is problematic in some
  86106. * environments so there is an additional option to specify a set of
  86107. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86108. *
  86109. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86110. * opaque structure for a data source.
  86111. *
  86112. * The callback function prototypes are similar (but not identical) to the
  86113. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86114. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86115. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86116. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86117. * is required. \warning You generally CANNOT directly use fseek or ftell
  86118. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86119. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86120. * large files. You will have to find an equivalent function (e.g. ftello),
  86121. * or write a wrapper. The same is true for feof() since this is usually
  86122. * implemented as a macro, not as a function whose address can be taken.
  86123. *
  86124. * \{
  86125. */
  86126. #ifdef __cplusplus
  86127. extern "C" {
  86128. #endif
  86129. /** This is the opaque handle type used by the callbacks. Typically
  86130. * this is a \c FILE* or address of a file descriptor.
  86131. */
  86132. typedef void* FLAC__IOHandle;
  86133. /** Signature for the read callback.
  86134. * The signature and semantics match POSIX fread() implementations
  86135. * and can generally be used interchangeably.
  86136. *
  86137. * \param ptr The address of the read buffer.
  86138. * \param size The size of the records to be read.
  86139. * \param nmemb The number of records to be read.
  86140. * \param handle The handle to the data source.
  86141. * \retval size_t
  86142. * The number of records read.
  86143. */
  86144. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86145. /** Signature for the write callback.
  86146. * The signature and semantics match POSIX fwrite() implementations
  86147. * and can generally be used interchangeably.
  86148. *
  86149. * \param ptr The address of the write buffer.
  86150. * \param size The size of the records to be written.
  86151. * \param nmemb The number of records to be written.
  86152. * \param handle The handle to the data source.
  86153. * \retval size_t
  86154. * The number of records written.
  86155. */
  86156. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86157. /** Signature for the seek callback.
  86158. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86159. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86160. * and 32-bits wide.
  86161. *
  86162. * \param handle The handle to the data source.
  86163. * \param offset The new position, relative to \a whence
  86164. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86165. * \retval int
  86166. * \c 0 on success, \c -1 on error.
  86167. */
  86168. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86169. /** Signature for the tell callback.
  86170. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86171. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86172. * and 32-bits wide.
  86173. *
  86174. * \param handle The handle to the data source.
  86175. * \retval FLAC__int64
  86176. * The current position on success, \c -1 on error.
  86177. */
  86178. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86179. /** Signature for the EOF callback.
  86180. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86181. * on many systems, feof() is a macro, so in this case a wrapper function
  86182. * must be provided instead.
  86183. *
  86184. * \param handle The handle to the data source.
  86185. * \retval int
  86186. * \c 0 if not at end of file, nonzero if at end of file.
  86187. */
  86188. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86189. /** Signature for the close callback.
  86190. * The signature and semantics match POSIX fclose() implementations
  86191. * and can generally be used interchangeably.
  86192. *
  86193. * \param handle The handle to the data source.
  86194. * \retval int
  86195. * \c 0 on success, \c EOF on error.
  86196. */
  86197. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86198. /** A structure for holding a set of callbacks.
  86199. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86200. * describe which of the callbacks are required. The ones that are not
  86201. * required may be set to NULL.
  86202. *
  86203. * If the seek requirement for an interface is optional, you can signify that
  86204. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86205. */
  86206. typedef struct {
  86207. FLAC__IOCallback_Read read;
  86208. FLAC__IOCallback_Write write;
  86209. FLAC__IOCallback_Seek seek;
  86210. FLAC__IOCallback_Tell tell;
  86211. FLAC__IOCallback_Eof eof;
  86212. FLAC__IOCallback_Close close;
  86213. } FLAC__IOCallbacks;
  86214. /* \} */
  86215. #ifdef __cplusplus
  86216. }
  86217. #endif
  86218. #endif
  86219. /*** End of inlined file: callback.h ***/
  86220. /*** Start of inlined file: format.h ***/
  86221. #ifndef FLAC__FORMAT_H
  86222. #define FLAC__FORMAT_H
  86223. #ifdef __cplusplus
  86224. extern "C" {
  86225. #endif
  86226. /** \file include/FLAC/format.h
  86227. *
  86228. * \brief
  86229. * This module contains structure definitions for the representation
  86230. * of FLAC format components in memory. These are the basic
  86231. * structures used by the rest of the interfaces.
  86232. *
  86233. * See the detailed documentation in the
  86234. * \link flac_format format \endlink module.
  86235. */
  86236. /** \defgroup flac_format FLAC/format.h: format components
  86237. * \ingroup flac
  86238. *
  86239. * \brief
  86240. * This module contains structure definitions for the representation
  86241. * of FLAC format components in memory. These are the basic
  86242. * structures used by the rest of the interfaces.
  86243. *
  86244. * First, you should be familiar with the
  86245. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86246. * follow directly from the specification. As a user of libFLAC, the
  86247. * interesting parts really are the structures that describe the frame
  86248. * header and metadata blocks.
  86249. *
  86250. * The format structures here are very primitive, designed to store
  86251. * information in an efficient way. Reading information from the
  86252. * structures is easy but creating or modifying them directly is
  86253. * more complex. For the most part, as a user of a library, editing
  86254. * is not necessary; however, for metadata blocks it is, so there are
  86255. * convenience functions provided in the \link flac_metadata metadata
  86256. * module \endlink to simplify the manipulation of metadata blocks.
  86257. *
  86258. * \note
  86259. * It's not the best convention, but symbols ending in _LEN are in bits
  86260. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86261. * global variables because they are usually used when declaring byte
  86262. * arrays and some compilers require compile-time knowledge of array
  86263. * sizes when declared on the stack.
  86264. *
  86265. * \{
  86266. */
  86267. /*
  86268. Most of the values described in this file are defined by the FLAC
  86269. format specification. There is nothing to tune here.
  86270. */
  86271. /** The largest legal metadata type code. */
  86272. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86273. /** The minimum block size, in samples, permitted by the format. */
  86274. #define FLAC__MIN_BLOCK_SIZE (16u)
  86275. /** The maximum block size, in samples, permitted by the format. */
  86276. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86277. /** The maximum block size, in samples, permitted by the FLAC subset for
  86278. * sample rates up to 48kHz. */
  86279. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86280. /** The maximum number of channels permitted by the format. */
  86281. #define FLAC__MAX_CHANNELS (8u)
  86282. /** The minimum sample resolution permitted by the format. */
  86283. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86284. /** The maximum sample resolution permitted by the format. */
  86285. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86286. /** The maximum sample resolution permitted by libFLAC.
  86287. *
  86288. * \warning
  86289. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86290. * the reference encoder/decoder is currently limited to 24 bits because
  86291. * of prevalent 32-bit math, so make sure and use this value when
  86292. * appropriate.
  86293. */
  86294. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86295. /** The maximum sample rate permitted by the format. The value is
  86296. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86297. * as to why.
  86298. */
  86299. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86300. /** The maximum LPC order permitted by the format. */
  86301. #define FLAC__MAX_LPC_ORDER (32u)
  86302. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86303. * up to 48kHz. */
  86304. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86305. /** The minimum quantized linear predictor coefficient precision
  86306. * permitted by the format.
  86307. */
  86308. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86309. /** The maximum quantized linear predictor coefficient precision
  86310. * permitted by the format.
  86311. */
  86312. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86313. /** The maximum order of the fixed predictors permitted by the format. */
  86314. #define FLAC__MAX_FIXED_ORDER (4u)
  86315. /** The maximum Rice partition order permitted by the format. */
  86316. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86317. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86318. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86319. /** The version string of the release, stamped onto the libraries and binaries.
  86320. *
  86321. * \note
  86322. * This does not correspond to the shared library version number, which
  86323. * is used to determine binary compatibility.
  86324. */
  86325. extern FLAC_API const char *FLAC__VERSION_STRING;
  86326. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86327. * This is a NUL-terminated ASCII string; when inserted into the
  86328. * VORBIS_COMMENT the trailing null is stripped.
  86329. */
  86330. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86331. /** The byte string representation of the beginning of a FLAC stream. */
  86332. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86333. /** The 32-bit integer big-endian representation of the beginning of
  86334. * a FLAC stream.
  86335. */
  86336. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86337. /** The length of the FLAC signature in bits. */
  86338. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86339. /** The length of the FLAC signature in bytes. */
  86340. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86341. /*****************************************************************************
  86342. *
  86343. * Subframe structures
  86344. *
  86345. *****************************************************************************/
  86346. /*****************************************************************************/
  86347. /** An enumeration of the available entropy coding methods. */
  86348. typedef enum {
  86349. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86350. /**< Residual is coded by partitioning into contexts, each with it's own
  86351. * 4-bit Rice parameter. */
  86352. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86353. /**< Residual is coded by partitioning into contexts, each with it's own
  86354. * 5-bit Rice parameter. */
  86355. } FLAC__EntropyCodingMethodType;
  86356. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86357. *
  86358. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86359. * give the string equivalent. The contents should not be modified.
  86360. */
  86361. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86362. /** Contents of a Rice partitioned residual
  86363. */
  86364. typedef struct {
  86365. unsigned *parameters;
  86366. /**< The Rice parameters for each context. */
  86367. unsigned *raw_bits;
  86368. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86369. * partitions and zero for unescaped partitions.
  86370. */
  86371. unsigned capacity_by_order;
  86372. /**< The capacity of the \a parameters and \a raw_bits arrays
  86373. * specified as an order, i.e. the number of array elements
  86374. * allocated is 2 ^ \a capacity_by_order.
  86375. */
  86376. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86377. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86378. */
  86379. typedef struct {
  86380. unsigned order;
  86381. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86382. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86383. /**< The context's Rice parameters and/or raw bits. */
  86384. } FLAC__EntropyCodingMethod_PartitionedRice;
  86385. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86386. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86387. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86388. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86389. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86390. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86391. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86392. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86393. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86394. */
  86395. typedef struct {
  86396. FLAC__EntropyCodingMethodType type;
  86397. union {
  86398. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86399. } data;
  86400. } FLAC__EntropyCodingMethod;
  86401. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86402. /*****************************************************************************/
  86403. /** An enumeration of the available subframe types. */
  86404. typedef enum {
  86405. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86406. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86407. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86408. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86409. } FLAC__SubframeType;
  86410. /** Maps a FLAC__SubframeType to a C string.
  86411. *
  86412. * Using a FLAC__SubframeType as the index to this array will
  86413. * give the string equivalent. The contents should not be modified.
  86414. */
  86415. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86416. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86417. */
  86418. typedef struct {
  86419. FLAC__int32 value; /**< The constant signal value. */
  86420. } FLAC__Subframe_Constant;
  86421. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86422. */
  86423. typedef struct {
  86424. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86425. } FLAC__Subframe_Verbatim;
  86426. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86427. */
  86428. typedef struct {
  86429. FLAC__EntropyCodingMethod entropy_coding_method;
  86430. /**< The residual coding method. */
  86431. unsigned order;
  86432. /**< The polynomial order. */
  86433. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86434. /**< Warmup samples to prime the predictor, length == order. */
  86435. const FLAC__int32 *residual;
  86436. /**< The residual signal, length == (blocksize minus order) samples. */
  86437. } FLAC__Subframe_Fixed;
  86438. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86439. */
  86440. typedef struct {
  86441. FLAC__EntropyCodingMethod entropy_coding_method;
  86442. /**< The residual coding method. */
  86443. unsigned order;
  86444. /**< The FIR order. */
  86445. unsigned qlp_coeff_precision;
  86446. /**< Quantized FIR filter coefficient precision in bits. */
  86447. int quantization_level;
  86448. /**< The qlp coeff shift needed. */
  86449. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86450. /**< FIR filter coefficients. */
  86451. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86452. /**< Warmup samples to prime the predictor, length == order. */
  86453. const FLAC__int32 *residual;
  86454. /**< The residual signal, length == (blocksize minus order) samples. */
  86455. } FLAC__Subframe_LPC;
  86456. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86457. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86458. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86459. */
  86460. typedef struct {
  86461. FLAC__SubframeType type;
  86462. union {
  86463. FLAC__Subframe_Constant constant;
  86464. FLAC__Subframe_Fixed fixed;
  86465. FLAC__Subframe_LPC lpc;
  86466. FLAC__Subframe_Verbatim verbatim;
  86467. } data;
  86468. unsigned wasted_bits;
  86469. } FLAC__Subframe;
  86470. /** == 1 (bit)
  86471. *
  86472. * This used to be a zero-padding bit (hence the name
  86473. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86474. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86475. * to mean something else.
  86476. */
  86477. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86478. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86479. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86480. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86481. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86482. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86483. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86484. /*****************************************************************************/
  86485. /*****************************************************************************
  86486. *
  86487. * Frame structures
  86488. *
  86489. *****************************************************************************/
  86490. /** An enumeration of the available channel assignments. */
  86491. typedef enum {
  86492. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86493. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86494. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86495. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86496. } FLAC__ChannelAssignment;
  86497. /** Maps a FLAC__ChannelAssignment to a C string.
  86498. *
  86499. * Using a FLAC__ChannelAssignment as the index to this array will
  86500. * give the string equivalent. The contents should not be modified.
  86501. */
  86502. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86503. /** An enumeration of the possible frame numbering methods. */
  86504. typedef enum {
  86505. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86506. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86507. } FLAC__FrameNumberType;
  86508. /** Maps a FLAC__FrameNumberType to a C string.
  86509. *
  86510. * Using a FLAC__FrameNumberType as the index to this array will
  86511. * give the string equivalent. The contents should not be modified.
  86512. */
  86513. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86514. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86515. */
  86516. typedef struct {
  86517. unsigned blocksize;
  86518. /**< The number of samples per subframe. */
  86519. unsigned sample_rate;
  86520. /**< The sample rate in Hz. */
  86521. unsigned channels;
  86522. /**< The number of channels (== number of subframes). */
  86523. FLAC__ChannelAssignment channel_assignment;
  86524. /**< The channel assignment for the frame. */
  86525. unsigned bits_per_sample;
  86526. /**< The sample resolution. */
  86527. FLAC__FrameNumberType number_type;
  86528. /**< The numbering scheme used for the frame. As a convenience, the
  86529. * decoder will always convert a frame number to a sample number because
  86530. * the rules are complex. */
  86531. union {
  86532. FLAC__uint32 frame_number;
  86533. FLAC__uint64 sample_number;
  86534. } number;
  86535. /**< The frame number or sample number of first sample in frame;
  86536. * use the \a number_type value to determine which to use. */
  86537. FLAC__uint8 crc;
  86538. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86539. * of the raw frame header bytes, meaning everything before the CRC byte
  86540. * including the sync code.
  86541. */
  86542. } FLAC__FrameHeader;
  86543. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86544. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86545. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86546. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86547. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86548. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86549. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86550. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86551. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86552. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86553. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86554. */
  86555. typedef struct {
  86556. FLAC__uint16 crc;
  86557. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86558. * 0) of the bytes before the crc, back to and including the frame header
  86559. * sync code.
  86560. */
  86561. } FLAC__FrameFooter;
  86562. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86563. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86564. */
  86565. typedef struct {
  86566. FLAC__FrameHeader header;
  86567. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86568. FLAC__FrameFooter footer;
  86569. } FLAC__Frame;
  86570. /*****************************************************************************/
  86571. /*****************************************************************************
  86572. *
  86573. * Meta-data structures
  86574. *
  86575. *****************************************************************************/
  86576. /** An enumeration of the available metadata block types. */
  86577. typedef enum {
  86578. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86579. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86580. FLAC__METADATA_TYPE_PADDING = 1,
  86581. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86582. FLAC__METADATA_TYPE_APPLICATION = 2,
  86583. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86584. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86585. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86586. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86587. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86588. FLAC__METADATA_TYPE_CUESHEET = 5,
  86589. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86590. FLAC__METADATA_TYPE_PICTURE = 6,
  86591. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86592. FLAC__METADATA_TYPE_UNDEFINED = 7
  86593. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86594. } FLAC__MetadataType;
  86595. /** Maps a FLAC__MetadataType to a C string.
  86596. *
  86597. * Using a FLAC__MetadataType as the index to this array will
  86598. * give the string equivalent. The contents should not be modified.
  86599. */
  86600. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86601. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86602. */
  86603. typedef struct {
  86604. unsigned min_blocksize, max_blocksize;
  86605. unsigned min_framesize, max_framesize;
  86606. unsigned sample_rate;
  86607. unsigned channels;
  86608. unsigned bits_per_sample;
  86609. FLAC__uint64 total_samples;
  86610. FLAC__byte md5sum[16];
  86611. } FLAC__StreamMetadata_StreamInfo;
  86612. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86613. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86614. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86615. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86616. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86617. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86618. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86619. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86620. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86621. /** The total stream length of the STREAMINFO block in bytes. */
  86622. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86623. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86624. */
  86625. typedef struct {
  86626. int dummy;
  86627. /**< Conceptually this is an empty struct since we don't store the
  86628. * padding bytes. Empty structs are not allowed by some C compilers,
  86629. * hence the dummy.
  86630. */
  86631. } FLAC__StreamMetadata_Padding;
  86632. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86633. */
  86634. typedef struct {
  86635. FLAC__byte id[4];
  86636. FLAC__byte *data;
  86637. } FLAC__StreamMetadata_Application;
  86638. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86639. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86640. */
  86641. typedef struct {
  86642. FLAC__uint64 sample_number;
  86643. /**< The sample number of the target frame. */
  86644. FLAC__uint64 stream_offset;
  86645. /**< The offset, in bytes, of the target frame with respect to
  86646. * beginning of the first frame. */
  86647. unsigned frame_samples;
  86648. /**< The number of samples in the target frame. */
  86649. } FLAC__StreamMetadata_SeekPoint;
  86650. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86651. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86652. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86653. /** The total stream length of a seek point in bytes. */
  86654. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86655. /** The value used in the \a sample_number field of
  86656. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86657. * point (== 0xffffffffffffffff).
  86658. */
  86659. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86660. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86661. *
  86662. * \note From the format specification:
  86663. * - The seek points must be sorted by ascending sample number.
  86664. * - Each seek point's sample number must be the first sample of the
  86665. * target frame.
  86666. * - Each seek point's sample number must be unique within the table.
  86667. * - Existence of a SEEKTABLE block implies a correct setting of
  86668. * total_samples in the stream_info block.
  86669. * - Behavior is undefined when more than one SEEKTABLE block is
  86670. * present in a stream.
  86671. */
  86672. typedef struct {
  86673. unsigned num_points;
  86674. FLAC__StreamMetadata_SeekPoint *points;
  86675. } FLAC__StreamMetadata_SeekTable;
  86676. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86677. *
  86678. * For convenience, the APIs maintain a trailing NUL character at the end of
  86679. * \a entry which is not counted toward \a length, i.e.
  86680. * \code strlen(entry) == length \endcode
  86681. */
  86682. typedef struct {
  86683. FLAC__uint32 length;
  86684. FLAC__byte *entry;
  86685. } FLAC__StreamMetadata_VorbisComment_Entry;
  86686. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86687. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86688. */
  86689. typedef struct {
  86690. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86691. FLAC__uint32 num_comments;
  86692. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86693. } FLAC__StreamMetadata_VorbisComment;
  86694. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86695. /** FLAC CUESHEET track index structure. (See the
  86696. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86697. * the full description of each field.)
  86698. */
  86699. typedef struct {
  86700. FLAC__uint64 offset;
  86701. /**< Offset in samples, relative to the track offset, of the index
  86702. * point.
  86703. */
  86704. FLAC__byte number;
  86705. /**< The index point number. */
  86706. } FLAC__StreamMetadata_CueSheet_Index;
  86707. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86708. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86709. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86710. /** FLAC CUESHEET track structure. (See the
  86711. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86712. * the full description of each field.)
  86713. */
  86714. typedef struct {
  86715. FLAC__uint64 offset;
  86716. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86717. FLAC__byte number;
  86718. /**< The track number. */
  86719. char isrc[13];
  86720. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86721. unsigned type:1;
  86722. /**< The track type: 0 for audio, 1 for non-audio. */
  86723. unsigned pre_emphasis:1;
  86724. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86725. FLAC__byte num_indices;
  86726. /**< The number of track index points. */
  86727. FLAC__StreamMetadata_CueSheet_Index *indices;
  86728. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86729. } FLAC__StreamMetadata_CueSheet_Track;
  86730. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86731. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86732. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86733. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86734. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86735. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86736. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86737. /** FLAC CUESHEET structure. (See the
  86738. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86739. * for the full description of each field.)
  86740. */
  86741. typedef struct {
  86742. char media_catalog_number[129];
  86743. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86744. * general, the media catalog number may be 0 to 128 bytes long; any
  86745. * unused characters should be right-padded with NUL characters.
  86746. */
  86747. FLAC__uint64 lead_in;
  86748. /**< The number of lead-in samples. */
  86749. FLAC__bool is_cd;
  86750. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86751. unsigned num_tracks;
  86752. /**< The number of tracks. */
  86753. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86754. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86755. } FLAC__StreamMetadata_CueSheet;
  86756. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86757. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86758. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86759. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86760. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86761. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86762. typedef enum {
  86763. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86764. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86765. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86766. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86767. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86768. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86769. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86770. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86771. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86772. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86773. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86774. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86775. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86776. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86777. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86778. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86779. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86780. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86781. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86782. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86783. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86784. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86785. } FLAC__StreamMetadata_Picture_Type;
  86786. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86787. *
  86788. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86789. * will give the string equivalent. The contents should not be
  86790. * modified.
  86791. */
  86792. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86793. /** FLAC PICTURE structure. (See the
  86794. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86795. * for the full description of each field.)
  86796. */
  86797. typedef struct {
  86798. FLAC__StreamMetadata_Picture_Type type;
  86799. /**< The kind of picture stored. */
  86800. char *mime_type;
  86801. /**< Picture data's MIME type, in ASCII printable characters
  86802. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86803. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86804. * MIME type of '-->' is also allowed, in which case the picture
  86805. * data should be a complete URL. In file storage, the MIME type is
  86806. * stored as a 32-bit length followed by the ASCII string with no NUL
  86807. * terminator, but is converted to a plain C string in this structure
  86808. * for convenience.
  86809. */
  86810. FLAC__byte *description;
  86811. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86812. * the description is stored as a 32-bit length followed by the UTF-8
  86813. * string with no NUL terminator, but is converted to a plain C string
  86814. * in this structure for convenience.
  86815. */
  86816. FLAC__uint32 width;
  86817. /**< Picture's width in pixels. */
  86818. FLAC__uint32 height;
  86819. /**< Picture's height in pixels. */
  86820. FLAC__uint32 depth;
  86821. /**< Picture's color depth in bits-per-pixel. */
  86822. FLAC__uint32 colors;
  86823. /**< For indexed palettes (like GIF), picture's number of colors (the
  86824. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86825. */
  86826. FLAC__uint32 data_length;
  86827. /**< Length of binary picture data in bytes. */
  86828. FLAC__byte *data;
  86829. /**< Binary picture data. */
  86830. } FLAC__StreamMetadata_Picture;
  86831. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86832. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86833. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86834. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86835. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86836. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86837. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86838. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86839. /** Structure that is used when a metadata block of unknown type is loaded.
  86840. * The contents are opaque. The structure is used only internally to
  86841. * correctly handle unknown metadata.
  86842. */
  86843. typedef struct {
  86844. FLAC__byte *data;
  86845. } FLAC__StreamMetadata_Unknown;
  86846. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86847. */
  86848. typedef struct {
  86849. FLAC__MetadataType type;
  86850. /**< The type of the metadata block; used determine which member of the
  86851. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86852. * then \a data.unknown must be used. */
  86853. FLAC__bool is_last;
  86854. /**< \c true if this metadata block is the last, else \a false */
  86855. unsigned length;
  86856. /**< Length, in bytes, of the block data as it appears in the stream. */
  86857. union {
  86858. FLAC__StreamMetadata_StreamInfo stream_info;
  86859. FLAC__StreamMetadata_Padding padding;
  86860. FLAC__StreamMetadata_Application application;
  86861. FLAC__StreamMetadata_SeekTable seek_table;
  86862. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86863. FLAC__StreamMetadata_CueSheet cue_sheet;
  86864. FLAC__StreamMetadata_Picture picture;
  86865. FLAC__StreamMetadata_Unknown unknown;
  86866. } data;
  86867. /**< Polymorphic block data; use the \a type value to determine which
  86868. * to use. */
  86869. } FLAC__StreamMetadata;
  86870. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86871. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86872. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86873. /** The total stream length of a metadata block header in bytes. */
  86874. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86875. /*****************************************************************************/
  86876. /*****************************************************************************
  86877. *
  86878. * Utility functions
  86879. *
  86880. *****************************************************************************/
  86881. /** Tests that a sample rate is valid for FLAC.
  86882. *
  86883. * \param sample_rate The sample rate to test for compliance.
  86884. * \retval FLAC__bool
  86885. * \c true if the given sample rate conforms to the specification, else
  86886. * \c false.
  86887. */
  86888. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86889. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86890. * for valid sample rates are slightly more complex since the rate has to
  86891. * be expressible completely in the frame header.
  86892. *
  86893. * \param sample_rate The sample rate to test for compliance.
  86894. * \retval FLAC__bool
  86895. * \c true if the given sample rate conforms to the specification for the
  86896. * subset, else \c false.
  86897. */
  86898. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86899. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86900. * comment specification.
  86901. *
  86902. * Vorbis comment names must be composed only of characters from
  86903. * [0x20-0x3C,0x3E-0x7D].
  86904. *
  86905. * \param name A NUL-terminated string to be checked.
  86906. * \assert
  86907. * \code name != NULL \endcode
  86908. * \retval FLAC__bool
  86909. * \c false if entry name is illegal, else \c true.
  86910. */
  86911. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86912. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86913. * comment specification.
  86914. *
  86915. * Vorbis comment values must be valid UTF-8 sequences.
  86916. *
  86917. * \param value A string to be checked.
  86918. * \param length A the length of \a value in bytes. May be
  86919. * \c (unsigned)(-1) to indicate that \a value is a plain
  86920. * UTF-8 NUL-terminated string.
  86921. * \assert
  86922. * \code value != NULL \endcode
  86923. * \retval FLAC__bool
  86924. * \c false if entry name is illegal, else \c true.
  86925. */
  86926. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86927. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86928. * comment specification.
  86929. *
  86930. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86931. * 'value' must be legal according to
  86932. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86933. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86934. *
  86935. * \param entry An entry to be checked.
  86936. * \param length The length of \a entry in bytes.
  86937. * \assert
  86938. * \code value != NULL \endcode
  86939. * \retval FLAC__bool
  86940. * \c false if entry name is illegal, else \c true.
  86941. */
  86942. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86943. /** Check a seek table to see if it conforms to the FLAC specification.
  86944. * See the format specification for limits on the contents of the
  86945. * seek table.
  86946. *
  86947. * \param seek_table A pointer to a seek table to be checked.
  86948. * \assert
  86949. * \code seek_table != NULL \endcode
  86950. * \retval FLAC__bool
  86951. * \c false if seek table is illegal, else \c true.
  86952. */
  86953. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86954. /** Sort a seek table's seek points according to the format specification.
  86955. * This includes a "unique-ification" step to remove duplicates, i.e.
  86956. * seek points with identical \a sample_number values. Duplicate seek
  86957. * points are converted into placeholder points and sorted to the end of
  86958. * the table.
  86959. *
  86960. * \param seek_table A pointer to a seek table to be sorted.
  86961. * \assert
  86962. * \code seek_table != NULL \endcode
  86963. * \retval unsigned
  86964. * The number of duplicate seek points converted into placeholders.
  86965. */
  86966. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86967. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86968. * See the format specification for limits on the contents of the
  86969. * cue sheet.
  86970. *
  86971. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86972. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86973. * stringent requirements for a CD-DA (audio) disc.
  86974. * \param violation Address of a pointer to a string. If there is a
  86975. * violation, a pointer to a string explanation of the
  86976. * violation will be returned here. \a violation may be
  86977. * \c NULL if you don't need the returned string. Do not
  86978. * free the returned string; it will always point to static
  86979. * data.
  86980. * \assert
  86981. * \code cue_sheet != NULL \endcode
  86982. * \retval FLAC__bool
  86983. * \c false if cue sheet is illegal, else \c true.
  86984. */
  86985. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86986. /** Check picture data to see if it conforms to the FLAC specification.
  86987. * See the format specification for limits on the contents of the
  86988. * PICTURE block.
  86989. *
  86990. * \param picture A pointer to existing picture data to be checked.
  86991. * \param violation Address of a pointer to a string. If there is a
  86992. * violation, a pointer to a string explanation of the
  86993. * violation will be returned here. \a violation may be
  86994. * \c NULL if you don't need the returned string. Do not
  86995. * free the returned string; it will always point to static
  86996. * data.
  86997. * \assert
  86998. * \code picture != NULL \endcode
  86999. * \retval FLAC__bool
  87000. * \c false if picture data is illegal, else \c true.
  87001. */
  87002. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87003. /* \} */
  87004. #ifdef __cplusplus
  87005. }
  87006. #endif
  87007. #endif
  87008. /*** End of inlined file: format.h ***/
  87009. /*** Start of inlined file: metadata.h ***/
  87010. #ifndef FLAC__METADATA_H
  87011. #define FLAC__METADATA_H
  87012. #include <sys/types.h> /* for off_t */
  87013. /* --------------------------------------------------------------------
  87014. (For an example of how all these routines are used, see the source
  87015. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87016. metaflac in src/metaflac/)
  87017. ------------------------------------------------------------------*/
  87018. /** \file include/FLAC/metadata.h
  87019. *
  87020. * \brief
  87021. * This module provides functions for creating and manipulating FLAC
  87022. * metadata blocks in memory, and three progressively more powerful
  87023. * interfaces for traversing and editing metadata in FLAC files.
  87024. *
  87025. * See the detailed documentation for each interface in the
  87026. * \link flac_metadata metadata \endlink module.
  87027. */
  87028. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87029. * \ingroup flac
  87030. *
  87031. * \brief
  87032. * This module provides functions for creating and manipulating FLAC
  87033. * metadata blocks in memory, and three progressively more powerful
  87034. * interfaces for traversing and editing metadata in native FLAC files.
  87035. * Note that currently only the Chain interface (level 2) supports Ogg
  87036. * FLAC files, and it is read-only i.e. no writing back changed
  87037. * metadata to file.
  87038. *
  87039. * There are three metadata interfaces of increasing complexity:
  87040. *
  87041. * Level 0:
  87042. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87043. * PICTURE blocks.
  87044. *
  87045. * Level 1:
  87046. * Read-write access to all metadata blocks. This level is write-
  87047. * efficient in most cases (more on this below), and uses less memory
  87048. * than level 2.
  87049. *
  87050. * Level 2:
  87051. * Read-write access to all metadata blocks. This level is write-
  87052. * efficient in all cases, but uses more memory since all metadata for
  87053. * the whole file is read into memory and manipulated before writing
  87054. * out again.
  87055. *
  87056. * What do we mean by efficient? Since FLAC metadata appears at the
  87057. * beginning of the file, when writing metadata back to a FLAC file
  87058. * it is possible to grow or shrink the metadata such that the entire
  87059. * file must be rewritten. However, if the size remains the same during
  87060. * changes or PADDING blocks are utilized, only the metadata needs to be
  87061. * overwritten, which is much faster.
  87062. *
  87063. * Efficient means the whole file is rewritten at most one time, and only
  87064. * when necessary. Level 1 is not efficient only in the case that you
  87065. * cause more than one metadata block to grow or shrink beyond what can
  87066. * be accomodated by padding. In this case you should probably use level
  87067. * 2, which allows you to edit all the metadata for a file in memory and
  87068. * write it out all at once.
  87069. *
  87070. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87071. * front of the file.
  87072. *
  87073. * All levels access files via their filenames. In addition, level 2
  87074. * has additional alternative read and write functions that take an I/O
  87075. * handle and callbacks, for situations where access by filename is not
  87076. * possible.
  87077. *
  87078. * In addition to the three interfaces, this module defines functions for
  87079. * creating and manipulating various metadata objects in memory. As we see
  87080. * from the Format module, FLAC metadata blocks in memory are very primitive
  87081. * structures for storing information in an efficient way. Reading
  87082. * information from the structures is easy but creating or modifying them
  87083. * directly is more complex. The metadata object routines here facilitate
  87084. * this by taking care of the consistency and memory management drudgery.
  87085. *
  87086. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87087. * metadata however, you will not probably not need these.
  87088. *
  87089. * From a dependency standpoint, none of the encoders or decoders require
  87090. * the metadata module. This is so that embedded users can strip out the
  87091. * metadata module from libFLAC to reduce the size and complexity.
  87092. */
  87093. #ifdef __cplusplus
  87094. extern "C" {
  87095. #endif
  87096. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87097. * \ingroup flac_metadata
  87098. *
  87099. * \brief
  87100. * The level 0 interface consists of individual routines to read the
  87101. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87102. * only a filename.
  87103. *
  87104. * They try to skip any ID3v2 tag at the head of the file.
  87105. *
  87106. * \{
  87107. */
  87108. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87109. * will try to skip any ID3v2 tag at the head of the file.
  87110. *
  87111. * \param filename The path to the FLAC file to read.
  87112. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87113. * FLAC__StreamMetadata is a simple structure with no
  87114. * memory allocation involved, you pass the address of
  87115. * an existing structure. It need not be initialized.
  87116. * \assert
  87117. * \code filename != NULL \endcode
  87118. * \code streaminfo != NULL \endcode
  87119. * \retval FLAC__bool
  87120. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87121. * \c false if there was a memory allocation error, a file decoder error,
  87122. * or the file contained no STREAMINFO block. (A memory allocation error
  87123. * is possible because this function must set up a file decoder.)
  87124. */
  87125. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87126. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87127. * function will try to skip any ID3v2 tag at the head of the file.
  87128. *
  87129. * \param filename The path to the FLAC file to read.
  87130. * \param tags The address where the returned pointer will be
  87131. * stored. The \a tags object must be deleted by
  87132. * the caller using FLAC__metadata_object_delete().
  87133. * \assert
  87134. * \code filename != NULL \endcode
  87135. * \code tags != NULL \endcode
  87136. * \retval FLAC__bool
  87137. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87138. * and \a *tags will be set to the address of the metadata structure.
  87139. * Returns \c false if there was a memory allocation error, a file
  87140. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87141. * \a *tags will be set to \c NULL.
  87142. */
  87143. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87144. /** Read the CUESHEET metadata block of the given FLAC file. This
  87145. * function will try to skip any ID3v2 tag at the head of the file.
  87146. *
  87147. * \param filename The path to the FLAC file to read.
  87148. * \param cuesheet The address where the returned pointer will be
  87149. * stored. The \a cuesheet object must be deleted by
  87150. * the caller using FLAC__metadata_object_delete().
  87151. * \assert
  87152. * \code filename != NULL \endcode
  87153. * \code cuesheet != NULL \endcode
  87154. * \retval FLAC__bool
  87155. * \c true if a valid CUESHEET block was read from \a filename,
  87156. * and \a *cuesheet will be set to the address of the metadata
  87157. * structure. Returns \c false if there was a memory allocation
  87158. * error, a file decoder error, or the file contained no CUESHEET
  87159. * block, and \a *cuesheet will be set to \c NULL.
  87160. */
  87161. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87162. /** Read a PICTURE metadata block of the given FLAC file. This
  87163. * function will try to skip any ID3v2 tag at the head of the file.
  87164. * Since there can be more than one PICTURE block in a file, this
  87165. * function takes a number of parameters that act as constraints to
  87166. * the search. The PICTURE block with the largest area matching all
  87167. * the constraints will be returned, or \a *picture will be set to
  87168. * \c NULL if there was no such block.
  87169. *
  87170. * \param filename The path to the FLAC file to read.
  87171. * \param picture The address where the returned pointer will be
  87172. * stored. The \a picture object must be deleted by
  87173. * the caller using FLAC__metadata_object_delete().
  87174. * \param type The desired picture type. Use \c -1 to mean
  87175. * "any type".
  87176. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87177. * string will be matched exactly. Use \c NULL to
  87178. * mean "any MIME type".
  87179. * \param description The desired description. The string will be
  87180. * matched exactly. Use \c NULL to mean "any
  87181. * description".
  87182. * \param max_width The maximum width in pixels desired. Use
  87183. * \c (unsigned)(-1) to mean "any width".
  87184. * \param max_height The maximum height in pixels desired. Use
  87185. * \c (unsigned)(-1) to mean "any height".
  87186. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87187. * Use \c (unsigned)(-1) to mean "any depth".
  87188. * \param max_colors The maximum number of colors desired. Use
  87189. * \c (unsigned)(-1) to mean "any number of colors".
  87190. * \assert
  87191. * \code filename != NULL \endcode
  87192. * \code picture != NULL \endcode
  87193. * \retval FLAC__bool
  87194. * \c true if a valid PICTURE block was read from \a filename,
  87195. * and \a *picture will be set to the address of the metadata
  87196. * structure. Returns \c false if there was a memory allocation
  87197. * error, a file decoder error, or the file contained no PICTURE
  87198. * block, and \a *picture will be set to \c NULL.
  87199. */
  87200. 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);
  87201. /* \} */
  87202. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87203. * \ingroup flac_metadata
  87204. *
  87205. * \brief
  87206. * The level 1 interface provides read-write access to FLAC file metadata and
  87207. * operates directly on the FLAC file.
  87208. *
  87209. * The general usage of this interface is:
  87210. *
  87211. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87212. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87213. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87214. * see if the file is writable, or only read access is allowed.
  87215. * - Use FLAC__metadata_simple_iterator_next() and
  87216. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87217. * This is does not read the actual blocks themselves.
  87218. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87219. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87220. * forward from the front of the file.
  87221. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87222. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87223. * the current iterator position. The returned object is yours to modify
  87224. * and free.
  87225. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87226. * back. You must have write permission to the original file. Make sure to
  87227. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87228. * below.
  87229. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87230. * Use the object creation functions from
  87231. * \link flac_metadata_object here \endlink to generate new objects.
  87232. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87233. * currently referred to by the iterator, or replace it with padding.
  87234. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87235. * finished.
  87236. *
  87237. * \note
  87238. * The FLAC file remains open the whole time between
  87239. * FLAC__metadata_simple_iterator_init() and
  87240. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87241. * the file during this time.
  87242. *
  87243. * \note
  87244. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87245. * FLAC__StreamMetadata objects. These are managed automatically.
  87246. *
  87247. * \note
  87248. * If any of the modification functions
  87249. * (FLAC__metadata_simple_iterator_set_block(),
  87250. * FLAC__metadata_simple_iterator_delete_block(),
  87251. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87252. * you should delete the iterator as it may no longer be valid.
  87253. *
  87254. * \{
  87255. */
  87256. struct FLAC__Metadata_SimpleIterator;
  87257. /** The opaque structure definition for the level 1 iterator type.
  87258. * See the
  87259. * \link flac_metadata_level1 metadata level 1 module \endlink
  87260. * for a detailed description.
  87261. */
  87262. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87263. /** Status type for FLAC__Metadata_SimpleIterator.
  87264. *
  87265. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87266. */
  87267. typedef enum {
  87268. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87269. /**< The iterator is in the normal OK state */
  87270. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87271. /**< The data passed into a function violated the function's usage criteria */
  87272. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87273. /**< The iterator could not open the target file */
  87274. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87275. /**< The iterator could not find the FLAC signature at the start of the file */
  87276. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87277. /**< The iterator tried to write to a file that was not writable */
  87278. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87279. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87280. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87281. /**< The iterator encountered an error while reading the FLAC file */
  87282. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87283. /**< The iterator encountered an error while seeking in the FLAC file */
  87284. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87285. /**< The iterator encountered an error while writing the FLAC file */
  87286. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87287. /**< The iterator encountered an error renaming the FLAC file */
  87288. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87289. /**< The iterator encountered an error removing the temporary file */
  87290. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87291. /**< Memory allocation failed */
  87292. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87293. /**< The caller violated an assertion or an unexpected error occurred */
  87294. } FLAC__Metadata_SimpleIteratorStatus;
  87295. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87296. *
  87297. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87298. * will give the string equivalent. The contents should not be modified.
  87299. */
  87300. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87301. /** Create a new iterator instance.
  87302. *
  87303. * \retval FLAC__Metadata_SimpleIterator*
  87304. * \c NULL if there was an error allocating memory, else the new instance.
  87305. */
  87306. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87307. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87308. *
  87309. * \param iterator A pointer to an existing iterator.
  87310. * \assert
  87311. * \code iterator != NULL \endcode
  87312. */
  87313. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87314. /** Get the current status of the iterator. Call this after a function
  87315. * returns \c false to get the reason for the error. Also resets the status
  87316. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87317. *
  87318. * \param iterator A pointer to an existing iterator.
  87319. * \assert
  87320. * \code iterator != NULL \endcode
  87321. * \retval FLAC__Metadata_SimpleIteratorStatus
  87322. * The current status of the iterator.
  87323. */
  87324. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87325. /** Initialize the iterator to point to the first metadata block in the
  87326. * given FLAC file.
  87327. *
  87328. * \param iterator A pointer to an existing iterator.
  87329. * \param filename The path to the FLAC file.
  87330. * \param read_only If \c true, the FLAC file will be opened
  87331. * in read-only mode; if \c false, the FLAC
  87332. * file will be opened for edit even if no
  87333. * edits are performed.
  87334. * \param preserve_file_stats If \c true, the owner and modification
  87335. * time will be preserved even if the FLAC
  87336. * file is written to.
  87337. * \assert
  87338. * \code iterator != NULL \endcode
  87339. * \code filename != NULL \endcode
  87340. * \retval FLAC__bool
  87341. * \c false if a memory allocation error occurs, the file can't be
  87342. * opened, or another error occurs, else \c true.
  87343. */
  87344. 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);
  87345. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87346. * FLAC__metadata_simple_iterator_set_block() and
  87347. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87348. *
  87349. * \param iterator A pointer to an existing iterator.
  87350. * \assert
  87351. * \code iterator != NULL \endcode
  87352. * \retval FLAC__bool
  87353. * See above.
  87354. */
  87355. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87356. /** Moves the iterator forward one metadata block, returning \c false if
  87357. * already at the end.
  87358. *
  87359. * \param iterator A pointer to an existing initialized iterator.
  87360. * \assert
  87361. * \code iterator != NULL \endcode
  87362. * \a iterator has been successfully initialized with
  87363. * FLAC__metadata_simple_iterator_init()
  87364. * \retval FLAC__bool
  87365. * \c false if already at the last metadata block of the chain, else
  87366. * \c true.
  87367. */
  87368. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87369. /** Moves the iterator backward one metadata block, returning \c false if
  87370. * already at the beginning.
  87371. *
  87372. * \param iterator A pointer to an existing initialized iterator.
  87373. * \assert
  87374. * \code iterator != NULL \endcode
  87375. * \a iterator has been successfully initialized with
  87376. * FLAC__metadata_simple_iterator_init()
  87377. * \retval FLAC__bool
  87378. * \c false if already at the first metadata block of the chain, else
  87379. * \c true.
  87380. */
  87381. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87382. /** Returns a flag telling if the current metadata block is the last.
  87383. *
  87384. * \param iterator A pointer to an existing initialized iterator.
  87385. * \assert
  87386. * \code iterator != NULL \endcode
  87387. * \a iterator has been successfully initialized with
  87388. * FLAC__metadata_simple_iterator_init()
  87389. * \retval FLAC__bool
  87390. * \c true if the current metadata block is the last in the file,
  87391. * else \c false.
  87392. */
  87393. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87394. /** Get the offset of the metadata block at the current position. This
  87395. * avoids reading the actual block data which can save time for large
  87396. * blocks.
  87397. *
  87398. * \param iterator A pointer to an existing initialized iterator.
  87399. * \assert
  87400. * \code iterator != NULL \endcode
  87401. * \a iterator has been successfully initialized with
  87402. * FLAC__metadata_simple_iterator_init()
  87403. * \retval off_t
  87404. * The offset of the metadata block at the current iterator position.
  87405. * This is the byte offset relative to the beginning of the file of
  87406. * the current metadata block's header.
  87407. */
  87408. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87409. /** Get the type of the metadata block at the current position. This
  87410. * avoids reading the actual block data which can save time for large
  87411. * blocks.
  87412. *
  87413. * \param iterator A pointer to an existing initialized iterator.
  87414. * \assert
  87415. * \code iterator != NULL \endcode
  87416. * \a iterator has been successfully initialized with
  87417. * FLAC__metadata_simple_iterator_init()
  87418. * \retval FLAC__MetadataType
  87419. * The type of the metadata block at the current iterator position.
  87420. */
  87421. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87422. /** Get the length of the metadata block at the current position. This
  87423. * avoids reading the actual block data which can save time for large
  87424. * blocks.
  87425. *
  87426. * \param iterator A pointer to an existing initialized iterator.
  87427. * \assert
  87428. * \code iterator != NULL \endcode
  87429. * \a iterator has been successfully initialized with
  87430. * FLAC__metadata_simple_iterator_init()
  87431. * \retval unsigned
  87432. * The length of the metadata block at the current iterator position.
  87433. * The is same length as that in the
  87434. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87435. * i.e. the length of the metadata body that follows the header.
  87436. */
  87437. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87438. /** Get the application ID of the \c APPLICATION block at the current
  87439. * position. This avoids reading the actual block data which can save
  87440. * time for large blocks.
  87441. *
  87442. * \param iterator A pointer to an existing initialized iterator.
  87443. * \param id A pointer to a buffer of at least \c 4 bytes where
  87444. * the ID will be stored.
  87445. * \assert
  87446. * \code iterator != NULL \endcode
  87447. * \code id != NULL \endcode
  87448. * \a iterator has been successfully initialized with
  87449. * FLAC__metadata_simple_iterator_init()
  87450. * \retval FLAC__bool
  87451. * \c true if the ID was successfully read, else \c false, in which
  87452. * case you should check FLAC__metadata_simple_iterator_status() to
  87453. * find out why. If the status is
  87454. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87455. * current metadata block is not an \c APPLICATION block. Otherwise
  87456. * if the status is
  87457. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87458. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87459. * occurred and the iterator can no longer be used.
  87460. */
  87461. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87462. /** Get the metadata block at the current position. You can modify the
  87463. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87464. * write it back to the FLAC file.
  87465. *
  87466. * You must call FLAC__metadata_object_delete() on the returned object
  87467. * when you are finished with it.
  87468. *
  87469. * \param iterator A pointer to an existing initialized iterator.
  87470. * \assert
  87471. * \code iterator != NULL \endcode
  87472. * \a iterator has been successfully initialized with
  87473. * FLAC__metadata_simple_iterator_init()
  87474. * \retval FLAC__StreamMetadata*
  87475. * The current metadata block, or \c NULL if there was a memory
  87476. * allocation error.
  87477. */
  87478. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87479. /** Write a block back to the FLAC file. This function tries to be
  87480. * as efficient as possible; how the block is actually written is
  87481. * shown by the following:
  87482. *
  87483. * Existing block is a STREAMINFO block and the new block is a
  87484. * STREAMINFO block: the new block is written in place. Make sure
  87485. * you know what you're doing when changing the values of a
  87486. * STREAMINFO block.
  87487. *
  87488. * Existing block is a STREAMINFO block and the new block is a
  87489. * not a STREAMINFO block: this is an error since the first block
  87490. * must be a STREAMINFO block. Returns \c false without altering the
  87491. * file.
  87492. *
  87493. * Existing block is not a STREAMINFO block and the new block is a
  87494. * STREAMINFO block: this is an error since there may be only one
  87495. * STREAMINFO block. Returns \c false without altering the file.
  87496. *
  87497. * Existing block and new block are the same length: the existing
  87498. * block will be replaced by the new block, written in place.
  87499. *
  87500. * Existing block is longer than new block: if use_padding is \c true,
  87501. * the existing block will be overwritten in place with the new
  87502. * block followed by a PADDING block, if possible, to make the total
  87503. * size the same as the existing block. Remember that a padding
  87504. * block requires at least four bytes so if the difference in size
  87505. * between the new block and existing block is less than that, the
  87506. * entire file will have to be rewritten, using the new block's
  87507. * exact size. If use_padding is \c false, the entire file will be
  87508. * rewritten, replacing the existing block by the new block.
  87509. *
  87510. * Existing block is shorter than new block: if use_padding is \c true,
  87511. * the function will try and expand the new block into the following
  87512. * PADDING block, if it exists and doing so won't shrink the PADDING
  87513. * block to less than 4 bytes. If there is no following PADDING
  87514. * block, or it will shrink to less than 4 bytes, or use_padding is
  87515. * \c false, the entire file is rewritten, replacing the existing block
  87516. * with the new block. Note that in this case any following PADDING
  87517. * block is preserved as is.
  87518. *
  87519. * After writing the block, the iterator will remain in the same
  87520. * place, i.e. pointing to the new block.
  87521. *
  87522. * \param iterator A pointer to an existing initialized iterator.
  87523. * \param block The block to set.
  87524. * \param use_padding See above.
  87525. * \assert
  87526. * \code iterator != NULL \endcode
  87527. * \a iterator has been successfully initialized with
  87528. * FLAC__metadata_simple_iterator_init()
  87529. * \code block != NULL \endcode
  87530. * \retval FLAC__bool
  87531. * \c true if successful, else \c false.
  87532. */
  87533. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87534. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87535. * except that instead of writing over an existing block, it appends
  87536. * a block after the existing block. \a use_padding is again used to
  87537. * tell the function to try an expand into following padding in an
  87538. * attempt to avoid rewriting the entire file.
  87539. *
  87540. * This function will fail and return \c false if given a STREAMINFO
  87541. * block.
  87542. *
  87543. * After writing the block, the iterator will be pointing to the
  87544. * new block.
  87545. *
  87546. * \param iterator A pointer to an existing initialized iterator.
  87547. * \param block The block to set.
  87548. * \param use_padding See above.
  87549. * \assert
  87550. * \code iterator != NULL \endcode
  87551. * \a iterator has been successfully initialized with
  87552. * FLAC__metadata_simple_iterator_init()
  87553. * \code block != NULL \endcode
  87554. * \retval FLAC__bool
  87555. * \c true if successful, else \c false.
  87556. */
  87557. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87558. /** Deletes the block at the current position. This will cause the
  87559. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87560. * in which case the block will be replaced by an equal-sized PADDING
  87561. * block. The iterator will be left pointing to the block before the
  87562. * one just deleted.
  87563. *
  87564. * You may not delete the STREAMINFO block.
  87565. *
  87566. * \param iterator A pointer to an existing initialized iterator.
  87567. * \param use_padding See above.
  87568. * \assert
  87569. * \code iterator != NULL \endcode
  87570. * \a iterator has been successfully initialized with
  87571. * FLAC__metadata_simple_iterator_init()
  87572. * \retval FLAC__bool
  87573. * \c true if successful, else \c false.
  87574. */
  87575. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87576. /* \} */
  87577. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87578. * \ingroup flac_metadata
  87579. *
  87580. * \brief
  87581. * The level 2 interface provides read-write access to FLAC file metadata;
  87582. * all metadata is read into memory, operated on in memory, and then written
  87583. * to file, which is more efficient than level 1 when editing multiple blocks.
  87584. *
  87585. * Currently Ogg FLAC is supported for read only, via
  87586. * FLAC__metadata_chain_read_ogg() but a subsequent
  87587. * FLAC__metadata_chain_write() will fail.
  87588. *
  87589. * The general usage of this interface is:
  87590. *
  87591. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87592. * linked list of FLAC metadata blocks.
  87593. * - Read all metadata into the the chain from a FLAC file using
  87594. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87595. * check the status.
  87596. * - Optionally, consolidate the padding using
  87597. * FLAC__metadata_chain_merge_padding() or
  87598. * FLAC__metadata_chain_sort_padding().
  87599. * - Create a new iterator using FLAC__metadata_iterator_new()
  87600. * - Initialize the iterator to point to the first element in the chain
  87601. * using FLAC__metadata_iterator_init()
  87602. * - Traverse the chain using FLAC__metadata_iterator_next and
  87603. * FLAC__metadata_iterator_prev().
  87604. * - Get a block for reading or modification using
  87605. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87606. * inside the chain is returned, so the block is yours to modify.
  87607. * Changes will be reflected in the FLAC file when you write the
  87608. * chain. You can also add and delete blocks (see functions below).
  87609. * - When done, write out the chain using FLAC__metadata_chain_write().
  87610. * Make sure to read the whole comment to the function below.
  87611. * - Delete the chain using FLAC__metadata_chain_delete().
  87612. *
  87613. * \note
  87614. * Even though the FLAC file is not open while the chain is being
  87615. * manipulated, you must not alter the file externally during
  87616. * this time. The chain assumes the FLAC file will not change
  87617. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87618. * and FLAC__metadata_chain_write().
  87619. *
  87620. * \note
  87621. * Do not modify the is_last, length, or type fields of returned
  87622. * FLAC__StreamMetadata objects. These are managed automatically.
  87623. *
  87624. * \note
  87625. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87626. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87627. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87628. * become owned by the chain and they will be deleted when the chain is
  87629. * deleted.
  87630. *
  87631. * \{
  87632. */
  87633. struct FLAC__Metadata_Chain;
  87634. /** The opaque structure definition for the level 2 chain type.
  87635. */
  87636. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87637. struct FLAC__Metadata_Iterator;
  87638. /** The opaque structure definition for the level 2 iterator type.
  87639. */
  87640. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87641. typedef enum {
  87642. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87643. /**< The chain is in the normal OK state */
  87644. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87645. /**< The data passed into a function violated the function's usage criteria */
  87646. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87647. /**< The chain could not open the target file */
  87648. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87649. /**< The chain could not find the FLAC signature at the start of the file */
  87650. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87651. /**< The chain tried to write to a file that was not writable */
  87652. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87653. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87654. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87655. /**< The chain encountered an error while reading the FLAC file */
  87656. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87657. /**< The chain encountered an error while seeking in the FLAC file */
  87658. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87659. /**< The chain encountered an error while writing the FLAC file */
  87660. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87661. /**< The chain encountered an error renaming the FLAC file */
  87662. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87663. /**< The chain encountered an error removing the temporary file */
  87664. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87665. /**< Memory allocation failed */
  87666. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87667. /**< The caller violated an assertion or an unexpected error occurred */
  87668. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87669. /**< One or more of the required callbacks was NULL */
  87670. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87671. /**< FLAC__metadata_chain_write() was called on a chain read by
  87672. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87673. * or
  87674. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87675. * was called on a chain read by
  87676. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87677. * Matching read/write methods must always be used. */
  87678. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87679. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87680. * chain write requires a tempfile; use
  87681. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87682. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87683. * called when the chain write does not require a tempfile; use
  87684. * FLAC__metadata_chain_write_with_callbacks() instead.
  87685. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87686. * before writing via callbacks. */
  87687. } FLAC__Metadata_ChainStatus;
  87688. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87689. *
  87690. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87691. * will give the string equivalent. The contents should not be modified.
  87692. */
  87693. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87694. /*********** FLAC__Metadata_Chain ***********/
  87695. /** Create a new chain instance.
  87696. *
  87697. * \retval FLAC__Metadata_Chain*
  87698. * \c NULL if there was an error allocating memory, else the new instance.
  87699. */
  87700. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87701. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87702. *
  87703. * \param chain A pointer to an existing chain.
  87704. * \assert
  87705. * \code chain != NULL \endcode
  87706. */
  87707. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87708. /** Get the current status of the chain. Call this after a function
  87709. * returns \c false to get the reason for the error. Also resets the
  87710. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87711. *
  87712. * \param chain A pointer to an existing chain.
  87713. * \assert
  87714. * \code chain != NULL \endcode
  87715. * \retval FLAC__Metadata_ChainStatus
  87716. * The current status of the chain.
  87717. */
  87718. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87719. /** Read all metadata from a FLAC file into the chain.
  87720. *
  87721. * \param chain A pointer to an existing chain.
  87722. * \param filename The path to the FLAC file to read.
  87723. * \assert
  87724. * \code chain != NULL \endcode
  87725. * \code filename != NULL \endcode
  87726. * \retval FLAC__bool
  87727. * \c true if a valid list of metadata blocks was read from
  87728. * \a filename, else \c false. On failure, check the status with
  87729. * FLAC__metadata_chain_status().
  87730. */
  87731. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87732. /** Read all metadata from an Ogg FLAC file into the chain.
  87733. *
  87734. * \note Ogg FLAC metadata data writing is not supported yet and
  87735. * FLAC__metadata_chain_write() will fail.
  87736. *
  87737. * \param chain A pointer to an existing chain.
  87738. * \param filename The path to the Ogg FLAC file to read.
  87739. * \assert
  87740. * \code chain != NULL \endcode
  87741. * \code filename != NULL \endcode
  87742. * \retval FLAC__bool
  87743. * \c true if a valid list of metadata blocks was read from
  87744. * \a filename, else \c false. On failure, check the status with
  87745. * FLAC__metadata_chain_status().
  87746. */
  87747. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87748. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87749. *
  87750. * The \a handle need only be open for reading, but must be seekable.
  87751. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87752. * for Windows).
  87753. *
  87754. * \param chain A pointer to an existing chain.
  87755. * \param handle The I/O handle of the FLAC stream to read. The
  87756. * handle will NOT be closed after the metadata is read;
  87757. * that is the duty of the caller.
  87758. * \param callbacks
  87759. * A set of callbacks to use for I/O. The mandatory
  87760. * callbacks are \a read, \a seek, and \a tell.
  87761. * \assert
  87762. * \code chain != NULL \endcode
  87763. * \retval FLAC__bool
  87764. * \c true if a valid list of metadata blocks was read from
  87765. * \a handle, else \c false. On failure, check the status with
  87766. * FLAC__metadata_chain_status().
  87767. */
  87768. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87769. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87770. *
  87771. * The \a handle need only be open for reading, but must be seekable.
  87772. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87773. * for Windows).
  87774. *
  87775. * \note Ogg FLAC metadata data writing is not supported yet and
  87776. * FLAC__metadata_chain_write() will fail.
  87777. *
  87778. * \param chain A pointer to an existing chain.
  87779. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87780. * handle will NOT be closed after the metadata is read;
  87781. * that is the duty of the caller.
  87782. * \param callbacks
  87783. * A set of callbacks to use for I/O. The mandatory
  87784. * callbacks are \a read, \a seek, and \a tell.
  87785. * \assert
  87786. * \code chain != NULL \endcode
  87787. * \retval FLAC__bool
  87788. * \c true if a valid list of metadata blocks was read from
  87789. * \a handle, else \c false. On failure, check the status with
  87790. * FLAC__metadata_chain_status().
  87791. */
  87792. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87793. /** Checks if writing the given chain would require the use of a
  87794. * temporary file, or if it could be written in place.
  87795. *
  87796. * Under certain conditions, padding can be utilized so that writing
  87797. * edited metadata back to the FLAC file does not require rewriting the
  87798. * entire file. If rewriting is required, then a temporary workfile is
  87799. * required. When writing metadata using callbacks, you must check
  87800. * this function to know whether to call
  87801. * FLAC__metadata_chain_write_with_callbacks() or
  87802. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87803. * writing with FLAC__metadata_chain_write(), the temporary file is
  87804. * handled internally.
  87805. *
  87806. * \param chain A pointer to an existing chain.
  87807. * \param use_padding
  87808. * Whether or not padding will be allowed to be used
  87809. * during the write. The value of \a use_padding given
  87810. * here must match the value later passed to
  87811. * FLAC__metadata_chain_write_with_callbacks() or
  87812. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87813. * \assert
  87814. * \code chain != NULL \endcode
  87815. * \retval FLAC__bool
  87816. * \c true if writing the current chain would require a tempfile, or
  87817. * \c false if metadata can be written in place.
  87818. */
  87819. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87820. /** Write all metadata out to the FLAC file. This function tries to be as
  87821. * efficient as possible; how the metadata is actually written is shown by
  87822. * the following:
  87823. *
  87824. * If the current chain is the same size as the existing metadata, the new
  87825. * data is written in place.
  87826. *
  87827. * If the current chain is longer than the existing metadata, and
  87828. * \a use_padding is \c true, and the last block is a PADDING block of
  87829. * sufficient length, the function will truncate the final padding block
  87830. * so that the overall size of the metadata is the same as the existing
  87831. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87832. * the above conditions are met, the entire FLAC file must be rewritten.
  87833. * If you want to use padding this way it is a good idea to call
  87834. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87835. * amount of padding to work with, unless you need to preserve ordering
  87836. * of the PADDING blocks for some reason.
  87837. *
  87838. * If the current chain is shorter than the existing metadata, and
  87839. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87840. * is extended to make the overall size the same as the existing data. If
  87841. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87842. * PADDING block is added to the end of the new data to make it the same
  87843. * size as the existing data (if possible, see the note to
  87844. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87845. * and the new data is written in place. If none of the above apply or
  87846. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87847. *
  87848. * If \a preserve_file_stats is \c true, the owner and modification time will
  87849. * be preserved even if the FLAC file is written.
  87850. *
  87851. * For this write function to be used, the chain must have been read with
  87852. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87853. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87854. *
  87855. * \param chain A pointer to an existing chain.
  87856. * \param use_padding See above.
  87857. * \param preserve_file_stats See above.
  87858. * \assert
  87859. * \code chain != NULL \endcode
  87860. * \retval FLAC__bool
  87861. * \c true if the write succeeded, else \c false. On failure,
  87862. * check the status with FLAC__metadata_chain_status().
  87863. */
  87864. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87865. /** Write all metadata out to a FLAC stream via callbacks.
  87866. *
  87867. * (See FLAC__metadata_chain_write() for the details on how padding is
  87868. * used to write metadata in place if possible.)
  87869. *
  87870. * The \a handle must be open for updating and be seekable. The
  87871. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87872. * for Windows).
  87873. *
  87874. * For this write function to be used, the chain must have been read with
  87875. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87876. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87877. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87878. * \c false.
  87879. *
  87880. * \param chain A pointer to an existing chain.
  87881. * \param use_padding See FLAC__metadata_chain_write()
  87882. * \param handle The I/O handle of the FLAC stream to write. The
  87883. * handle will NOT be closed after the metadata is
  87884. * written; that is the duty of the caller.
  87885. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87886. * callbacks are \a write and \a seek.
  87887. * \assert
  87888. * \code chain != NULL \endcode
  87889. * \retval FLAC__bool
  87890. * \c true if the write succeeded, else \c false. On failure,
  87891. * check the status with FLAC__metadata_chain_status().
  87892. */
  87893. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87894. /** Write all metadata out to a FLAC stream via callbacks.
  87895. *
  87896. * (See FLAC__metadata_chain_write() for the details on how padding is
  87897. * used to write metadata in place if possible.)
  87898. *
  87899. * This version of the write-with-callbacks function must be used when
  87900. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87901. * this function, you must supply an I/O handle corresponding to the
  87902. * FLAC file to edit, and a temporary handle to which the new FLAC
  87903. * file will be written. It is the caller's job to move this temporary
  87904. * FLAC file on top of the original FLAC file to complete the metadata
  87905. * edit.
  87906. *
  87907. * The \a handle must be open for reading and be seekable. The
  87908. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87909. * for Windows).
  87910. *
  87911. * The \a temp_handle must be open for writing. The
  87912. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87913. * for Windows). It should be an empty stream, or at least positioned
  87914. * at the start-of-file (in which case it is the caller's duty to
  87915. * truncate it on return).
  87916. *
  87917. * For this write function to be used, the chain must have been read with
  87918. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87919. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87920. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87921. * \c true.
  87922. *
  87923. * \param chain A pointer to an existing chain.
  87924. * \param use_padding See FLAC__metadata_chain_write()
  87925. * \param handle The I/O handle of the original FLAC stream to read.
  87926. * The handle will NOT be closed after the metadata is
  87927. * written; that is the duty of the caller.
  87928. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87929. * The mandatory callbacks are \a read, \a seek, and
  87930. * \a eof.
  87931. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87932. * handle will NOT be closed after the metadata is
  87933. * written; that is the duty of the caller.
  87934. * \param temp_callbacks
  87935. * A set of callbacks to use for I/O on temp_handle.
  87936. * The only mandatory callback is \a write.
  87937. * \assert
  87938. * \code chain != NULL \endcode
  87939. * \retval FLAC__bool
  87940. * \c true if the write succeeded, else \c false. On failure,
  87941. * check the status with FLAC__metadata_chain_status().
  87942. */
  87943. 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);
  87944. /** Merge adjacent PADDING blocks into a single block.
  87945. *
  87946. * \note This function does not write to the FLAC file, it only
  87947. * modifies the chain.
  87948. *
  87949. * \warning Any iterator on the current chain will become invalid after this
  87950. * call. You should delete the iterator and get a new one.
  87951. *
  87952. * \param chain A pointer to an existing chain.
  87953. * \assert
  87954. * \code chain != NULL \endcode
  87955. */
  87956. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87957. /** This function will move all PADDING blocks to the end on the metadata,
  87958. * then merge them into a single block.
  87959. *
  87960. * \note This function does not write to the FLAC file, it only
  87961. * modifies the chain.
  87962. *
  87963. * \warning Any iterator on the current chain will become invalid after this
  87964. * call. You should delete the iterator and get a new one.
  87965. *
  87966. * \param chain A pointer to an existing chain.
  87967. * \assert
  87968. * \code chain != NULL \endcode
  87969. */
  87970. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87971. /*********** FLAC__Metadata_Iterator ***********/
  87972. /** Create a new iterator instance.
  87973. *
  87974. * \retval FLAC__Metadata_Iterator*
  87975. * \c NULL if there was an error allocating memory, else the new instance.
  87976. */
  87977. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87978. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87979. *
  87980. * \param iterator A pointer to an existing iterator.
  87981. * \assert
  87982. * \code iterator != NULL \endcode
  87983. */
  87984. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87985. /** Initialize the iterator to point to the first metadata block in the
  87986. * given chain.
  87987. *
  87988. * \param iterator A pointer to an existing iterator.
  87989. * \param chain A pointer to an existing and initialized (read) chain.
  87990. * \assert
  87991. * \code iterator != NULL \endcode
  87992. * \code chain != NULL \endcode
  87993. */
  87994. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87995. /** Moves the iterator forward one metadata block, returning \c false if
  87996. * already at the end.
  87997. *
  87998. * \param iterator A pointer to an existing initialized iterator.
  87999. * \assert
  88000. * \code iterator != NULL \endcode
  88001. * \a iterator has been successfully initialized with
  88002. * FLAC__metadata_iterator_init()
  88003. * \retval FLAC__bool
  88004. * \c false if already at the last metadata block of the chain, else
  88005. * \c true.
  88006. */
  88007. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88008. /** Moves the iterator backward one metadata block, returning \c false if
  88009. * already at the beginning.
  88010. *
  88011. * \param iterator A pointer to an existing initialized iterator.
  88012. * \assert
  88013. * \code iterator != NULL \endcode
  88014. * \a iterator has been successfully initialized with
  88015. * FLAC__metadata_iterator_init()
  88016. * \retval FLAC__bool
  88017. * \c false if already at the first metadata block of the chain, else
  88018. * \c true.
  88019. */
  88020. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88021. /** Get the type of the metadata block at the current position.
  88022. *
  88023. * \param iterator A pointer to an existing initialized iterator.
  88024. * \assert
  88025. * \code iterator != NULL \endcode
  88026. * \a iterator has been successfully initialized with
  88027. * FLAC__metadata_iterator_init()
  88028. * \retval FLAC__MetadataType
  88029. * The type of the metadata block at the current iterator position.
  88030. */
  88031. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88032. /** Get the metadata block at the current position. You can modify
  88033. * the block in place but must write the chain before the changes
  88034. * are reflected to the FLAC file. You do not need to call
  88035. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88036. * the pointer returned by FLAC__metadata_iterator_get_block()
  88037. * points directly into the chain.
  88038. *
  88039. * \warning
  88040. * Do not call FLAC__metadata_object_delete() on the returned object;
  88041. * to delete a block use FLAC__metadata_iterator_delete_block().
  88042. *
  88043. * \param iterator A pointer to an existing initialized iterator.
  88044. * \assert
  88045. * \code iterator != NULL \endcode
  88046. * \a iterator has been successfully initialized with
  88047. * FLAC__metadata_iterator_init()
  88048. * \retval FLAC__StreamMetadata*
  88049. * The current metadata block.
  88050. */
  88051. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88052. /** Set the metadata block at the current position, replacing the existing
  88053. * block. The new block passed in becomes owned by the chain and it will be
  88054. * deleted when the chain is deleted.
  88055. *
  88056. * \param iterator A pointer to an existing initialized iterator.
  88057. * \param block A pointer to a metadata block.
  88058. * \assert
  88059. * \code iterator != NULL \endcode
  88060. * \a iterator has been successfully initialized with
  88061. * FLAC__metadata_iterator_init()
  88062. * \code block != NULL \endcode
  88063. * \retval FLAC__bool
  88064. * \c false if the conditions in the above description are not met, or
  88065. * a memory allocation error occurs, otherwise \c true.
  88066. */
  88067. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88068. /** Removes the current block from the chain. If \a replace_with_padding is
  88069. * \c true, the block will instead be replaced with a padding block of equal
  88070. * size. You can not delete the STREAMINFO block. The iterator will be
  88071. * left pointing to the block before the one just "deleted", even if
  88072. * \a replace_with_padding is \c true.
  88073. *
  88074. * \param iterator A pointer to an existing initialized iterator.
  88075. * \param replace_with_padding See above.
  88076. * \assert
  88077. * \code iterator != NULL \endcode
  88078. * \a iterator has been successfully initialized with
  88079. * FLAC__metadata_iterator_init()
  88080. * \retval FLAC__bool
  88081. * \c false if the conditions in the above description are not met,
  88082. * otherwise \c true.
  88083. */
  88084. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88085. /** Insert a new block before the current block. You cannot insert a block
  88086. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88087. * as there can be only one, the one that already exists at the head when you
  88088. * read in a chain. The chain takes ownership of the new block and it will be
  88089. * deleted when the chain is deleted. The iterator will be left pointing to
  88090. * the new block.
  88091. *
  88092. * \param iterator A pointer to an existing initialized iterator.
  88093. * \param block A pointer to a metadata block to insert.
  88094. * \assert
  88095. * \code iterator != NULL \endcode
  88096. * \a iterator has been successfully initialized with
  88097. * FLAC__metadata_iterator_init()
  88098. * \retval FLAC__bool
  88099. * \c false if the conditions in the above description are not met, or
  88100. * a memory allocation error occurs, otherwise \c true.
  88101. */
  88102. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88103. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88104. * block as there can be only one, the one that already exists at the head when
  88105. * you read in a chain. The chain takes ownership of the new block and it will
  88106. * be deleted when the chain is deleted. The iterator will be left pointing to
  88107. * the new block.
  88108. *
  88109. * \param iterator A pointer to an existing initialized iterator.
  88110. * \param block A pointer to a metadata block to insert.
  88111. * \assert
  88112. * \code iterator != NULL \endcode
  88113. * \a iterator has been successfully initialized with
  88114. * FLAC__metadata_iterator_init()
  88115. * \retval FLAC__bool
  88116. * \c false if the conditions in the above description are not met, or
  88117. * a memory allocation error occurs, otherwise \c true.
  88118. */
  88119. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88120. /* \} */
  88121. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88122. * \ingroup flac_metadata
  88123. *
  88124. * \brief
  88125. * This module contains methods for manipulating FLAC metadata objects.
  88126. *
  88127. * Since many are variable length we have to be careful about the memory
  88128. * management. We decree that all pointers to data in the object are
  88129. * owned by the object and memory-managed by the object.
  88130. *
  88131. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88132. * functions to create all instances. When using the
  88133. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88134. * \a copy to \c true to have the function make it's own copy of the data, or
  88135. * to \c false to give the object ownership of your data. In the latter case
  88136. * your pointer must be freeable by free() and will be free()d when the object
  88137. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88138. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88139. * the length argument is 0 and the \a copy argument is \c false.
  88140. *
  88141. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88142. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88143. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88144. * case of a memory allocation error.
  88145. *
  88146. * We don't have the convenience of C++ here, so note that the library relies
  88147. * on you to keep the types straight. In other words, if you pass, for
  88148. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88149. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88150. * failure.
  88151. *
  88152. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88153. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88154. * toward the length or stored in the stream, but it can make working with plain
  88155. * comments (those that don't contain embedded-NULs in the value) easier.
  88156. * Entries passed into these functions have trailing NULs added if missing, and
  88157. * returned entries are guaranteed to have a trailing NUL.
  88158. *
  88159. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88160. * comment entry/name/value will first validate that it complies with the Vorbis
  88161. * comment specification and return false if it does not.
  88162. *
  88163. * There is no need to recalculate the length field on metadata blocks you
  88164. * have modified. They will be calculated automatically before they are
  88165. * written back to a file.
  88166. *
  88167. * \{
  88168. */
  88169. /** Create a new metadata object instance of the given type.
  88170. *
  88171. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88172. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88173. * the vendor string set (but zero comments).
  88174. *
  88175. * Do not pass in a value greater than or equal to
  88176. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88177. * doing.
  88178. *
  88179. * \param type Type of object to create
  88180. * \retval FLAC__StreamMetadata*
  88181. * \c NULL if there was an error allocating memory or the type code is
  88182. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88183. */
  88184. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88185. /** Create a copy of an existing metadata object.
  88186. *
  88187. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88188. * object is also copied. The caller takes ownership of the new block and
  88189. * is responsible for freeing it with FLAC__metadata_object_delete().
  88190. *
  88191. * \param object Pointer to object to copy.
  88192. * \assert
  88193. * \code object != NULL \endcode
  88194. * \retval FLAC__StreamMetadata*
  88195. * \c NULL if there was an error allocating memory, else the new instance.
  88196. */
  88197. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88198. /** Free a metadata object. Deletes the object pointed to by \a object.
  88199. *
  88200. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88201. * object is also deleted.
  88202. *
  88203. * \param object A pointer to an existing object.
  88204. * \assert
  88205. * \code object != NULL \endcode
  88206. */
  88207. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88208. /** Compares two metadata objects.
  88209. *
  88210. * The compare is "deep", i.e. dynamically allocated data within the
  88211. * object is also compared.
  88212. *
  88213. * \param block1 A pointer to an existing object.
  88214. * \param block2 A pointer to an existing object.
  88215. * \assert
  88216. * \code block1 != NULL \endcode
  88217. * \code block2 != NULL \endcode
  88218. * \retval FLAC__bool
  88219. * \c true if objects are identical, else \c false.
  88220. */
  88221. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88222. /** Sets the application data of an APPLICATION block.
  88223. *
  88224. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88225. * takes ownership of the pointer. The existing data will be freed if this
  88226. * function is successful, otherwise the original data will remain if \a copy
  88227. * is \c true and malloc() fails.
  88228. *
  88229. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88230. *
  88231. * \param object A pointer to an existing APPLICATION object.
  88232. * \param data A pointer to the data to set.
  88233. * \param length The length of \a data in bytes.
  88234. * \param copy See above.
  88235. * \assert
  88236. * \code object != NULL \endcode
  88237. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88238. * \code (data != NULL && length > 0) ||
  88239. * (data == NULL && length == 0 && copy == false) \endcode
  88240. * \retval FLAC__bool
  88241. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88242. */
  88243. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88244. /** Resize the seekpoint array.
  88245. *
  88246. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88247. * points will be added to the end.
  88248. *
  88249. * \param object A pointer to an existing SEEKTABLE object.
  88250. * \param new_num_points The desired length of the array; may be \c 0.
  88251. * \assert
  88252. * \code object != NULL \endcode
  88253. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88254. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88255. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88256. * \retval FLAC__bool
  88257. * \c false if memory allocation error, else \c true.
  88258. */
  88259. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88260. /** Set a seekpoint in a seektable.
  88261. *
  88262. * \param object A pointer to an existing SEEKTABLE object.
  88263. * \param point_num Index into seekpoint array to set.
  88264. * \param point The point to set.
  88265. * \assert
  88266. * \code object != NULL \endcode
  88267. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88268. * \code object->data.seek_table.num_points > point_num \endcode
  88269. */
  88270. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88271. /** Insert a seekpoint into a seektable.
  88272. *
  88273. * \param object A pointer to an existing SEEKTABLE object.
  88274. * \param point_num Index into seekpoint array to set.
  88275. * \param point The point to set.
  88276. * \assert
  88277. * \code object != NULL \endcode
  88278. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88279. * \code object->data.seek_table.num_points >= point_num \endcode
  88280. * \retval FLAC__bool
  88281. * \c false if memory allocation error, else \c true.
  88282. */
  88283. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88284. /** Delete a seekpoint from a seektable.
  88285. *
  88286. * \param object A pointer to an existing SEEKTABLE object.
  88287. * \param point_num Index into seekpoint array to set.
  88288. * \assert
  88289. * \code object != NULL \endcode
  88290. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88291. * \code object->data.seek_table.num_points > point_num \endcode
  88292. * \retval FLAC__bool
  88293. * \c false if memory allocation error, else \c true.
  88294. */
  88295. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88296. /** Check a seektable to see if it conforms to the FLAC specification.
  88297. * See the format specification for limits on the contents of the
  88298. * seektable.
  88299. *
  88300. * \param object A pointer to an existing SEEKTABLE object.
  88301. * \assert
  88302. * \code object != NULL \endcode
  88303. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88304. * \retval FLAC__bool
  88305. * \c false if seek table is illegal, else \c true.
  88306. */
  88307. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88308. /** Append a number of placeholder points to the end of a seek table.
  88309. *
  88310. * \note
  88311. * As with the other ..._seektable_template_... functions, you should
  88312. * call FLAC__metadata_object_seektable_template_sort() when finished
  88313. * to make the seek table legal.
  88314. *
  88315. * \param object A pointer to an existing SEEKTABLE object.
  88316. * \param num The number of placeholder points to append.
  88317. * \assert
  88318. * \code object != NULL \endcode
  88319. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88320. * \retval FLAC__bool
  88321. * \c false if memory allocation fails, else \c true.
  88322. */
  88323. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88324. /** Append a specific seek point template to the end of a seek table.
  88325. *
  88326. * \note
  88327. * As with the other ..._seektable_template_... functions, you should
  88328. * call FLAC__metadata_object_seektable_template_sort() when finished
  88329. * to make the seek table legal.
  88330. *
  88331. * \param object A pointer to an existing SEEKTABLE object.
  88332. * \param sample_number The sample number of the seek point template.
  88333. * \assert
  88334. * \code object != NULL \endcode
  88335. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88336. * \retval FLAC__bool
  88337. * \c false if memory allocation fails, else \c true.
  88338. */
  88339. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88340. /** Append specific seek point templates to the end of a seek table.
  88341. *
  88342. * \note
  88343. * As with the other ..._seektable_template_... functions, you should
  88344. * call FLAC__metadata_object_seektable_template_sort() when finished
  88345. * to make the seek table legal.
  88346. *
  88347. * \param object A pointer to an existing SEEKTABLE object.
  88348. * \param sample_numbers An array of sample numbers for the seek points.
  88349. * \param num The number of seek point templates to append.
  88350. * \assert
  88351. * \code object != NULL \endcode
  88352. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88353. * \retval FLAC__bool
  88354. * \c false if memory allocation fails, else \c true.
  88355. */
  88356. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88357. /** Append a set of evenly-spaced seek point templates to the end of a
  88358. * seek table.
  88359. *
  88360. * \note
  88361. * As with the other ..._seektable_template_... functions, you should
  88362. * call FLAC__metadata_object_seektable_template_sort() when finished
  88363. * to make the seek table legal.
  88364. *
  88365. * \param object A pointer to an existing SEEKTABLE object.
  88366. * \param num The number of placeholder points to append.
  88367. * \param total_samples The total number of samples to be encoded;
  88368. * the seekpoints will be spaced approximately
  88369. * \a total_samples / \a num samples apart.
  88370. * \assert
  88371. * \code object != NULL \endcode
  88372. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88373. * \code total_samples > 0 \endcode
  88374. * \retval FLAC__bool
  88375. * \c false if memory allocation fails, else \c true.
  88376. */
  88377. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88378. /** Append a set of evenly-spaced seek point templates to the end of a
  88379. * seek table.
  88380. *
  88381. * \note
  88382. * As with the other ..._seektable_template_... functions, you should
  88383. * call FLAC__metadata_object_seektable_template_sort() when finished
  88384. * to make the seek table legal.
  88385. *
  88386. * \param object A pointer to an existing SEEKTABLE object.
  88387. * \param samples The number of samples apart to space the placeholder
  88388. * points. The first point will be at sample \c 0, the
  88389. * second at sample \a samples, then 2*\a samples, and
  88390. * so on. As long as \a samples and \a total_samples
  88391. * are greater than \c 0, there will always be at least
  88392. * one seekpoint at sample \c 0.
  88393. * \param total_samples The total number of samples to be encoded;
  88394. * the seekpoints will be spaced
  88395. * \a samples samples apart.
  88396. * \assert
  88397. * \code object != NULL \endcode
  88398. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88399. * \code samples > 0 \endcode
  88400. * \code total_samples > 0 \endcode
  88401. * \retval FLAC__bool
  88402. * \c false if memory allocation fails, else \c true.
  88403. */
  88404. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88405. /** Sort a seek table's seek points according to the format specification,
  88406. * removing duplicates.
  88407. *
  88408. * \param object A pointer to a seek table to be sorted.
  88409. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88410. * If \c true, duplicates are deleted and the seek table is
  88411. * shrunk appropriately; the number of placeholder points
  88412. * present in the seek table will be the same after the call
  88413. * as before.
  88414. * \assert
  88415. * \code object != NULL \endcode
  88416. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88417. * \retval FLAC__bool
  88418. * \c false if realloc() fails, else \c true.
  88419. */
  88420. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88421. /** Sets the vendor string in a VORBIS_COMMENT block.
  88422. *
  88423. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88424. * one already.
  88425. *
  88426. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88427. * takes ownership of the \c entry.entry pointer.
  88428. *
  88429. * \note If this function returns \c false, the caller still owns the
  88430. * pointer.
  88431. *
  88432. * \param object A pointer to an existing VORBIS_COMMENT object.
  88433. * \param entry The entry to set the vendor string to.
  88434. * \param copy See above.
  88435. * \assert
  88436. * \code object != NULL \endcode
  88437. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88438. * \code (entry.entry != NULL && entry.length > 0) ||
  88439. * (entry.entry == NULL && entry.length == 0) \endcode
  88440. * \retval FLAC__bool
  88441. * \c false if memory allocation fails or \a entry does not comply with the
  88442. * Vorbis comment specification, else \c true.
  88443. */
  88444. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88445. /** Resize the comment array.
  88446. *
  88447. * If the size shrinks, elements will truncated; if it grows, new empty
  88448. * fields will be added to the end.
  88449. *
  88450. * \param object A pointer to an existing VORBIS_COMMENT object.
  88451. * \param new_num_comments The desired length of the array; may be \c 0.
  88452. * \assert
  88453. * \code object != NULL \endcode
  88454. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88455. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88456. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88457. * \retval FLAC__bool
  88458. * \c false if memory allocation fails, else \c true.
  88459. */
  88460. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88461. /** Sets a comment in a VORBIS_COMMENT block.
  88462. *
  88463. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88464. * one already.
  88465. *
  88466. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88467. * takes ownership of the \c entry.entry pointer.
  88468. *
  88469. * \note If this function returns \c false, the caller still owns the
  88470. * pointer.
  88471. *
  88472. * \param object A pointer to an existing VORBIS_COMMENT object.
  88473. * \param comment_num Index into comment array to set.
  88474. * \param entry The entry to set the comment to.
  88475. * \param copy See above.
  88476. * \assert
  88477. * \code object != NULL \endcode
  88478. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88479. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88480. * \code (entry.entry != NULL && entry.length > 0) ||
  88481. * (entry.entry == NULL && entry.length == 0) \endcode
  88482. * \retval FLAC__bool
  88483. * \c false if memory allocation fails or \a entry does not comply with the
  88484. * Vorbis comment specification, else \c true.
  88485. */
  88486. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88487. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88488. *
  88489. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88490. * one already.
  88491. *
  88492. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88493. * takes ownership of the \c entry.entry pointer.
  88494. *
  88495. * \note If this function returns \c false, the caller still owns the
  88496. * pointer.
  88497. *
  88498. * \param object A pointer to an existing VORBIS_COMMENT object.
  88499. * \param comment_num The index at which to insert the comment. The comments
  88500. * at and after \a comment_num move right one position.
  88501. * To append a comment to the end, set \a comment_num to
  88502. * \c object->data.vorbis_comment.num_comments .
  88503. * \param entry The comment to insert.
  88504. * \param copy See above.
  88505. * \assert
  88506. * \code object != NULL \endcode
  88507. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88508. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88509. * \code (entry.entry != NULL && entry.length > 0) ||
  88510. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88511. * \retval FLAC__bool
  88512. * \c false if memory allocation fails or \a entry does not comply with the
  88513. * Vorbis comment specification, else \c true.
  88514. */
  88515. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88516. /** Appends a comment to a VORBIS_COMMENT block.
  88517. *
  88518. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88519. * one already.
  88520. *
  88521. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88522. * takes ownership of the \c entry.entry pointer.
  88523. *
  88524. * \note If this function returns \c false, the caller still owns the
  88525. * pointer.
  88526. *
  88527. * \param object A pointer to an existing VORBIS_COMMENT object.
  88528. * \param entry The comment to insert.
  88529. * \param copy See above.
  88530. * \assert
  88531. * \code object != NULL \endcode
  88532. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88533. * \code (entry.entry != NULL && entry.length > 0) ||
  88534. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88535. * \retval FLAC__bool
  88536. * \c false if memory allocation fails or \a entry does not comply with the
  88537. * Vorbis comment specification, else \c true.
  88538. */
  88539. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88540. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88541. *
  88542. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88543. * one already.
  88544. *
  88545. * Depending on the the value of \a all, either all or just the first comment
  88546. * whose field name(s) match the given entry's name will be replaced by the
  88547. * given entry. If no comments match, \a entry will simply be appended.
  88548. *
  88549. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88550. * takes ownership of the \c entry.entry pointer.
  88551. *
  88552. * \note If this function returns \c false, the caller still owns the
  88553. * pointer.
  88554. *
  88555. * \param object A pointer to an existing VORBIS_COMMENT object.
  88556. * \param entry The comment to insert.
  88557. * \param all If \c true, all comments whose field name matches
  88558. * \a entry's field name will be removed, and \a entry will
  88559. * be inserted at the position of the first matching
  88560. * comment. If \c false, only the first comment whose
  88561. * field name matches \a entry's field name will be
  88562. * replaced with \a entry.
  88563. * \param copy See above.
  88564. * \assert
  88565. * \code object != NULL \endcode
  88566. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88567. * \code (entry.entry != NULL && entry.length > 0) ||
  88568. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88569. * \retval FLAC__bool
  88570. * \c false if memory allocation fails or \a entry does not comply with the
  88571. * Vorbis comment specification, else \c true.
  88572. */
  88573. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88574. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88575. *
  88576. * \param object A pointer to an existing VORBIS_COMMENT object.
  88577. * \param comment_num The index of the comment to delete.
  88578. * \assert
  88579. * \code object != NULL \endcode
  88580. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88581. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88582. * \retval FLAC__bool
  88583. * \c false if realloc() fails, else \c true.
  88584. */
  88585. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88586. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88587. *
  88588. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88589. * memory and shall be owned by the caller. For convenience the entry will
  88590. * have a terminating NUL.
  88591. *
  88592. * \param entry A pointer to a Vorbis comment entry. The entry's
  88593. * \c entry pointer should not point to allocated
  88594. * memory as it will be overwritten.
  88595. * \param field_name The field name in ASCII, \c NUL terminated.
  88596. * \param field_value The field value in UTF-8, \c NUL terminated.
  88597. * \assert
  88598. * \code entry != NULL \endcode
  88599. * \code field_name != NULL \endcode
  88600. * \code field_value != NULL \endcode
  88601. * \retval FLAC__bool
  88602. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88603. * not comply with the Vorbis comment specification, else \c true.
  88604. */
  88605. 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);
  88606. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88607. *
  88608. * The returned pointers to name and value will be allocated by malloc()
  88609. * and shall be owned by the caller.
  88610. *
  88611. * \param entry An existing Vorbis comment entry.
  88612. * \param field_name The address of where the returned pointer to the
  88613. * field name will be stored.
  88614. * \param field_value The address of where the returned pointer to the
  88615. * field value will be stored.
  88616. * \assert
  88617. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88618. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88619. * \code field_name != NULL \endcode
  88620. * \code field_value != NULL \endcode
  88621. * \retval FLAC__bool
  88622. * \c false if memory allocation fails or \a entry does not comply with the
  88623. * Vorbis comment specification, else \c true.
  88624. */
  88625. 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);
  88626. /** Check if the given Vorbis comment entry's field name matches the given
  88627. * field name.
  88628. *
  88629. * \param entry An existing Vorbis comment entry.
  88630. * \param field_name The field name to check.
  88631. * \param field_name_length The length of \a field_name, not including the
  88632. * terminating \c NUL.
  88633. * \assert
  88634. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88635. * \retval FLAC__bool
  88636. * \c true if the field names match, else \c false
  88637. */
  88638. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88639. /** Find a Vorbis comment with the given field name.
  88640. *
  88641. * The search begins at entry number \a offset; use an offset of 0 to
  88642. * search from the beginning of the comment array.
  88643. *
  88644. * \param object A pointer to an existing VORBIS_COMMENT object.
  88645. * \param offset The offset into the comment array from where to start
  88646. * the search.
  88647. * \param field_name The field name of the comment to find.
  88648. * \assert
  88649. * \code object != NULL \endcode
  88650. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88651. * \code field_name != NULL \endcode
  88652. * \retval int
  88653. * The offset in the comment array of the first comment whose field
  88654. * name matches \a field_name, or \c -1 if no match was found.
  88655. */
  88656. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88657. /** Remove first Vorbis comment matching the given field name.
  88658. *
  88659. * \param object A pointer to an existing VORBIS_COMMENT object.
  88660. * \param field_name The field name of comment to delete.
  88661. * \assert
  88662. * \code object != NULL \endcode
  88663. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88664. * \retval int
  88665. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88666. * \c 1 for one matching entry deleted.
  88667. */
  88668. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88669. /** Remove all Vorbis comments matching the given field name.
  88670. *
  88671. * \param object A pointer to an existing VORBIS_COMMENT object.
  88672. * \param field_name The field name of comments to delete.
  88673. * \assert
  88674. * \code object != NULL \endcode
  88675. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88676. * \retval int
  88677. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88678. * else the number of matching entries deleted.
  88679. */
  88680. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88681. /** Create a new CUESHEET track instance.
  88682. *
  88683. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88684. *
  88685. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88686. * \c NULL if there was an error allocating memory, else the new instance.
  88687. */
  88688. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88689. /** Create a copy of an existing CUESHEET track object.
  88690. *
  88691. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88692. * object is also copied. The caller takes ownership of the new object and
  88693. * is responsible for freeing it with
  88694. * FLAC__metadata_object_cuesheet_track_delete().
  88695. *
  88696. * \param object Pointer to object to copy.
  88697. * \assert
  88698. * \code object != NULL \endcode
  88699. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88700. * \c NULL if there was an error allocating memory, else the new instance.
  88701. */
  88702. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88703. /** Delete a CUESHEET track object
  88704. *
  88705. * \param object A pointer to an existing CUESHEET track object.
  88706. * \assert
  88707. * \code object != NULL \endcode
  88708. */
  88709. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88710. /** Resize a track's index point array.
  88711. *
  88712. * If the size shrinks, elements will truncated; if it grows, new blank
  88713. * indices will be added to the end.
  88714. *
  88715. * \param object A pointer to an existing CUESHEET object.
  88716. * \param track_num The index of the track to modify. NOTE: this is not
  88717. * necessarily the same as the track's \a number field.
  88718. * \param new_num_indices The desired length of the array; may be \c 0.
  88719. * \assert
  88720. * \code object != NULL \endcode
  88721. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88722. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88723. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88724. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88725. * \retval FLAC__bool
  88726. * \c false if memory allocation error, else \c true.
  88727. */
  88728. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88729. /** Insert an index point in a CUESHEET track at the given index.
  88730. *
  88731. * \param object A pointer to an existing CUESHEET object.
  88732. * \param track_num The index of the track to modify. NOTE: this is not
  88733. * necessarily the same as the track's \a number field.
  88734. * \param index_num The index into the track's index array at which to
  88735. * insert the index point. NOTE: this is not necessarily
  88736. * the same as the index point's \a number field. The
  88737. * indices at and after \a index_num move right one
  88738. * position. To append an index point to the end, set
  88739. * \a index_num to
  88740. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88741. * \param index The index point to insert.
  88742. * \assert
  88743. * \code object != NULL \endcode
  88744. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88745. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88746. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88747. * \retval FLAC__bool
  88748. * \c false if realloc() fails, else \c true.
  88749. */
  88750. 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);
  88751. /** Insert a blank index point in a CUESHEET track at the given index.
  88752. *
  88753. * A blank index point is one in which all field values are zero.
  88754. *
  88755. * \param object A pointer to an existing CUESHEET object.
  88756. * \param track_num The index of the track to modify. NOTE: this is not
  88757. * necessarily the same as the track's \a number field.
  88758. * \param index_num The index into the track's index array at which to
  88759. * insert the index point. NOTE: this is not necessarily
  88760. * the same as the index point's \a number field. The
  88761. * indices at and after \a index_num move right one
  88762. * position. To append an index point to the end, set
  88763. * \a index_num to
  88764. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88765. * \assert
  88766. * \code object != NULL \endcode
  88767. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88768. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88769. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88770. * \retval FLAC__bool
  88771. * \c false if realloc() fails, else \c true.
  88772. */
  88773. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88774. /** Delete an index point in a CUESHEET track at the given index.
  88775. *
  88776. * \param object A pointer to an existing CUESHEET object.
  88777. * \param track_num The index into the track array of the track to
  88778. * modify. NOTE: this is not necessarily the same
  88779. * as the track's \a number field.
  88780. * \param index_num The index into the track's index array of the index
  88781. * to delete. NOTE: this is not necessarily the same
  88782. * as the index's \a number field.
  88783. * \assert
  88784. * \code object != NULL \endcode
  88785. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88786. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88787. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88788. * \retval FLAC__bool
  88789. * \c false if realloc() fails, else \c true.
  88790. */
  88791. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88792. /** Resize the track array.
  88793. *
  88794. * If the size shrinks, elements will truncated; if it grows, new blank
  88795. * tracks will be added to the end.
  88796. *
  88797. * \param object A pointer to an existing CUESHEET object.
  88798. * \param new_num_tracks The desired length of the array; may be \c 0.
  88799. * \assert
  88800. * \code object != NULL \endcode
  88801. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88802. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88803. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88804. * \retval FLAC__bool
  88805. * \c false if memory allocation error, else \c true.
  88806. */
  88807. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88808. /** Sets a track in a CUESHEET block.
  88809. *
  88810. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88811. * takes ownership of the \a track pointer.
  88812. *
  88813. * \param object A pointer to an existing CUESHEET object.
  88814. * \param track_num Index into track array to set. NOTE: this is not
  88815. * necessarily the same as the track's \a number field.
  88816. * \param track The track to set the track to. You may safely pass in
  88817. * a const pointer if \a copy is \c true.
  88818. * \param copy See above.
  88819. * \assert
  88820. * \code object != NULL \endcode
  88821. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88822. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88823. * \code (track->indices != NULL && track->num_indices > 0) ||
  88824. * (track->indices == NULL && track->num_indices == 0)
  88825. * \retval FLAC__bool
  88826. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88827. */
  88828. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88829. /** Insert a track in a CUESHEET block at the given index.
  88830. *
  88831. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88832. * takes ownership of the \a track pointer.
  88833. *
  88834. * \param object A pointer to an existing CUESHEET object.
  88835. * \param track_num The index at which to insert the track. NOTE: this
  88836. * is not necessarily the same as the track's \a number
  88837. * field. The tracks at and after \a track_num move right
  88838. * one position. To append a track to the end, set
  88839. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88840. * \param track The track to insert. You may safely pass in a const
  88841. * pointer if \a copy is \c true.
  88842. * \param copy See above.
  88843. * \assert
  88844. * \code object != NULL \endcode
  88845. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88846. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88847. * \retval FLAC__bool
  88848. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88849. */
  88850. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88851. /** Insert a blank track in a CUESHEET block at the given index.
  88852. *
  88853. * A blank track is one in which all field values are zero.
  88854. *
  88855. * \param object A pointer to an existing CUESHEET object.
  88856. * \param track_num The index at which to insert the track. NOTE: this
  88857. * is not necessarily the same as the track's \a number
  88858. * field. The tracks at and after \a track_num move right
  88859. * one position. To append a track to the end, set
  88860. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88861. * \assert
  88862. * \code object != NULL \endcode
  88863. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88864. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88865. * \retval FLAC__bool
  88866. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88867. */
  88868. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88869. /** Delete a track in a CUESHEET block at the given index.
  88870. *
  88871. * \param object A pointer to an existing CUESHEET object.
  88872. * \param track_num The index into the track array of the track to
  88873. * delete. NOTE: this is not necessarily the same
  88874. * as the track's \a number field.
  88875. * \assert
  88876. * \code object != NULL \endcode
  88877. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88878. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88879. * \retval FLAC__bool
  88880. * \c false if realloc() fails, else \c true.
  88881. */
  88882. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88883. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88884. * See the format specification for limits on the contents of the
  88885. * cue sheet.
  88886. *
  88887. * \param object A pointer to an existing CUESHEET object.
  88888. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88889. * stringent requirements for a CD-DA (audio) disc.
  88890. * \param violation Address of a pointer to a string. If there is a
  88891. * violation, a pointer to a string explanation of the
  88892. * violation will be returned here. \a violation may be
  88893. * \c NULL if you don't need the returned string. Do not
  88894. * free the returned string; it will always point to static
  88895. * data.
  88896. * \assert
  88897. * \code object != NULL \endcode
  88898. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88899. * \retval FLAC__bool
  88900. * \c false if cue sheet is illegal, else \c true.
  88901. */
  88902. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88903. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88904. * assumes the cue sheet corresponds to a CD; the result is undefined
  88905. * if the cuesheet's is_cd bit is not set.
  88906. *
  88907. * \param object A pointer to an existing CUESHEET object.
  88908. * \assert
  88909. * \code object != NULL \endcode
  88910. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88911. * \retval FLAC__uint32
  88912. * The unsigned integer representation of the CDDB/freedb ID
  88913. */
  88914. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88915. /** Sets the MIME type of a PICTURE block.
  88916. *
  88917. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88918. * takes ownership of the pointer. The existing string will be freed if this
  88919. * function is successful, otherwise the original string will remain if \a copy
  88920. * is \c true and malloc() fails.
  88921. *
  88922. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88923. *
  88924. * \param object A pointer to an existing PICTURE object.
  88925. * \param mime_type A pointer to the MIME type string. The string must be
  88926. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88927. * is done.
  88928. * \param copy See above.
  88929. * \assert
  88930. * \code object != NULL \endcode
  88931. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88932. * \code (mime_type != NULL) \endcode
  88933. * \retval FLAC__bool
  88934. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88935. */
  88936. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88937. /** Sets the description of a PICTURE block.
  88938. *
  88939. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88940. * takes ownership of the pointer. The existing string will be freed if this
  88941. * function is successful, otherwise the original string will remain if \a copy
  88942. * is \c true and malloc() fails.
  88943. *
  88944. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88945. *
  88946. * \param object A pointer to an existing PICTURE object.
  88947. * \param description A pointer to the description string. The string must be
  88948. * valid UTF-8, NUL-terminated. No validation is done.
  88949. * \param copy See above.
  88950. * \assert
  88951. * \code object != NULL \endcode
  88952. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88953. * \code (description != NULL) \endcode
  88954. * \retval FLAC__bool
  88955. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88956. */
  88957. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88958. /** Sets the picture data of a PICTURE block.
  88959. *
  88960. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88961. * takes ownership of the pointer. Also sets the \a data_length field of the
  88962. * metadata object to what is passed in as the \a length parameter. The
  88963. * existing data will be freed if this function is successful, otherwise the
  88964. * original data and data_length will remain if \a copy is \c true and
  88965. * malloc() fails.
  88966. *
  88967. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88968. *
  88969. * \param object A pointer to an existing PICTURE object.
  88970. * \param data A pointer to the data to set.
  88971. * \param length The length of \a data in bytes.
  88972. * \param copy See above.
  88973. * \assert
  88974. * \code object != NULL \endcode
  88975. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88976. * \code (data != NULL && length > 0) ||
  88977. * (data == NULL && length == 0 && copy == false) \endcode
  88978. * \retval FLAC__bool
  88979. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88980. */
  88981. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88982. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88983. * See the format specification for limits on the contents of the
  88984. * PICTURE block.
  88985. *
  88986. * \param object A pointer to existing PICTURE block to be checked.
  88987. * \param violation Address of a pointer to a string. If there is a
  88988. * violation, a pointer to a string explanation of the
  88989. * violation will be returned here. \a violation may be
  88990. * \c NULL if you don't need the returned string. Do not
  88991. * free the returned string; it will always point to static
  88992. * data.
  88993. * \assert
  88994. * \code object != NULL \endcode
  88995. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88996. * \retval FLAC__bool
  88997. * \c false if PICTURE block is illegal, else \c true.
  88998. */
  88999. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89000. /* \} */
  89001. #ifdef __cplusplus
  89002. }
  89003. #endif
  89004. #endif
  89005. /*** End of inlined file: metadata.h ***/
  89006. /*** Start of inlined file: stream_decoder.h ***/
  89007. #ifndef FLAC__STREAM_DECODER_H
  89008. #define FLAC__STREAM_DECODER_H
  89009. #include <stdio.h> /* for FILE */
  89010. #ifdef __cplusplus
  89011. extern "C" {
  89012. #endif
  89013. /** \file include/FLAC/stream_decoder.h
  89014. *
  89015. * \brief
  89016. * This module contains the functions which implement the stream
  89017. * decoder.
  89018. *
  89019. * See the detailed documentation in the
  89020. * \link flac_stream_decoder stream decoder \endlink module.
  89021. */
  89022. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89023. * \ingroup flac
  89024. *
  89025. * \brief
  89026. * This module describes the decoder layers provided by libFLAC.
  89027. *
  89028. * The stream decoder can be used to decode complete streams either from
  89029. * the client via callbacks, or directly from a file, depending on how
  89030. * it is initialized. When decoding via callbacks, the client provides
  89031. * callbacks for reading FLAC data and writing decoded samples, and
  89032. * handling metadata and errors. If the client also supplies seek-related
  89033. * callback, the decoder function for sample-accurate seeking within the
  89034. * FLAC input is also available. When decoding from a file, the client
  89035. * needs only supply a filename or open \c FILE* and write/metadata/error
  89036. * callbacks; the rest of the callbacks are supplied internally. For more
  89037. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89038. */
  89039. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89040. * \ingroup flac_decoder
  89041. *
  89042. * \brief
  89043. * This module contains the functions which implement the stream
  89044. * decoder.
  89045. *
  89046. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89047. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89048. *
  89049. * The basic usage of this decoder is as follows:
  89050. * - The program creates an instance of a decoder using
  89051. * FLAC__stream_decoder_new().
  89052. * - The program overrides the default settings using
  89053. * FLAC__stream_decoder_set_*() functions.
  89054. * - The program initializes the instance to validate the settings and
  89055. * prepare for decoding using
  89056. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89057. * or FLAC__stream_decoder_init_file() for native FLAC,
  89058. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89059. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89060. * - The program calls the FLAC__stream_decoder_process_*() functions
  89061. * to decode data, which subsequently calls the callbacks.
  89062. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89063. * which flushes the input and output and resets the decoder to the
  89064. * uninitialized state.
  89065. * - The instance may be used again or deleted with
  89066. * FLAC__stream_decoder_delete().
  89067. *
  89068. * In more detail, the program will create a new instance by calling
  89069. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89070. * functions to override the default decoder options, and call
  89071. * one of the FLAC__stream_decoder_init_*() functions.
  89072. *
  89073. * There are three initialization functions for native FLAC, one for
  89074. * setting up the decoder to decode FLAC data from the client via
  89075. * callbacks, and two for decoding directly from a FLAC file.
  89076. *
  89077. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89078. * You must also supply several callbacks for handling I/O. Some (like
  89079. * seeking) are optional, depending on the capabilities of the input.
  89080. *
  89081. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89082. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89083. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89084. * the other callbacks internally.
  89085. *
  89086. * There are three similarly-named init functions for decoding from Ogg
  89087. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89088. * library has been built with Ogg support.
  89089. *
  89090. * Once the decoder is initialized, your program will call one of several
  89091. * functions to start the decoding process:
  89092. *
  89093. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89094. * most one metadata block or audio frame and return, calling either the
  89095. * metadata callback or write callback, respectively, once. If the decoder
  89096. * loses sync it will return with only the error callback being called.
  89097. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89098. * to process the stream from the current location and stop upon reaching
  89099. * the first audio frame. The client will get one metadata, write, or error
  89100. * callback per metadata block, audio frame, or sync error, respectively.
  89101. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89102. * to process the stream from the current location until the read callback
  89103. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89104. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89105. * write, or error callback per metadata block, audio frame, or sync error,
  89106. * respectively.
  89107. *
  89108. * When the decoder has finished decoding (normally or through an abort),
  89109. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89110. * ensures the decoder is in the correct state and frees memory. Then the
  89111. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89112. * again to decode another stream.
  89113. *
  89114. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89115. * At any point after the stream decoder has been initialized, the client can
  89116. * call this function to seek to an exact sample within the stream.
  89117. * Subsequently, the first time the write callback is called it will be
  89118. * passed a (possibly partial) block starting at that sample.
  89119. *
  89120. * If the client cannot seek via the callback interface provided, but still
  89121. * has another way of seeking, it can flush the decoder using
  89122. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89123. * through the read callback.
  89124. *
  89125. * The stream decoder also provides MD5 signature checking. If this is
  89126. * turned on before initialization, FLAC__stream_decoder_finish() will
  89127. * report when the decoded MD5 signature does not match the one stored
  89128. * in the STREAMINFO block. MD5 checking is automatically turned off
  89129. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89130. * in the STREAMINFO block or when a seek is attempted.
  89131. *
  89132. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89133. * attention. By default, the decoder only calls the metadata_callback for
  89134. * the STREAMINFO block. These functions allow you to tell the decoder
  89135. * explicitly which blocks to parse and return via the metadata_callback
  89136. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89137. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89138. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89139. * which blocks to return. Remember that metadata blocks can potentially
  89140. * be big (for example, cover art) so filtering out the ones you don't
  89141. * use can reduce the memory requirements of the decoder. Also note the
  89142. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89143. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89144. * filtering APPLICATION blocks based on the application ID.
  89145. *
  89146. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89147. * they still can legally be filtered from the metadata_callback.
  89148. *
  89149. * \note
  89150. * The "set" functions may only be called when the decoder is in the
  89151. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89152. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89153. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89154. * return \c true, otherwise \c false.
  89155. *
  89156. * \note
  89157. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89158. * defaults, including the callbacks.
  89159. *
  89160. * \{
  89161. */
  89162. /** State values for a FLAC__StreamDecoder
  89163. *
  89164. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89165. */
  89166. typedef enum {
  89167. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89168. /**< The decoder is ready to search for metadata. */
  89169. FLAC__STREAM_DECODER_READ_METADATA,
  89170. /**< The decoder is ready to or is in the process of reading metadata. */
  89171. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89172. /**< The decoder is ready to or is in the process of searching for the
  89173. * frame sync code.
  89174. */
  89175. FLAC__STREAM_DECODER_READ_FRAME,
  89176. /**< The decoder is ready to or is in the process of reading a frame. */
  89177. FLAC__STREAM_DECODER_END_OF_STREAM,
  89178. /**< The decoder has reached the end of the stream. */
  89179. FLAC__STREAM_DECODER_OGG_ERROR,
  89180. /**< An error occurred in the underlying Ogg layer. */
  89181. FLAC__STREAM_DECODER_SEEK_ERROR,
  89182. /**< An error occurred while seeking. The decoder must be flushed
  89183. * with FLAC__stream_decoder_flush() or reset with
  89184. * FLAC__stream_decoder_reset() before decoding can continue.
  89185. */
  89186. FLAC__STREAM_DECODER_ABORTED,
  89187. /**< The decoder was aborted by the read callback. */
  89188. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89189. /**< An error occurred allocating memory. The decoder is in an invalid
  89190. * state and can no longer be used.
  89191. */
  89192. FLAC__STREAM_DECODER_UNINITIALIZED
  89193. /**< The decoder is in the uninitialized state; one of the
  89194. * FLAC__stream_decoder_init_*() functions must be called before samples
  89195. * can be processed.
  89196. */
  89197. } FLAC__StreamDecoderState;
  89198. /** Maps a FLAC__StreamDecoderState to a C string.
  89199. *
  89200. * Using a FLAC__StreamDecoderState as the index to this array
  89201. * will give the string equivalent. The contents should not be modified.
  89202. */
  89203. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89204. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89205. */
  89206. typedef enum {
  89207. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89208. /**< Initialization was successful. */
  89209. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89210. /**< The library was not compiled with support for the given container
  89211. * format.
  89212. */
  89213. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89214. /**< A required callback was not supplied. */
  89215. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89216. /**< An error occurred allocating memory. */
  89217. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89218. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89219. * FLAC__stream_decoder_init_ogg_file(). */
  89220. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89221. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89222. * already initialized, usually because
  89223. * FLAC__stream_decoder_finish() was not called.
  89224. */
  89225. } FLAC__StreamDecoderInitStatus;
  89226. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89227. *
  89228. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89229. * will give the string equivalent. The contents should not be modified.
  89230. */
  89231. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89232. /** Return values for the FLAC__StreamDecoder read callback.
  89233. */
  89234. typedef enum {
  89235. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89236. /**< The read was OK and decoding can continue. */
  89237. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89238. /**< The read was attempted while at the end of the stream. Note that
  89239. * the client must only return this value when the read callback was
  89240. * called when already at the end of the stream. Otherwise, if the read
  89241. * itself moves to the end of the stream, the client should still return
  89242. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89243. * the next read callback it should return
  89244. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89245. * of \c 0.
  89246. */
  89247. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89248. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89249. } FLAC__StreamDecoderReadStatus;
  89250. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89251. *
  89252. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89253. * will give the string equivalent. The contents should not be modified.
  89254. */
  89255. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89256. /** Return values for the FLAC__StreamDecoder seek callback.
  89257. */
  89258. typedef enum {
  89259. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89260. /**< The seek was OK and decoding can continue. */
  89261. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89262. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89263. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89264. /**< Client does not support seeking. */
  89265. } FLAC__StreamDecoderSeekStatus;
  89266. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89267. *
  89268. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89269. * will give the string equivalent. The contents should not be modified.
  89270. */
  89271. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89272. /** Return values for the FLAC__StreamDecoder tell callback.
  89273. */
  89274. typedef enum {
  89275. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89276. /**< The tell was OK and decoding can continue. */
  89277. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89278. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89279. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89280. /**< Client does not support telling the position. */
  89281. } FLAC__StreamDecoderTellStatus;
  89282. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89283. *
  89284. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89285. * will give the string equivalent. The contents should not be modified.
  89286. */
  89287. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89288. /** Return values for the FLAC__StreamDecoder length callback.
  89289. */
  89290. typedef enum {
  89291. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89292. /**< The length call was OK and decoding can continue. */
  89293. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89294. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89295. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89296. /**< Client does not support reporting the length. */
  89297. } FLAC__StreamDecoderLengthStatus;
  89298. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89299. *
  89300. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89301. * will give the string equivalent. The contents should not be modified.
  89302. */
  89303. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89304. /** Return values for the FLAC__StreamDecoder write callback.
  89305. */
  89306. typedef enum {
  89307. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89308. /**< The write was OK and decoding can continue. */
  89309. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89310. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89311. } FLAC__StreamDecoderWriteStatus;
  89312. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89313. *
  89314. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89315. * will give the string equivalent. The contents should not be modified.
  89316. */
  89317. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89318. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89319. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89320. * all. The rest could be caused by bad sync (false synchronization on
  89321. * data that is not the start of a frame) or corrupted data. The error
  89322. * itself is the decoder's best guess at what happened assuming a correct
  89323. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89324. * could be caused by a correct sync on the start of a frame, but some
  89325. * data in the frame header was corrupted. Or it could be the result of
  89326. * syncing on a point the stream that looked like the starting of a frame
  89327. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89328. * could be because the decoder encountered a valid frame made by a future
  89329. * version of the encoder which it cannot parse, or because of a false
  89330. * sync making it appear as though an encountered frame was generated by
  89331. * a future encoder.
  89332. */
  89333. typedef enum {
  89334. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89335. /**< An error in the stream caused the decoder to lose synchronization. */
  89336. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89337. /**< The decoder encountered a corrupted frame header. */
  89338. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89339. /**< The frame's data did not match the CRC in the footer. */
  89340. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89341. /**< The decoder encountered reserved fields in use in the stream. */
  89342. } FLAC__StreamDecoderErrorStatus;
  89343. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89344. *
  89345. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89346. * will give the string equivalent. The contents should not be modified.
  89347. */
  89348. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89349. /***********************************************************************
  89350. *
  89351. * class FLAC__StreamDecoder
  89352. *
  89353. ***********************************************************************/
  89354. struct FLAC__StreamDecoderProtected;
  89355. struct FLAC__StreamDecoderPrivate;
  89356. /** The opaque structure definition for the stream decoder type.
  89357. * See the \link flac_stream_decoder stream decoder module \endlink
  89358. * for a detailed description.
  89359. */
  89360. typedef struct {
  89361. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89362. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89363. } FLAC__StreamDecoder;
  89364. /** Signature for the read callback.
  89365. *
  89366. * A function pointer matching this signature must be passed to
  89367. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89368. * called when the decoder needs more input data. The address of the
  89369. * buffer to be filled is supplied, along with the number of bytes the
  89370. * buffer can hold. The callback may choose to supply less data and
  89371. * modify the byte count but must be careful not to overflow the buffer.
  89372. * The callback then returns a status code chosen from
  89373. * FLAC__StreamDecoderReadStatus.
  89374. *
  89375. * Here is an example of a read callback for stdio streams:
  89376. * \code
  89377. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89378. * {
  89379. * FILE *file = ((MyClientData*)client_data)->file;
  89380. * if(*bytes > 0) {
  89381. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89382. * if(ferror(file))
  89383. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89384. * else if(*bytes == 0)
  89385. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89386. * else
  89387. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89388. * }
  89389. * else
  89390. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89391. * }
  89392. * \endcode
  89393. *
  89394. * \note In general, FLAC__StreamDecoder functions which change the
  89395. * state should not be called on the \a decoder while in the callback.
  89396. *
  89397. * \param decoder The decoder instance calling the callback.
  89398. * \param buffer A pointer to a location for the callee to store
  89399. * data to be decoded.
  89400. * \param bytes A pointer to the size of the buffer. On entry
  89401. * to the callback, it contains the maximum number
  89402. * of bytes that may be stored in \a buffer. The
  89403. * callee must set it to the actual number of bytes
  89404. * stored (0 in case of error or end-of-stream) before
  89405. * returning.
  89406. * \param client_data The callee's client data set through
  89407. * FLAC__stream_decoder_init_*().
  89408. * \retval FLAC__StreamDecoderReadStatus
  89409. * The callee's return status. Note that the callback should return
  89410. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89411. * zero bytes were read and there is no more data to be read.
  89412. */
  89413. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89414. /** Signature for the seek callback.
  89415. *
  89416. * A function pointer matching this signature may be passed to
  89417. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89418. * called when the decoder needs to seek the input stream. The decoder
  89419. * will pass the absolute byte offset to seek to, 0 meaning the
  89420. * beginning of the stream.
  89421. *
  89422. * Here is an example of a seek callback for stdio streams:
  89423. * \code
  89424. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89425. * {
  89426. * FILE *file = ((MyClientData*)client_data)->file;
  89427. * if(file == stdin)
  89428. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89429. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89430. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89431. * else
  89432. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89433. * }
  89434. * \endcode
  89435. *
  89436. * \note In general, FLAC__StreamDecoder functions which change the
  89437. * state should not be called on the \a decoder while in the callback.
  89438. *
  89439. * \param decoder The decoder instance calling the callback.
  89440. * \param absolute_byte_offset The offset from the beginning of the stream
  89441. * to seek to.
  89442. * \param client_data The callee's client data set through
  89443. * FLAC__stream_decoder_init_*().
  89444. * \retval FLAC__StreamDecoderSeekStatus
  89445. * The callee's return status.
  89446. */
  89447. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89448. /** Signature for the tell callback.
  89449. *
  89450. * A function pointer matching this signature may be passed to
  89451. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89452. * called when the decoder wants to know the current position of the
  89453. * stream. The callback should return the byte offset from the
  89454. * beginning of the stream.
  89455. *
  89456. * Here is an example of a tell callback for stdio streams:
  89457. * \code
  89458. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89459. * {
  89460. * FILE *file = ((MyClientData*)client_data)->file;
  89461. * off_t pos;
  89462. * if(file == stdin)
  89463. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89464. * else if((pos = ftello(file)) < 0)
  89465. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89466. * else {
  89467. * *absolute_byte_offset = (FLAC__uint64)pos;
  89468. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89469. * }
  89470. * }
  89471. * \endcode
  89472. *
  89473. * \note In general, FLAC__StreamDecoder functions which change the
  89474. * state should not be called on the \a decoder while in the callback.
  89475. *
  89476. * \param decoder The decoder instance calling the callback.
  89477. * \param absolute_byte_offset A pointer to storage for the current offset
  89478. * from the beginning of the stream.
  89479. * \param client_data The callee's client data set through
  89480. * FLAC__stream_decoder_init_*().
  89481. * \retval FLAC__StreamDecoderTellStatus
  89482. * The callee's return status.
  89483. */
  89484. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89485. /** Signature for the length callback.
  89486. *
  89487. * A function pointer matching this signature may be passed to
  89488. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89489. * called when the decoder wants to know the total length of the stream
  89490. * in bytes.
  89491. *
  89492. * Here is an example of a length callback for stdio streams:
  89493. * \code
  89494. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89495. * {
  89496. * FILE *file = ((MyClientData*)client_data)->file;
  89497. * struct stat filestats;
  89498. *
  89499. * if(file == stdin)
  89500. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89501. * else if(fstat(fileno(file), &filestats) != 0)
  89502. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89503. * else {
  89504. * *stream_length = (FLAC__uint64)filestats.st_size;
  89505. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89506. * }
  89507. * }
  89508. * \endcode
  89509. *
  89510. * \note In general, FLAC__StreamDecoder functions which change the
  89511. * state should not be called on the \a decoder while in the callback.
  89512. *
  89513. * \param decoder The decoder instance calling the callback.
  89514. * \param stream_length A pointer to storage for the length of the stream
  89515. * in bytes.
  89516. * \param client_data The callee's client data set through
  89517. * FLAC__stream_decoder_init_*().
  89518. * \retval FLAC__StreamDecoderLengthStatus
  89519. * The callee's return status.
  89520. */
  89521. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89522. /** Signature for the EOF callback.
  89523. *
  89524. * A function pointer matching this signature may be passed to
  89525. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89526. * called when the decoder needs to know if the end of the stream has
  89527. * been reached.
  89528. *
  89529. * Here is an example of a EOF callback for stdio streams:
  89530. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89531. * \code
  89532. * {
  89533. * FILE *file = ((MyClientData*)client_data)->file;
  89534. * return feof(file)? true : false;
  89535. * }
  89536. * \endcode
  89537. *
  89538. * \note In general, FLAC__StreamDecoder functions which change the
  89539. * state should not be called on the \a decoder while in the callback.
  89540. *
  89541. * \param decoder The decoder instance calling the callback.
  89542. * \param client_data The callee's client data set through
  89543. * FLAC__stream_decoder_init_*().
  89544. * \retval FLAC__bool
  89545. * \c true if the currently at the end of the stream, else \c false.
  89546. */
  89547. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89548. /** Signature for the write callback.
  89549. *
  89550. * A function pointer matching this signature must be passed to one of
  89551. * the FLAC__stream_decoder_init_*() functions.
  89552. * The supplied function will be called when the decoder has decoded a
  89553. * single audio frame. The decoder will pass the frame metadata as well
  89554. * as an array of pointers (one for each channel) pointing to the
  89555. * decoded audio.
  89556. *
  89557. * \note In general, FLAC__StreamDecoder functions which change the
  89558. * state should not be called on the \a decoder while in the callback.
  89559. *
  89560. * \param decoder The decoder instance calling the callback.
  89561. * \param frame The description of the decoded frame. See
  89562. * FLAC__Frame.
  89563. * \param buffer An array of pointers to decoded channels of data.
  89564. * Each pointer will point to an array of signed
  89565. * samples of length \a frame->header.blocksize.
  89566. * Channels will be ordered according to the FLAC
  89567. * specification; see the documentation for the
  89568. * <A HREF="../format.html#frame_header">frame header</A>.
  89569. * \param client_data The callee's client data set through
  89570. * FLAC__stream_decoder_init_*().
  89571. * \retval FLAC__StreamDecoderWriteStatus
  89572. * The callee's return status.
  89573. */
  89574. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89575. /** Signature for the metadata callback.
  89576. *
  89577. * A function pointer matching this signature must be passed to one of
  89578. * the FLAC__stream_decoder_init_*() functions.
  89579. * The supplied function will be called when the decoder has decoded a
  89580. * metadata block. In a valid FLAC file there will always be one
  89581. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89582. * These will be supplied by the decoder in the same order as they
  89583. * appear in the stream and always before the first audio frame (i.e.
  89584. * write callback). The metadata block that is passed in must not be
  89585. * modified, and it doesn't live beyond the callback, so you should make
  89586. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89587. * elsewhere. Since metadata blocks can potentially be large, by
  89588. * default the decoder only calls the metadata callback for the
  89589. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89590. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89591. *
  89592. * \note In general, FLAC__StreamDecoder functions which change the
  89593. * state should not be called on the \a decoder while in the callback.
  89594. *
  89595. * \param decoder The decoder instance calling the callback.
  89596. * \param metadata The decoded metadata block.
  89597. * \param client_data The callee's client data set through
  89598. * FLAC__stream_decoder_init_*().
  89599. */
  89600. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89601. /** Signature for the error callback.
  89602. *
  89603. * A function pointer matching this signature must be passed to one of
  89604. * the FLAC__stream_decoder_init_*() functions.
  89605. * The supplied function will be called whenever an error occurs during
  89606. * decoding.
  89607. *
  89608. * \note In general, FLAC__StreamDecoder functions which change the
  89609. * state should not be called on the \a decoder while in the callback.
  89610. *
  89611. * \param decoder The decoder instance calling the callback.
  89612. * \param status The error encountered by the decoder.
  89613. * \param client_data The callee's client data set through
  89614. * FLAC__stream_decoder_init_*().
  89615. */
  89616. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89617. /***********************************************************************
  89618. *
  89619. * Class constructor/destructor
  89620. *
  89621. ***********************************************************************/
  89622. /** Create a new stream decoder instance. The instance is created with
  89623. * default settings; see the individual FLAC__stream_decoder_set_*()
  89624. * functions for each setting's default.
  89625. *
  89626. * \retval FLAC__StreamDecoder*
  89627. * \c NULL if there was an error allocating memory, else the new instance.
  89628. */
  89629. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89630. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89631. *
  89632. * \param decoder A pointer to an existing decoder.
  89633. * \assert
  89634. * \code decoder != NULL \endcode
  89635. */
  89636. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89637. /***********************************************************************
  89638. *
  89639. * Public class method prototypes
  89640. *
  89641. ***********************************************************************/
  89642. /** Set the serial number for the FLAC stream within the Ogg container.
  89643. * The default behavior is to use the serial number of the first Ogg
  89644. * page. Setting a serial number here will explicitly specify which
  89645. * stream is to be decoded.
  89646. *
  89647. * \note
  89648. * This does not need to be set for native FLAC decoding.
  89649. *
  89650. * \default \c use serial number of first page
  89651. * \param decoder A decoder instance to set.
  89652. * \param serial_number See above.
  89653. * \assert
  89654. * \code decoder != NULL \endcode
  89655. * \retval FLAC__bool
  89656. * \c false if the decoder is already initialized, else \c true.
  89657. */
  89658. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89659. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89660. * compute the MD5 signature of the unencoded audio data while decoding
  89661. * and compare it to the signature from the STREAMINFO block, if it
  89662. * exists, during FLAC__stream_decoder_finish().
  89663. *
  89664. * MD5 signature checking will be turned off (until the next
  89665. * FLAC__stream_decoder_reset()) if there is no signature in the
  89666. * STREAMINFO block or when a seek is attempted.
  89667. *
  89668. * Clients that do not use the MD5 check should leave this off to speed
  89669. * up decoding.
  89670. *
  89671. * \default \c false
  89672. * \param decoder A decoder instance to set.
  89673. * \param value Flag value (see above).
  89674. * \assert
  89675. * \code decoder != NULL \endcode
  89676. * \retval FLAC__bool
  89677. * \c false if the decoder is already initialized, else \c true.
  89678. */
  89679. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89680. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89681. *
  89682. * \default By default, only the \c STREAMINFO block is returned via the
  89683. * metadata callback.
  89684. * \param decoder A decoder instance to set.
  89685. * \param type See above.
  89686. * \assert
  89687. * \code decoder != NULL \endcode
  89688. * \a type is valid
  89689. * \retval FLAC__bool
  89690. * \c false if the decoder is already initialized, else \c true.
  89691. */
  89692. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89693. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89694. * given \a id.
  89695. *
  89696. * \default By default, only the \c STREAMINFO block is returned via the
  89697. * metadata callback.
  89698. * \param decoder A decoder instance to set.
  89699. * \param id See above.
  89700. * \assert
  89701. * \code decoder != NULL \endcode
  89702. * \code id != NULL \endcode
  89703. * \retval FLAC__bool
  89704. * \c false if the decoder is already initialized, else \c true.
  89705. */
  89706. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89707. /** Direct the decoder to pass on all metadata blocks of any type.
  89708. *
  89709. * \default By default, only the \c STREAMINFO block is returned via the
  89710. * metadata callback.
  89711. * \param decoder A decoder instance to set.
  89712. * \assert
  89713. * \code decoder != NULL \endcode
  89714. * \retval FLAC__bool
  89715. * \c false if the decoder is already initialized, else \c true.
  89716. */
  89717. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89718. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89719. *
  89720. * \default By default, only the \c STREAMINFO block is returned via the
  89721. * metadata callback.
  89722. * \param decoder A decoder instance to set.
  89723. * \param type See above.
  89724. * \assert
  89725. * \code decoder != NULL \endcode
  89726. * \a type is valid
  89727. * \retval FLAC__bool
  89728. * \c false if the decoder is already initialized, else \c true.
  89729. */
  89730. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89731. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89732. * the given \a id.
  89733. *
  89734. * \default By default, only the \c STREAMINFO block is returned via the
  89735. * metadata callback.
  89736. * \param decoder A decoder instance to set.
  89737. * \param id See above.
  89738. * \assert
  89739. * \code decoder != NULL \endcode
  89740. * \code id != NULL \endcode
  89741. * \retval FLAC__bool
  89742. * \c false if the decoder is already initialized, else \c true.
  89743. */
  89744. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89745. /** Direct the decoder to filter out all metadata blocks of any type.
  89746. *
  89747. * \default By default, only the \c STREAMINFO block is returned via the
  89748. * metadata callback.
  89749. * \param decoder A decoder instance to set.
  89750. * \assert
  89751. * \code decoder != NULL \endcode
  89752. * \retval FLAC__bool
  89753. * \c false if the decoder is already initialized, else \c true.
  89754. */
  89755. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89756. /** Get the current decoder state.
  89757. *
  89758. * \param decoder A decoder instance to query.
  89759. * \assert
  89760. * \code decoder != NULL \endcode
  89761. * \retval FLAC__StreamDecoderState
  89762. * The current decoder state.
  89763. */
  89764. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89765. /** Get the current decoder state as a C string.
  89766. *
  89767. * \param decoder A decoder instance to query.
  89768. * \assert
  89769. * \code decoder != NULL \endcode
  89770. * \retval const char *
  89771. * The decoder state as a C string. Do not modify the contents.
  89772. */
  89773. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89774. /** Get the "MD5 signature checking" flag.
  89775. * This is the value of the setting, not whether or not the decoder is
  89776. * currently checking the MD5 (remember, it can be turned off automatically
  89777. * by a seek). When the decoder is reset the flag will be restored to the
  89778. * value returned by this function.
  89779. *
  89780. * \param decoder A decoder instance to query.
  89781. * \assert
  89782. * \code decoder != NULL \endcode
  89783. * \retval FLAC__bool
  89784. * See above.
  89785. */
  89786. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89787. /** Get the total number of samples in the stream being decoded.
  89788. * Will only be valid after decoding has started and will contain the
  89789. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89790. *
  89791. * \param decoder A decoder instance to query.
  89792. * \assert
  89793. * \code decoder != NULL \endcode
  89794. * \retval unsigned
  89795. * See above.
  89796. */
  89797. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89798. /** Get the current number of channels in the stream being decoded.
  89799. * Will only be valid after decoding has started and will contain the
  89800. * value from the most recently decoded frame header.
  89801. *
  89802. * \param decoder A decoder instance to query.
  89803. * \assert
  89804. * \code decoder != NULL \endcode
  89805. * \retval unsigned
  89806. * See above.
  89807. */
  89808. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89809. /** Get the current channel assignment in the stream being decoded.
  89810. * Will only be valid after decoding has started and will contain the
  89811. * value from the most recently decoded frame header.
  89812. *
  89813. * \param decoder A decoder instance to query.
  89814. * \assert
  89815. * \code decoder != NULL \endcode
  89816. * \retval FLAC__ChannelAssignment
  89817. * See above.
  89818. */
  89819. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89820. /** Get the current sample resolution in the stream being decoded.
  89821. * Will only be valid after decoding has started and will contain the
  89822. * value from the most recently decoded frame header.
  89823. *
  89824. * \param decoder A decoder instance to query.
  89825. * \assert
  89826. * \code decoder != NULL \endcode
  89827. * \retval unsigned
  89828. * See above.
  89829. */
  89830. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89831. /** Get the current sample rate in Hz of the stream being decoded.
  89832. * Will only be valid after decoding has started and will contain the
  89833. * value from the most recently decoded frame header.
  89834. *
  89835. * \param decoder A decoder instance to query.
  89836. * \assert
  89837. * \code decoder != NULL \endcode
  89838. * \retval unsigned
  89839. * See above.
  89840. */
  89841. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89842. /** Get the current blocksize of the stream being decoded.
  89843. * Will only be valid after decoding has started and will contain the
  89844. * value from the most recently decoded frame header.
  89845. *
  89846. * \param decoder A decoder instance to query.
  89847. * \assert
  89848. * \code decoder != NULL \endcode
  89849. * \retval unsigned
  89850. * See above.
  89851. */
  89852. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89853. /** Returns the decoder's current read position within the stream.
  89854. * The position is the byte offset from the start of the stream.
  89855. * Bytes before this position have been fully decoded. Note that
  89856. * there may still be undecoded bytes in the decoder's read FIFO.
  89857. * The returned position is correct even after a seek.
  89858. *
  89859. * \warning This function currently only works for native FLAC,
  89860. * not Ogg FLAC streams.
  89861. *
  89862. * \param decoder A decoder instance to query.
  89863. * \param position Address at which to return the desired position.
  89864. * \assert
  89865. * \code decoder != NULL \endcode
  89866. * \code position != NULL \endcode
  89867. * \retval FLAC__bool
  89868. * \c true if successful, \c false if the stream is not native FLAC,
  89869. * or there was an error from the 'tell' callback or it returned
  89870. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89871. */
  89872. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89873. /** Initialize the decoder instance to decode native FLAC streams.
  89874. *
  89875. * This flavor of initialization sets up the decoder to decode from a
  89876. * native FLAC stream. I/O is performed via callbacks to the client.
  89877. * For decoding from a plain file via filename or open FILE*,
  89878. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89879. * provide a simpler interface.
  89880. *
  89881. * This function should be called after FLAC__stream_decoder_new() and
  89882. * FLAC__stream_decoder_set_*() but before any of the
  89883. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89884. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89885. * if initialization succeeded.
  89886. *
  89887. * \param decoder An uninitialized decoder instance.
  89888. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89889. * pointer must not be \c NULL.
  89890. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89891. * pointer may be \c NULL if seeking is not
  89892. * supported. If \a seek_callback is not \c NULL then a
  89893. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89894. * Alternatively, a dummy seek callback that just
  89895. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89896. * may also be supplied, all though this is slightly
  89897. * less efficient for the decoder.
  89898. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89899. * pointer may be \c NULL if not supported by the client. If
  89900. * \a seek_callback is not \c NULL then a
  89901. * \a tell_callback must also be supplied.
  89902. * Alternatively, a dummy tell callback that just
  89903. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89904. * may also be supplied, all though this is slightly
  89905. * less efficient for the decoder.
  89906. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89907. * pointer may be \c NULL if not supported by the client. If
  89908. * \a seek_callback is not \c NULL then a
  89909. * \a length_callback must also be supplied.
  89910. * Alternatively, a dummy length callback that just
  89911. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89912. * may also be supplied, all though this is slightly
  89913. * less efficient for the decoder.
  89914. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89915. * pointer may be \c NULL if not supported by the client. If
  89916. * \a seek_callback is not \c NULL then a
  89917. * \a eof_callback must also be supplied.
  89918. * Alternatively, a dummy length callback that just
  89919. * returns \c false
  89920. * may also be supplied, all though this is slightly
  89921. * less efficient for the decoder.
  89922. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89923. * pointer must not be \c NULL.
  89924. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89925. * pointer may be \c NULL if the callback is not
  89926. * desired.
  89927. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89928. * pointer must not be \c NULL.
  89929. * \param client_data This value will be supplied to callbacks in their
  89930. * \a client_data argument.
  89931. * \assert
  89932. * \code decoder != NULL \endcode
  89933. * \retval FLAC__StreamDecoderInitStatus
  89934. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89935. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89936. */
  89937. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89938. FLAC__StreamDecoder *decoder,
  89939. FLAC__StreamDecoderReadCallback read_callback,
  89940. FLAC__StreamDecoderSeekCallback seek_callback,
  89941. FLAC__StreamDecoderTellCallback tell_callback,
  89942. FLAC__StreamDecoderLengthCallback length_callback,
  89943. FLAC__StreamDecoderEofCallback eof_callback,
  89944. FLAC__StreamDecoderWriteCallback write_callback,
  89945. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89946. FLAC__StreamDecoderErrorCallback error_callback,
  89947. void *client_data
  89948. );
  89949. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89950. *
  89951. * This flavor of initialization sets up the decoder to decode from a
  89952. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89953. * client. For decoding from a plain file via filename or open FILE*,
  89954. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89955. * provide a simpler interface.
  89956. *
  89957. * This function should be called after FLAC__stream_decoder_new() and
  89958. * FLAC__stream_decoder_set_*() but before any of the
  89959. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89960. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89961. * if initialization succeeded.
  89962. *
  89963. * \note Support for Ogg FLAC in the library is optional. If this
  89964. * library has been built without support for Ogg FLAC, this function
  89965. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89966. *
  89967. * \param decoder An uninitialized decoder instance.
  89968. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89969. * pointer must not be \c NULL.
  89970. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89971. * pointer may be \c NULL if seeking is not
  89972. * supported. If \a seek_callback is not \c NULL then a
  89973. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89974. * Alternatively, a dummy seek callback that just
  89975. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89976. * may also be supplied, all though this is slightly
  89977. * less efficient for the decoder.
  89978. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89979. * pointer may be \c NULL if not supported by the client. If
  89980. * \a seek_callback is not \c NULL then a
  89981. * \a tell_callback must also be supplied.
  89982. * Alternatively, a dummy tell callback that just
  89983. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89984. * may also be supplied, all though this is slightly
  89985. * less efficient for the decoder.
  89986. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89987. * pointer may be \c NULL if not supported by the client. If
  89988. * \a seek_callback is not \c NULL then a
  89989. * \a length_callback must also be supplied.
  89990. * Alternatively, a dummy length callback that just
  89991. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89992. * may also be supplied, all though this is slightly
  89993. * less efficient for the decoder.
  89994. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89995. * pointer may be \c NULL if not supported by the client. If
  89996. * \a seek_callback is not \c NULL then a
  89997. * \a eof_callback must also be supplied.
  89998. * Alternatively, a dummy length callback that just
  89999. * returns \c false
  90000. * may also be supplied, all though this is slightly
  90001. * less efficient for the decoder.
  90002. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90003. * pointer must not be \c NULL.
  90004. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90005. * pointer may be \c NULL if the callback is not
  90006. * desired.
  90007. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90008. * pointer must not be \c NULL.
  90009. * \param client_data This value will be supplied to callbacks in their
  90010. * \a client_data argument.
  90011. * \assert
  90012. * \code decoder != NULL \endcode
  90013. * \retval FLAC__StreamDecoderInitStatus
  90014. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90015. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90016. */
  90017. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90018. FLAC__StreamDecoder *decoder,
  90019. FLAC__StreamDecoderReadCallback read_callback,
  90020. FLAC__StreamDecoderSeekCallback seek_callback,
  90021. FLAC__StreamDecoderTellCallback tell_callback,
  90022. FLAC__StreamDecoderLengthCallback length_callback,
  90023. FLAC__StreamDecoderEofCallback eof_callback,
  90024. FLAC__StreamDecoderWriteCallback write_callback,
  90025. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90026. FLAC__StreamDecoderErrorCallback error_callback,
  90027. void *client_data
  90028. );
  90029. /** Initialize the decoder instance to decode native FLAC files.
  90030. *
  90031. * This flavor of initialization sets up the decoder to decode from a
  90032. * plain native FLAC file. For non-stdio streams, you must use
  90033. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90034. *
  90035. * This function should be called after FLAC__stream_decoder_new() and
  90036. * FLAC__stream_decoder_set_*() but before any of the
  90037. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90038. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90039. * if initialization succeeded.
  90040. *
  90041. * \param decoder An uninitialized decoder instance.
  90042. * \param file An open FLAC file. The file should have been
  90043. * opened with mode \c "rb" and rewound. The file
  90044. * becomes owned by the decoder and should not be
  90045. * manipulated by the client while decoding.
  90046. * Unless \a file is \c stdin, it will be closed
  90047. * when FLAC__stream_decoder_finish() is called.
  90048. * Note however that seeking will not work when
  90049. * decoding from \c stdout since it is not seekable.
  90050. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90051. * pointer must not be \c NULL.
  90052. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90053. * pointer may be \c NULL if the callback is not
  90054. * desired.
  90055. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90056. * pointer must not be \c NULL.
  90057. * \param client_data This value will be supplied to callbacks in their
  90058. * \a client_data argument.
  90059. * \assert
  90060. * \code decoder != NULL \endcode
  90061. * \code file != NULL \endcode
  90062. * \retval FLAC__StreamDecoderInitStatus
  90063. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90064. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90065. */
  90066. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90067. FLAC__StreamDecoder *decoder,
  90068. FILE *file,
  90069. FLAC__StreamDecoderWriteCallback write_callback,
  90070. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90071. FLAC__StreamDecoderErrorCallback error_callback,
  90072. void *client_data
  90073. );
  90074. /** Initialize the decoder instance to decode Ogg FLAC files.
  90075. *
  90076. * This flavor of initialization sets up the decoder to decode from a
  90077. * plain Ogg FLAC file. For non-stdio streams, you must use
  90078. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90079. *
  90080. * This function should be called after FLAC__stream_decoder_new() and
  90081. * FLAC__stream_decoder_set_*() but before any of the
  90082. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90083. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90084. * if initialization succeeded.
  90085. *
  90086. * \note Support for Ogg FLAC in the library is optional. If this
  90087. * library has been built without support for Ogg FLAC, this function
  90088. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90089. *
  90090. * \param decoder An uninitialized decoder instance.
  90091. * \param file An open FLAC file. The file should have been
  90092. * opened with mode \c "rb" and rewound. The file
  90093. * becomes owned by the decoder and should not be
  90094. * manipulated by the client while decoding.
  90095. * Unless \a file is \c stdin, it will be closed
  90096. * when FLAC__stream_decoder_finish() is called.
  90097. * Note however that seeking will not work when
  90098. * decoding from \c stdout since it is not seekable.
  90099. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90100. * pointer must not be \c NULL.
  90101. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90102. * pointer may be \c NULL if the callback is not
  90103. * desired.
  90104. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90105. * pointer must not be \c NULL.
  90106. * \param client_data This value will be supplied to callbacks in their
  90107. * \a client_data argument.
  90108. * \assert
  90109. * \code decoder != NULL \endcode
  90110. * \code file != NULL \endcode
  90111. * \retval FLAC__StreamDecoderInitStatus
  90112. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90113. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90114. */
  90115. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90116. FLAC__StreamDecoder *decoder,
  90117. FILE *file,
  90118. FLAC__StreamDecoderWriteCallback write_callback,
  90119. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90120. FLAC__StreamDecoderErrorCallback error_callback,
  90121. void *client_data
  90122. );
  90123. /** Initialize the decoder instance to decode native FLAC files.
  90124. *
  90125. * This flavor of initialization sets up the decoder to decode from a plain
  90126. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90127. * example, with Unicode filenames on Windows), you must use
  90128. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90129. * and provide callbacks for the I/O.
  90130. *
  90131. * This function should be called after FLAC__stream_decoder_new() and
  90132. * FLAC__stream_decoder_set_*() but before any of the
  90133. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90134. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90135. * if initialization succeeded.
  90136. *
  90137. * \param decoder An uninitialized decoder instance.
  90138. * \param filename The name of the file to decode from. The file will
  90139. * be opened with fopen(). Use \c NULL to decode from
  90140. * \c stdin. Note that \c stdin is not seekable.
  90141. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90142. * pointer must not be \c NULL.
  90143. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90144. * pointer may be \c NULL if the callback is not
  90145. * desired.
  90146. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90147. * pointer must not be \c NULL.
  90148. * \param client_data This value will be supplied to callbacks in their
  90149. * \a client_data argument.
  90150. * \assert
  90151. * \code decoder != NULL \endcode
  90152. * \retval FLAC__StreamDecoderInitStatus
  90153. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90154. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90155. */
  90156. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90157. FLAC__StreamDecoder *decoder,
  90158. const char *filename,
  90159. FLAC__StreamDecoderWriteCallback write_callback,
  90160. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90161. FLAC__StreamDecoderErrorCallback error_callback,
  90162. void *client_data
  90163. );
  90164. /** Initialize the decoder instance to decode Ogg FLAC files.
  90165. *
  90166. * This flavor of initialization sets up the decoder to decode from a plain
  90167. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90168. * example, with Unicode filenames on Windows), you must use
  90169. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90170. * and provide callbacks for the I/O.
  90171. *
  90172. * This function should be called after FLAC__stream_decoder_new() and
  90173. * FLAC__stream_decoder_set_*() but before any of the
  90174. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90175. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90176. * if initialization succeeded.
  90177. *
  90178. * \note Support for Ogg FLAC in the library is optional. If this
  90179. * library has been built without support for Ogg FLAC, this function
  90180. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90181. *
  90182. * \param decoder An uninitialized decoder instance.
  90183. * \param filename The name of the file to decode from. The file will
  90184. * be opened with fopen(). Use \c NULL to decode from
  90185. * \c stdin. Note that \c stdin is not seekable.
  90186. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90187. * pointer must not be \c NULL.
  90188. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90189. * pointer may be \c NULL if the callback is not
  90190. * desired.
  90191. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90192. * pointer must not be \c NULL.
  90193. * \param client_data This value will be supplied to callbacks in their
  90194. * \a client_data argument.
  90195. * \assert
  90196. * \code decoder != NULL \endcode
  90197. * \retval FLAC__StreamDecoderInitStatus
  90198. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90199. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90200. */
  90201. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90202. FLAC__StreamDecoder *decoder,
  90203. const char *filename,
  90204. FLAC__StreamDecoderWriteCallback write_callback,
  90205. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90206. FLAC__StreamDecoderErrorCallback error_callback,
  90207. void *client_data
  90208. );
  90209. /** Finish the decoding process.
  90210. * Flushes the decoding buffer, releases resources, resets the decoder
  90211. * settings to their defaults, and returns the decoder state to
  90212. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90213. *
  90214. * In the event of a prematurely-terminated decode, it is not strictly
  90215. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90216. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90217. * with a FLAC__stream_decoder_finish().
  90218. *
  90219. * \param decoder An uninitialized decoder instance.
  90220. * \assert
  90221. * \code decoder != NULL \endcode
  90222. * \retval FLAC__bool
  90223. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90224. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90225. * signature does not match the one computed by the decoder; else
  90226. * \c true.
  90227. */
  90228. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90229. /** Flush the stream input.
  90230. * The decoder's input buffer will be cleared and the state set to
  90231. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90232. * off MD5 checking.
  90233. *
  90234. * \param decoder A decoder instance.
  90235. * \assert
  90236. * \code decoder != NULL \endcode
  90237. * \retval FLAC__bool
  90238. * \c true if successful, else \c false if a memory allocation
  90239. * error occurs (in which case the state will be set to
  90240. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90241. */
  90242. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90243. /** Reset the decoding process.
  90244. * The decoder's input buffer will be cleared and the state set to
  90245. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90246. * FLAC__stream_decoder_finish() except that the settings are
  90247. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90248. * before decoding again. MD5 checking will be restored to its original
  90249. * setting.
  90250. *
  90251. * If the decoder is seekable, or was initialized with
  90252. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90253. * the decoder will also attempt to seek to the beginning of the file.
  90254. * If this rewind fails, this function will return \c false. It follows
  90255. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90256. * \c stdin.
  90257. *
  90258. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90259. * and is not seekable (i.e. no seek callback was provided or the seek
  90260. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90261. * is the duty of the client to start feeding data from the beginning of
  90262. * the stream on the next FLAC__stream_decoder_process() or
  90263. * FLAC__stream_decoder_process_interleaved() call.
  90264. *
  90265. * \param decoder A decoder instance.
  90266. * \assert
  90267. * \code decoder != NULL \endcode
  90268. * \retval FLAC__bool
  90269. * \c true if successful, else \c false if a memory allocation occurs
  90270. * (in which case the state will be set to
  90271. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90272. * occurs (the state will be unchanged).
  90273. */
  90274. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90275. /** Decode one metadata block or audio frame.
  90276. * This version instructs the decoder to decode a either a single metadata
  90277. * block or a single frame and stop, unless the callbacks return a fatal
  90278. * error or the read callback returns
  90279. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90280. *
  90281. * As the decoder needs more input it will call the read callback.
  90282. * Depending on what was decoded, the metadata or write callback will be
  90283. * called with the decoded metadata block or audio frame.
  90284. *
  90285. * Unless there is a fatal read error or end of stream, this function
  90286. * will return once one whole frame is decoded. In other words, if the
  90287. * stream is not synchronized or points to a corrupt frame header, the
  90288. * decoder will continue to try and resync until it gets to a valid
  90289. * frame, then decode one frame, then return. If the decoder points to
  90290. * a frame whose frame CRC in the frame footer does not match the
  90291. * computed frame CRC, this function will issue a
  90292. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90293. * error callback, and return, having decoded one complete, although
  90294. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90295. * correct length to the write callback.)
  90296. *
  90297. * \param decoder An initialized decoder instance.
  90298. * \assert
  90299. * \code decoder != NULL \endcode
  90300. * \retval FLAC__bool
  90301. * \c false if any fatal read, write, or memory allocation error
  90302. * occurred (meaning decoding must stop), else \c true; for more
  90303. * information about the decoder, check the decoder state with
  90304. * FLAC__stream_decoder_get_state().
  90305. */
  90306. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90307. /** Decode until the end of the metadata.
  90308. * This version instructs the decoder to decode from the current position
  90309. * and continue until all the metadata has been read, or until the
  90310. * callbacks return a fatal error or the read callback returns
  90311. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90312. *
  90313. * As the decoder needs more input it will call the read callback.
  90314. * As each metadata block is decoded, the metadata callback will be called
  90315. * with the decoded metadata.
  90316. *
  90317. * \param decoder An initialized decoder instance.
  90318. * \assert
  90319. * \code decoder != NULL \endcode
  90320. * \retval FLAC__bool
  90321. * \c false if any fatal read, write, or memory allocation error
  90322. * occurred (meaning decoding must stop), else \c true; for more
  90323. * information about the decoder, check the decoder state with
  90324. * FLAC__stream_decoder_get_state().
  90325. */
  90326. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90327. /** Decode until the end of the stream.
  90328. * This version instructs the decoder to decode from the current position
  90329. * and continue until the end of stream (the read callback returns
  90330. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90331. * callbacks return a fatal error.
  90332. *
  90333. * As the decoder needs more input it will call the read callback.
  90334. * As each metadata block and frame is decoded, the metadata or write
  90335. * callback will be called with the decoded metadata or frame.
  90336. *
  90337. * \param decoder An initialized decoder instance.
  90338. * \assert
  90339. * \code decoder != NULL \endcode
  90340. * \retval FLAC__bool
  90341. * \c false if any fatal read, write, or memory allocation error
  90342. * occurred (meaning decoding must stop), else \c true; for more
  90343. * information about the decoder, check the decoder state with
  90344. * FLAC__stream_decoder_get_state().
  90345. */
  90346. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90347. /** Skip one audio frame.
  90348. * This version instructs the decoder to 'skip' a single frame and stop,
  90349. * unless the callbacks return a fatal error or the read callback returns
  90350. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90351. *
  90352. * The decoding flow is the same as what occurs when
  90353. * FLAC__stream_decoder_process_single() is called to process an audio
  90354. * frame, except that this function does not decode the parsed data into
  90355. * PCM or call the write callback. The integrity of the frame is still
  90356. * checked the same way as in the other process functions.
  90357. *
  90358. * This function will return once one whole frame is skipped, in the
  90359. * same way that FLAC__stream_decoder_process_single() will return once
  90360. * one whole frame is decoded.
  90361. *
  90362. * This function can be used in more quickly determining FLAC frame
  90363. * boundaries when decoding of the actual data is not needed, for
  90364. * example when an application is separating a FLAC stream into frames
  90365. * for editing or storing in a container. To do this, the application
  90366. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90367. * to the next frame, then use
  90368. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90369. * boundary.
  90370. *
  90371. * This function should only be called when the stream has advanced
  90372. * past all the metadata, otherwise it will return \c false.
  90373. *
  90374. * \param decoder An initialized decoder instance not in a metadata
  90375. * state.
  90376. * \assert
  90377. * \code decoder != NULL \endcode
  90378. * \retval FLAC__bool
  90379. * \c false if any fatal read, write, or memory allocation error
  90380. * occurred (meaning decoding must stop), or if the decoder
  90381. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90382. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90383. * information about the decoder, check the decoder state with
  90384. * FLAC__stream_decoder_get_state().
  90385. */
  90386. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90387. /** Flush the input and seek to an absolute sample.
  90388. * Decoding will resume at the given sample. Note that because of
  90389. * this, the next write callback may contain a partial block. The
  90390. * client must support seeking the input or this function will fail
  90391. * and return \c false. Furthermore, if the decoder state is
  90392. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90393. * with FLAC__stream_decoder_flush() or reset with
  90394. * FLAC__stream_decoder_reset() before decoding can continue.
  90395. *
  90396. * \param decoder A decoder instance.
  90397. * \param sample The target sample number to seek to.
  90398. * \assert
  90399. * \code decoder != NULL \endcode
  90400. * \retval FLAC__bool
  90401. * \c true if successful, else \c false.
  90402. */
  90403. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90404. /* \} */
  90405. #ifdef __cplusplus
  90406. }
  90407. #endif
  90408. #endif
  90409. /*** End of inlined file: stream_decoder.h ***/
  90410. /*** Start of inlined file: stream_encoder.h ***/
  90411. #ifndef FLAC__STREAM_ENCODER_H
  90412. #define FLAC__STREAM_ENCODER_H
  90413. #include <stdio.h> /* for FILE */
  90414. #ifdef __cplusplus
  90415. extern "C" {
  90416. #endif
  90417. /** \file include/FLAC/stream_encoder.h
  90418. *
  90419. * \brief
  90420. * This module contains the functions which implement the stream
  90421. * encoder.
  90422. *
  90423. * See the detailed documentation in the
  90424. * \link flac_stream_encoder stream encoder \endlink module.
  90425. */
  90426. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90427. * \ingroup flac
  90428. *
  90429. * \brief
  90430. * This module describes the encoder layers provided by libFLAC.
  90431. *
  90432. * The stream encoder can be used to encode complete streams either to the
  90433. * client via callbacks, or directly to a file, depending on how it is
  90434. * initialized. When encoding via callbacks, the client provides a write
  90435. * callback which will be called whenever FLAC data is ready to be written.
  90436. * If the client also supplies a seek callback, the encoder will also
  90437. * automatically handle the writing back of metadata discovered while
  90438. * encoding, like stream info, seek points offsets, etc. When encoding to
  90439. * a file, the client needs only supply a filename or open \c FILE* and an
  90440. * optional progress callback for periodic notification of progress; the
  90441. * write and seek callbacks are supplied internally. For more info see the
  90442. * \link flac_stream_encoder stream encoder \endlink module.
  90443. */
  90444. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90445. * \ingroup flac_encoder
  90446. *
  90447. * \brief
  90448. * This module contains the functions which implement the stream
  90449. * encoder.
  90450. *
  90451. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90452. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90453. *
  90454. * The basic usage of this encoder is as follows:
  90455. * - The program creates an instance of an encoder using
  90456. * FLAC__stream_encoder_new().
  90457. * - The program overrides the default settings using
  90458. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90459. * functions should be called:
  90460. * - FLAC__stream_encoder_set_channels()
  90461. * - FLAC__stream_encoder_set_bits_per_sample()
  90462. * - FLAC__stream_encoder_set_sample_rate()
  90463. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90464. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90465. * - If the application wants to control the compression level or set its own
  90466. * metadata, then the following should also be called:
  90467. * - FLAC__stream_encoder_set_compression_level()
  90468. * - FLAC__stream_encoder_set_verify()
  90469. * - FLAC__stream_encoder_set_metadata()
  90470. * - The rest of the set functions should only be called if the client needs
  90471. * exact control over how the audio is compressed; thorough understanding
  90472. * of the FLAC format is necessary to achieve good results.
  90473. * - The program initializes the instance to validate the settings and
  90474. * prepare for encoding using
  90475. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90476. * or FLAC__stream_encoder_init_file() for native FLAC
  90477. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90478. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90479. * - The program calls FLAC__stream_encoder_process() or
  90480. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90481. * subsequently calls the callbacks when there is encoder data ready
  90482. * to be written.
  90483. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90484. * which causes the encoder to encode any data still in its input pipe,
  90485. * update the metadata with the final encoding statistics if output
  90486. * seeking is possible, and finally reset the encoder to the
  90487. * uninitialized state.
  90488. * - The instance may be used again or deleted with
  90489. * FLAC__stream_encoder_delete().
  90490. *
  90491. * In more detail, the stream encoder functions similarly to the
  90492. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90493. * callbacks and more options. Typically the client will create a new
  90494. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90495. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90496. * calling one of the FLAC__stream_encoder_init_*() functions.
  90497. *
  90498. * Unlike the decoders, the stream encoder has many options that can
  90499. * affect the speed and compression ratio. When setting these parameters
  90500. * you should have some basic knowledge of the format (see the
  90501. * <A HREF="../documentation.html#format">user-level documentation</A>
  90502. * or the <A HREF="../format.html">formal description</A>). The
  90503. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90504. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90505. * functions will do this, so make sure to pay attention to the state
  90506. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90507. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90508. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90509. * the constructor.
  90510. *
  90511. * There are three initialization functions for native FLAC, one for
  90512. * setting up the encoder to encode FLAC data to the client via
  90513. * callbacks, and two for encoding directly to a file.
  90514. *
  90515. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90516. * You must also supply a write callback which will be called anytime
  90517. * there is raw encoded data to write. If the client can seek the output
  90518. * it is best to also supply seek and tell callbacks, as this allows the
  90519. * encoder to go back after encoding is finished to write back
  90520. * information that was collected while encoding, like seek point offsets,
  90521. * frame sizes, etc.
  90522. *
  90523. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90524. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90525. * filename or open \c FILE*; the encoder will handle all the callbacks
  90526. * internally. You may also supply a progress callback for periodic
  90527. * notification of the encoding progress.
  90528. *
  90529. * There are three similarly-named init functions for encoding to Ogg
  90530. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90531. * library has been built with Ogg support.
  90532. *
  90533. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90534. * call the write callback several times, once with the \c fLaC signature,
  90535. * and once for each encoded metadata block. Note that for Ogg FLAC
  90536. * encoding you will usually get at least twice the number of callbacks than
  90537. * with native FLAC, one for the Ogg page header and one for the page body.
  90538. *
  90539. * After initializing the instance, the client may feed audio data to the
  90540. * encoder in one of two ways:
  90541. *
  90542. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90543. * will pass an array of pointers to buffers, one for each channel, to
  90544. * the encoder, each of the same length. The samples need not be
  90545. * block-aligned, but each channel should have the same number of samples.
  90546. * - Channel interleaved, through
  90547. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90548. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90549. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90550. * Again, the samples need not be block-aligned but they must be
  90551. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90552. * the last value channelN_sampleM.
  90553. *
  90554. * Note that for either process call, each sample in the buffers should be a
  90555. * signed integer, right-justified to the resolution set by
  90556. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90557. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90558. *
  90559. * When the client is finished encoding data, it calls
  90560. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90561. * data still in its input pipe, and call the metadata callback with the
  90562. * final encoding statistics. Then the instance may be deleted with
  90563. * FLAC__stream_encoder_delete() or initialized again to encode another
  90564. * stream.
  90565. *
  90566. * For programs that write their own metadata, but that do not know the
  90567. * actual metadata until after encoding, it is advantageous to instruct
  90568. * the encoder to write a PADDING block of the correct size, so that
  90569. * instead of rewriting the whole stream after encoding, the program can
  90570. * just overwrite the PADDING block. If only the maximum size of the
  90571. * metadata is known, the program can write a slightly larger padding
  90572. * block, then split it after encoding.
  90573. *
  90574. * Make sure you understand how lengths are calculated. All FLAC metadata
  90575. * blocks have a 4 byte header which contains the type and length. This
  90576. * length does not include the 4 bytes of the header. See the format page
  90577. * for the specification of metadata blocks and their lengths.
  90578. *
  90579. * \note
  90580. * If you are writing the FLAC data to a file via callbacks, make sure it
  90581. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90582. * after the first encoding pass, the encoder will try to seek back to the
  90583. * beginning of the stream, to the STREAMINFO block, to write some data
  90584. * there. (If using FLAC__stream_encoder_init*_file() or
  90585. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90586. *
  90587. * \note
  90588. * The "set" functions may only be called when the encoder is in the
  90589. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90590. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90591. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90592. * return \c true, otherwise \c false.
  90593. *
  90594. * \note
  90595. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90596. * defaults.
  90597. *
  90598. * \{
  90599. */
  90600. /** State values for a FLAC__StreamEncoder.
  90601. *
  90602. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90603. *
  90604. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90605. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90606. * must be deleted with FLAC__stream_encoder_delete().
  90607. */
  90608. typedef enum {
  90609. FLAC__STREAM_ENCODER_OK = 0,
  90610. /**< The encoder is in the normal OK state and samples can be processed. */
  90611. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90612. /**< The encoder is in the uninitialized state; one of the
  90613. * FLAC__stream_encoder_init_*() functions must be called before samples
  90614. * can be processed.
  90615. */
  90616. FLAC__STREAM_ENCODER_OGG_ERROR,
  90617. /**< An error occurred in the underlying Ogg layer. */
  90618. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90619. /**< An error occurred in the underlying verify stream decoder;
  90620. * check FLAC__stream_encoder_get_verify_decoder_state().
  90621. */
  90622. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90623. /**< The verify decoder detected a mismatch between the original
  90624. * audio signal and the decoded audio signal.
  90625. */
  90626. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90627. /**< One of the callbacks returned a fatal error. */
  90628. FLAC__STREAM_ENCODER_IO_ERROR,
  90629. /**< An I/O error occurred while opening/reading/writing a file.
  90630. * Check \c errno.
  90631. */
  90632. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90633. /**< An error occurred while writing the stream; usually, the
  90634. * write_callback returned an error.
  90635. */
  90636. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90637. /**< Memory allocation failed. */
  90638. } FLAC__StreamEncoderState;
  90639. /** Maps a FLAC__StreamEncoderState to a C string.
  90640. *
  90641. * Using a FLAC__StreamEncoderState as the index to this array
  90642. * will give the string equivalent. The contents should not be modified.
  90643. */
  90644. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90645. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90646. */
  90647. typedef enum {
  90648. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90649. /**< Initialization was successful. */
  90650. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90651. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90652. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90653. /**< The library was not compiled with support for the given container
  90654. * format.
  90655. */
  90656. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90657. /**< A required callback was not supplied. */
  90658. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90659. /**< The encoder has an invalid setting for number of channels. */
  90660. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90661. /**< The encoder has an invalid setting for bits-per-sample.
  90662. * FLAC supports 4-32 bps but the reference encoder currently supports
  90663. * only up to 24 bps.
  90664. */
  90665. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90666. /**< The encoder has an invalid setting for the input sample rate. */
  90667. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90668. /**< The encoder has an invalid setting for the block size. */
  90669. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90670. /**< The encoder has an invalid setting for the maximum LPC order. */
  90671. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90672. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90673. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90674. /**< The specified block size is less than the maximum LPC order. */
  90675. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90676. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90677. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90678. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90679. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90680. * - One of the metadata blocks contains an undefined type
  90681. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90682. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90683. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90684. */
  90685. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90686. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90687. * already initialized, usually because
  90688. * FLAC__stream_encoder_finish() was not called.
  90689. */
  90690. } FLAC__StreamEncoderInitStatus;
  90691. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90692. *
  90693. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90694. * will give the string equivalent. The contents should not be modified.
  90695. */
  90696. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90697. /** Return values for the FLAC__StreamEncoder read callback.
  90698. */
  90699. typedef enum {
  90700. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90701. /**< The read was OK and decoding can continue. */
  90702. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90703. /**< The read was attempted at the end of the stream. */
  90704. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90705. /**< An unrecoverable error occurred. */
  90706. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90707. /**< Client does not support reading back from the output. */
  90708. } FLAC__StreamEncoderReadStatus;
  90709. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90710. *
  90711. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90712. * will give the string equivalent. The contents should not be modified.
  90713. */
  90714. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90715. /** Return values for the FLAC__StreamEncoder write callback.
  90716. */
  90717. typedef enum {
  90718. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90719. /**< The write was OK and encoding can continue. */
  90720. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90721. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90722. } FLAC__StreamEncoderWriteStatus;
  90723. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90724. *
  90725. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90726. * will give the string equivalent. The contents should not be modified.
  90727. */
  90728. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90729. /** Return values for the FLAC__StreamEncoder seek callback.
  90730. */
  90731. typedef enum {
  90732. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90733. /**< The seek was OK and encoding can continue. */
  90734. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90735. /**< An unrecoverable error occurred. */
  90736. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90737. /**< Client does not support seeking. */
  90738. } FLAC__StreamEncoderSeekStatus;
  90739. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90740. *
  90741. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90742. * will give the string equivalent. The contents should not be modified.
  90743. */
  90744. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90745. /** Return values for the FLAC__StreamEncoder tell callback.
  90746. */
  90747. typedef enum {
  90748. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90749. /**< The tell was OK and encoding can continue. */
  90750. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90751. /**< An unrecoverable error occurred. */
  90752. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90753. /**< Client does not support seeking. */
  90754. } FLAC__StreamEncoderTellStatus;
  90755. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90756. *
  90757. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90758. * will give the string equivalent. The contents should not be modified.
  90759. */
  90760. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90761. /***********************************************************************
  90762. *
  90763. * class FLAC__StreamEncoder
  90764. *
  90765. ***********************************************************************/
  90766. struct FLAC__StreamEncoderProtected;
  90767. struct FLAC__StreamEncoderPrivate;
  90768. /** The opaque structure definition for the stream encoder type.
  90769. * See the \link flac_stream_encoder stream encoder module \endlink
  90770. * for a detailed description.
  90771. */
  90772. typedef struct {
  90773. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90774. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90775. } FLAC__StreamEncoder;
  90776. /** Signature for the read callback.
  90777. *
  90778. * A function pointer matching this signature must be passed to
  90779. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90780. * The supplied function will be called when the encoder needs to read back
  90781. * encoded data. This happens during the metadata callback, when the encoder
  90782. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90783. * while encoding. The address of the buffer to be filled is supplied, along
  90784. * with the number of bytes the buffer can hold. The callback may choose to
  90785. * supply less data and modify the byte count but must be careful not to
  90786. * overflow the buffer. The callback then returns a status code chosen from
  90787. * FLAC__StreamEncoderReadStatus.
  90788. *
  90789. * Here is an example of a read callback for stdio streams:
  90790. * \code
  90791. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90792. * {
  90793. * FILE *file = ((MyClientData*)client_data)->file;
  90794. * if(*bytes > 0) {
  90795. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90796. * if(ferror(file))
  90797. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90798. * else if(*bytes == 0)
  90799. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90800. * else
  90801. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90802. * }
  90803. * else
  90804. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90805. * }
  90806. * \endcode
  90807. *
  90808. * \note In general, FLAC__StreamEncoder functions which change the
  90809. * state should not be called on the \a encoder while in the callback.
  90810. *
  90811. * \param encoder The encoder instance calling the callback.
  90812. * \param buffer A pointer to a location for the callee to store
  90813. * data to be encoded.
  90814. * \param bytes A pointer to the size of the buffer. On entry
  90815. * to the callback, it contains the maximum number
  90816. * of bytes that may be stored in \a buffer. The
  90817. * callee must set it to the actual number of bytes
  90818. * stored (0 in case of error or end-of-stream) before
  90819. * returning.
  90820. * \param client_data The callee's client data set through
  90821. * FLAC__stream_encoder_set_client_data().
  90822. * \retval FLAC__StreamEncoderReadStatus
  90823. * The callee's return status.
  90824. */
  90825. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90826. /** Signature for the write callback.
  90827. *
  90828. * A function pointer matching this signature must be passed to
  90829. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90830. * by the encoder anytime there is raw encoded data ready to write. It may
  90831. * include metadata mixed with encoded audio frames and the data is not
  90832. * guaranteed to be aligned on frame or metadata block boundaries.
  90833. *
  90834. * The only duty of the callback is to write out the \a bytes worth of data
  90835. * in \a buffer to the current position in the output stream. The arguments
  90836. * \a samples and \a current_frame are purely informational. If \a samples
  90837. * is greater than \c 0, then \a current_frame will hold the current frame
  90838. * number that is being written; otherwise it indicates that the write
  90839. * callback is being called to write metadata.
  90840. *
  90841. * \note
  90842. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90843. * write callback will be called twice when writing each audio
  90844. * frame; once for the page header, and once for the page body.
  90845. * When writing the page header, the \a samples argument to the
  90846. * write callback will be \c 0.
  90847. *
  90848. * \note In general, FLAC__StreamEncoder functions which change the
  90849. * state should not be called on the \a encoder while in the callback.
  90850. *
  90851. * \param encoder The encoder instance calling the callback.
  90852. * \param buffer An array of encoded data of length \a bytes.
  90853. * \param bytes The byte length of \a buffer.
  90854. * \param samples The number of samples encoded by \a buffer.
  90855. * \c 0 has a special meaning; see above.
  90856. * \param current_frame The number of the current frame being encoded.
  90857. * \param client_data The callee's client data set through
  90858. * FLAC__stream_encoder_init_*().
  90859. * \retval FLAC__StreamEncoderWriteStatus
  90860. * The callee's return status.
  90861. */
  90862. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90863. /** Signature for the seek callback.
  90864. *
  90865. * A function pointer matching this signature may be passed to
  90866. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90867. * when the encoder needs to seek the output stream. The encoder will pass
  90868. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90869. *
  90870. * Here is an example of a seek callback for stdio streams:
  90871. * \code
  90872. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90873. * {
  90874. * FILE *file = ((MyClientData*)client_data)->file;
  90875. * if(file == stdin)
  90876. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90877. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90878. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90879. * else
  90880. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90881. * }
  90882. * \endcode
  90883. *
  90884. * \note In general, FLAC__StreamEncoder functions which change the
  90885. * state should not be called on the \a encoder while in the callback.
  90886. *
  90887. * \param encoder The encoder instance calling the callback.
  90888. * \param absolute_byte_offset The offset from the beginning of the stream
  90889. * to seek to.
  90890. * \param client_data The callee's client data set through
  90891. * FLAC__stream_encoder_init_*().
  90892. * \retval FLAC__StreamEncoderSeekStatus
  90893. * The callee's return status.
  90894. */
  90895. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90896. /** Signature for the tell callback.
  90897. *
  90898. * A function pointer matching this signature may be passed to
  90899. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90900. * when the encoder needs to know the current position of the output stream.
  90901. *
  90902. * \warning
  90903. * The callback must return the true current byte offset of the output to
  90904. * which the encoder is writing. If you are buffering the output, make
  90905. * sure and take this into account. If you are writing directly to a
  90906. * FILE* from your write callback, ftell() is sufficient. If you are
  90907. * writing directly to a file descriptor from your write callback, you
  90908. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90909. * these points to rewrite metadata after encoding.
  90910. *
  90911. * Here is an example of a tell callback for stdio streams:
  90912. * \code
  90913. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90914. * {
  90915. * FILE *file = ((MyClientData*)client_data)->file;
  90916. * off_t pos;
  90917. * if(file == stdin)
  90918. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90919. * else if((pos = ftello(file)) < 0)
  90920. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90921. * else {
  90922. * *absolute_byte_offset = (FLAC__uint64)pos;
  90923. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90924. * }
  90925. * }
  90926. * \endcode
  90927. *
  90928. * \note In general, FLAC__StreamEncoder functions which change the
  90929. * state should not be called on the \a encoder while in the callback.
  90930. *
  90931. * \param encoder The encoder instance calling the callback.
  90932. * \param absolute_byte_offset The address at which to store the current
  90933. * position of the output.
  90934. * \param client_data The callee's client data set through
  90935. * FLAC__stream_encoder_init_*().
  90936. * \retval FLAC__StreamEncoderTellStatus
  90937. * The callee's return status.
  90938. */
  90939. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90940. /** Signature for the metadata callback.
  90941. *
  90942. * A function pointer matching this signature may be passed to
  90943. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90944. * once at the end of encoding with the populated STREAMINFO structure. This
  90945. * is so the client can seek back to the beginning of the file and write the
  90946. * STREAMINFO block with the correct statistics after encoding (like
  90947. * minimum/maximum frame size and total samples).
  90948. *
  90949. * \note In general, FLAC__StreamEncoder functions which change the
  90950. * state should not be called on the \a encoder while in the callback.
  90951. *
  90952. * \param encoder The encoder instance calling the callback.
  90953. * \param metadata The final populated STREAMINFO block.
  90954. * \param client_data The callee's client data set through
  90955. * FLAC__stream_encoder_init_*().
  90956. */
  90957. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90958. /** Signature for the progress callback.
  90959. *
  90960. * A function pointer matching this signature may be passed to
  90961. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90962. * The supplied function will be called when the encoder has finished
  90963. * writing a frame. The \c total_frames_estimate argument to the
  90964. * callback will be based on the value from
  90965. * FLAC__stream_encoder_set_total_samples_estimate().
  90966. *
  90967. * \note In general, FLAC__StreamEncoder functions which change the
  90968. * state should not be called on the \a encoder while in the callback.
  90969. *
  90970. * \param encoder The encoder instance calling the callback.
  90971. * \param bytes_written Bytes written so far.
  90972. * \param samples_written Samples written so far.
  90973. * \param frames_written Frames written so far.
  90974. * \param total_frames_estimate The estimate of the total number of
  90975. * frames to be written.
  90976. * \param client_data The callee's client data set through
  90977. * FLAC__stream_encoder_init_*().
  90978. */
  90979. 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);
  90980. /***********************************************************************
  90981. *
  90982. * Class constructor/destructor
  90983. *
  90984. ***********************************************************************/
  90985. /** Create a new stream encoder instance. The instance is created with
  90986. * default settings; see the individual FLAC__stream_encoder_set_*()
  90987. * functions for each setting's default.
  90988. *
  90989. * \retval FLAC__StreamEncoder*
  90990. * \c NULL if there was an error allocating memory, else the new instance.
  90991. */
  90992. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90993. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90994. *
  90995. * \param encoder A pointer to an existing encoder.
  90996. * \assert
  90997. * \code encoder != NULL \endcode
  90998. */
  90999. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91000. /***********************************************************************
  91001. *
  91002. * Public class method prototypes
  91003. *
  91004. ***********************************************************************/
  91005. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91006. *
  91007. * \note
  91008. * This does not need to be set for native FLAC encoding.
  91009. *
  91010. * \note
  91011. * It is recommended to set a serial number explicitly as the default of '0'
  91012. * may collide with other streams.
  91013. *
  91014. * \default \c 0
  91015. * \param encoder An encoder instance to set.
  91016. * \param serial_number See above.
  91017. * \assert
  91018. * \code encoder != NULL \endcode
  91019. * \retval FLAC__bool
  91020. * \c false if the encoder is already initialized, else \c true.
  91021. */
  91022. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91023. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91024. * encoded output by feeding it through an internal decoder and comparing
  91025. * the original signal against the decoded signal. If a mismatch occurs,
  91026. * the process call will return \c false. Note that this will slow the
  91027. * encoding process by the extra time required for decoding and comparison.
  91028. *
  91029. * \default \c false
  91030. * \param encoder An encoder instance to set.
  91031. * \param value Flag value (see above).
  91032. * \assert
  91033. * \code encoder != NULL \endcode
  91034. * \retval FLAC__bool
  91035. * \c false if the encoder is already initialized, else \c true.
  91036. */
  91037. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91038. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91039. * the encoder will comply with the Subset and will check the
  91040. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91041. * comply. If \c false, the settings may take advantage of the full
  91042. * range that the format allows.
  91043. *
  91044. * Make sure you know what it entails before setting this to \c false.
  91045. *
  91046. * \default \c true
  91047. * \param encoder An encoder instance to set.
  91048. * \param value Flag value (see above).
  91049. * \assert
  91050. * \code encoder != NULL \endcode
  91051. * \retval FLAC__bool
  91052. * \c false if the encoder is already initialized, else \c true.
  91053. */
  91054. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91055. /** Set the number of channels to be encoded.
  91056. *
  91057. * \default \c 2
  91058. * \param encoder An encoder instance to set.
  91059. * \param value See above.
  91060. * \assert
  91061. * \code encoder != NULL \endcode
  91062. * \retval FLAC__bool
  91063. * \c false if the encoder is already initialized, else \c true.
  91064. */
  91065. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91066. /** Set the sample resolution of the input to be encoded.
  91067. *
  91068. * \warning
  91069. * Do not feed the encoder data that is wider than the value you
  91070. * set here or you will generate an invalid stream.
  91071. *
  91072. * \default \c 16
  91073. * \param encoder An encoder instance to set.
  91074. * \param value See above.
  91075. * \assert
  91076. * \code encoder != NULL \endcode
  91077. * \retval FLAC__bool
  91078. * \c false if the encoder is already initialized, else \c true.
  91079. */
  91080. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91081. /** Set the sample rate (in Hz) of the input to be encoded.
  91082. *
  91083. * \default \c 44100
  91084. * \param encoder An encoder instance to set.
  91085. * \param value See above.
  91086. * \assert
  91087. * \code encoder != NULL \endcode
  91088. * \retval FLAC__bool
  91089. * \c false if the encoder is already initialized, else \c true.
  91090. */
  91091. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91092. /** Set the compression level
  91093. *
  91094. * The compression level is roughly proportional to the amount of effort
  91095. * the encoder expends to compress the file. A higher level usually
  91096. * means more computation but higher compression. The default level is
  91097. * suitable for most applications.
  91098. *
  91099. * Currently the levels range from \c 0 (fastest, least compression) to
  91100. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91101. * treated as \c 8.
  91102. *
  91103. * This function automatically calls the following other \c _set_
  91104. * functions with appropriate values, so the client does not need to
  91105. * unless it specifically wants to override them:
  91106. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91107. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91108. * - FLAC__stream_encoder_set_apodization()
  91109. * - FLAC__stream_encoder_set_max_lpc_order()
  91110. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91111. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91112. * - FLAC__stream_encoder_set_do_escape_coding()
  91113. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91114. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91115. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91116. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91117. *
  91118. * The actual values set for each level are:
  91119. * <table>
  91120. * <tr>
  91121. * <td><b>level</b><td>
  91122. * <td>do mid-side stereo<td>
  91123. * <td>loose mid-side stereo<td>
  91124. * <td>apodization<td>
  91125. * <td>max lpc order<td>
  91126. * <td>qlp coeff precision<td>
  91127. * <td>qlp coeff prec search<td>
  91128. * <td>escape coding<td>
  91129. * <td>exhaustive model search<td>
  91130. * <td>min residual partition order<td>
  91131. * <td>max residual partition order<td>
  91132. * <td>rice parameter search dist<td>
  91133. * </tr>
  91134. * <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>
  91135. * <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>
  91136. * <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>
  91137. * <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>
  91138. * <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>
  91139. * <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>
  91140. * <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>
  91141. * <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>
  91142. * <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>
  91143. * </table>
  91144. *
  91145. * \default \c 5
  91146. * \param encoder An encoder instance to set.
  91147. * \param value See above.
  91148. * \assert
  91149. * \code encoder != NULL \endcode
  91150. * \retval FLAC__bool
  91151. * \c false if the encoder is already initialized, else \c true.
  91152. */
  91153. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91154. /** Set the blocksize to use while encoding.
  91155. *
  91156. * The number of samples to use per frame. Use \c 0 to let the encoder
  91157. * estimate a blocksize; this is usually best.
  91158. *
  91159. * \default \c 0
  91160. * \param encoder An encoder instance to set.
  91161. * \param value See above.
  91162. * \assert
  91163. * \code encoder != NULL \endcode
  91164. * \retval FLAC__bool
  91165. * \c false if the encoder is already initialized, else \c true.
  91166. */
  91167. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91168. /** Set to \c true to enable mid-side encoding on stereo input. The
  91169. * number of channels must be 2 for this to have any effect. Set to
  91170. * \c false to use only independent channel coding.
  91171. *
  91172. * \default \c false
  91173. * \param encoder An encoder instance to set.
  91174. * \param value Flag value (see above).
  91175. * \assert
  91176. * \code encoder != NULL \endcode
  91177. * \retval FLAC__bool
  91178. * \c false if the encoder is already initialized, else \c true.
  91179. */
  91180. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91181. /** Set to \c true to enable adaptive switching between mid-side and
  91182. * left-right encoding on stereo input. Set to \c false to use
  91183. * exhaustive searching. Setting this to \c true requires
  91184. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91185. * \c true in order to have any effect.
  91186. *
  91187. * \default \c false
  91188. * \param encoder An encoder instance to set.
  91189. * \param value Flag value (see above).
  91190. * \assert
  91191. * \code encoder != NULL \endcode
  91192. * \retval FLAC__bool
  91193. * \c false if the encoder is already initialized, else \c true.
  91194. */
  91195. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91196. /** Sets the apodization function(s) the encoder will use when windowing
  91197. * audio data for LPC analysis.
  91198. *
  91199. * The \a specification is a plain ASCII string which specifies exactly
  91200. * which functions to use. There may be more than one (up to 32),
  91201. * separated by \c ';' characters. Some functions take one or more
  91202. * comma-separated arguments in parentheses.
  91203. *
  91204. * The available functions are \c bartlett, \c bartlett_hann,
  91205. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91206. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91207. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91208. *
  91209. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91210. * (0<STDDEV<=0.5).
  91211. *
  91212. * For \c tukey(P), P specifies the fraction of the window that is
  91213. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91214. * corresponds to \c hann.
  91215. *
  91216. * Example specifications are \c "blackman" or
  91217. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91218. *
  91219. * Any function that is specified erroneously is silently dropped. Up
  91220. * to 32 functions are kept, the rest are dropped. If the specification
  91221. * is empty the encoder defaults to \c "tukey(0.5)".
  91222. *
  91223. * When more than one function is specified, then for every subframe the
  91224. * encoder will try each of them separately and choose the window that
  91225. * results in the smallest compressed subframe.
  91226. *
  91227. * Note that each function specified causes the encoder to occupy a
  91228. * floating point array in which to store the window.
  91229. *
  91230. * \default \c "tukey(0.5)"
  91231. * \param encoder An encoder instance to set.
  91232. * \param specification See above.
  91233. * \assert
  91234. * \code encoder != NULL \endcode
  91235. * \code specification != NULL \endcode
  91236. * \retval FLAC__bool
  91237. * \c false if the encoder is already initialized, else \c true.
  91238. */
  91239. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91240. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91241. *
  91242. * \default \c 0
  91243. * \param encoder An encoder instance to set.
  91244. * \param value See above.
  91245. * \assert
  91246. * \code encoder != NULL \endcode
  91247. * \retval FLAC__bool
  91248. * \c false if the encoder is already initialized, else \c true.
  91249. */
  91250. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91251. /** Set the precision, in bits, of the quantized linear predictor
  91252. * coefficients, or \c 0 to let the encoder select it based on the
  91253. * blocksize.
  91254. *
  91255. * \note
  91256. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91257. * be less than 32.
  91258. *
  91259. * \default \c 0
  91260. * \param encoder An encoder instance to set.
  91261. * \param value See above.
  91262. * \assert
  91263. * \code encoder != NULL \endcode
  91264. * \retval FLAC__bool
  91265. * \c false if the encoder is already initialized, else \c true.
  91266. */
  91267. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91268. /** Set to \c false to use only the specified quantized linear predictor
  91269. * coefficient precision, or \c true to search neighboring precision
  91270. * values and use the best one.
  91271. *
  91272. * \default \c false
  91273. * \param encoder An encoder instance to set.
  91274. * \param value See above.
  91275. * \assert
  91276. * \code encoder != NULL \endcode
  91277. * \retval FLAC__bool
  91278. * \c false if the encoder is already initialized, else \c true.
  91279. */
  91280. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91281. /** Deprecated. Setting this value has no effect.
  91282. *
  91283. * \default \c false
  91284. * \param encoder An encoder instance to set.
  91285. * \param value See above.
  91286. * \assert
  91287. * \code encoder != NULL \endcode
  91288. * \retval FLAC__bool
  91289. * \c false if the encoder is already initialized, else \c true.
  91290. */
  91291. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91292. /** Set to \c false to let the encoder estimate the best model order
  91293. * based on the residual signal energy, or \c true to force the
  91294. * encoder to evaluate all order models and select the best.
  91295. *
  91296. * \default \c false
  91297. * \param encoder An encoder instance to set.
  91298. * \param value See above.
  91299. * \assert
  91300. * \code encoder != NULL \endcode
  91301. * \retval FLAC__bool
  91302. * \c false if the encoder is already initialized, else \c true.
  91303. */
  91304. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91305. /** Set the minimum partition order to search when coding the residual.
  91306. * This is used in tandem with
  91307. * FLAC__stream_encoder_set_max_residual_partition_order().
  91308. *
  91309. * The partition order determines the context size in the residual.
  91310. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91311. *
  91312. * Set both min and max values to \c 0 to force a single context,
  91313. * whose Rice parameter is based on the residual signal variance.
  91314. * Otherwise, set a min and max order, and the encoder will search
  91315. * all orders, using the mean of each context for its Rice parameter,
  91316. * and use the best.
  91317. *
  91318. * \default \c 0
  91319. * \param encoder An encoder instance to set.
  91320. * \param value See above.
  91321. * \assert
  91322. * \code encoder != NULL \endcode
  91323. * \retval FLAC__bool
  91324. * \c false if the encoder is already initialized, else \c true.
  91325. */
  91326. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91327. /** Set the maximum partition order to search when coding the residual.
  91328. * This is used in tandem with
  91329. * FLAC__stream_encoder_set_min_residual_partition_order().
  91330. *
  91331. * The partition order determines the context size in the residual.
  91332. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91333. *
  91334. * Set both min and max values to \c 0 to force a single context,
  91335. * whose Rice parameter is based on the residual signal variance.
  91336. * Otherwise, set a min and max order, and the encoder will search
  91337. * all orders, using the mean of each context for its Rice parameter,
  91338. * and use the best.
  91339. *
  91340. * \default \c 0
  91341. * \param encoder An encoder instance to set.
  91342. * \param value See above.
  91343. * \assert
  91344. * \code encoder != NULL \endcode
  91345. * \retval FLAC__bool
  91346. * \c false if the encoder is already initialized, else \c true.
  91347. */
  91348. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91349. /** Deprecated. Setting this value has no effect.
  91350. *
  91351. * \default \c 0
  91352. * \param encoder An encoder instance to set.
  91353. * \param value See above.
  91354. * \assert
  91355. * \code encoder != NULL \endcode
  91356. * \retval FLAC__bool
  91357. * \c false if the encoder is already initialized, else \c true.
  91358. */
  91359. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91360. /** Set an estimate of the total samples that will be encoded.
  91361. * This is merely an estimate and may be set to \c 0 if unknown.
  91362. * This value will be written to the STREAMINFO block before encoding,
  91363. * and can remove the need for the caller to rewrite the value later
  91364. * if the value is known before encoding.
  91365. *
  91366. * \default \c 0
  91367. * \param encoder An encoder instance to set.
  91368. * \param value See above.
  91369. * \assert
  91370. * \code encoder != NULL \endcode
  91371. * \retval FLAC__bool
  91372. * \c false if the encoder is already initialized, else \c true.
  91373. */
  91374. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91375. /** Set the metadata blocks to be emitted to the stream before encoding.
  91376. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91377. * array of pointers to metadata blocks. The array is non-const since
  91378. * the encoder may need to change the \a is_last flag inside them, and
  91379. * in some cases update seek point offsets. Otherwise, the encoder will
  91380. * not modify or free the blocks. It is up to the caller to free the
  91381. * metadata blocks after encoding finishes.
  91382. *
  91383. * \note
  91384. * The encoder stores only copies of the pointers in the \a metadata array;
  91385. * the metadata blocks themselves must survive at least until after
  91386. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91387. *
  91388. * \note
  91389. * The STREAMINFO block is always written and no STREAMINFO block may
  91390. * occur in the supplied array.
  91391. *
  91392. * \note
  91393. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91394. * in the \a metadata array, but the client has specified that it does not
  91395. * support seeking, then the SEEKTABLE will be written verbatim. However
  91396. * by itself this is not very useful as the client will not know the stream
  91397. * offsets for the seekpoints ahead of time. In order to get a proper
  91398. * seektable the client must support seeking. See next note.
  91399. *
  91400. * \note
  91401. * SEEKTABLE blocks are handled specially. Since you will not know
  91402. * the values for the seek point stream offsets, you should pass in
  91403. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91404. * required sample numbers (or placeholder points), with \c 0 for the
  91405. * \a frame_samples and \a stream_offset fields for each point. If the
  91406. * client has specified that it supports seeking by providing a seek
  91407. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91408. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91409. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91410. * then while it is encoding the encoder will fill the stream offsets in
  91411. * for you and when encoding is finished, it will seek back and write the
  91412. * real values into the SEEKTABLE block in the stream. There are helper
  91413. * routines for manipulating seektable template blocks; see metadata.h:
  91414. * FLAC__metadata_object_seektable_template_*(). If the client does
  91415. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91416. * will slow down or remove the ability to seek in the FLAC stream.
  91417. *
  91418. * \note
  91419. * The encoder instance \b will modify the first \c SEEKTABLE block
  91420. * as it transforms the template to a valid seektable while encoding,
  91421. * but it is still up to the caller to free all metadata blocks after
  91422. * encoding.
  91423. *
  91424. * \note
  91425. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91426. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91427. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91428. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91429. * block is present in the \a metadata array, libFLAC will write an
  91430. * empty one, containing only the vendor string.
  91431. *
  91432. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91433. * the second metadata block of the stream. The encoder already supplies
  91434. * the STREAMINFO block automatically. If \a metadata does not contain a
  91435. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91436. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91437. * first, the init function will reorder \a metadata by moving the
  91438. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91439. * blocks will remain as they were.
  91440. *
  91441. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91442. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91443. * return \c false.
  91444. *
  91445. * \default \c NULL, 0
  91446. * \param encoder An encoder instance to set.
  91447. * \param metadata See above.
  91448. * \param num_blocks See above.
  91449. * \assert
  91450. * \code encoder != NULL \endcode
  91451. * \retval FLAC__bool
  91452. * \c false if the encoder is already initialized, else \c true.
  91453. * \c false if the encoder is already initialized, or if
  91454. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91455. */
  91456. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91457. /** Get the current encoder state.
  91458. *
  91459. * \param encoder An encoder instance to query.
  91460. * \assert
  91461. * \code encoder != NULL \endcode
  91462. * \retval FLAC__StreamEncoderState
  91463. * The current encoder state.
  91464. */
  91465. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91466. /** Get the state of the verify stream decoder.
  91467. * Useful when the stream encoder state is
  91468. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91469. *
  91470. * \param encoder An encoder instance to query.
  91471. * \assert
  91472. * \code encoder != NULL \endcode
  91473. * \retval FLAC__StreamDecoderState
  91474. * The verify stream decoder state.
  91475. */
  91476. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91477. /** Get the current encoder state as a C string.
  91478. * This version automatically resolves
  91479. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91480. * verify decoder's state.
  91481. *
  91482. * \param encoder A encoder instance to query.
  91483. * \assert
  91484. * \code encoder != NULL \endcode
  91485. * \retval const char *
  91486. * The encoder state as a C string. Do not modify the contents.
  91487. */
  91488. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91489. /** Get relevant values about the nature of a verify decoder error.
  91490. * Useful when the stream encoder state is
  91491. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91492. * be addresses in which the stats will be returned, or NULL if value
  91493. * is not desired.
  91494. *
  91495. * \param encoder An encoder instance to query.
  91496. * \param absolute_sample The absolute sample number of the mismatch.
  91497. * \param frame_number The number of the frame in which the mismatch occurred.
  91498. * \param channel The channel in which the mismatch occurred.
  91499. * \param sample The number of the sample (relative to the frame) in
  91500. * which the mismatch occurred.
  91501. * \param expected The expected value for the sample in question.
  91502. * \param got The actual value returned by the decoder.
  91503. * \assert
  91504. * \code encoder != NULL \endcode
  91505. */
  91506. 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);
  91507. /** Get the "verify" flag.
  91508. *
  91509. * \param encoder An encoder instance to query.
  91510. * \assert
  91511. * \code encoder != NULL \endcode
  91512. * \retval FLAC__bool
  91513. * See FLAC__stream_encoder_set_verify().
  91514. */
  91515. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91516. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91517. *
  91518. * \param encoder An encoder instance to query.
  91519. * \assert
  91520. * \code encoder != NULL \endcode
  91521. * \retval FLAC__bool
  91522. * See FLAC__stream_encoder_set_streamable_subset().
  91523. */
  91524. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91525. /** Get the number of input channels being processed.
  91526. *
  91527. * \param encoder An encoder instance to query.
  91528. * \assert
  91529. * \code encoder != NULL \endcode
  91530. * \retval unsigned
  91531. * See FLAC__stream_encoder_set_channels().
  91532. */
  91533. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91534. /** Get the input sample resolution setting.
  91535. *
  91536. * \param encoder An encoder instance to query.
  91537. * \assert
  91538. * \code encoder != NULL \endcode
  91539. * \retval unsigned
  91540. * See FLAC__stream_encoder_set_bits_per_sample().
  91541. */
  91542. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91543. /** Get the input sample rate setting.
  91544. *
  91545. * \param encoder An encoder instance to query.
  91546. * \assert
  91547. * \code encoder != NULL \endcode
  91548. * \retval unsigned
  91549. * See FLAC__stream_encoder_set_sample_rate().
  91550. */
  91551. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91552. /** Get the blocksize setting.
  91553. *
  91554. * \param encoder An encoder instance to query.
  91555. * \assert
  91556. * \code encoder != NULL \endcode
  91557. * \retval unsigned
  91558. * See FLAC__stream_encoder_set_blocksize().
  91559. */
  91560. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91561. /** Get the "mid/side stereo coding" flag.
  91562. *
  91563. * \param encoder An encoder instance to query.
  91564. * \assert
  91565. * \code encoder != NULL \endcode
  91566. * \retval FLAC__bool
  91567. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91568. */
  91569. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91570. /** Get the "adaptive mid/side switching" flag.
  91571. *
  91572. * \param encoder An encoder instance to query.
  91573. * \assert
  91574. * \code encoder != NULL \endcode
  91575. * \retval FLAC__bool
  91576. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91577. */
  91578. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91579. /** Get the maximum LPC order setting.
  91580. *
  91581. * \param encoder An encoder instance to query.
  91582. * \assert
  91583. * \code encoder != NULL \endcode
  91584. * \retval unsigned
  91585. * See FLAC__stream_encoder_set_max_lpc_order().
  91586. */
  91587. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91588. /** Get the quantized linear predictor coefficient precision setting.
  91589. *
  91590. * \param encoder An encoder instance to query.
  91591. * \assert
  91592. * \code encoder != NULL \endcode
  91593. * \retval unsigned
  91594. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91595. */
  91596. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91597. /** Get the qlp coefficient precision search flag.
  91598. *
  91599. * \param encoder An encoder instance to query.
  91600. * \assert
  91601. * \code encoder != NULL \endcode
  91602. * \retval FLAC__bool
  91603. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91604. */
  91605. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91606. /** Get the "escape coding" flag.
  91607. *
  91608. * \param encoder An encoder instance to query.
  91609. * \assert
  91610. * \code encoder != NULL \endcode
  91611. * \retval FLAC__bool
  91612. * See FLAC__stream_encoder_set_do_escape_coding().
  91613. */
  91614. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91615. /** Get the exhaustive model search flag.
  91616. *
  91617. * \param encoder An encoder instance to query.
  91618. * \assert
  91619. * \code encoder != NULL \endcode
  91620. * \retval FLAC__bool
  91621. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91622. */
  91623. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91624. /** Get the minimum residual partition order setting.
  91625. *
  91626. * \param encoder An encoder instance to query.
  91627. * \assert
  91628. * \code encoder != NULL \endcode
  91629. * \retval unsigned
  91630. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91631. */
  91632. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91633. /** Get maximum residual partition order setting.
  91634. *
  91635. * \param encoder An encoder instance to query.
  91636. * \assert
  91637. * \code encoder != NULL \endcode
  91638. * \retval unsigned
  91639. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91640. */
  91641. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91642. /** Get the Rice parameter search distance setting.
  91643. *
  91644. * \param encoder An encoder instance to query.
  91645. * \assert
  91646. * \code encoder != NULL \endcode
  91647. * \retval unsigned
  91648. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91649. */
  91650. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91651. /** Get the previously set estimate of the total samples to be encoded.
  91652. * The encoder merely mimics back the value given to
  91653. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91654. * other way of knowing how many samples the client will encode.
  91655. *
  91656. * \param encoder An encoder instance to set.
  91657. * \assert
  91658. * \code encoder != NULL \endcode
  91659. * \retval FLAC__uint64
  91660. * See FLAC__stream_encoder_get_total_samples_estimate().
  91661. */
  91662. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91663. /** Initialize the encoder instance to encode native FLAC streams.
  91664. *
  91665. * This flavor of initialization sets up the encoder to encode to a
  91666. * native FLAC stream. I/O is performed via callbacks to the client.
  91667. * For encoding to a plain file via filename or open \c FILE*,
  91668. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91669. * provide a simpler interface.
  91670. *
  91671. * This function should be called after FLAC__stream_encoder_new() and
  91672. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91673. * or FLAC__stream_encoder_process_interleaved().
  91674. * initialization succeeded.
  91675. *
  91676. * The call to FLAC__stream_encoder_init_stream() currently will also
  91677. * immediately call the write callback several times, once with the \c fLaC
  91678. * signature, and once for each encoded metadata block.
  91679. *
  91680. * \param encoder An uninitialized encoder instance.
  91681. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91682. * pointer must not be \c NULL.
  91683. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91684. * pointer may be \c NULL if seeking is not
  91685. * supported. The encoder uses seeking to go back
  91686. * and write some some stream statistics to the
  91687. * STREAMINFO block; this is recommended but not
  91688. * necessary to create a valid FLAC stream. If
  91689. * \a seek_callback is not \c NULL then a
  91690. * \a tell_callback must also be supplied.
  91691. * Alternatively, a dummy seek callback that just
  91692. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91693. * may also be supplied, all though this is slightly
  91694. * less efficient for the encoder.
  91695. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91696. * pointer may be \c NULL if seeking is not
  91697. * supported. If \a seek_callback is \c NULL then
  91698. * this argument will be ignored. If
  91699. * \a seek_callback is not \c NULL then a
  91700. * \a tell_callback must also be supplied.
  91701. * Alternatively, a dummy tell callback that just
  91702. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91703. * may also be supplied, all though this is slightly
  91704. * less efficient for the encoder.
  91705. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91706. * pointer may be \c NULL if the callback is not
  91707. * desired. If the client provides a seek callback,
  91708. * this function is not necessary as the encoder
  91709. * will automatically seek back and update the
  91710. * STREAMINFO block. It may also be \c NULL if the
  91711. * client does not support seeking, since it will
  91712. * have no way of going back to update the
  91713. * STREAMINFO. However the client can still supply
  91714. * a callback if it would like to know the details
  91715. * from the STREAMINFO.
  91716. * \param client_data This value will be supplied to callbacks in their
  91717. * \a client_data argument.
  91718. * \assert
  91719. * \code encoder != NULL \endcode
  91720. * \retval FLAC__StreamEncoderInitStatus
  91721. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91722. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91723. */
  91724. 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);
  91725. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91726. *
  91727. * This flavor of initialization sets up the encoder to encode to a FLAC
  91728. * stream in an Ogg container. I/O is performed via callbacks to the
  91729. * client. For encoding to a plain file via filename or open \c FILE*,
  91730. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91731. * provide a simpler interface.
  91732. *
  91733. * This function should be called after FLAC__stream_encoder_new() and
  91734. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91735. * or FLAC__stream_encoder_process_interleaved().
  91736. * initialization succeeded.
  91737. *
  91738. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91739. * immediately call the write callback several times to write the metadata
  91740. * packets.
  91741. *
  91742. * \param encoder An uninitialized encoder instance.
  91743. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91744. * pointer must not be \c NULL if \a seek_callback
  91745. * is non-NULL since they are both needed to be
  91746. * able to write data back to the Ogg FLAC stream
  91747. * in the post-encode phase.
  91748. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91749. * pointer must not be \c NULL.
  91750. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91751. * pointer may be \c NULL if seeking is not
  91752. * supported. The encoder uses seeking to go back
  91753. * and write some some stream statistics to the
  91754. * STREAMINFO block; this is recommended but not
  91755. * necessary to create a valid FLAC stream. If
  91756. * \a seek_callback is not \c NULL then a
  91757. * \a tell_callback must also be supplied.
  91758. * Alternatively, a dummy seek callback that just
  91759. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91760. * may also be supplied, all though this is slightly
  91761. * less efficient for the encoder.
  91762. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91763. * pointer may be \c NULL if seeking is not
  91764. * supported. If \a seek_callback is \c NULL then
  91765. * this argument will be ignored. If
  91766. * \a seek_callback is not \c NULL then a
  91767. * \a tell_callback must also be supplied.
  91768. * Alternatively, a dummy tell callback that just
  91769. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91770. * may also be supplied, all though this is slightly
  91771. * less efficient for the encoder.
  91772. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91773. * pointer may be \c NULL if the callback is not
  91774. * desired. If the client provides a seek callback,
  91775. * this function is not necessary as the encoder
  91776. * will automatically seek back and update the
  91777. * STREAMINFO block. It may also be \c NULL if the
  91778. * client does not support seeking, since it will
  91779. * have no way of going back to update the
  91780. * STREAMINFO. However the client can still supply
  91781. * a callback if it would like to know the details
  91782. * from the STREAMINFO.
  91783. * \param client_data This value will be supplied to callbacks in their
  91784. * \a client_data argument.
  91785. * \assert
  91786. * \code encoder != NULL \endcode
  91787. * \retval FLAC__StreamEncoderInitStatus
  91788. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91789. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91790. */
  91791. 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);
  91792. /** Initialize the encoder instance to encode native FLAC files.
  91793. *
  91794. * This flavor of initialization sets up the encoder to encode to a
  91795. * plain native FLAC file. For non-stdio streams, you must use
  91796. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91797. *
  91798. * This function should be called after FLAC__stream_encoder_new() and
  91799. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91800. * or FLAC__stream_encoder_process_interleaved().
  91801. * initialization succeeded.
  91802. *
  91803. * \param encoder An uninitialized encoder instance.
  91804. * \param file An open file. The file should have been opened
  91805. * with mode \c "w+b" and rewound. The file
  91806. * becomes owned by the encoder and should not be
  91807. * manipulated by the client while encoding.
  91808. * Unless \a file is \c stdout, it will be closed
  91809. * when FLAC__stream_encoder_finish() is called.
  91810. * Note however that a proper SEEKTABLE cannot be
  91811. * created when encoding to \c stdout since it is
  91812. * not seekable.
  91813. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91814. * pointer may be \c NULL if the callback is not
  91815. * desired.
  91816. * \param client_data This value will be supplied to callbacks in their
  91817. * \a client_data argument.
  91818. * \assert
  91819. * \code encoder != NULL \endcode
  91820. * \code file != NULL \endcode
  91821. * \retval FLAC__StreamEncoderInitStatus
  91822. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91823. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91824. */
  91825. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91826. /** Initialize the encoder instance to encode Ogg FLAC files.
  91827. *
  91828. * This flavor of initialization sets up the encoder to encode to a
  91829. * plain Ogg FLAC file. For non-stdio streams, you must use
  91830. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91831. *
  91832. * This function should be called after FLAC__stream_encoder_new() and
  91833. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91834. * or FLAC__stream_encoder_process_interleaved().
  91835. * initialization succeeded.
  91836. *
  91837. * \param encoder An uninitialized encoder instance.
  91838. * \param file An open file. The file should have been opened
  91839. * with mode \c "w+b" and rewound. The file
  91840. * becomes owned by the encoder and should not be
  91841. * manipulated by the client while encoding.
  91842. * Unless \a file is \c stdout, it will be closed
  91843. * when FLAC__stream_encoder_finish() is called.
  91844. * Note however that a proper SEEKTABLE cannot be
  91845. * created when encoding to \c stdout since it is
  91846. * not seekable.
  91847. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91848. * pointer may be \c NULL if the callback is not
  91849. * desired.
  91850. * \param client_data This value will be supplied to callbacks in their
  91851. * \a client_data argument.
  91852. * \assert
  91853. * \code encoder != NULL \endcode
  91854. * \code file != NULL \endcode
  91855. * \retval FLAC__StreamEncoderInitStatus
  91856. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91857. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91858. */
  91859. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91860. /** Initialize the encoder instance to encode native FLAC files.
  91861. *
  91862. * This flavor of initialization sets up the encoder to encode to a plain
  91863. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91864. * with Unicode filenames on Windows), you must use
  91865. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91866. * and provide callbacks for the I/O.
  91867. *
  91868. * This function should be called after FLAC__stream_encoder_new() and
  91869. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91870. * or FLAC__stream_encoder_process_interleaved().
  91871. * initialization succeeded.
  91872. *
  91873. * \param encoder An uninitialized encoder instance.
  91874. * \param filename The name of the file to encode to. The file will
  91875. * be opened with fopen(). Use \c NULL to encode to
  91876. * \c stdout. Note however that a proper SEEKTABLE
  91877. * cannot be created when encoding to \c stdout since
  91878. * it is not seekable.
  91879. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91880. * pointer may be \c NULL if the callback is not
  91881. * desired.
  91882. * \param client_data This value will be supplied to callbacks in their
  91883. * \a client_data argument.
  91884. * \assert
  91885. * \code encoder != NULL \endcode
  91886. * \retval FLAC__StreamEncoderInitStatus
  91887. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91888. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91889. */
  91890. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91891. /** Initialize the encoder instance to encode Ogg FLAC files.
  91892. *
  91893. * This flavor of initialization sets up the encoder to encode to a plain
  91894. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91895. * with Unicode filenames on Windows), you must use
  91896. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91897. * and provide callbacks for the I/O.
  91898. *
  91899. * This function should be called after FLAC__stream_encoder_new() and
  91900. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91901. * or FLAC__stream_encoder_process_interleaved().
  91902. * initialization succeeded.
  91903. *
  91904. * \param encoder An uninitialized encoder instance.
  91905. * \param filename The name of the file to encode to. The file will
  91906. * be opened with fopen(). Use \c NULL to encode to
  91907. * \c stdout. Note however that a proper SEEKTABLE
  91908. * cannot be created when encoding to \c stdout since
  91909. * it is not seekable.
  91910. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91911. * pointer may be \c NULL if the callback is not
  91912. * desired.
  91913. * \param client_data This value will be supplied to callbacks in their
  91914. * \a client_data argument.
  91915. * \assert
  91916. * \code encoder != NULL \endcode
  91917. * \retval FLAC__StreamEncoderInitStatus
  91918. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91919. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91920. */
  91921. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91922. /** Finish the encoding process.
  91923. * Flushes the encoding buffer, releases resources, resets the encoder
  91924. * settings to their defaults, and returns the encoder state to
  91925. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91926. * one or more write callbacks before returning, and will generate
  91927. * a metadata callback.
  91928. *
  91929. * Note that in the course of processing the last frame, errors can
  91930. * occur, so the caller should be sure to check the return value to
  91931. * ensure the file was encoded properly.
  91932. *
  91933. * In the event of a prematurely-terminated encode, it is not strictly
  91934. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91935. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91936. * with a FLAC__stream_encoder_finish().
  91937. *
  91938. * \param encoder An uninitialized encoder instance.
  91939. * \assert
  91940. * \code encoder != NULL \endcode
  91941. * \retval FLAC__bool
  91942. * \c false if an error occurred processing the last frame; or if verify
  91943. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91944. * verify mismatch; else \c true. If \c false, caller should check the
  91945. * state with FLAC__stream_encoder_get_state() for more information
  91946. * about the error.
  91947. */
  91948. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91949. /** Submit data for encoding.
  91950. * This version allows you to supply the input data via an array of
  91951. * pointers, each pointer pointing to an array of \a samples samples
  91952. * representing one channel. The samples need not be block-aligned,
  91953. * but each channel should have the same number of samples. Each sample
  91954. * should be a signed integer, right-justified to the resolution set by
  91955. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91956. * resolution is 16 bits per sample, the samples should all be in the
  91957. * range [-32768,32767].
  91958. *
  91959. * For applications where channel order is important, channels must
  91960. * follow the order as described in the
  91961. * <A HREF="../format.html#frame_header">frame header</A>.
  91962. *
  91963. * \param encoder An initialized encoder instance in the OK state.
  91964. * \param buffer An array of pointers to each channel's signal.
  91965. * \param samples The number of samples in one channel.
  91966. * \assert
  91967. * \code encoder != NULL \endcode
  91968. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91969. * \retval FLAC__bool
  91970. * \c true if successful, else \c false; in this case, check the
  91971. * encoder state with FLAC__stream_encoder_get_state() to see what
  91972. * went wrong.
  91973. */
  91974. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91975. /** Submit data for encoding.
  91976. * This version allows you to supply the input data where the channels
  91977. * are interleaved into a single array (i.e. channel0_sample0,
  91978. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91979. * The samples need not be block-aligned but they must be
  91980. * sample-aligned, i.e. the first value should be channel0_sample0
  91981. * and the last value channelN_sampleM. Each sample should be a signed
  91982. * integer, right-justified to the resolution set by
  91983. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91984. * resolution is 16 bits per sample, the samples should all be in the
  91985. * range [-32768,32767].
  91986. *
  91987. * For applications where channel order is important, channels must
  91988. * follow the order as described in the
  91989. * <A HREF="../format.html#frame_header">frame header</A>.
  91990. *
  91991. * \param encoder An initialized encoder instance in the OK state.
  91992. * \param buffer An array of channel-interleaved data (see above).
  91993. * \param samples The number of samples in one channel, the same as for
  91994. * FLAC__stream_encoder_process(). For example, if
  91995. * encoding two channels, \c 1000 \a samples corresponds
  91996. * to a \a buffer of 2000 values.
  91997. * \assert
  91998. * \code encoder != NULL \endcode
  91999. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92000. * \retval FLAC__bool
  92001. * \c true if successful, else \c false; in this case, check the
  92002. * encoder state with FLAC__stream_encoder_get_state() to see what
  92003. * went wrong.
  92004. */
  92005. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92006. /* \} */
  92007. #ifdef __cplusplus
  92008. }
  92009. #endif
  92010. #endif
  92011. /*** End of inlined file: stream_encoder.h ***/
  92012. #ifdef _MSC_VER
  92013. /* OPT: an MSVC built-in would be better */
  92014. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92015. {
  92016. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92017. return (x>>16) | (x<<16);
  92018. }
  92019. #endif
  92020. #if defined(_MSC_VER) && defined(_X86_)
  92021. /* OPT: an MSVC built-in would be better */
  92022. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92023. {
  92024. __asm {
  92025. mov edx, start
  92026. mov ecx, len
  92027. test ecx, ecx
  92028. loop1:
  92029. jz done1
  92030. mov eax, [edx]
  92031. bswap eax
  92032. mov [edx], eax
  92033. add edx, 4
  92034. dec ecx
  92035. jmp short loop1
  92036. done1:
  92037. }
  92038. }
  92039. #endif
  92040. /** \mainpage
  92041. *
  92042. * \section intro Introduction
  92043. *
  92044. * This is the documentation for the FLAC C and C++ APIs. It is
  92045. * highly interconnected; this introduction should give you a top
  92046. * level idea of the structure and how to find the information you
  92047. * need. As a prerequisite you should have at least a basic
  92048. * knowledge of the FLAC format, documented
  92049. * <A HREF="../format.html">here</A>.
  92050. *
  92051. * \section c_api FLAC C API
  92052. *
  92053. * The FLAC C API is the interface to libFLAC, a set of structures
  92054. * describing the components of FLAC streams, and functions for
  92055. * encoding and decoding streams, as well as manipulating FLAC
  92056. * metadata in files. The public include files will be installed
  92057. * in your include area (for example /usr/include/FLAC/...).
  92058. *
  92059. * By writing a little code and linking against libFLAC, it is
  92060. * relatively easy to add FLAC support to another program. The
  92061. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92062. * Complete source code of libFLAC as well as the command-line
  92063. * encoder and plugins is available and is a useful source of
  92064. * examples.
  92065. *
  92066. * Aside from encoders and decoders, libFLAC provides a powerful
  92067. * metadata interface for manipulating metadata in FLAC files. It
  92068. * allows the user to add, delete, and modify FLAC metadata blocks
  92069. * and it can automatically take advantage of PADDING blocks to avoid
  92070. * rewriting the entire FLAC file when changing the size of the
  92071. * metadata.
  92072. *
  92073. * libFLAC usually only requires the standard C library and C math
  92074. * library. In particular, threading is not used so there is no
  92075. * dependency on a thread library. However, libFLAC does not use
  92076. * global variables and should be thread-safe.
  92077. *
  92078. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92079. * However the metadata editing interfaces currently have limited
  92080. * read-only support for Ogg FLAC files.
  92081. *
  92082. * \section cpp_api FLAC C++ API
  92083. *
  92084. * The FLAC C++ API is a set of classes that encapsulate the
  92085. * structures and functions in libFLAC. They provide slightly more
  92086. * functionality with respect to metadata but are otherwise
  92087. * equivalent. For the most part, they share the same usage as
  92088. * their counterparts in libFLAC, and the FLAC C API documentation
  92089. * can be used as a supplement. The public include files
  92090. * for the C++ API will be installed in your include area (for
  92091. * example /usr/include/FLAC++/...).
  92092. *
  92093. * libFLAC++ is also licensed under
  92094. * <A HREF="../license.html">Xiph's BSD license</A>.
  92095. *
  92096. * \section getting_started Getting Started
  92097. *
  92098. * A good starting point for learning the API is to browse through
  92099. * the <A HREF="modules.html">modules</A>. Modules are logical
  92100. * groupings of related functions or classes, which correspond roughly
  92101. * to header files or sections of header files. Each module includes a
  92102. * detailed description of the general usage of its functions or
  92103. * classes.
  92104. *
  92105. * From there you can go on to look at the documentation of
  92106. * individual functions. You can see different views of the individual
  92107. * functions through the links in top bar across this page.
  92108. *
  92109. * If you prefer a more hands-on approach, you can jump right to some
  92110. * <A HREF="../documentation_example_code.html">example code</A>.
  92111. *
  92112. * \section porting_guide Porting Guide
  92113. *
  92114. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92115. * has been introduced which gives detailed instructions on how to
  92116. * port your code to newer versions of FLAC.
  92117. *
  92118. * \section embedded_developers Embedded Developers
  92119. *
  92120. * libFLAC has grown larger over time as more functionality has been
  92121. * included, but much of it may be unnecessary for a particular embedded
  92122. * implementation. Unused parts may be pruned by some simple editing of
  92123. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92124. * metadata interface are all independent from each other.
  92125. *
  92126. * It is easiest to just describe the dependencies:
  92127. *
  92128. * - All modules depend on the \link flac_format Format \endlink module.
  92129. * - The decoders and encoders depend on the bitbuffer.
  92130. * - The decoder is independent of the encoder. The encoder uses the
  92131. * decoder because of the verify feature, but this can be removed if
  92132. * not needed.
  92133. * - Parts of the metadata interface require the stream decoder (but not
  92134. * the encoder).
  92135. * - Ogg support is selectable through the compile time macro
  92136. * \c FLAC__HAS_OGG.
  92137. *
  92138. * For example, if your application only requires the stream decoder, no
  92139. * encoder, and no metadata interface, you can remove the stream encoder
  92140. * and the metadata interface, which will greatly reduce the size of the
  92141. * library.
  92142. *
  92143. * Also, there are several places in the libFLAC code with comments marked
  92144. * with "OPT:" where a #define can be changed to enable code that might be
  92145. * faster on a specific platform. Experimenting with these can yield faster
  92146. * binaries.
  92147. */
  92148. /** \defgroup porting Porting Guide for New Versions
  92149. *
  92150. * This module describes differences in the library interfaces from
  92151. * version to version. It assists in the porting of code that uses
  92152. * the libraries to newer versions of FLAC.
  92153. *
  92154. * One simple facility for making porting easier that has been added
  92155. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92156. * library's includes (e.g. \c include/FLAC/export.h). The
  92157. * \c #defines mirror the libraries'
  92158. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92159. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92160. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92161. * These can be used to support multiple versions of an API during the
  92162. * transition phase, e.g.
  92163. *
  92164. * \code
  92165. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92166. * legacy code
  92167. * #else
  92168. * new code
  92169. * #endif
  92170. * \endcode
  92171. *
  92172. * The the source will work for multiple versions and the legacy code can
  92173. * easily be removed when the transition is complete.
  92174. *
  92175. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92176. * include/FLAC/export.h), which can be used to determine whether or not
  92177. * the library has been compiled with support for Ogg FLAC. This is
  92178. * simpler than trying to call an Ogg init function and catching the
  92179. * error.
  92180. */
  92181. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92182. * \ingroup porting
  92183. *
  92184. * \brief
  92185. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92186. *
  92187. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92188. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92189. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92190. * decoding layers and three encoding layers have been merged into a
  92191. * single stream decoder and stream encoder. That is, the functionality
  92192. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92193. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92194. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92195. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92196. * is there is now a single API that can be used to encode or decode
  92197. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92198. * on both seekable and non-seekable streams.
  92199. *
  92200. * Instead of creating an encoder or decoder of a certain layer, now the
  92201. * client will always create a FLAC__StreamEncoder or
  92202. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92203. * initialization function. For example, for the decoder,
  92204. * FLAC__stream_decoder_init() has been replaced by
  92205. * FLAC__stream_decoder_init_stream(). This init function takes
  92206. * callbacks for the I/O, and the seeking callbacks are optional. This
  92207. * allows the client to use the same object for seekable and
  92208. * non-seekable streams. For decoding a FLAC file directly, the client
  92209. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92210. * and fewer callbacks; most of the other callbacks are supplied
  92211. * internally. For situations where fopen()ing by filename is not
  92212. * possible (e.g. Unicode filenames on Windows) the client can instead
  92213. * open the file itself and supply the FILE* to
  92214. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92215. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92216. * Since the callbacks and client data are now passed to the init
  92217. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92218. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92219. * rest of the calls to the decoder are the same as before.
  92220. *
  92221. * There are counterpart init functions for Ogg FLAC, e.g.
  92222. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92223. * and callbacks are the same as for native FLAC.
  92224. *
  92225. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92226. * been set up like so:
  92227. *
  92228. * \code
  92229. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92230. * if(decoder == NULL) do_something;
  92231. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92232. * [... other settings ...]
  92233. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92234. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92235. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92236. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92237. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92238. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92239. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92240. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92241. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92242. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92243. * \endcode
  92244. *
  92245. * In FLAC 1.1.3 it is like this:
  92246. *
  92247. * \code
  92248. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92249. * if(decoder == NULL) do_something;
  92250. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92251. * [... other settings ...]
  92252. * if(FLAC__stream_decoder_init_stream(
  92253. * decoder,
  92254. * my_read_callback,
  92255. * my_seek_callback, // or NULL
  92256. * my_tell_callback, // or NULL
  92257. * my_length_callback, // or NULL
  92258. * my_eof_callback, // or NULL
  92259. * my_write_callback,
  92260. * my_metadata_callback, // or NULL
  92261. * my_error_callback,
  92262. * my_client_data
  92263. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92264. * \endcode
  92265. *
  92266. * or you could do;
  92267. *
  92268. * \code
  92269. * [...]
  92270. * FILE *file = fopen("somefile.flac","rb");
  92271. * if(file == NULL) do_somthing;
  92272. * if(FLAC__stream_decoder_init_FILE(
  92273. * decoder,
  92274. * file,
  92275. * my_write_callback,
  92276. * my_metadata_callback, // or NULL
  92277. * my_error_callback,
  92278. * my_client_data
  92279. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92280. * \endcode
  92281. *
  92282. * or just:
  92283. *
  92284. * \code
  92285. * [...]
  92286. * if(FLAC__stream_decoder_init_file(
  92287. * decoder,
  92288. * "somefile.flac",
  92289. * my_write_callback,
  92290. * my_metadata_callback, // or NULL
  92291. * my_error_callback,
  92292. * my_client_data
  92293. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92294. * \endcode
  92295. *
  92296. * Another small change to the decoder is in how it handles unparseable
  92297. * streams. Before, when the decoder found an unparseable stream
  92298. * (reserved for when the decoder encounters a stream from a future
  92299. * encoder that it can't parse), it changed the state to
  92300. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92301. * drops sync and calls the error callback with a new error code
  92302. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92303. * more robust. If your error callback does not discriminate on the the
  92304. * error state, your code does not need to be changed.
  92305. *
  92306. * The encoder now has a new setting:
  92307. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92308. * method used to window the data before LPC analysis. You only need to
  92309. * add a call to this function if the default is not suitable. There
  92310. * are also two new convenience functions that may be useful:
  92311. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92312. * FLAC__metadata_get_cuesheet().
  92313. *
  92314. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92315. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92316. * is now \c size_t instead of \c unsigned.
  92317. */
  92318. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92319. * \ingroup porting
  92320. *
  92321. * \brief
  92322. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92323. *
  92324. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92325. * There was a slight change in the implementation of
  92326. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92327. * of the \a metadata array of pointers so the client no longer needs
  92328. * to maintain it after the call. The objects themselves that are
  92329. * pointed to by the array are still not copied though and must be
  92330. * maintained until the call to FLAC__stream_encoder_finish().
  92331. */
  92332. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92333. * \ingroup porting
  92334. *
  92335. * \brief
  92336. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92337. *
  92338. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92339. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92340. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92341. *
  92342. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92343. * has changed to reflect the conversion of one of the reserved bits
  92344. * into active use. It used to be \c 2 and now is \c 1. However the
  92345. * FLAC frame header length has not changed, so to skip the proper
  92346. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92347. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92348. */
  92349. /** \defgroup flac FLAC C API
  92350. *
  92351. * The FLAC C API is the interface to libFLAC, a set of structures
  92352. * describing the components of FLAC streams, and functions for
  92353. * encoding and decoding streams, as well as manipulating FLAC
  92354. * metadata in files.
  92355. *
  92356. * You should start with the format components as all other modules
  92357. * are dependent on it.
  92358. */
  92359. #endif
  92360. /*** End of inlined file: all.h ***/
  92361. /*** Start of inlined file: bitmath.c ***/
  92362. /*** Start of inlined file: juce_FlacHeader.h ***/
  92363. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92364. // tasks..
  92365. #define VERSION "1.2.1"
  92366. #define FLAC__NO_DLL 1
  92367. #if JUCE_MSVC
  92368. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92369. #endif
  92370. #if JUCE_MAC
  92371. #define FLAC__SYS_DARWIN 1
  92372. #endif
  92373. /*** End of inlined file: juce_FlacHeader.h ***/
  92374. #if JUCE_USE_FLAC
  92375. #if HAVE_CONFIG_H
  92376. # include <config.h>
  92377. #endif
  92378. /*** Start of inlined file: bitmath.h ***/
  92379. #ifndef FLAC__PRIVATE__BITMATH_H
  92380. #define FLAC__PRIVATE__BITMATH_H
  92381. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92382. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92383. unsigned FLAC__bitmath_silog2(int v);
  92384. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92385. #endif
  92386. /*** End of inlined file: bitmath.h ***/
  92387. /* An example of what FLAC__bitmath_ilog2() computes:
  92388. *
  92389. * ilog2( 0) = assertion failure
  92390. * ilog2( 1) = 0
  92391. * ilog2( 2) = 1
  92392. * ilog2( 3) = 1
  92393. * ilog2( 4) = 2
  92394. * ilog2( 5) = 2
  92395. * ilog2( 6) = 2
  92396. * ilog2( 7) = 2
  92397. * ilog2( 8) = 3
  92398. * ilog2( 9) = 3
  92399. * ilog2(10) = 3
  92400. * ilog2(11) = 3
  92401. * ilog2(12) = 3
  92402. * ilog2(13) = 3
  92403. * ilog2(14) = 3
  92404. * ilog2(15) = 3
  92405. * ilog2(16) = 4
  92406. * ilog2(17) = 4
  92407. * ilog2(18) = 4
  92408. */
  92409. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92410. {
  92411. unsigned l = 0;
  92412. FLAC__ASSERT(v > 0);
  92413. while(v >>= 1)
  92414. l++;
  92415. return l;
  92416. }
  92417. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92418. {
  92419. unsigned l = 0;
  92420. FLAC__ASSERT(v > 0);
  92421. while(v >>= 1)
  92422. l++;
  92423. return l;
  92424. }
  92425. /* An example of what FLAC__bitmath_silog2() computes:
  92426. *
  92427. * silog2(-10) = 5
  92428. * silog2(- 9) = 5
  92429. * silog2(- 8) = 4
  92430. * silog2(- 7) = 4
  92431. * silog2(- 6) = 4
  92432. * silog2(- 5) = 4
  92433. * silog2(- 4) = 3
  92434. * silog2(- 3) = 3
  92435. * silog2(- 2) = 2
  92436. * silog2(- 1) = 2
  92437. * silog2( 0) = 0
  92438. * silog2( 1) = 2
  92439. * silog2( 2) = 3
  92440. * silog2( 3) = 3
  92441. * silog2( 4) = 4
  92442. * silog2( 5) = 4
  92443. * silog2( 6) = 4
  92444. * silog2( 7) = 4
  92445. * silog2( 8) = 5
  92446. * silog2( 9) = 5
  92447. * silog2( 10) = 5
  92448. */
  92449. unsigned FLAC__bitmath_silog2(int v)
  92450. {
  92451. while(1) {
  92452. if(v == 0) {
  92453. return 0;
  92454. }
  92455. else if(v > 0) {
  92456. unsigned l = 0;
  92457. while(v) {
  92458. l++;
  92459. v >>= 1;
  92460. }
  92461. return l+1;
  92462. }
  92463. else if(v == -1) {
  92464. return 2;
  92465. }
  92466. else {
  92467. v++;
  92468. v = -v;
  92469. }
  92470. }
  92471. }
  92472. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92473. {
  92474. while(1) {
  92475. if(v == 0) {
  92476. return 0;
  92477. }
  92478. else if(v > 0) {
  92479. unsigned l = 0;
  92480. while(v) {
  92481. l++;
  92482. v >>= 1;
  92483. }
  92484. return l+1;
  92485. }
  92486. else if(v == -1) {
  92487. return 2;
  92488. }
  92489. else {
  92490. v++;
  92491. v = -v;
  92492. }
  92493. }
  92494. }
  92495. #endif
  92496. /*** End of inlined file: bitmath.c ***/
  92497. /*** Start of inlined file: bitreader.c ***/
  92498. /*** Start of inlined file: juce_FlacHeader.h ***/
  92499. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92500. // tasks..
  92501. #define VERSION "1.2.1"
  92502. #define FLAC__NO_DLL 1
  92503. #if JUCE_MSVC
  92504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92505. #endif
  92506. #if JUCE_MAC
  92507. #define FLAC__SYS_DARWIN 1
  92508. #endif
  92509. /*** End of inlined file: juce_FlacHeader.h ***/
  92510. #if JUCE_USE_FLAC
  92511. #if HAVE_CONFIG_H
  92512. # include <config.h>
  92513. #endif
  92514. #include <stdlib.h> /* for malloc() */
  92515. #include <string.h> /* for memcpy(), memset() */
  92516. #ifdef _MSC_VER
  92517. #include <winsock.h> /* for ntohl() */
  92518. #elif defined FLAC__SYS_DARWIN
  92519. #include <machine/endian.h> /* for ntohl() */
  92520. #elif defined __MINGW32__
  92521. #include <winsock.h> /* for ntohl() */
  92522. #else
  92523. #include <netinet/in.h> /* for ntohl() */
  92524. #endif
  92525. /*** Start of inlined file: bitreader.h ***/
  92526. #ifndef FLAC__PRIVATE__BITREADER_H
  92527. #define FLAC__PRIVATE__BITREADER_H
  92528. #include <stdio.h> /* for FILE */
  92529. /*** Start of inlined file: cpu.h ***/
  92530. #ifndef FLAC__PRIVATE__CPU_H
  92531. #define FLAC__PRIVATE__CPU_H
  92532. #ifdef HAVE_CONFIG_H
  92533. #include <config.h>
  92534. #endif
  92535. typedef enum {
  92536. FLAC__CPUINFO_TYPE_IA32,
  92537. FLAC__CPUINFO_TYPE_PPC,
  92538. FLAC__CPUINFO_TYPE_UNKNOWN
  92539. } FLAC__CPUInfo_Type;
  92540. typedef struct {
  92541. FLAC__bool cpuid;
  92542. FLAC__bool bswap;
  92543. FLAC__bool cmov;
  92544. FLAC__bool mmx;
  92545. FLAC__bool fxsr;
  92546. FLAC__bool sse;
  92547. FLAC__bool sse2;
  92548. FLAC__bool sse3;
  92549. FLAC__bool ssse3;
  92550. FLAC__bool _3dnow;
  92551. FLAC__bool ext3dnow;
  92552. FLAC__bool extmmx;
  92553. } FLAC__CPUInfo_IA32;
  92554. typedef struct {
  92555. FLAC__bool altivec;
  92556. FLAC__bool ppc64;
  92557. } FLAC__CPUInfo_PPC;
  92558. typedef struct {
  92559. FLAC__bool use_asm;
  92560. FLAC__CPUInfo_Type type;
  92561. union {
  92562. FLAC__CPUInfo_IA32 ia32;
  92563. FLAC__CPUInfo_PPC ppc;
  92564. } data;
  92565. } FLAC__CPUInfo;
  92566. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92567. #ifndef FLAC__NO_ASM
  92568. #ifdef FLAC__CPU_IA32
  92569. #ifdef FLAC__HAS_NASM
  92570. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92571. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92572. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92573. #endif
  92574. #endif
  92575. #endif
  92576. #endif
  92577. /*** End of inlined file: cpu.h ***/
  92578. /*
  92579. * opaque structure definition
  92580. */
  92581. struct FLAC__BitReader;
  92582. typedef struct FLAC__BitReader FLAC__BitReader;
  92583. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92584. /*
  92585. * construction, deletion, initialization, etc functions
  92586. */
  92587. FLAC__BitReader *FLAC__bitreader_new(void);
  92588. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92589. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92590. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92591. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92592. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92593. /*
  92594. * CRC functions
  92595. */
  92596. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92597. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92598. /*
  92599. * info functions
  92600. */
  92601. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92602. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92603. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92604. /*
  92605. * read functions
  92606. */
  92607. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92608. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92609. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92610. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92611. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92612. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92613. 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! */
  92614. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92615. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92616. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92617. #ifndef FLAC__NO_ASM
  92618. # ifdef FLAC__CPU_IA32
  92619. # ifdef FLAC__HAS_NASM
  92620. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92621. # endif
  92622. # endif
  92623. #endif
  92624. #if 0 /* UNUSED */
  92625. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92626. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92627. #endif
  92628. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92629. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92630. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92631. #endif
  92632. /*** End of inlined file: bitreader.h ***/
  92633. /*** Start of inlined file: crc.h ***/
  92634. #ifndef FLAC__PRIVATE__CRC_H
  92635. #define FLAC__PRIVATE__CRC_H
  92636. /* 8 bit CRC generator, MSB shifted first
  92637. ** polynomial = x^8 + x^2 + x^1 + x^0
  92638. ** init = 0
  92639. */
  92640. extern FLAC__byte const FLAC__crc8_table[256];
  92641. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92642. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92643. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92644. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92645. /* 16 bit CRC generator, MSB shifted first
  92646. ** polynomial = x^16 + x^15 + x^2 + x^0
  92647. ** init = 0
  92648. */
  92649. extern unsigned FLAC__crc16_table[256];
  92650. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92651. /* this alternate may be faster on some systems/compilers */
  92652. #if 0
  92653. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92654. #endif
  92655. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92656. #endif
  92657. /*** End of inlined file: crc.h ***/
  92658. /* Things should be fastest when this matches the machine word size */
  92659. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92660. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92661. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92662. typedef FLAC__uint32 brword;
  92663. #define FLAC__BYTES_PER_WORD 4
  92664. #define FLAC__BITS_PER_WORD 32
  92665. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92666. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92667. #if WORDS_BIGENDIAN
  92668. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92669. #else
  92670. #if defined (_MSC_VER) && defined (_X86_)
  92671. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92672. #else
  92673. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92674. #endif
  92675. #endif
  92676. /* counts the # of zero MSBs in a word */
  92677. #define COUNT_ZERO_MSBS(word) ( \
  92678. (word) <= 0xffff ? \
  92679. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92680. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92681. )
  92682. /* this alternate might be slightly faster on some systems/compilers: */
  92683. #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])) )
  92684. /*
  92685. * This should be at least twice as large as the largest number of words
  92686. * required to represent any 'number' (in any encoding) you are going to
  92687. * read. With FLAC this is on the order of maybe a few hundred bits.
  92688. * If the buffer is smaller than that, the decoder won't be able to read
  92689. * in a whole number that is in a variable length encoding (e.g. Rice).
  92690. * But to be practical it should be at least 1K bytes.
  92691. *
  92692. * Increase this number to decrease the number of read callbacks, at the
  92693. * expense of using more memory. Or decrease for the reverse effect,
  92694. * keeping in mind the limit from the first paragraph. The optimal size
  92695. * also depends on the CPU cache size and other factors; some twiddling
  92696. * may be necessary to squeeze out the best performance.
  92697. */
  92698. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92699. static const unsigned char byte_to_unary_table[] = {
  92700. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92701. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92702. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92703. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92704. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92705. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92706. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92707. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92716. };
  92717. #ifdef min
  92718. #undef min
  92719. #endif
  92720. #define min(x,y) ((x)<(y)?(x):(y))
  92721. #ifdef max
  92722. #undef max
  92723. #endif
  92724. #define max(x,y) ((x)>(y)?(x):(y))
  92725. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92726. #ifdef _MSC_VER
  92727. #define FLAC__U64L(x) x
  92728. #else
  92729. #define FLAC__U64L(x) x##LLU
  92730. #endif
  92731. #ifndef FLaC__INLINE
  92732. #define FLaC__INLINE
  92733. #endif
  92734. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92735. struct FLAC__BitReader {
  92736. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92737. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92738. brword *buffer;
  92739. unsigned capacity; /* in words */
  92740. unsigned words; /* # of completed words in buffer */
  92741. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92742. unsigned consumed_words; /* #words ... */
  92743. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92744. unsigned read_crc16; /* the running frame CRC */
  92745. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92746. FLAC__BitReaderReadCallback read_callback;
  92747. void *client_data;
  92748. FLAC__CPUInfo cpu_info;
  92749. };
  92750. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92751. {
  92752. register unsigned crc = br->read_crc16;
  92753. #if FLAC__BYTES_PER_WORD == 4
  92754. switch(br->crc16_align) {
  92755. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92756. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92757. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92758. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92759. }
  92760. #elif FLAC__BYTES_PER_WORD == 8
  92761. switch(br->crc16_align) {
  92762. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92763. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92764. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92765. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92766. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92767. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92768. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92769. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92770. }
  92771. #else
  92772. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92773. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92774. br->read_crc16 = crc;
  92775. #endif
  92776. br->crc16_align = 0;
  92777. }
  92778. /* would be static except it needs to be called by asm routines */
  92779. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92780. {
  92781. unsigned start, end;
  92782. size_t bytes;
  92783. FLAC__byte *target;
  92784. /* first shift the unconsumed buffer data toward the front as much as possible */
  92785. if(br->consumed_words > 0) {
  92786. start = br->consumed_words;
  92787. end = br->words + (br->bytes? 1:0);
  92788. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92789. br->words -= start;
  92790. br->consumed_words = 0;
  92791. }
  92792. /*
  92793. * set the target for reading, taking into account word alignment and endianness
  92794. */
  92795. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92796. if(bytes == 0)
  92797. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92798. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92799. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92800. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92801. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92802. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92803. * ^^-------target, bytes=3
  92804. * on LE machines, have to byteswap the odd tail word so nothing is
  92805. * overwritten:
  92806. */
  92807. #if WORDS_BIGENDIAN
  92808. #else
  92809. if(br->bytes)
  92810. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92811. #endif
  92812. /* now it looks like:
  92813. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92814. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92815. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92816. * ^^-------target, bytes=3
  92817. */
  92818. /* read in the data; note that the callback may return a smaller number of bytes */
  92819. if(!br->read_callback(target, &bytes, br->client_data))
  92820. return false;
  92821. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92822. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92823. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92824. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92825. * now have to byteswap on LE machines:
  92826. */
  92827. #if WORDS_BIGENDIAN
  92828. #else
  92829. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92830. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92831. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92832. start = br->words;
  92833. local_swap32_block_(br->buffer + start, end - start);
  92834. }
  92835. else
  92836. # endif
  92837. for(start = br->words; start < end; start++)
  92838. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92839. #endif
  92840. /* now it looks like:
  92841. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92842. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92843. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92844. * finally we'll update the reader values:
  92845. */
  92846. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92847. br->words = end / FLAC__BYTES_PER_WORD;
  92848. br->bytes = end % FLAC__BYTES_PER_WORD;
  92849. return true;
  92850. }
  92851. /***********************************************************************
  92852. *
  92853. * Class constructor/destructor
  92854. *
  92855. ***********************************************************************/
  92856. FLAC__BitReader *FLAC__bitreader_new(void)
  92857. {
  92858. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92859. /* calloc() implies:
  92860. memset(br, 0, sizeof(FLAC__BitReader));
  92861. br->buffer = 0;
  92862. br->capacity = 0;
  92863. br->words = br->bytes = 0;
  92864. br->consumed_words = br->consumed_bits = 0;
  92865. br->read_callback = 0;
  92866. br->client_data = 0;
  92867. */
  92868. return br;
  92869. }
  92870. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92871. {
  92872. FLAC__ASSERT(0 != br);
  92873. FLAC__bitreader_free(br);
  92874. free(br);
  92875. }
  92876. /***********************************************************************
  92877. *
  92878. * Public class methods
  92879. *
  92880. ***********************************************************************/
  92881. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92882. {
  92883. FLAC__ASSERT(0 != br);
  92884. br->words = br->bytes = 0;
  92885. br->consumed_words = br->consumed_bits = 0;
  92886. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92887. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92888. if(br->buffer == 0)
  92889. return false;
  92890. br->read_callback = rcb;
  92891. br->client_data = cd;
  92892. br->cpu_info = cpu;
  92893. return true;
  92894. }
  92895. void FLAC__bitreader_free(FLAC__BitReader *br)
  92896. {
  92897. FLAC__ASSERT(0 != br);
  92898. if(0 != br->buffer)
  92899. free(br->buffer);
  92900. br->buffer = 0;
  92901. br->capacity = 0;
  92902. br->words = br->bytes = 0;
  92903. br->consumed_words = br->consumed_bits = 0;
  92904. br->read_callback = 0;
  92905. br->client_data = 0;
  92906. }
  92907. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92908. {
  92909. br->words = br->bytes = 0;
  92910. br->consumed_words = br->consumed_bits = 0;
  92911. return true;
  92912. }
  92913. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92914. {
  92915. unsigned i, j;
  92916. if(br == 0) {
  92917. fprintf(out, "bitreader is NULL\n");
  92918. }
  92919. else {
  92920. 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);
  92921. for(i = 0; i < br->words; i++) {
  92922. fprintf(out, "%08X: ", i);
  92923. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92924. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92925. fprintf(out, ".");
  92926. else
  92927. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92928. fprintf(out, "\n");
  92929. }
  92930. if(br->bytes > 0) {
  92931. fprintf(out, "%08X: ", i);
  92932. for(j = 0; j < br->bytes*8; j++)
  92933. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92934. fprintf(out, ".");
  92935. else
  92936. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92937. fprintf(out, "\n");
  92938. }
  92939. }
  92940. }
  92941. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92942. {
  92943. FLAC__ASSERT(0 != br);
  92944. FLAC__ASSERT(0 != br->buffer);
  92945. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92946. br->read_crc16 = (unsigned)seed;
  92947. br->crc16_align = br->consumed_bits;
  92948. }
  92949. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92950. {
  92951. FLAC__ASSERT(0 != br);
  92952. FLAC__ASSERT(0 != br->buffer);
  92953. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92954. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92955. /* CRC any tail bytes in a partially-consumed word */
  92956. if(br->consumed_bits) {
  92957. const brword tail = br->buffer[br->consumed_words];
  92958. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92959. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92960. }
  92961. return br->read_crc16;
  92962. }
  92963. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92964. {
  92965. return ((br->consumed_bits & 7) == 0);
  92966. }
  92967. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92968. {
  92969. return 8 - (br->consumed_bits & 7);
  92970. }
  92971. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92972. {
  92973. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92974. }
  92975. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92976. {
  92977. FLAC__ASSERT(0 != br);
  92978. FLAC__ASSERT(0 != br->buffer);
  92979. FLAC__ASSERT(bits <= 32);
  92980. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92981. FLAC__ASSERT(br->consumed_words <= br->words);
  92982. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92983. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92984. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92985. *val = 0;
  92986. return true;
  92987. }
  92988. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92989. if(!bitreader_read_from_client_(br))
  92990. return false;
  92991. }
  92992. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92993. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92994. if(br->consumed_bits) {
  92995. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92996. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92997. const brword word = br->buffer[br->consumed_words];
  92998. if(bits < n) {
  92999. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93000. br->consumed_bits += bits;
  93001. return true;
  93002. }
  93003. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93004. bits -= n;
  93005. crc16_update_word_(br, word);
  93006. br->consumed_words++;
  93007. br->consumed_bits = 0;
  93008. 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 */
  93009. *val <<= bits;
  93010. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93011. br->consumed_bits = bits;
  93012. }
  93013. return true;
  93014. }
  93015. else {
  93016. const brword word = br->buffer[br->consumed_words];
  93017. if(bits < FLAC__BITS_PER_WORD) {
  93018. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93019. br->consumed_bits = bits;
  93020. return true;
  93021. }
  93022. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93023. *val = word;
  93024. crc16_update_word_(br, word);
  93025. br->consumed_words++;
  93026. return true;
  93027. }
  93028. }
  93029. else {
  93030. /* in this case we're starting our read at a partial tail word;
  93031. * the reader has guaranteed that we have at least 'bits' bits
  93032. * available to read, which makes this case simpler.
  93033. */
  93034. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93035. if(br->consumed_bits) {
  93036. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93037. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93038. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93039. br->consumed_bits += bits;
  93040. return true;
  93041. }
  93042. else {
  93043. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93044. br->consumed_bits += bits;
  93045. return true;
  93046. }
  93047. }
  93048. }
  93049. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93050. {
  93051. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93052. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93053. return false;
  93054. /* sign-extend: */
  93055. *val <<= (32-bits);
  93056. *val >>= (32-bits);
  93057. return true;
  93058. }
  93059. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93060. {
  93061. FLAC__uint32 hi, lo;
  93062. if(bits > 32) {
  93063. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93064. return false;
  93065. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93066. return false;
  93067. *val = hi;
  93068. *val <<= 32;
  93069. *val |= lo;
  93070. }
  93071. else {
  93072. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93073. return false;
  93074. *val = lo;
  93075. }
  93076. return true;
  93077. }
  93078. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93079. {
  93080. FLAC__uint32 x8, x32 = 0;
  93081. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93082. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93083. return false;
  93084. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93085. return false;
  93086. x32 |= (x8 << 8);
  93087. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93088. return false;
  93089. x32 |= (x8 << 16);
  93090. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93091. return false;
  93092. x32 |= (x8 << 24);
  93093. *val = x32;
  93094. return true;
  93095. }
  93096. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93097. {
  93098. /*
  93099. * OPT: a faster implementation is possible but probably not that useful
  93100. * since this is only called a couple of times in the metadata readers.
  93101. */
  93102. FLAC__ASSERT(0 != br);
  93103. FLAC__ASSERT(0 != br->buffer);
  93104. if(bits > 0) {
  93105. const unsigned n = br->consumed_bits & 7;
  93106. unsigned m;
  93107. FLAC__uint32 x;
  93108. if(n != 0) {
  93109. m = min(8-n, bits);
  93110. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93111. return false;
  93112. bits -= m;
  93113. }
  93114. m = bits / 8;
  93115. if(m > 0) {
  93116. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93117. return false;
  93118. bits %= 8;
  93119. }
  93120. if(bits > 0) {
  93121. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93122. return false;
  93123. }
  93124. }
  93125. return true;
  93126. }
  93127. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93128. {
  93129. FLAC__uint32 x;
  93130. FLAC__ASSERT(0 != br);
  93131. FLAC__ASSERT(0 != br->buffer);
  93132. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93133. /* step 1: skip over partial head word to get word aligned */
  93134. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93135. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93136. return false;
  93137. nvals--;
  93138. }
  93139. if(0 == nvals)
  93140. return true;
  93141. /* step 2: skip whole words in chunks */
  93142. while(nvals >= FLAC__BYTES_PER_WORD) {
  93143. if(br->consumed_words < br->words) {
  93144. br->consumed_words++;
  93145. nvals -= FLAC__BYTES_PER_WORD;
  93146. }
  93147. else if(!bitreader_read_from_client_(br))
  93148. return false;
  93149. }
  93150. /* step 3: skip any remainder from partial tail bytes */
  93151. while(nvals) {
  93152. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93153. return false;
  93154. nvals--;
  93155. }
  93156. return true;
  93157. }
  93158. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93159. {
  93160. FLAC__uint32 x;
  93161. FLAC__ASSERT(0 != br);
  93162. FLAC__ASSERT(0 != br->buffer);
  93163. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93164. /* step 1: read from partial head word to get word aligned */
  93165. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93166. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93167. return false;
  93168. *val++ = (FLAC__byte)x;
  93169. nvals--;
  93170. }
  93171. if(0 == nvals)
  93172. return true;
  93173. /* step 2: read whole words in chunks */
  93174. while(nvals >= FLAC__BYTES_PER_WORD) {
  93175. if(br->consumed_words < br->words) {
  93176. const brword word = br->buffer[br->consumed_words++];
  93177. #if FLAC__BYTES_PER_WORD == 4
  93178. val[0] = (FLAC__byte)(word >> 24);
  93179. val[1] = (FLAC__byte)(word >> 16);
  93180. val[2] = (FLAC__byte)(word >> 8);
  93181. val[3] = (FLAC__byte)word;
  93182. #elif FLAC__BYTES_PER_WORD == 8
  93183. val[0] = (FLAC__byte)(word >> 56);
  93184. val[1] = (FLAC__byte)(word >> 48);
  93185. val[2] = (FLAC__byte)(word >> 40);
  93186. val[3] = (FLAC__byte)(word >> 32);
  93187. val[4] = (FLAC__byte)(word >> 24);
  93188. val[5] = (FLAC__byte)(word >> 16);
  93189. val[6] = (FLAC__byte)(word >> 8);
  93190. val[7] = (FLAC__byte)word;
  93191. #else
  93192. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93193. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93194. #endif
  93195. val += FLAC__BYTES_PER_WORD;
  93196. nvals -= FLAC__BYTES_PER_WORD;
  93197. }
  93198. else if(!bitreader_read_from_client_(br))
  93199. return false;
  93200. }
  93201. /* step 3: read any remainder from partial tail bytes */
  93202. while(nvals) {
  93203. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93204. return false;
  93205. *val++ = (FLAC__byte)x;
  93206. nvals--;
  93207. }
  93208. return true;
  93209. }
  93210. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93211. #if 0 /* slow but readable version */
  93212. {
  93213. unsigned bit;
  93214. FLAC__ASSERT(0 != br);
  93215. FLAC__ASSERT(0 != br->buffer);
  93216. *val = 0;
  93217. while(1) {
  93218. if(!FLAC__bitreader_read_bit(br, &bit))
  93219. return false;
  93220. if(bit)
  93221. break;
  93222. else
  93223. *val++;
  93224. }
  93225. return true;
  93226. }
  93227. #else
  93228. {
  93229. unsigned i;
  93230. FLAC__ASSERT(0 != br);
  93231. FLAC__ASSERT(0 != br->buffer);
  93232. *val = 0;
  93233. while(1) {
  93234. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93235. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93236. if(b) {
  93237. i = COUNT_ZERO_MSBS(b);
  93238. *val += i;
  93239. i++;
  93240. br->consumed_bits += i;
  93241. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93242. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93243. br->consumed_words++;
  93244. br->consumed_bits = 0;
  93245. }
  93246. return true;
  93247. }
  93248. else {
  93249. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93250. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93251. br->consumed_words++;
  93252. br->consumed_bits = 0;
  93253. /* didn't find stop bit yet, have to keep going... */
  93254. }
  93255. }
  93256. /* at this point we've eaten up all the whole words; have to try
  93257. * reading through any tail bytes before calling the read callback.
  93258. * this is a repeat of the above logic adjusted for the fact we
  93259. * don't have a whole word. note though if the client is feeding
  93260. * us data a byte at a time (unlikely), br->consumed_bits may not
  93261. * be zero.
  93262. */
  93263. if(br->bytes) {
  93264. const unsigned end = br->bytes * 8;
  93265. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93266. if(b) {
  93267. i = COUNT_ZERO_MSBS(b);
  93268. *val += i;
  93269. i++;
  93270. br->consumed_bits += i;
  93271. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93272. return true;
  93273. }
  93274. else {
  93275. *val += end - br->consumed_bits;
  93276. br->consumed_bits += end;
  93277. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93278. /* didn't find stop bit yet, have to keep going... */
  93279. }
  93280. }
  93281. if(!bitreader_read_from_client_(br))
  93282. return false;
  93283. }
  93284. }
  93285. #endif
  93286. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93287. {
  93288. FLAC__uint32 lsbs = 0, msbs = 0;
  93289. unsigned uval;
  93290. FLAC__ASSERT(0 != br);
  93291. FLAC__ASSERT(0 != br->buffer);
  93292. FLAC__ASSERT(parameter <= 31);
  93293. /* read the unary MSBs and end bit */
  93294. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93295. return false;
  93296. /* read the binary LSBs */
  93297. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93298. return false;
  93299. /* compose the value */
  93300. uval = (msbs << parameter) | lsbs;
  93301. if(uval & 1)
  93302. *val = -((int)(uval >> 1)) - 1;
  93303. else
  93304. *val = (int)(uval >> 1);
  93305. return true;
  93306. }
  93307. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93308. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93309. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93310. /* OPT: possibly faster version for use with MSVC */
  93311. #ifdef _MSC_VER
  93312. {
  93313. unsigned i;
  93314. unsigned uval = 0;
  93315. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93316. /* try and get br->consumed_words and br->consumed_bits into register;
  93317. * must remember to flush them back to *br before calling other
  93318. * bitwriter functions that use them, and before returning */
  93319. register unsigned cwords;
  93320. register unsigned cbits;
  93321. FLAC__ASSERT(0 != br);
  93322. FLAC__ASSERT(0 != br->buffer);
  93323. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93324. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93325. FLAC__ASSERT(parameter < 32);
  93326. /* 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 */
  93327. if(nvals == 0)
  93328. return true;
  93329. cbits = br->consumed_bits;
  93330. cwords = br->consumed_words;
  93331. while(1) {
  93332. /* read unary part */
  93333. while(1) {
  93334. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93335. brword b = br->buffer[cwords] << cbits;
  93336. if(b) {
  93337. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93338. __asm {
  93339. bsr eax, b
  93340. not eax
  93341. and eax, 31
  93342. mov i, eax
  93343. }
  93344. #else
  93345. i = COUNT_ZERO_MSBS(b);
  93346. #endif
  93347. uval += i;
  93348. bits = parameter;
  93349. i++;
  93350. cbits += i;
  93351. if(cbits == FLAC__BITS_PER_WORD) {
  93352. crc16_update_word_(br, br->buffer[cwords]);
  93353. cwords++;
  93354. cbits = 0;
  93355. }
  93356. goto break1;
  93357. }
  93358. else {
  93359. uval += FLAC__BITS_PER_WORD - cbits;
  93360. crc16_update_word_(br, br->buffer[cwords]);
  93361. cwords++;
  93362. cbits = 0;
  93363. /* didn't find stop bit yet, have to keep going... */
  93364. }
  93365. }
  93366. /* at this point we've eaten up all the whole words; have to try
  93367. * reading through any tail bytes before calling the read callback.
  93368. * this is a repeat of the above logic adjusted for the fact we
  93369. * don't have a whole word. note though if the client is feeding
  93370. * us data a byte at a time (unlikely), br->consumed_bits may not
  93371. * be zero.
  93372. */
  93373. if(br->bytes) {
  93374. const unsigned end = br->bytes * 8;
  93375. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93376. if(b) {
  93377. i = COUNT_ZERO_MSBS(b);
  93378. uval += i;
  93379. bits = parameter;
  93380. i++;
  93381. cbits += i;
  93382. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93383. goto break1;
  93384. }
  93385. else {
  93386. uval += end - cbits;
  93387. cbits += end;
  93388. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93389. /* didn't find stop bit yet, have to keep going... */
  93390. }
  93391. }
  93392. /* flush registers and read; bitreader_read_from_client_() does
  93393. * not touch br->consumed_bits at all but we still need to set
  93394. * it in case it fails and we have to return false.
  93395. */
  93396. br->consumed_bits = cbits;
  93397. br->consumed_words = cwords;
  93398. if(!bitreader_read_from_client_(br))
  93399. return false;
  93400. cwords = br->consumed_words;
  93401. }
  93402. break1:
  93403. /* read binary part */
  93404. FLAC__ASSERT(cwords <= br->words);
  93405. if(bits) {
  93406. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93407. /* flush registers and read; bitreader_read_from_client_() does
  93408. * not touch br->consumed_bits at all but we still need to set
  93409. * it in case it fails and we have to return false.
  93410. */
  93411. br->consumed_bits = cbits;
  93412. br->consumed_words = cwords;
  93413. if(!bitreader_read_from_client_(br))
  93414. return false;
  93415. cwords = br->consumed_words;
  93416. }
  93417. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93418. if(cbits) {
  93419. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93420. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93421. const brword word = br->buffer[cwords];
  93422. if(bits < n) {
  93423. uval <<= bits;
  93424. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93425. cbits += bits;
  93426. goto break2;
  93427. }
  93428. uval <<= n;
  93429. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93430. bits -= n;
  93431. crc16_update_word_(br, word);
  93432. cwords++;
  93433. cbits = 0;
  93434. 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 */
  93435. uval <<= bits;
  93436. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93437. cbits = bits;
  93438. }
  93439. goto break2;
  93440. }
  93441. else {
  93442. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93443. uval <<= bits;
  93444. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93445. cbits = bits;
  93446. goto break2;
  93447. }
  93448. }
  93449. else {
  93450. /* in this case we're starting our read at a partial tail word;
  93451. * the reader has guaranteed that we have at least 'bits' bits
  93452. * available to read, which makes this case simpler.
  93453. */
  93454. uval <<= bits;
  93455. if(cbits) {
  93456. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93457. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93458. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93459. cbits += bits;
  93460. goto break2;
  93461. }
  93462. else {
  93463. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93464. cbits += bits;
  93465. goto break2;
  93466. }
  93467. }
  93468. }
  93469. break2:
  93470. /* compose the value */
  93471. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93472. /* are we done? */
  93473. --nvals;
  93474. if(nvals == 0) {
  93475. br->consumed_bits = cbits;
  93476. br->consumed_words = cwords;
  93477. return true;
  93478. }
  93479. uval = 0;
  93480. ++vals;
  93481. }
  93482. }
  93483. #else
  93484. {
  93485. unsigned i;
  93486. unsigned uval = 0;
  93487. /* try and get br->consumed_words and br->consumed_bits into register;
  93488. * must remember to flush them back to *br before calling other
  93489. * bitwriter functions that use them, and before returning */
  93490. register unsigned cwords;
  93491. register unsigned cbits;
  93492. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93493. FLAC__ASSERT(0 != br);
  93494. FLAC__ASSERT(0 != br->buffer);
  93495. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93496. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93497. FLAC__ASSERT(parameter < 32);
  93498. /* 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 */
  93499. if(nvals == 0)
  93500. return true;
  93501. cbits = br->consumed_bits;
  93502. cwords = br->consumed_words;
  93503. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93504. while(1) {
  93505. /* read unary part */
  93506. while(1) {
  93507. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93508. brword b = br->buffer[cwords] << cbits;
  93509. if(b) {
  93510. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93511. asm volatile (
  93512. "bsrl %1, %0;"
  93513. "notl %0;"
  93514. "andl $31, %0;"
  93515. : "=r"(i)
  93516. : "r"(b)
  93517. );
  93518. #else
  93519. i = COUNT_ZERO_MSBS(b);
  93520. #endif
  93521. uval += i;
  93522. cbits += i;
  93523. cbits++; /* skip over stop bit */
  93524. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93525. crc16_update_word_(br, br->buffer[cwords]);
  93526. cwords++;
  93527. cbits = 0;
  93528. }
  93529. goto break1;
  93530. }
  93531. else {
  93532. uval += FLAC__BITS_PER_WORD - cbits;
  93533. crc16_update_word_(br, br->buffer[cwords]);
  93534. cwords++;
  93535. cbits = 0;
  93536. /* didn't find stop bit yet, have to keep going... */
  93537. }
  93538. }
  93539. /* at this point we've eaten up all the whole words; have to try
  93540. * reading through any tail bytes before calling the read callback.
  93541. * this is a repeat of the above logic adjusted for the fact we
  93542. * don't have a whole word. note though if the client is feeding
  93543. * us data a byte at a time (unlikely), br->consumed_bits may not
  93544. * be zero.
  93545. */
  93546. if(br->bytes) {
  93547. const unsigned end = br->bytes * 8;
  93548. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93549. if(b) {
  93550. i = COUNT_ZERO_MSBS(b);
  93551. uval += i;
  93552. cbits += i;
  93553. cbits++; /* skip over stop bit */
  93554. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93555. goto break1;
  93556. }
  93557. else {
  93558. uval += end - cbits;
  93559. cbits += end;
  93560. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93561. /* didn't find stop bit yet, have to keep going... */
  93562. }
  93563. }
  93564. /* flush registers and read; bitreader_read_from_client_() does
  93565. * not touch br->consumed_bits at all but we still need to set
  93566. * it in case it fails and we have to return false.
  93567. */
  93568. br->consumed_bits = cbits;
  93569. br->consumed_words = cwords;
  93570. if(!bitreader_read_from_client_(br))
  93571. return false;
  93572. cwords = br->consumed_words;
  93573. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93574. /* + uval to offset our count by the # of unary bits already
  93575. * consumed before the read, because we will add these back
  93576. * in all at once at break1
  93577. */
  93578. }
  93579. break1:
  93580. ucbits -= uval;
  93581. ucbits--; /* account for stop bit */
  93582. /* read binary part */
  93583. FLAC__ASSERT(cwords <= br->words);
  93584. if(parameter) {
  93585. while(ucbits < parameter) {
  93586. /* flush registers and read; bitreader_read_from_client_() does
  93587. * not touch br->consumed_bits at all but we still need to set
  93588. * it in case it fails and we have to return false.
  93589. */
  93590. br->consumed_bits = cbits;
  93591. br->consumed_words = cwords;
  93592. if(!bitreader_read_from_client_(br))
  93593. return false;
  93594. cwords = br->consumed_words;
  93595. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93596. }
  93597. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93598. if(cbits) {
  93599. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93600. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93601. const brword word = br->buffer[cwords];
  93602. if(parameter < n) {
  93603. uval <<= parameter;
  93604. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93605. cbits += parameter;
  93606. }
  93607. else {
  93608. uval <<= n;
  93609. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93610. crc16_update_word_(br, word);
  93611. cwords++;
  93612. cbits = parameter - n;
  93613. 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 */
  93614. uval <<= cbits;
  93615. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93616. }
  93617. }
  93618. }
  93619. else {
  93620. cbits = parameter;
  93621. uval <<= parameter;
  93622. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93623. }
  93624. }
  93625. else {
  93626. /* in this case we're starting our read at a partial tail word;
  93627. * the reader has guaranteed that we have at least 'parameter'
  93628. * bits available to read, which makes this case simpler.
  93629. */
  93630. uval <<= parameter;
  93631. if(cbits) {
  93632. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93633. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93634. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93635. cbits += parameter;
  93636. }
  93637. else {
  93638. cbits = parameter;
  93639. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93640. }
  93641. }
  93642. }
  93643. ucbits -= parameter;
  93644. /* compose the value */
  93645. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93646. /* are we done? */
  93647. --nvals;
  93648. if(nvals == 0) {
  93649. br->consumed_bits = cbits;
  93650. br->consumed_words = cwords;
  93651. return true;
  93652. }
  93653. uval = 0;
  93654. ++vals;
  93655. }
  93656. }
  93657. #endif
  93658. #if 0 /* UNUSED */
  93659. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93660. {
  93661. FLAC__uint32 lsbs = 0, msbs = 0;
  93662. unsigned bit, uval, k;
  93663. FLAC__ASSERT(0 != br);
  93664. FLAC__ASSERT(0 != br->buffer);
  93665. k = FLAC__bitmath_ilog2(parameter);
  93666. /* read the unary MSBs and end bit */
  93667. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93668. return false;
  93669. /* read the binary LSBs */
  93670. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93671. return false;
  93672. if(parameter == 1u<<k) {
  93673. /* compose the value */
  93674. uval = (msbs << k) | lsbs;
  93675. }
  93676. else {
  93677. unsigned d = (1 << (k+1)) - parameter;
  93678. if(lsbs >= d) {
  93679. if(!FLAC__bitreader_read_bit(br, &bit))
  93680. return false;
  93681. lsbs <<= 1;
  93682. lsbs |= bit;
  93683. lsbs -= d;
  93684. }
  93685. /* compose the value */
  93686. uval = msbs * parameter + lsbs;
  93687. }
  93688. /* unfold unsigned to signed */
  93689. if(uval & 1)
  93690. *val = -((int)(uval >> 1)) - 1;
  93691. else
  93692. *val = (int)(uval >> 1);
  93693. return true;
  93694. }
  93695. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93696. {
  93697. FLAC__uint32 lsbs, msbs = 0;
  93698. unsigned bit, k;
  93699. FLAC__ASSERT(0 != br);
  93700. FLAC__ASSERT(0 != br->buffer);
  93701. k = FLAC__bitmath_ilog2(parameter);
  93702. /* read the unary MSBs and end bit */
  93703. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93704. return false;
  93705. /* read the binary LSBs */
  93706. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93707. return false;
  93708. if(parameter == 1u<<k) {
  93709. /* compose the value */
  93710. *val = (msbs << k) | lsbs;
  93711. }
  93712. else {
  93713. unsigned d = (1 << (k+1)) - parameter;
  93714. if(lsbs >= d) {
  93715. if(!FLAC__bitreader_read_bit(br, &bit))
  93716. return false;
  93717. lsbs <<= 1;
  93718. lsbs |= bit;
  93719. lsbs -= d;
  93720. }
  93721. /* compose the value */
  93722. *val = msbs * parameter + lsbs;
  93723. }
  93724. return true;
  93725. }
  93726. #endif /* UNUSED */
  93727. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93728. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93729. {
  93730. FLAC__uint32 v = 0;
  93731. FLAC__uint32 x;
  93732. unsigned i;
  93733. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93734. return false;
  93735. if(raw)
  93736. raw[(*rawlen)++] = (FLAC__byte)x;
  93737. if(!(x & 0x80)) { /* 0xxxxxxx */
  93738. v = x;
  93739. i = 0;
  93740. }
  93741. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93742. v = x & 0x1F;
  93743. i = 1;
  93744. }
  93745. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93746. v = x & 0x0F;
  93747. i = 2;
  93748. }
  93749. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93750. v = x & 0x07;
  93751. i = 3;
  93752. }
  93753. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93754. v = x & 0x03;
  93755. i = 4;
  93756. }
  93757. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93758. v = x & 0x01;
  93759. i = 5;
  93760. }
  93761. else {
  93762. *val = 0xffffffff;
  93763. return true;
  93764. }
  93765. for( ; i; i--) {
  93766. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93767. return false;
  93768. if(raw)
  93769. raw[(*rawlen)++] = (FLAC__byte)x;
  93770. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93771. *val = 0xffffffff;
  93772. return true;
  93773. }
  93774. v <<= 6;
  93775. v |= (x & 0x3F);
  93776. }
  93777. *val = v;
  93778. return true;
  93779. }
  93780. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93781. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93782. {
  93783. FLAC__uint64 v = 0;
  93784. FLAC__uint32 x;
  93785. unsigned i;
  93786. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93787. return false;
  93788. if(raw)
  93789. raw[(*rawlen)++] = (FLAC__byte)x;
  93790. if(!(x & 0x80)) { /* 0xxxxxxx */
  93791. v = x;
  93792. i = 0;
  93793. }
  93794. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93795. v = x & 0x1F;
  93796. i = 1;
  93797. }
  93798. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93799. v = x & 0x0F;
  93800. i = 2;
  93801. }
  93802. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93803. v = x & 0x07;
  93804. i = 3;
  93805. }
  93806. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93807. v = x & 0x03;
  93808. i = 4;
  93809. }
  93810. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93811. v = x & 0x01;
  93812. i = 5;
  93813. }
  93814. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93815. v = 0;
  93816. i = 6;
  93817. }
  93818. else {
  93819. *val = FLAC__U64L(0xffffffffffffffff);
  93820. return true;
  93821. }
  93822. for( ; i; i--) {
  93823. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93824. return false;
  93825. if(raw)
  93826. raw[(*rawlen)++] = (FLAC__byte)x;
  93827. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93828. *val = FLAC__U64L(0xffffffffffffffff);
  93829. return true;
  93830. }
  93831. v <<= 6;
  93832. v |= (x & 0x3F);
  93833. }
  93834. *val = v;
  93835. return true;
  93836. }
  93837. #endif
  93838. /*** End of inlined file: bitreader.c ***/
  93839. /*** Start of inlined file: bitwriter.c ***/
  93840. /*** Start of inlined file: juce_FlacHeader.h ***/
  93841. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93842. // tasks..
  93843. #define VERSION "1.2.1"
  93844. #define FLAC__NO_DLL 1
  93845. #if JUCE_MSVC
  93846. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93847. #endif
  93848. #if JUCE_MAC
  93849. #define FLAC__SYS_DARWIN 1
  93850. #endif
  93851. /*** End of inlined file: juce_FlacHeader.h ***/
  93852. #if JUCE_USE_FLAC
  93853. #if HAVE_CONFIG_H
  93854. # include <config.h>
  93855. #endif
  93856. #include <stdlib.h> /* for malloc() */
  93857. #include <string.h> /* for memcpy(), memset() */
  93858. #ifdef _MSC_VER
  93859. #include <winsock.h> /* for ntohl() */
  93860. #elif defined FLAC__SYS_DARWIN
  93861. #include <machine/endian.h> /* for ntohl() */
  93862. #elif defined __MINGW32__
  93863. #include <winsock.h> /* for ntohl() */
  93864. #else
  93865. #include <netinet/in.h> /* for ntohl() */
  93866. #endif
  93867. #if 0 /* UNUSED */
  93868. #endif
  93869. /*** Start of inlined file: bitwriter.h ***/
  93870. #ifndef FLAC__PRIVATE__BITWRITER_H
  93871. #define FLAC__PRIVATE__BITWRITER_H
  93872. #include <stdio.h> /* for FILE */
  93873. /*
  93874. * opaque structure definition
  93875. */
  93876. struct FLAC__BitWriter;
  93877. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93878. /*
  93879. * construction, deletion, initialization, etc functions
  93880. */
  93881. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93882. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93883. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93884. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93885. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93886. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93887. /*
  93888. * CRC functions
  93889. *
  93890. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93891. */
  93892. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93893. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93894. /*
  93895. * info functions
  93896. */
  93897. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93898. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93899. /*
  93900. * direct buffer access
  93901. *
  93902. * there may be no calls on the bitwriter between get and release.
  93903. * the bitwriter continues to own the returned buffer.
  93904. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93905. */
  93906. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93907. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93908. /*
  93909. * write functions
  93910. */
  93911. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93912. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93913. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93914. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93915. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93916. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93917. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93918. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93919. #if 0 /* UNUSED */
  93920. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93921. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93922. #endif
  93923. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93924. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93925. #if 0 /* UNUSED */
  93926. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93927. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93928. #endif
  93929. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93930. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93931. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93932. #endif
  93933. /*** End of inlined file: bitwriter.h ***/
  93934. /*** Start of inlined file: alloc.h ***/
  93935. #ifndef FLAC__SHARE__ALLOC_H
  93936. #define FLAC__SHARE__ALLOC_H
  93937. #if HAVE_CONFIG_H
  93938. # include <config.h>
  93939. #endif
  93940. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93941. * before #including this file, otherwise SIZE_MAX might not be defined
  93942. */
  93943. #include <limits.h> /* for SIZE_MAX */
  93944. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93945. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93946. #endif
  93947. #include <stdlib.h> /* for size_t, malloc(), etc */
  93948. #ifndef SIZE_MAX
  93949. # ifndef SIZE_T_MAX
  93950. # ifdef _MSC_VER
  93951. # define SIZE_T_MAX UINT_MAX
  93952. # else
  93953. # error
  93954. # endif
  93955. # endif
  93956. # define SIZE_MAX SIZE_T_MAX
  93957. #endif
  93958. #ifndef FLaC__INLINE
  93959. #define FLaC__INLINE
  93960. #endif
  93961. /* avoid malloc()ing 0 bytes, see:
  93962. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93963. */
  93964. static FLaC__INLINE void *safe_malloc_(size_t size)
  93965. {
  93966. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93967. if(!size)
  93968. size++;
  93969. return malloc(size);
  93970. }
  93971. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93972. {
  93973. if(!nmemb || !size)
  93974. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93975. return calloc(nmemb, size);
  93976. }
  93977. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93978. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93979. {
  93980. size2 += size1;
  93981. if(size2 < size1)
  93982. return 0;
  93983. return safe_malloc_(size2);
  93984. }
  93985. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93986. {
  93987. size2 += size1;
  93988. if(size2 < size1)
  93989. return 0;
  93990. size3 += size2;
  93991. if(size3 < size2)
  93992. return 0;
  93993. return safe_malloc_(size3);
  93994. }
  93995. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93996. {
  93997. size2 += size1;
  93998. if(size2 < size1)
  93999. return 0;
  94000. size3 += size2;
  94001. if(size3 < size2)
  94002. return 0;
  94003. size4 += size3;
  94004. if(size4 < size3)
  94005. return 0;
  94006. return safe_malloc_(size4);
  94007. }
  94008. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94009. #if 0
  94010. needs support for cases where sizeof(size_t) != 4
  94011. {
  94012. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94013. if(sizeof(size_t) == 4) {
  94014. if ((double)size1 * (double)size2 < 4294967296.0)
  94015. return malloc(size1*size2);
  94016. }
  94017. return 0;
  94018. }
  94019. #else
  94020. /* better? */
  94021. {
  94022. if(!size1 || !size2)
  94023. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94024. if(size1 > SIZE_MAX / size2)
  94025. return 0;
  94026. return malloc(size1*size2);
  94027. }
  94028. #endif
  94029. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94030. {
  94031. if(!size1 || !size2 || !size3)
  94032. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94033. if(size1 > SIZE_MAX / size2)
  94034. return 0;
  94035. size1 *= size2;
  94036. if(size1 > SIZE_MAX / size3)
  94037. return 0;
  94038. return malloc(size1*size3);
  94039. }
  94040. /* size1*size2 + size3 */
  94041. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94042. {
  94043. if(!size1 || !size2)
  94044. return safe_malloc_(size3);
  94045. if(size1 > SIZE_MAX / size2)
  94046. return 0;
  94047. return safe_malloc_add_2op_(size1*size2, size3);
  94048. }
  94049. /* size1 * (size2 + size3) */
  94050. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94051. {
  94052. if(!size1 || (!size2 && !size3))
  94053. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94054. size2 += size3;
  94055. if(size2 < size3)
  94056. return 0;
  94057. return safe_malloc_mul_2op_(size1, size2);
  94058. }
  94059. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94060. {
  94061. size2 += size1;
  94062. if(size2 < size1)
  94063. return 0;
  94064. return realloc(ptr, size2);
  94065. }
  94066. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94067. {
  94068. size2 += size1;
  94069. if(size2 < size1)
  94070. return 0;
  94071. size3 += size2;
  94072. if(size3 < size2)
  94073. return 0;
  94074. return realloc(ptr, size3);
  94075. }
  94076. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94077. {
  94078. size2 += size1;
  94079. if(size2 < size1)
  94080. return 0;
  94081. size3 += size2;
  94082. if(size3 < size2)
  94083. return 0;
  94084. size4 += size3;
  94085. if(size4 < size3)
  94086. return 0;
  94087. return realloc(ptr, size4);
  94088. }
  94089. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94090. {
  94091. if(!size1 || !size2)
  94092. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94093. if(size1 > SIZE_MAX / size2)
  94094. return 0;
  94095. return realloc(ptr, size1*size2);
  94096. }
  94097. /* size1 * (size2 + size3) */
  94098. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94099. {
  94100. if(!size1 || (!size2 && !size3))
  94101. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94102. size2 += size3;
  94103. if(size2 < size3)
  94104. return 0;
  94105. return safe_realloc_mul_2op_(ptr, size1, size2);
  94106. }
  94107. #endif
  94108. /*** End of inlined file: alloc.h ***/
  94109. /* Things should be fastest when this matches the machine word size */
  94110. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94111. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94112. typedef FLAC__uint32 bwword;
  94113. #define FLAC__BYTES_PER_WORD 4
  94114. #define FLAC__BITS_PER_WORD 32
  94115. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94116. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94117. #if WORDS_BIGENDIAN
  94118. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94119. #else
  94120. #ifdef _MSC_VER
  94121. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94122. #else
  94123. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94124. #endif
  94125. #endif
  94126. /*
  94127. * The default capacity here doesn't matter too much. The buffer always grows
  94128. * to hold whatever is written to it. Usually the encoder will stop adding at
  94129. * a frame or metadata block, then write that out and clear the buffer for the
  94130. * next one.
  94131. */
  94132. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94133. /* When growing, increment 4K at a time */
  94134. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94135. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94136. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94137. #ifdef min
  94138. #undef min
  94139. #endif
  94140. #define min(x,y) ((x)<(y)?(x):(y))
  94141. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94142. #ifdef _MSC_VER
  94143. #define FLAC__U64L(x) x
  94144. #else
  94145. #define FLAC__U64L(x) x##LLU
  94146. #endif
  94147. #ifndef FLaC__INLINE
  94148. #define FLaC__INLINE
  94149. #endif
  94150. struct FLAC__BitWriter {
  94151. bwword *buffer;
  94152. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94153. unsigned capacity; /* capacity of buffer in words */
  94154. unsigned words; /* # of complete words in buffer */
  94155. unsigned bits; /* # of used bits in accum */
  94156. };
  94157. /* * WATCHOUT: The current implementation only grows the buffer. */
  94158. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94159. {
  94160. unsigned new_capacity;
  94161. bwword *new_buffer;
  94162. FLAC__ASSERT(0 != bw);
  94163. FLAC__ASSERT(0 != bw->buffer);
  94164. /* calculate total words needed to store 'bits_to_add' additional bits */
  94165. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94166. /* it's possible (due to pessimism in the growth estimation that
  94167. * leads to this call) that we don't actually need to grow
  94168. */
  94169. if(bw->capacity >= new_capacity)
  94170. return true;
  94171. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94172. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94173. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94174. /* make sure we got everything right */
  94175. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94176. FLAC__ASSERT(new_capacity > bw->capacity);
  94177. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94178. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94179. if(new_buffer == 0)
  94180. return false;
  94181. bw->buffer = new_buffer;
  94182. bw->capacity = new_capacity;
  94183. return true;
  94184. }
  94185. /***********************************************************************
  94186. *
  94187. * Class constructor/destructor
  94188. *
  94189. ***********************************************************************/
  94190. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94191. {
  94192. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94193. /* note that calloc() sets all members to 0 for us */
  94194. return bw;
  94195. }
  94196. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94197. {
  94198. FLAC__ASSERT(0 != bw);
  94199. FLAC__bitwriter_free(bw);
  94200. free(bw);
  94201. }
  94202. /***********************************************************************
  94203. *
  94204. * Public class methods
  94205. *
  94206. ***********************************************************************/
  94207. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94208. {
  94209. FLAC__ASSERT(0 != bw);
  94210. bw->words = bw->bits = 0;
  94211. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94212. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94213. if(bw->buffer == 0)
  94214. return false;
  94215. return true;
  94216. }
  94217. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94218. {
  94219. FLAC__ASSERT(0 != bw);
  94220. if(0 != bw->buffer)
  94221. free(bw->buffer);
  94222. bw->buffer = 0;
  94223. bw->capacity = 0;
  94224. bw->words = bw->bits = 0;
  94225. }
  94226. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94227. {
  94228. bw->words = bw->bits = 0;
  94229. }
  94230. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94231. {
  94232. unsigned i, j;
  94233. if(bw == 0) {
  94234. fprintf(out, "bitwriter is NULL\n");
  94235. }
  94236. else {
  94237. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94238. for(i = 0; i < bw->words; i++) {
  94239. fprintf(out, "%08X: ", i);
  94240. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94241. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94242. fprintf(out, "\n");
  94243. }
  94244. if(bw->bits > 0) {
  94245. fprintf(out, "%08X: ", i);
  94246. for(j = 0; j < bw->bits; j++)
  94247. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94248. fprintf(out, "\n");
  94249. }
  94250. }
  94251. }
  94252. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94253. {
  94254. const FLAC__byte *buffer;
  94255. size_t bytes;
  94256. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94257. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94258. return false;
  94259. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94260. FLAC__bitwriter_release_buffer(bw);
  94261. return true;
  94262. }
  94263. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94264. {
  94265. const FLAC__byte *buffer;
  94266. size_t bytes;
  94267. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94268. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94269. return false;
  94270. *crc = FLAC__crc8(buffer, bytes);
  94271. FLAC__bitwriter_release_buffer(bw);
  94272. return true;
  94273. }
  94274. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94275. {
  94276. return ((bw->bits & 7) == 0);
  94277. }
  94278. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94279. {
  94280. return FLAC__TOTAL_BITS(bw);
  94281. }
  94282. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94283. {
  94284. FLAC__ASSERT((bw->bits & 7) == 0);
  94285. /* double protection */
  94286. if(bw->bits & 7)
  94287. return false;
  94288. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94289. if(bw->bits) {
  94290. FLAC__ASSERT(bw->words <= bw->capacity);
  94291. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94292. return false;
  94293. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94294. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94295. }
  94296. /* now we can just return what we have */
  94297. *buffer = (FLAC__byte*)bw->buffer;
  94298. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94299. return true;
  94300. }
  94301. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94302. {
  94303. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94304. * get-mode' flag could be added everywhere and then cleared here
  94305. */
  94306. (void)bw;
  94307. }
  94308. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94309. {
  94310. unsigned n;
  94311. FLAC__ASSERT(0 != bw);
  94312. FLAC__ASSERT(0 != bw->buffer);
  94313. if(bits == 0)
  94314. return true;
  94315. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94316. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94317. return false;
  94318. /* first part gets to word alignment */
  94319. if(bw->bits) {
  94320. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94321. bw->accum <<= n;
  94322. bits -= n;
  94323. bw->bits += n;
  94324. if(bw->bits == FLAC__BITS_PER_WORD) {
  94325. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94326. bw->bits = 0;
  94327. }
  94328. else
  94329. return true;
  94330. }
  94331. /* do whole words */
  94332. while(bits >= FLAC__BITS_PER_WORD) {
  94333. bw->buffer[bw->words++] = 0;
  94334. bits -= FLAC__BITS_PER_WORD;
  94335. }
  94336. /* do any leftovers */
  94337. if(bits > 0) {
  94338. bw->accum = 0;
  94339. bw->bits = bits;
  94340. }
  94341. return true;
  94342. }
  94343. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94344. {
  94345. register unsigned left;
  94346. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94347. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94348. FLAC__ASSERT(0 != bw);
  94349. FLAC__ASSERT(0 != bw->buffer);
  94350. FLAC__ASSERT(bits <= 32);
  94351. if(bits == 0)
  94352. return true;
  94353. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94354. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94355. return false;
  94356. left = FLAC__BITS_PER_WORD - bw->bits;
  94357. if(bits < left) {
  94358. bw->accum <<= bits;
  94359. bw->accum |= val;
  94360. bw->bits += bits;
  94361. }
  94362. 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 */
  94363. bw->accum <<= left;
  94364. bw->accum |= val >> (bw->bits = bits - left);
  94365. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94366. bw->accum = val;
  94367. }
  94368. else {
  94369. bw->accum = val;
  94370. bw->bits = 0;
  94371. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94372. }
  94373. return true;
  94374. }
  94375. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94376. {
  94377. /* zero-out unused bits */
  94378. if(bits < 32)
  94379. val &= (~(0xffffffff << bits));
  94380. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94381. }
  94382. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94383. {
  94384. /* this could be a little faster but it's not used for much */
  94385. if(bits > 32) {
  94386. return
  94387. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94388. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94389. }
  94390. else
  94391. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94392. }
  94393. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94394. {
  94395. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94396. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94397. return false;
  94398. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94399. return false;
  94400. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94401. return false;
  94402. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94403. return false;
  94404. return true;
  94405. }
  94406. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94407. {
  94408. unsigned i;
  94409. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94410. for(i = 0; i < nvals; i++) {
  94411. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94412. return false;
  94413. }
  94414. return true;
  94415. }
  94416. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94417. {
  94418. if(val < 32)
  94419. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94420. else
  94421. return
  94422. FLAC__bitwriter_write_zeroes(bw, val) &&
  94423. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94424. }
  94425. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94426. {
  94427. FLAC__uint32 uval;
  94428. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94429. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94430. uval = (val<<1) ^ (val>>31);
  94431. return 1 + parameter + (uval >> parameter);
  94432. }
  94433. #if 0 /* UNUSED */
  94434. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94435. {
  94436. unsigned bits, msbs, uval;
  94437. unsigned k;
  94438. FLAC__ASSERT(parameter > 0);
  94439. /* fold signed to unsigned */
  94440. if(val < 0)
  94441. uval = (unsigned)(((-(++val)) << 1) + 1);
  94442. else
  94443. uval = (unsigned)(val << 1);
  94444. k = FLAC__bitmath_ilog2(parameter);
  94445. if(parameter == 1u<<k) {
  94446. FLAC__ASSERT(k <= 30);
  94447. msbs = uval >> k;
  94448. bits = 1 + k + msbs;
  94449. }
  94450. else {
  94451. unsigned q, r, d;
  94452. d = (1 << (k+1)) - parameter;
  94453. q = uval / parameter;
  94454. r = uval - (q * parameter);
  94455. bits = 1 + q + k;
  94456. if(r >= d)
  94457. bits++;
  94458. }
  94459. return bits;
  94460. }
  94461. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94462. {
  94463. unsigned bits, msbs;
  94464. unsigned k;
  94465. FLAC__ASSERT(parameter > 0);
  94466. k = FLAC__bitmath_ilog2(parameter);
  94467. if(parameter == 1u<<k) {
  94468. FLAC__ASSERT(k <= 30);
  94469. msbs = uval >> k;
  94470. bits = 1 + k + msbs;
  94471. }
  94472. else {
  94473. unsigned q, r, d;
  94474. d = (1 << (k+1)) - parameter;
  94475. q = uval / parameter;
  94476. r = uval - (q * parameter);
  94477. bits = 1 + q + k;
  94478. if(r >= d)
  94479. bits++;
  94480. }
  94481. return bits;
  94482. }
  94483. #endif /* UNUSED */
  94484. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94485. {
  94486. unsigned total_bits, interesting_bits, msbs;
  94487. FLAC__uint32 uval, pattern;
  94488. FLAC__ASSERT(0 != bw);
  94489. FLAC__ASSERT(0 != bw->buffer);
  94490. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94491. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94492. uval = (val<<1) ^ (val>>31);
  94493. msbs = uval >> parameter;
  94494. interesting_bits = 1 + parameter;
  94495. total_bits = interesting_bits + msbs;
  94496. pattern = 1 << parameter; /* the unary end bit */
  94497. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94498. if(total_bits <= 32)
  94499. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94500. else
  94501. return
  94502. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94503. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94504. }
  94505. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94506. {
  94507. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94508. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94509. FLAC__uint32 uval;
  94510. unsigned left;
  94511. const unsigned lsbits = 1 + parameter;
  94512. unsigned msbits;
  94513. FLAC__ASSERT(0 != bw);
  94514. FLAC__ASSERT(0 != bw->buffer);
  94515. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94516. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94517. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94518. while(nvals) {
  94519. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94520. uval = (*vals<<1) ^ (*vals>>31);
  94521. msbits = uval >> parameter;
  94522. #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) */
  94523. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94524. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94525. bw->bits = bw->bits + msbits + lsbits;
  94526. uval |= mask1; /* set stop bit */
  94527. uval &= mask2; /* mask off unused top bits */
  94528. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94529. bw->accum <<= msbits;
  94530. bw->accum <<= lsbits;
  94531. bw->accum |= uval;
  94532. if(bw->bits == FLAC__BITS_PER_WORD) {
  94533. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94534. bw->bits = 0;
  94535. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94536. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94537. FLAC__ASSERT(bw->capacity == bw->words);
  94538. return false;
  94539. }
  94540. }
  94541. }
  94542. else {
  94543. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94544. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94545. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94546. bw->bits = bw->bits + msbits + lsbits;
  94547. uval |= mask1; /* set stop bit */
  94548. uval &= mask2; /* mask off unused top bits */
  94549. bw->accum <<= msbits + lsbits;
  94550. bw->accum |= uval;
  94551. }
  94552. else {
  94553. #endif
  94554. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94555. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94556. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94557. return false;
  94558. if(msbits) {
  94559. /* first part gets to word alignment */
  94560. if(bw->bits) {
  94561. left = FLAC__BITS_PER_WORD - bw->bits;
  94562. if(msbits < left) {
  94563. bw->accum <<= msbits;
  94564. bw->bits += msbits;
  94565. goto break1;
  94566. }
  94567. else {
  94568. bw->accum <<= left;
  94569. msbits -= left;
  94570. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94571. bw->bits = 0;
  94572. }
  94573. }
  94574. /* do whole words */
  94575. while(msbits >= FLAC__BITS_PER_WORD) {
  94576. bw->buffer[bw->words++] = 0;
  94577. msbits -= FLAC__BITS_PER_WORD;
  94578. }
  94579. /* do any leftovers */
  94580. if(msbits > 0) {
  94581. bw->accum = 0;
  94582. bw->bits = msbits;
  94583. }
  94584. }
  94585. break1:
  94586. uval |= mask1; /* set stop bit */
  94587. uval &= mask2; /* mask off unused top bits */
  94588. left = FLAC__BITS_PER_WORD - bw->bits;
  94589. if(lsbits < left) {
  94590. bw->accum <<= lsbits;
  94591. bw->accum |= uval;
  94592. bw->bits += lsbits;
  94593. }
  94594. else {
  94595. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94596. * be > lsbits (because of previous assertions) so it would have
  94597. * triggered the (lsbits<left) case above.
  94598. */
  94599. FLAC__ASSERT(bw->bits);
  94600. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94601. bw->accum <<= left;
  94602. bw->accum |= uval >> (bw->bits = lsbits - left);
  94603. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94604. bw->accum = uval;
  94605. }
  94606. #if 1
  94607. }
  94608. #endif
  94609. vals++;
  94610. nvals--;
  94611. }
  94612. return true;
  94613. }
  94614. #if 0 /* UNUSED */
  94615. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94616. {
  94617. unsigned total_bits, msbs, uval;
  94618. unsigned k;
  94619. FLAC__ASSERT(0 != bw);
  94620. FLAC__ASSERT(0 != bw->buffer);
  94621. FLAC__ASSERT(parameter > 0);
  94622. /* fold signed to unsigned */
  94623. if(val < 0)
  94624. uval = (unsigned)(((-(++val)) << 1) + 1);
  94625. else
  94626. uval = (unsigned)(val << 1);
  94627. k = FLAC__bitmath_ilog2(parameter);
  94628. if(parameter == 1u<<k) {
  94629. unsigned pattern;
  94630. FLAC__ASSERT(k <= 30);
  94631. msbs = uval >> k;
  94632. total_bits = 1 + k + msbs;
  94633. pattern = 1 << k; /* the unary end bit */
  94634. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94635. if(total_bits <= 32) {
  94636. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94637. return false;
  94638. }
  94639. else {
  94640. /* write the unary MSBs */
  94641. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94642. return false;
  94643. /* write the unary end bit and binary LSBs */
  94644. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94645. return false;
  94646. }
  94647. }
  94648. else {
  94649. unsigned q, r, d;
  94650. d = (1 << (k+1)) - parameter;
  94651. q = uval / parameter;
  94652. r = uval - (q * parameter);
  94653. /* write the unary MSBs */
  94654. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94655. return false;
  94656. /* write the unary end bit */
  94657. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94658. return false;
  94659. /* write the binary LSBs */
  94660. if(r >= d) {
  94661. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94662. return false;
  94663. }
  94664. else {
  94665. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94666. return false;
  94667. }
  94668. }
  94669. return true;
  94670. }
  94671. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94672. {
  94673. unsigned total_bits, msbs;
  94674. unsigned k;
  94675. FLAC__ASSERT(0 != bw);
  94676. FLAC__ASSERT(0 != bw->buffer);
  94677. FLAC__ASSERT(parameter > 0);
  94678. k = FLAC__bitmath_ilog2(parameter);
  94679. if(parameter == 1u<<k) {
  94680. unsigned pattern;
  94681. FLAC__ASSERT(k <= 30);
  94682. msbs = uval >> k;
  94683. total_bits = 1 + k + msbs;
  94684. pattern = 1 << k; /* the unary end bit */
  94685. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94686. if(total_bits <= 32) {
  94687. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94688. return false;
  94689. }
  94690. else {
  94691. /* write the unary MSBs */
  94692. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94693. return false;
  94694. /* write the unary end bit and binary LSBs */
  94695. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94696. return false;
  94697. }
  94698. }
  94699. else {
  94700. unsigned q, r, d;
  94701. d = (1 << (k+1)) - parameter;
  94702. q = uval / parameter;
  94703. r = uval - (q * parameter);
  94704. /* write the unary MSBs */
  94705. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94706. return false;
  94707. /* write the unary end bit */
  94708. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94709. return false;
  94710. /* write the binary LSBs */
  94711. if(r >= d) {
  94712. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94713. return false;
  94714. }
  94715. else {
  94716. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94717. return false;
  94718. }
  94719. }
  94720. return true;
  94721. }
  94722. #endif /* UNUSED */
  94723. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94724. {
  94725. FLAC__bool ok = 1;
  94726. FLAC__ASSERT(0 != bw);
  94727. FLAC__ASSERT(0 != bw->buffer);
  94728. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94729. if(val < 0x80) {
  94730. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94731. }
  94732. else if(val < 0x800) {
  94733. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94734. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94735. }
  94736. else if(val < 0x10000) {
  94737. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94738. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94739. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94740. }
  94741. else if(val < 0x200000) {
  94742. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94743. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94744. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94745. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94746. }
  94747. else if(val < 0x4000000) {
  94748. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94749. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94750. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94751. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94752. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94753. }
  94754. else {
  94755. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94756. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94757. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94758. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94759. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94760. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94761. }
  94762. return ok;
  94763. }
  94764. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94765. {
  94766. FLAC__bool ok = 1;
  94767. FLAC__ASSERT(0 != bw);
  94768. FLAC__ASSERT(0 != bw->buffer);
  94769. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94770. if(val < 0x80) {
  94771. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94772. }
  94773. else if(val < 0x800) {
  94774. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94775. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94776. }
  94777. else if(val < 0x10000) {
  94778. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94779. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94780. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94781. }
  94782. else if(val < 0x200000) {
  94783. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94784. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94785. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94786. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94787. }
  94788. else if(val < 0x4000000) {
  94789. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94790. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94791. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94792. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94793. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94794. }
  94795. else if(val < 0x80000000) {
  94796. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94797. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94798. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94799. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94800. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94801. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94802. }
  94803. else {
  94804. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94805. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94806. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94807. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94808. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94809. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94810. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94811. }
  94812. return ok;
  94813. }
  94814. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94815. {
  94816. /* 0-pad to byte boundary */
  94817. if(bw->bits & 7u)
  94818. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94819. else
  94820. return true;
  94821. }
  94822. #endif
  94823. /*** End of inlined file: bitwriter.c ***/
  94824. /*** Start of inlined file: cpu.c ***/
  94825. /*** Start of inlined file: juce_FlacHeader.h ***/
  94826. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94827. // tasks..
  94828. #define VERSION "1.2.1"
  94829. #define FLAC__NO_DLL 1
  94830. #if JUCE_MSVC
  94831. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94832. #endif
  94833. #if JUCE_MAC
  94834. #define FLAC__SYS_DARWIN 1
  94835. #endif
  94836. /*** End of inlined file: juce_FlacHeader.h ***/
  94837. #if JUCE_USE_FLAC
  94838. #if HAVE_CONFIG_H
  94839. # include <config.h>
  94840. #endif
  94841. #include <stdlib.h>
  94842. #include <stdio.h>
  94843. #if defined FLAC__CPU_IA32
  94844. # include <signal.h>
  94845. #elif defined FLAC__CPU_PPC
  94846. # if !defined FLAC__NO_ASM
  94847. # if defined FLAC__SYS_DARWIN
  94848. # include <sys/sysctl.h>
  94849. # include <mach/mach.h>
  94850. # include <mach/mach_host.h>
  94851. # include <mach/host_info.h>
  94852. # include <mach/machine.h>
  94853. # ifndef CPU_SUBTYPE_POWERPC_970
  94854. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94855. # endif
  94856. # else /* FLAC__SYS_DARWIN */
  94857. # include <signal.h>
  94858. # include <setjmp.h>
  94859. static sigjmp_buf jmpbuf;
  94860. static volatile sig_atomic_t canjump = 0;
  94861. static void sigill_handler (int sig)
  94862. {
  94863. if (!canjump) {
  94864. signal (sig, SIG_DFL);
  94865. raise (sig);
  94866. }
  94867. canjump = 0;
  94868. siglongjmp (jmpbuf, 1);
  94869. }
  94870. # endif /* FLAC__SYS_DARWIN */
  94871. # endif /* FLAC__NO_ASM */
  94872. #endif /* FLAC__CPU_PPC */
  94873. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94874. #include <sys/param.h>
  94875. #include <sys/sysctl.h>
  94876. #include <machine/cpu.h>
  94877. #endif
  94878. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94879. #include <sys/types.h>
  94880. #include <sys/sysctl.h>
  94881. #endif
  94882. #if defined(__APPLE__)
  94883. /* how to get sysctlbyname()? */
  94884. #endif
  94885. /* these are flags in EDX of CPUID AX=00000001 */
  94886. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94887. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94888. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94889. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94890. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94891. /* these are flags in ECX of CPUID AX=00000001 */
  94892. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94893. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94894. /* these are flags in EDX of CPUID AX=80000001 */
  94895. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94896. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94897. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94898. /*
  94899. * Extra stuff needed for detection of OS support for SSE on IA-32
  94900. */
  94901. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94902. # if defined(__linux__)
  94903. /*
  94904. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94905. * modify the return address to jump over the offending SSE instruction
  94906. * and also the operation following it that indicates the instruction
  94907. * executed successfully. In this way we use no global variables and
  94908. * stay thread-safe.
  94909. *
  94910. * 3 + 3 + 6:
  94911. * 3 bytes for "xorps xmm0,xmm0"
  94912. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94913. * 6 bytes extra in case our estimate is wrong
  94914. * 12 bytes puts us in the NOP "landing zone"
  94915. */
  94916. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94917. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94918. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94919. {
  94920. (void)signal;
  94921. sc.eip += 3 + 3 + 6;
  94922. }
  94923. # else
  94924. # include <sys/ucontext.h>
  94925. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94926. {
  94927. (void)signal, (void)si;
  94928. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94929. }
  94930. # endif
  94931. # elif defined(_MSC_VER)
  94932. # include <windows.h>
  94933. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94934. # ifdef USE_TRY_CATCH_FLAVOR
  94935. # else
  94936. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94937. {
  94938. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94939. ep->ContextRecord->Eip += 3 + 3 + 6;
  94940. return EXCEPTION_CONTINUE_EXECUTION;
  94941. }
  94942. return EXCEPTION_CONTINUE_SEARCH;
  94943. }
  94944. # endif
  94945. # endif
  94946. #endif
  94947. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94948. {
  94949. /*
  94950. * IA32-specific
  94951. */
  94952. #ifdef FLAC__CPU_IA32
  94953. info->type = FLAC__CPUINFO_TYPE_IA32;
  94954. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94955. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94956. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94957. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94958. info->data.ia32.cmov = false;
  94959. info->data.ia32.mmx = false;
  94960. info->data.ia32.fxsr = false;
  94961. info->data.ia32.sse = false;
  94962. info->data.ia32.sse2 = false;
  94963. info->data.ia32.sse3 = false;
  94964. info->data.ia32.ssse3 = false;
  94965. info->data.ia32._3dnow = false;
  94966. info->data.ia32.ext3dnow = false;
  94967. info->data.ia32.extmmx = false;
  94968. if(info->data.ia32.cpuid) {
  94969. /* http://www.sandpile.org/ia32/cpuid.htm */
  94970. FLAC__uint32 flags_edx, flags_ecx;
  94971. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94972. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94973. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94974. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94975. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94976. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94977. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94978. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94979. #ifdef FLAC__USE_3DNOW
  94980. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94981. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94982. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94983. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94984. #else
  94985. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94986. #endif
  94987. #ifdef DEBUG
  94988. fprintf(stderr, "CPU info (IA-32):\n");
  94989. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94990. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94991. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94992. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94993. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94994. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94995. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94996. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94997. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94998. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94999. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95000. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95001. #endif
  95002. /*
  95003. * now have to check for OS support of SSE/SSE2
  95004. */
  95005. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95006. #if defined FLAC__NO_SSE_OS
  95007. /* assume user knows better than us; turn it off */
  95008. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95009. #elif defined FLAC__SSE_OS
  95010. /* assume user knows better than us; leave as detected above */
  95011. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95012. int sse = 0;
  95013. size_t len;
  95014. /* at least one of these must work: */
  95015. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95016. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95017. if(!sse)
  95018. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95019. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95020. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95021. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95022. size_t len = sizeof(val);
  95023. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95024. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95025. else { /* double-check SSE2 */
  95026. mib[1] = CPU_SSE2;
  95027. len = sizeof(val);
  95028. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95029. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95030. }
  95031. # else
  95032. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95033. # endif
  95034. #elif defined(__linux__)
  95035. int sse = 0;
  95036. struct sigaction sigill_save;
  95037. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95038. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95039. #else
  95040. struct sigaction sigill_sse;
  95041. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95042. __sigemptyset(&sigill_sse.sa_mask);
  95043. 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 */
  95044. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95045. #endif
  95046. {
  95047. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95048. /* see sigill_handler_sse_os() for an explanation of the following: */
  95049. asm volatile (
  95050. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95051. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95052. "incl %0\n\t" /* SIGILL handler will jump over this */
  95053. /* landing zone */
  95054. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95055. "nop\n\t"
  95056. "nop\n\t"
  95057. "nop\n\t"
  95058. "nop\n\t"
  95059. "nop\n\t"
  95060. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95061. "nop\n\t"
  95062. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95063. : "=r"(sse)
  95064. : "r"(sse)
  95065. );
  95066. sigaction(SIGILL, &sigill_save, NULL);
  95067. }
  95068. if(!sse)
  95069. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95070. #elif defined(_MSC_VER)
  95071. # ifdef USE_TRY_CATCH_FLAVOR
  95072. _try {
  95073. __asm {
  95074. # if _MSC_VER <= 1200
  95075. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95076. _emit 0x0F
  95077. _emit 0x57
  95078. _emit 0xC0
  95079. # else
  95080. xorps xmm0,xmm0
  95081. # endif
  95082. }
  95083. }
  95084. _except(EXCEPTION_EXECUTE_HANDLER) {
  95085. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95086. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95087. }
  95088. # else
  95089. int sse = 0;
  95090. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95091. /* see GCC version above for explanation */
  95092. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95093. /* http://www.codeproject.com/cpp/gccasm.asp */
  95094. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95095. __asm {
  95096. # if _MSC_VER <= 1200
  95097. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95098. _emit 0x0F
  95099. _emit 0x57
  95100. _emit 0xC0
  95101. # else
  95102. xorps xmm0,xmm0
  95103. # endif
  95104. inc sse
  95105. nop
  95106. nop
  95107. nop
  95108. nop
  95109. nop
  95110. nop
  95111. nop
  95112. nop
  95113. nop
  95114. }
  95115. SetUnhandledExceptionFilter(save);
  95116. if(!sse)
  95117. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95118. # endif
  95119. #else
  95120. /* no way to test, disable to be safe */
  95121. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95122. #endif
  95123. #ifdef DEBUG
  95124. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95125. #endif
  95126. }
  95127. }
  95128. #else
  95129. info->use_asm = false;
  95130. #endif
  95131. /*
  95132. * PPC-specific
  95133. */
  95134. #elif defined FLAC__CPU_PPC
  95135. info->type = FLAC__CPUINFO_TYPE_PPC;
  95136. # if !defined FLAC__NO_ASM
  95137. info->use_asm = true;
  95138. # ifdef FLAC__USE_ALTIVEC
  95139. # if defined FLAC__SYS_DARWIN
  95140. {
  95141. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95142. size_t len = sizeof(val);
  95143. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95144. }
  95145. {
  95146. host_basic_info_data_t hostInfo;
  95147. mach_msg_type_number_t infoCount;
  95148. infoCount = HOST_BASIC_INFO_COUNT;
  95149. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95150. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95151. }
  95152. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95153. {
  95154. /* no Darwin, do it the brute-force way */
  95155. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95156. info->data.ppc.altivec = 0;
  95157. info->data.ppc.ppc64 = 0;
  95158. signal (SIGILL, sigill_handler);
  95159. canjump = 0;
  95160. if (!sigsetjmp (jmpbuf, 1)) {
  95161. canjump = 1;
  95162. asm volatile (
  95163. "mtspr 256, %0\n\t"
  95164. "vand %%v0, %%v0, %%v0"
  95165. :
  95166. : "r" (-1)
  95167. );
  95168. info->data.ppc.altivec = 1;
  95169. }
  95170. canjump = 0;
  95171. if (!sigsetjmp (jmpbuf, 1)) {
  95172. int x = 0;
  95173. canjump = 1;
  95174. /* PPC64 hardware implements the cntlzd instruction */
  95175. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95176. info->data.ppc.ppc64 = 1;
  95177. }
  95178. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95179. }
  95180. # endif
  95181. # else /* !FLAC__USE_ALTIVEC */
  95182. info->data.ppc.altivec = 0;
  95183. info->data.ppc.ppc64 = 0;
  95184. # endif
  95185. # else
  95186. info->use_asm = false;
  95187. # endif
  95188. /*
  95189. * unknown CPI
  95190. */
  95191. #else
  95192. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95193. info->use_asm = false;
  95194. #endif
  95195. }
  95196. #endif
  95197. /*** End of inlined file: cpu.c ***/
  95198. /*** Start of inlined file: crc.c ***/
  95199. /*** Start of inlined file: juce_FlacHeader.h ***/
  95200. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95201. // tasks..
  95202. #define VERSION "1.2.1"
  95203. #define FLAC__NO_DLL 1
  95204. #if JUCE_MSVC
  95205. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95206. #endif
  95207. #if JUCE_MAC
  95208. #define FLAC__SYS_DARWIN 1
  95209. #endif
  95210. /*** End of inlined file: juce_FlacHeader.h ***/
  95211. #if JUCE_USE_FLAC
  95212. #if HAVE_CONFIG_H
  95213. # include <config.h>
  95214. #endif
  95215. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95216. FLAC__byte const FLAC__crc8_table[256] = {
  95217. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95218. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95219. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95220. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95221. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95222. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95223. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95224. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95225. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95226. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95227. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95228. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95229. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95230. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95231. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95232. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95233. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95234. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95235. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95236. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95237. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95238. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95239. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95240. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95241. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95242. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95243. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95244. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95245. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95246. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95247. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95248. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95249. };
  95250. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95251. unsigned FLAC__crc16_table[256] = {
  95252. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95253. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95254. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95255. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95256. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95257. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95258. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95259. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95260. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95261. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95262. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95263. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95264. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95265. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95266. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95267. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95268. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95269. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95270. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95271. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95272. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95273. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95274. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95275. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95276. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95277. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95278. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95279. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95280. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95281. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95282. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95283. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95284. };
  95285. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95286. {
  95287. *crc = FLAC__crc8_table[*crc ^ data];
  95288. }
  95289. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95290. {
  95291. while(len--)
  95292. *crc = FLAC__crc8_table[*crc ^ *data++];
  95293. }
  95294. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95295. {
  95296. FLAC__uint8 crc = 0;
  95297. while(len--)
  95298. crc = FLAC__crc8_table[crc ^ *data++];
  95299. return crc;
  95300. }
  95301. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95302. {
  95303. unsigned crc = 0;
  95304. while(len--)
  95305. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95306. return crc;
  95307. }
  95308. #endif
  95309. /*** End of inlined file: crc.c ***/
  95310. /*** Start of inlined file: fixed.c ***/
  95311. /*** Start of inlined file: juce_FlacHeader.h ***/
  95312. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95313. // tasks..
  95314. #define VERSION "1.2.1"
  95315. #define FLAC__NO_DLL 1
  95316. #if JUCE_MSVC
  95317. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95318. #endif
  95319. #if JUCE_MAC
  95320. #define FLAC__SYS_DARWIN 1
  95321. #endif
  95322. /*** End of inlined file: juce_FlacHeader.h ***/
  95323. #if JUCE_USE_FLAC
  95324. #if HAVE_CONFIG_H
  95325. # include <config.h>
  95326. #endif
  95327. #include <math.h>
  95328. #include <string.h>
  95329. /*** Start of inlined file: fixed.h ***/
  95330. #ifndef FLAC__PRIVATE__FIXED_H
  95331. #define FLAC__PRIVATE__FIXED_H
  95332. #ifdef HAVE_CONFIG_H
  95333. #include <config.h>
  95334. #endif
  95335. /*** Start of inlined file: float.h ***/
  95336. #ifndef FLAC__PRIVATE__FLOAT_H
  95337. #define FLAC__PRIVATE__FLOAT_H
  95338. #ifdef HAVE_CONFIG_H
  95339. #include <config.h>
  95340. #endif
  95341. /*
  95342. * These typedefs make it easier to ensure that integer versions of
  95343. * the library really only contain integer operations. All the code
  95344. * in libFLAC should use FLAC__float and FLAC__double in place of
  95345. * float and double, and be protected by checks of the macro
  95346. * FLAC__INTEGER_ONLY_LIBRARY.
  95347. *
  95348. * FLAC__real is the basic floating point type used in LPC analysis.
  95349. */
  95350. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95351. typedef double FLAC__double;
  95352. typedef float FLAC__float;
  95353. /*
  95354. * WATCHOUT: changing FLAC__real will change the signatures of many
  95355. * functions that have assembly language equivalents and break them.
  95356. */
  95357. typedef float FLAC__real;
  95358. #else
  95359. /*
  95360. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95361. * for the integer part and lower 16 bits for the fractional part.
  95362. */
  95363. typedef FLAC__int32 FLAC__fixedpoint;
  95364. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95365. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95366. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95367. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95368. extern const FLAC__fixedpoint FLAC__FP_E;
  95369. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95370. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95371. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95372. /*
  95373. * FLAC__fixedpoint_log2()
  95374. * --------------------------------------------------------------------
  95375. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95376. * algorithm by Knuth for x >= 1.0
  95377. *
  95378. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95379. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95380. *
  95381. * 'precision' roughly limits the number of iterations that are done;
  95382. * use (unsigned)(-1) for maximum precision.
  95383. *
  95384. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95385. * function will punt and return 0.
  95386. *
  95387. * The return value will also have 'fracbits' fractional bits.
  95388. */
  95389. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95390. #endif
  95391. #endif
  95392. /*** End of inlined file: float.h ***/
  95393. /*** Start of inlined file: format.h ***/
  95394. #ifndef FLAC__PRIVATE__FORMAT_H
  95395. #define FLAC__PRIVATE__FORMAT_H
  95396. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95397. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95398. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95399. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95400. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95401. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95402. #endif
  95403. /*** End of inlined file: format.h ***/
  95404. /*
  95405. * FLAC__fixed_compute_best_predictor()
  95406. * --------------------------------------------------------------------
  95407. * Compute the best fixed predictor and the expected bits-per-sample
  95408. * of the residual signal for each order. The _wide() version uses
  95409. * 64-bit integers which is statistically necessary when bits-per-
  95410. * sample + log2(blocksize) > 30
  95411. *
  95412. * IN data[0,data_len-1]
  95413. * IN data_len
  95414. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95415. */
  95416. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95417. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95418. # ifndef FLAC__NO_ASM
  95419. # ifdef FLAC__CPU_IA32
  95420. # ifdef FLAC__HAS_NASM
  95421. 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]);
  95422. # endif
  95423. # endif
  95424. # endif
  95425. 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]);
  95426. #else
  95427. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95428. 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]);
  95429. #endif
  95430. /*
  95431. * FLAC__fixed_compute_residual()
  95432. * --------------------------------------------------------------------
  95433. * Compute the residual signal obtained from sutracting the predicted
  95434. * signal from the original.
  95435. *
  95436. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95437. * IN data_len length of original signal
  95438. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95439. * OUT residual[0,data_len-1] residual signal
  95440. */
  95441. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95442. /*
  95443. * FLAC__fixed_restore_signal()
  95444. * --------------------------------------------------------------------
  95445. * Restore the original signal by summing the residual and the
  95446. * predictor.
  95447. *
  95448. * IN residual[0,data_len-1] residual signal
  95449. * IN data_len length of original signal
  95450. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95451. * *** IMPORTANT: the caller must pass in the historical samples:
  95452. * IN data[-order,-1] previously-reconstructed historical samples
  95453. * OUT data[0,data_len-1] original signal
  95454. */
  95455. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95456. #endif
  95457. /*** End of inlined file: fixed.h ***/
  95458. #ifndef M_LN2
  95459. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95460. #define M_LN2 0.69314718055994530942
  95461. #endif
  95462. #ifdef min
  95463. #undef min
  95464. #endif
  95465. #define min(x,y) ((x) < (y)? (x) : (y))
  95466. #ifdef local_abs
  95467. #undef local_abs
  95468. #endif
  95469. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95470. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95471. /* rbps stands for residual bits per sample
  95472. *
  95473. * (ln(2) * err)
  95474. * rbps = log (-----------)
  95475. * 2 ( n )
  95476. */
  95477. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95478. {
  95479. FLAC__uint32 rbps;
  95480. unsigned bits; /* the number of bits required to represent a number */
  95481. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95482. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95483. FLAC__ASSERT(err > 0);
  95484. FLAC__ASSERT(n > 0);
  95485. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95486. if(err <= n)
  95487. return 0;
  95488. /*
  95489. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95490. * These allow us later to know we won't lose too much precision in the
  95491. * fixed-point division (err<<fracbits)/n.
  95492. */
  95493. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95494. err <<= fracbits;
  95495. err /= n;
  95496. /* err now holds err/n with fracbits fractional bits */
  95497. /*
  95498. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95499. * our purposes.
  95500. */
  95501. FLAC__ASSERT(err > 0);
  95502. bits = FLAC__bitmath_ilog2(err)+1;
  95503. if(bits > 16) {
  95504. err >>= (bits-16);
  95505. fracbits -= (bits-16);
  95506. }
  95507. rbps = (FLAC__uint32)err;
  95508. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95509. rbps *= FLAC__FP_LN2;
  95510. fracbits += 16;
  95511. FLAC__ASSERT(fracbits >= 0);
  95512. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95513. {
  95514. const int f = fracbits & 3;
  95515. if(f) {
  95516. rbps >>= f;
  95517. fracbits -= f;
  95518. }
  95519. }
  95520. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95521. if(rbps == 0)
  95522. return 0;
  95523. /*
  95524. * The return value must have 16 fractional bits. Since the whole part
  95525. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95526. * must be >= -3, these assertion allows us to be able to shift rbps
  95527. * left if necessary to get 16 fracbits without losing any bits of the
  95528. * whole part of rbps.
  95529. *
  95530. * There is a slight chance due to accumulated error that the whole part
  95531. * will require 6 bits, so we use 6 in the assertion. Really though as
  95532. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95533. */
  95534. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95535. FLAC__ASSERT(fracbits >= -3);
  95536. /* now shift the decimal point into place */
  95537. if(fracbits < 16)
  95538. return rbps << (16-fracbits);
  95539. else if(fracbits > 16)
  95540. return rbps >> (fracbits-16);
  95541. else
  95542. return rbps;
  95543. }
  95544. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95545. {
  95546. FLAC__uint32 rbps;
  95547. unsigned bits; /* the number of bits required to represent a number */
  95548. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95549. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95550. FLAC__ASSERT(err > 0);
  95551. FLAC__ASSERT(n > 0);
  95552. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95553. if(err <= n)
  95554. return 0;
  95555. /*
  95556. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95557. * These allow us later to know we won't lose too much precision in the
  95558. * fixed-point division (err<<fracbits)/n.
  95559. */
  95560. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95561. err <<= fracbits;
  95562. err /= n;
  95563. /* err now holds err/n with fracbits fractional bits */
  95564. /*
  95565. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95566. * our purposes.
  95567. */
  95568. FLAC__ASSERT(err > 0);
  95569. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95570. if(bits > 16) {
  95571. err >>= (bits-16);
  95572. fracbits -= (bits-16);
  95573. }
  95574. rbps = (FLAC__uint32)err;
  95575. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95576. rbps *= FLAC__FP_LN2;
  95577. fracbits += 16;
  95578. FLAC__ASSERT(fracbits >= 0);
  95579. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95580. {
  95581. const int f = fracbits & 3;
  95582. if(f) {
  95583. rbps >>= f;
  95584. fracbits -= f;
  95585. }
  95586. }
  95587. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95588. if(rbps == 0)
  95589. return 0;
  95590. /*
  95591. * The return value must have 16 fractional bits. Since the whole part
  95592. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95593. * must be >= -3, these assertion allows us to be able to shift rbps
  95594. * left if necessary to get 16 fracbits without losing any bits of the
  95595. * whole part of rbps.
  95596. *
  95597. * There is a slight chance due to accumulated error that the whole part
  95598. * will require 6 bits, so we use 6 in the assertion. Really though as
  95599. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95600. */
  95601. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95602. FLAC__ASSERT(fracbits >= -3);
  95603. /* now shift the decimal point into place */
  95604. if(fracbits < 16)
  95605. return rbps << (16-fracbits);
  95606. else if(fracbits > 16)
  95607. return rbps >> (fracbits-16);
  95608. else
  95609. return rbps;
  95610. }
  95611. #endif
  95612. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95613. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95614. #else
  95615. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95616. #endif
  95617. {
  95618. FLAC__int32 last_error_0 = data[-1];
  95619. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95620. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95621. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95622. FLAC__int32 error, save;
  95623. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95624. unsigned i, order;
  95625. for(i = 0; i < data_len; i++) {
  95626. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95627. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95628. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95629. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95630. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95631. }
  95632. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95633. order = 0;
  95634. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95635. order = 1;
  95636. else if(total_error_2 < min(total_error_3, total_error_4))
  95637. order = 2;
  95638. else if(total_error_3 < total_error_4)
  95639. order = 3;
  95640. else
  95641. order = 4;
  95642. /* Estimate the expected number of bits per residual signal sample. */
  95643. /* 'total_error*' is linearly related to the variance of the residual */
  95644. /* signal, so we use it directly to compute E(|x|) */
  95645. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95646. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95647. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95648. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95649. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95650. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95651. 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);
  95652. 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);
  95653. 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);
  95654. 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);
  95655. 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);
  95656. #else
  95657. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95658. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95659. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95660. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95661. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95662. #endif
  95663. return order;
  95664. }
  95665. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95666. 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])
  95667. #else
  95668. 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])
  95669. #endif
  95670. {
  95671. FLAC__int32 last_error_0 = data[-1];
  95672. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95673. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95674. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95675. FLAC__int32 error, save;
  95676. /* total_error_* are 64-bits to avoid overflow when encoding
  95677. * erratic signals when the bits-per-sample and blocksize are
  95678. * large.
  95679. */
  95680. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95681. unsigned i, order;
  95682. for(i = 0; i < data_len; i++) {
  95683. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95684. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95685. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95686. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95687. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95688. }
  95689. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95690. order = 0;
  95691. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95692. order = 1;
  95693. else if(total_error_2 < min(total_error_3, total_error_4))
  95694. order = 2;
  95695. else if(total_error_3 < total_error_4)
  95696. order = 3;
  95697. else
  95698. order = 4;
  95699. /* Estimate the expected number of bits per residual signal sample. */
  95700. /* 'total_error*' is linearly related to the variance of the residual */
  95701. /* signal, so we use it directly to compute E(|x|) */
  95702. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95703. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95704. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95705. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95706. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95707. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95708. #if defined _MSC_VER || defined __MINGW32__
  95709. /* with MSVC you have to spoon feed it the casting */
  95710. 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);
  95711. 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);
  95712. 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);
  95713. 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);
  95714. 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);
  95715. #else
  95716. 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);
  95717. 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);
  95718. 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);
  95719. 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);
  95720. 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);
  95721. #endif
  95722. #else
  95723. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95724. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95725. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95726. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95727. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95728. #endif
  95729. return order;
  95730. }
  95731. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95732. {
  95733. const int idata_len = (int)data_len;
  95734. int i;
  95735. switch(order) {
  95736. case 0:
  95737. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95738. memcpy(residual, data, sizeof(residual[0])*data_len);
  95739. break;
  95740. case 1:
  95741. for(i = 0; i < idata_len; i++)
  95742. residual[i] = data[i] - data[i-1];
  95743. break;
  95744. case 2:
  95745. for(i = 0; i < idata_len; i++)
  95746. #if 1 /* OPT: may be faster with some compilers on some systems */
  95747. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95748. #else
  95749. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95750. #endif
  95751. break;
  95752. case 3:
  95753. for(i = 0; i < idata_len; i++)
  95754. #if 1 /* OPT: may be faster with some compilers on some systems */
  95755. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95756. #else
  95757. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95758. #endif
  95759. break;
  95760. case 4:
  95761. for(i = 0; i < idata_len; i++)
  95762. #if 1 /* OPT: may be faster with some compilers on some systems */
  95763. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95764. #else
  95765. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95766. #endif
  95767. break;
  95768. default:
  95769. FLAC__ASSERT(0);
  95770. }
  95771. }
  95772. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95773. {
  95774. int i, idata_len = (int)data_len;
  95775. switch(order) {
  95776. case 0:
  95777. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95778. memcpy(data, residual, sizeof(residual[0])*data_len);
  95779. break;
  95780. case 1:
  95781. for(i = 0; i < idata_len; i++)
  95782. data[i] = residual[i] + data[i-1];
  95783. break;
  95784. case 2:
  95785. for(i = 0; i < idata_len; i++)
  95786. #if 1 /* OPT: may be faster with some compilers on some systems */
  95787. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95788. #else
  95789. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95790. #endif
  95791. break;
  95792. case 3:
  95793. for(i = 0; i < idata_len; i++)
  95794. #if 1 /* OPT: may be faster with some compilers on some systems */
  95795. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95796. #else
  95797. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95798. #endif
  95799. break;
  95800. case 4:
  95801. for(i = 0; i < idata_len; i++)
  95802. #if 1 /* OPT: may be faster with some compilers on some systems */
  95803. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95804. #else
  95805. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95806. #endif
  95807. break;
  95808. default:
  95809. FLAC__ASSERT(0);
  95810. }
  95811. }
  95812. #endif
  95813. /*** End of inlined file: fixed.c ***/
  95814. /*** Start of inlined file: float.c ***/
  95815. /*** Start of inlined file: juce_FlacHeader.h ***/
  95816. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95817. // tasks..
  95818. #define VERSION "1.2.1"
  95819. #define FLAC__NO_DLL 1
  95820. #if JUCE_MSVC
  95821. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95822. #endif
  95823. #if JUCE_MAC
  95824. #define FLAC__SYS_DARWIN 1
  95825. #endif
  95826. /*** End of inlined file: juce_FlacHeader.h ***/
  95827. #if JUCE_USE_FLAC
  95828. #if HAVE_CONFIG_H
  95829. # include <config.h>
  95830. #endif
  95831. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95832. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95833. #ifdef _MSC_VER
  95834. #define FLAC__U64L(x) x
  95835. #else
  95836. #define FLAC__U64L(x) x##LLU
  95837. #endif
  95838. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95839. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95840. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95841. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95842. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95843. /* Lookup tables for Knuth's logarithm algorithm */
  95844. #define LOG2_LOOKUP_PRECISION 16
  95845. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95846. {
  95847. /*
  95848. * 0 fraction bits
  95849. */
  95850. /* undefined */ 0x00000000,
  95851. /* lg(2/1) = */ 0x00000001,
  95852. /* lg(4/3) = */ 0x00000000,
  95853. /* lg(8/7) = */ 0x00000000,
  95854. /* lg(16/15) = */ 0x00000000,
  95855. /* lg(32/31) = */ 0x00000000,
  95856. /* lg(64/63) = */ 0x00000000,
  95857. /* lg(128/127) = */ 0x00000000,
  95858. /* lg(256/255) = */ 0x00000000,
  95859. /* lg(512/511) = */ 0x00000000,
  95860. /* lg(1024/1023) = */ 0x00000000,
  95861. /* lg(2048/2047) = */ 0x00000000,
  95862. /* lg(4096/4095) = */ 0x00000000,
  95863. /* lg(8192/8191) = */ 0x00000000,
  95864. /* lg(16384/16383) = */ 0x00000000,
  95865. /* lg(32768/32767) = */ 0x00000000
  95866. },
  95867. {
  95868. /*
  95869. * 4 fraction bits
  95870. */
  95871. /* undefined */ 0x00000000,
  95872. /* lg(2/1) = */ 0x00000010,
  95873. /* lg(4/3) = */ 0x00000007,
  95874. /* lg(8/7) = */ 0x00000003,
  95875. /* lg(16/15) = */ 0x00000001,
  95876. /* lg(32/31) = */ 0x00000001,
  95877. /* lg(64/63) = */ 0x00000000,
  95878. /* lg(128/127) = */ 0x00000000,
  95879. /* lg(256/255) = */ 0x00000000,
  95880. /* lg(512/511) = */ 0x00000000,
  95881. /* lg(1024/1023) = */ 0x00000000,
  95882. /* lg(2048/2047) = */ 0x00000000,
  95883. /* lg(4096/4095) = */ 0x00000000,
  95884. /* lg(8192/8191) = */ 0x00000000,
  95885. /* lg(16384/16383) = */ 0x00000000,
  95886. /* lg(32768/32767) = */ 0x00000000
  95887. },
  95888. {
  95889. /*
  95890. * 8 fraction bits
  95891. */
  95892. /* undefined */ 0x00000000,
  95893. /* lg(2/1) = */ 0x00000100,
  95894. /* lg(4/3) = */ 0x0000006a,
  95895. /* lg(8/7) = */ 0x00000031,
  95896. /* lg(16/15) = */ 0x00000018,
  95897. /* lg(32/31) = */ 0x0000000c,
  95898. /* lg(64/63) = */ 0x00000006,
  95899. /* lg(128/127) = */ 0x00000003,
  95900. /* lg(256/255) = */ 0x00000001,
  95901. /* lg(512/511) = */ 0x00000001,
  95902. /* lg(1024/1023) = */ 0x00000000,
  95903. /* lg(2048/2047) = */ 0x00000000,
  95904. /* lg(4096/4095) = */ 0x00000000,
  95905. /* lg(8192/8191) = */ 0x00000000,
  95906. /* lg(16384/16383) = */ 0x00000000,
  95907. /* lg(32768/32767) = */ 0x00000000
  95908. },
  95909. {
  95910. /*
  95911. * 12 fraction bits
  95912. */
  95913. /* undefined */ 0x00000000,
  95914. /* lg(2/1) = */ 0x00001000,
  95915. /* lg(4/3) = */ 0x000006a4,
  95916. /* lg(8/7) = */ 0x00000315,
  95917. /* lg(16/15) = */ 0x0000017d,
  95918. /* lg(32/31) = */ 0x000000bc,
  95919. /* lg(64/63) = */ 0x0000005d,
  95920. /* lg(128/127) = */ 0x0000002e,
  95921. /* lg(256/255) = */ 0x00000017,
  95922. /* lg(512/511) = */ 0x0000000c,
  95923. /* lg(1024/1023) = */ 0x00000006,
  95924. /* lg(2048/2047) = */ 0x00000003,
  95925. /* lg(4096/4095) = */ 0x00000001,
  95926. /* lg(8192/8191) = */ 0x00000001,
  95927. /* lg(16384/16383) = */ 0x00000000,
  95928. /* lg(32768/32767) = */ 0x00000000
  95929. },
  95930. {
  95931. /*
  95932. * 16 fraction bits
  95933. */
  95934. /* undefined */ 0x00000000,
  95935. /* lg(2/1) = */ 0x00010000,
  95936. /* lg(4/3) = */ 0x00006a40,
  95937. /* lg(8/7) = */ 0x00003151,
  95938. /* lg(16/15) = */ 0x000017d6,
  95939. /* lg(32/31) = */ 0x00000bba,
  95940. /* lg(64/63) = */ 0x000005d1,
  95941. /* lg(128/127) = */ 0x000002e6,
  95942. /* lg(256/255) = */ 0x00000172,
  95943. /* lg(512/511) = */ 0x000000b9,
  95944. /* lg(1024/1023) = */ 0x0000005c,
  95945. /* lg(2048/2047) = */ 0x0000002e,
  95946. /* lg(4096/4095) = */ 0x00000017,
  95947. /* lg(8192/8191) = */ 0x0000000c,
  95948. /* lg(16384/16383) = */ 0x00000006,
  95949. /* lg(32768/32767) = */ 0x00000003
  95950. },
  95951. {
  95952. /*
  95953. * 20 fraction bits
  95954. */
  95955. /* undefined */ 0x00000000,
  95956. /* lg(2/1) = */ 0x00100000,
  95957. /* lg(4/3) = */ 0x0006a3fe,
  95958. /* lg(8/7) = */ 0x00031513,
  95959. /* lg(16/15) = */ 0x00017d60,
  95960. /* lg(32/31) = */ 0x0000bb9d,
  95961. /* lg(64/63) = */ 0x00005d10,
  95962. /* lg(128/127) = */ 0x00002e59,
  95963. /* lg(256/255) = */ 0x00001721,
  95964. /* lg(512/511) = */ 0x00000b8e,
  95965. /* lg(1024/1023) = */ 0x000005c6,
  95966. /* lg(2048/2047) = */ 0x000002e3,
  95967. /* lg(4096/4095) = */ 0x00000171,
  95968. /* lg(8192/8191) = */ 0x000000b9,
  95969. /* lg(16384/16383) = */ 0x0000005c,
  95970. /* lg(32768/32767) = */ 0x0000002e
  95971. },
  95972. {
  95973. /*
  95974. * 24 fraction bits
  95975. */
  95976. /* undefined */ 0x00000000,
  95977. /* lg(2/1) = */ 0x01000000,
  95978. /* lg(4/3) = */ 0x006a3fe6,
  95979. /* lg(8/7) = */ 0x00315130,
  95980. /* lg(16/15) = */ 0x0017d605,
  95981. /* lg(32/31) = */ 0x000bb9ca,
  95982. /* lg(64/63) = */ 0x0005d0fc,
  95983. /* lg(128/127) = */ 0x0002e58f,
  95984. /* lg(256/255) = */ 0x0001720e,
  95985. /* lg(512/511) = */ 0x0000b8d8,
  95986. /* lg(1024/1023) = */ 0x00005c61,
  95987. /* lg(2048/2047) = */ 0x00002e2d,
  95988. /* lg(4096/4095) = */ 0x00001716,
  95989. /* lg(8192/8191) = */ 0x00000b8b,
  95990. /* lg(16384/16383) = */ 0x000005c5,
  95991. /* lg(32768/32767) = */ 0x000002e3
  95992. },
  95993. {
  95994. /*
  95995. * 28 fraction bits
  95996. */
  95997. /* undefined */ 0x00000000,
  95998. /* lg(2/1) = */ 0x10000000,
  95999. /* lg(4/3) = */ 0x06a3fe5c,
  96000. /* lg(8/7) = */ 0x03151301,
  96001. /* lg(16/15) = */ 0x017d6049,
  96002. /* lg(32/31) = */ 0x00bb9ca6,
  96003. /* lg(64/63) = */ 0x005d0fba,
  96004. /* lg(128/127) = */ 0x002e58f7,
  96005. /* lg(256/255) = */ 0x001720da,
  96006. /* lg(512/511) = */ 0x000b8d87,
  96007. /* lg(1024/1023) = */ 0x0005c60b,
  96008. /* lg(2048/2047) = */ 0x0002e2d7,
  96009. /* lg(4096/4095) = */ 0x00017160,
  96010. /* lg(8192/8191) = */ 0x0000b8ad,
  96011. /* lg(16384/16383) = */ 0x00005c56,
  96012. /* lg(32768/32767) = */ 0x00002e2b
  96013. }
  96014. };
  96015. #if 0
  96016. static const FLAC__uint64 log2_lookup_wide[] = {
  96017. {
  96018. /*
  96019. * 32 fraction bits
  96020. */
  96021. /* undefined */ 0x00000000,
  96022. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96023. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96024. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96025. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96026. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96027. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96028. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96029. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96030. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96031. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96032. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96033. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96034. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96035. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96036. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96037. },
  96038. {
  96039. /*
  96040. * 48 fraction bits
  96041. */
  96042. /* undefined */ 0x00000000,
  96043. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96044. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96045. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96046. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96047. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96048. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96049. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96050. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96051. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96052. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96053. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96054. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96055. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96056. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96057. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96058. }
  96059. };
  96060. #endif
  96061. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96062. {
  96063. const FLAC__uint32 ONE = (1u << fracbits);
  96064. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96065. FLAC__ASSERT(fracbits < 32);
  96066. FLAC__ASSERT((fracbits & 0x3) == 0);
  96067. if(x < ONE)
  96068. return 0;
  96069. if(precision > LOG2_LOOKUP_PRECISION)
  96070. precision = LOG2_LOOKUP_PRECISION;
  96071. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96072. {
  96073. FLAC__uint32 y = 0;
  96074. FLAC__uint32 z = x >> 1, k = 1;
  96075. while (x > ONE && k < precision) {
  96076. if (x - z >= ONE) {
  96077. x -= z;
  96078. z = x >> k;
  96079. y += table[k];
  96080. }
  96081. else {
  96082. z >>= 1;
  96083. k++;
  96084. }
  96085. }
  96086. return y;
  96087. }
  96088. }
  96089. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96090. #endif
  96091. /*** End of inlined file: float.c ***/
  96092. /*** Start of inlined file: format.c ***/
  96093. /*** Start of inlined file: juce_FlacHeader.h ***/
  96094. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96095. // tasks..
  96096. #define VERSION "1.2.1"
  96097. #define FLAC__NO_DLL 1
  96098. #if JUCE_MSVC
  96099. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96100. #endif
  96101. #if JUCE_MAC
  96102. #define FLAC__SYS_DARWIN 1
  96103. #endif
  96104. /*** End of inlined file: juce_FlacHeader.h ***/
  96105. #if JUCE_USE_FLAC
  96106. #if HAVE_CONFIG_H
  96107. # include <config.h>
  96108. #endif
  96109. #include <stdio.h>
  96110. #include <stdlib.h> /* for qsort() */
  96111. #include <string.h> /* for memset() */
  96112. #ifndef FLaC__INLINE
  96113. #define FLaC__INLINE
  96114. #endif
  96115. #ifdef min
  96116. #undef min
  96117. #endif
  96118. #define min(a,b) ((a)<(b)?(a):(b))
  96119. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96120. #ifdef _MSC_VER
  96121. #define FLAC__U64L(x) x
  96122. #else
  96123. #define FLAC__U64L(x) x##LLU
  96124. #endif
  96125. /* VERSION should come from configure */
  96126. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96127. ;
  96128. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96129. /* yet one more hack because of MSVC6: */
  96130. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96131. #else
  96132. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96133. #endif
  96134. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96135. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96136. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96137. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96138. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96139. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96140. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96141. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96142. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96143. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96144. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96145. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96146. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96147. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96148. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96149. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96150. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96151. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96152. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96153. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96154. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96155. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96156. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96157. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96158. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96159. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96160. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96161. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96162. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96163. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96164. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96165. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96166. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96167. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96168. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96169. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96170. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96171. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96172. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96173. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96174. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96175. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96176. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96177. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96178. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96179. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96180. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96181. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96182. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96183. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96184. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96185. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96186. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96187. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96188. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96189. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96190. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96191. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96192. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96193. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96194. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96195. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96196. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96197. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96198. "PARTITIONED_RICE",
  96199. "PARTITIONED_RICE2"
  96200. };
  96201. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96202. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96203. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96204. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96205. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96206. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96207. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96208. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96209. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96210. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96211. "CONSTANT",
  96212. "VERBATIM",
  96213. "FIXED",
  96214. "LPC"
  96215. };
  96216. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96217. "INDEPENDENT",
  96218. "LEFT_SIDE",
  96219. "RIGHT_SIDE",
  96220. "MID_SIDE"
  96221. };
  96222. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96223. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96224. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96225. };
  96226. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96227. "STREAMINFO",
  96228. "PADDING",
  96229. "APPLICATION",
  96230. "SEEKTABLE",
  96231. "VORBIS_COMMENT",
  96232. "CUESHEET",
  96233. "PICTURE"
  96234. };
  96235. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96236. "Other",
  96237. "32x32 pixels 'file icon' (PNG only)",
  96238. "Other file icon",
  96239. "Cover (front)",
  96240. "Cover (back)",
  96241. "Leaflet page",
  96242. "Media (e.g. label side of CD)",
  96243. "Lead artist/lead performer/soloist",
  96244. "Artist/performer",
  96245. "Conductor",
  96246. "Band/Orchestra",
  96247. "Composer",
  96248. "Lyricist/text writer",
  96249. "Recording Location",
  96250. "During recording",
  96251. "During performance",
  96252. "Movie/video screen capture",
  96253. "A bright coloured fish",
  96254. "Illustration",
  96255. "Band/artist logotype",
  96256. "Publisher/Studio logotype"
  96257. };
  96258. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96259. {
  96260. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96261. return false;
  96262. }
  96263. else
  96264. return true;
  96265. }
  96266. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96267. {
  96268. if(
  96269. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96270. (
  96271. sample_rate >= (1u << 16) &&
  96272. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96273. )
  96274. ) {
  96275. return false;
  96276. }
  96277. else
  96278. return true;
  96279. }
  96280. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96281. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96282. {
  96283. unsigned i;
  96284. FLAC__uint64 prev_sample_number = 0;
  96285. FLAC__bool got_prev = false;
  96286. FLAC__ASSERT(0 != seek_table);
  96287. for(i = 0; i < seek_table->num_points; i++) {
  96288. if(got_prev) {
  96289. if(
  96290. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96291. seek_table->points[i].sample_number <= prev_sample_number
  96292. )
  96293. return false;
  96294. }
  96295. prev_sample_number = seek_table->points[i].sample_number;
  96296. got_prev = true;
  96297. }
  96298. return true;
  96299. }
  96300. /* used as the sort predicate for qsort() */
  96301. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96302. {
  96303. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96304. if(l->sample_number == r->sample_number)
  96305. return 0;
  96306. else if(l->sample_number < r->sample_number)
  96307. return -1;
  96308. else
  96309. return 1;
  96310. }
  96311. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96312. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96313. {
  96314. unsigned i, j;
  96315. FLAC__bool first;
  96316. FLAC__ASSERT(0 != seek_table);
  96317. /* sort the seekpoints */
  96318. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96319. /* uniquify the seekpoints */
  96320. first = true;
  96321. for(i = j = 0; i < seek_table->num_points; i++) {
  96322. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96323. if(!first) {
  96324. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96325. continue;
  96326. }
  96327. }
  96328. first = false;
  96329. seek_table->points[j++] = seek_table->points[i];
  96330. }
  96331. for(i = j; i < seek_table->num_points; i++) {
  96332. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96333. seek_table->points[i].stream_offset = 0;
  96334. seek_table->points[i].frame_samples = 0;
  96335. }
  96336. return j;
  96337. }
  96338. /*
  96339. * also disallows non-shortest-form encodings, c.f.
  96340. * http://www.unicode.org/versions/corrigendum1.html
  96341. * and a more clear explanation at the end of this section:
  96342. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96343. */
  96344. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96345. {
  96346. FLAC__ASSERT(0 != utf8);
  96347. if ((utf8[0] & 0x80) == 0) {
  96348. return 1;
  96349. }
  96350. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96351. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96352. return 0;
  96353. return 2;
  96354. }
  96355. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96356. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96357. return 0;
  96358. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96359. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96360. return 0;
  96361. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96362. return 0;
  96363. return 3;
  96364. }
  96365. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96366. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96367. return 0;
  96368. return 4;
  96369. }
  96370. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96371. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96372. return 0;
  96373. return 5;
  96374. }
  96375. 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) {
  96376. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96377. return 0;
  96378. return 6;
  96379. }
  96380. else {
  96381. return 0;
  96382. }
  96383. }
  96384. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96385. {
  96386. char c;
  96387. for(c = *name; c; c = *(++name))
  96388. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96389. return false;
  96390. return true;
  96391. }
  96392. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96393. {
  96394. if(length == (unsigned)(-1)) {
  96395. while(*value) {
  96396. unsigned n = utf8len_(value);
  96397. if(n == 0)
  96398. return false;
  96399. value += n;
  96400. }
  96401. }
  96402. else {
  96403. const FLAC__byte *end = value + length;
  96404. while(value < end) {
  96405. unsigned n = utf8len_(value);
  96406. if(n == 0)
  96407. return false;
  96408. value += n;
  96409. }
  96410. if(value != end)
  96411. return false;
  96412. }
  96413. return true;
  96414. }
  96415. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96416. {
  96417. const FLAC__byte *s, *end;
  96418. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96419. if(*s < 0x20 || *s > 0x7D)
  96420. return false;
  96421. }
  96422. if(s == end)
  96423. return false;
  96424. s++; /* skip '=' */
  96425. while(s < end) {
  96426. unsigned n = utf8len_(s);
  96427. if(n == 0)
  96428. return false;
  96429. s += n;
  96430. }
  96431. if(s != end)
  96432. return false;
  96433. return true;
  96434. }
  96435. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96436. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96437. {
  96438. unsigned i, j;
  96439. if(check_cd_da_subset) {
  96440. if(cue_sheet->lead_in < 2 * 44100) {
  96441. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96442. return false;
  96443. }
  96444. if(cue_sheet->lead_in % 588 != 0) {
  96445. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96446. return false;
  96447. }
  96448. }
  96449. if(cue_sheet->num_tracks == 0) {
  96450. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96451. return false;
  96452. }
  96453. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96454. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96455. return false;
  96456. }
  96457. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96458. if(cue_sheet->tracks[i].number == 0) {
  96459. if(violation) *violation = "cue sheet may not have a track number 0";
  96460. return false;
  96461. }
  96462. if(check_cd_da_subset) {
  96463. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96464. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96465. return false;
  96466. }
  96467. }
  96468. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96469. if(violation) {
  96470. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96471. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96472. else
  96473. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96474. }
  96475. return false;
  96476. }
  96477. if(i < cue_sheet->num_tracks - 1) {
  96478. if(cue_sheet->tracks[i].num_indices == 0) {
  96479. if(violation) *violation = "cue sheet track must have at least one index point";
  96480. return false;
  96481. }
  96482. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96483. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96484. return false;
  96485. }
  96486. }
  96487. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96488. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96489. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96490. return false;
  96491. }
  96492. if(j > 0) {
  96493. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96494. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96495. return false;
  96496. }
  96497. }
  96498. }
  96499. }
  96500. return true;
  96501. }
  96502. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96503. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96504. {
  96505. char *p;
  96506. FLAC__byte *b;
  96507. for(p = picture->mime_type; *p; p++) {
  96508. if(*p < 0x20 || *p > 0x7e) {
  96509. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96510. return false;
  96511. }
  96512. }
  96513. for(b = picture->description; *b; ) {
  96514. unsigned n = utf8len_(b);
  96515. if(n == 0) {
  96516. if(violation) *violation = "description string must be valid UTF-8";
  96517. return false;
  96518. }
  96519. b += n;
  96520. }
  96521. return true;
  96522. }
  96523. /*
  96524. * These routines are private to libFLAC
  96525. */
  96526. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96527. {
  96528. return
  96529. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96530. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96531. blocksize,
  96532. predictor_order
  96533. );
  96534. }
  96535. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96536. {
  96537. unsigned max_rice_partition_order = 0;
  96538. while(!(blocksize & 1)) {
  96539. max_rice_partition_order++;
  96540. blocksize >>= 1;
  96541. }
  96542. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96543. }
  96544. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96545. {
  96546. unsigned max_rice_partition_order = limit;
  96547. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96548. max_rice_partition_order--;
  96549. FLAC__ASSERT(
  96550. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96551. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96552. );
  96553. return max_rice_partition_order;
  96554. }
  96555. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96556. {
  96557. FLAC__ASSERT(0 != object);
  96558. object->parameters = 0;
  96559. object->raw_bits = 0;
  96560. object->capacity_by_order = 0;
  96561. }
  96562. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96563. {
  96564. FLAC__ASSERT(0 != object);
  96565. if(0 != object->parameters)
  96566. free(object->parameters);
  96567. if(0 != object->raw_bits)
  96568. free(object->raw_bits);
  96569. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96570. }
  96571. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96572. {
  96573. FLAC__ASSERT(0 != object);
  96574. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96575. if(object->capacity_by_order < max_partition_order) {
  96576. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96577. return false;
  96578. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96579. return false;
  96580. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96581. object->capacity_by_order = max_partition_order;
  96582. }
  96583. return true;
  96584. }
  96585. #endif
  96586. /*** End of inlined file: format.c ***/
  96587. /*** Start of inlined file: lpc_flac.c ***/
  96588. /*** Start of inlined file: juce_FlacHeader.h ***/
  96589. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96590. // tasks..
  96591. #define VERSION "1.2.1"
  96592. #define FLAC__NO_DLL 1
  96593. #if JUCE_MSVC
  96594. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96595. #endif
  96596. #if JUCE_MAC
  96597. #define FLAC__SYS_DARWIN 1
  96598. #endif
  96599. /*** End of inlined file: juce_FlacHeader.h ***/
  96600. #if JUCE_USE_FLAC
  96601. #if HAVE_CONFIG_H
  96602. # include <config.h>
  96603. #endif
  96604. #include <math.h>
  96605. /*** Start of inlined file: lpc.h ***/
  96606. #ifndef FLAC__PRIVATE__LPC_H
  96607. #define FLAC__PRIVATE__LPC_H
  96608. #ifdef HAVE_CONFIG_H
  96609. #include <config.h>
  96610. #endif
  96611. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96612. /*
  96613. * FLAC__lpc_window_data()
  96614. * --------------------------------------------------------------------
  96615. * Applies the given window to the data.
  96616. * OPT: asm implementation
  96617. *
  96618. * IN in[0,data_len-1]
  96619. * IN window[0,data_len-1]
  96620. * OUT out[0,lag-1]
  96621. * IN data_len
  96622. */
  96623. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96624. /*
  96625. * FLAC__lpc_compute_autocorrelation()
  96626. * --------------------------------------------------------------------
  96627. * Compute the autocorrelation for lags between 0 and lag-1.
  96628. * Assumes data[] outside of [0,data_len-1] == 0.
  96629. * Asserts that lag > 0.
  96630. *
  96631. * IN data[0,data_len-1]
  96632. * IN data_len
  96633. * IN 0 < lag <= data_len
  96634. * OUT autoc[0,lag-1]
  96635. */
  96636. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96637. #ifndef FLAC__NO_ASM
  96638. # ifdef FLAC__CPU_IA32
  96639. # ifdef FLAC__HAS_NASM
  96640. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96641. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96642. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96643. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96644. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96645. # endif
  96646. # endif
  96647. #endif
  96648. /*
  96649. * FLAC__lpc_compute_lp_coefficients()
  96650. * --------------------------------------------------------------------
  96651. * Computes LP coefficients for orders 1..max_order.
  96652. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96653. * and there is no point in calculating a predictor.
  96654. *
  96655. * IN autoc[0,max_order] autocorrelation values
  96656. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96657. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96658. * *** IMPORTANT:
  96659. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96660. * OUT error[0,max_order-1] error for each order (more
  96661. * specifically, the variance of
  96662. * the error signal times # of
  96663. * samples in the signal)
  96664. *
  96665. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96666. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96667. * in lp_coeff[7][0,7], etc.
  96668. */
  96669. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96670. /*
  96671. * FLAC__lpc_quantize_coefficients()
  96672. * --------------------------------------------------------------------
  96673. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96674. * must be less than 32 (sizeof(FLAC__int32)*8).
  96675. *
  96676. * IN lp_coeff[0,order-1] LP coefficients
  96677. * IN order LP order
  96678. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96679. * desired precision (in bits, including sign
  96680. * bit) of largest coefficient
  96681. * OUT qlp_coeff[0,order-1] quantized coefficients
  96682. * OUT shift # of bits to shift right to get approximated
  96683. * LP coefficients. NOTE: could be negative.
  96684. * RETURN 0 => quantization OK
  96685. * 1 => coefficients require too much shifting for *shift to
  96686. * fit in the LPC subframe header. 'shift' is unset.
  96687. * 2 => coefficients are all zero, which is bad. 'shift' is
  96688. * unset.
  96689. */
  96690. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96691. /*
  96692. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96693. * --------------------------------------------------------------------
  96694. * Compute the residual signal obtained from sutracting the predicted
  96695. * signal from the original.
  96696. *
  96697. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96698. * IN data_len length of original signal
  96699. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96700. * IN order > 0 LP order
  96701. * IN lp_quantization quantization of LP coefficients in bits
  96702. * OUT residual[0,data_len-1] residual signal
  96703. */
  96704. 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[]);
  96705. 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[]);
  96706. #ifndef FLAC__NO_ASM
  96707. # ifdef FLAC__CPU_IA32
  96708. # ifdef FLAC__HAS_NASM
  96709. 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[]);
  96710. 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[]);
  96711. # endif
  96712. # endif
  96713. #endif
  96714. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96715. /*
  96716. * FLAC__lpc_restore_signal()
  96717. * --------------------------------------------------------------------
  96718. * Restore the original signal by summing the residual and the
  96719. * predictor.
  96720. *
  96721. * IN residual[0,data_len-1] residual signal
  96722. * IN data_len length of original signal
  96723. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96724. * IN order > 0 LP order
  96725. * IN lp_quantization quantization of LP coefficients in bits
  96726. * *** IMPORTANT: the caller must pass in the historical samples:
  96727. * IN data[-order,-1] previously-reconstructed historical samples
  96728. * OUT data[0,data_len-1] original signal
  96729. */
  96730. 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[]);
  96731. 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[]);
  96732. #ifndef FLAC__NO_ASM
  96733. # ifdef FLAC__CPU_IA32
  96734. # ifdef FLAC__HAS_NASM
  96735. 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[]);
  96736. 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[]);
  96737. # endif /* FLAC__HAS_NASM */
  96738. # elif defined FLAC__CPU_PPC
  96739. 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[]);
  96740. 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[]);
  96741. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96742. #endif /* FLAC__NO_ASM */
  96743. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96744. /*
  96745. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96746. * --------------------------------------------------------------------
  96747. * Compute the expected number of bits per residual signal sample
  96748. * based on the LP error (which is related to the residual variance).
  96749. *
  96750. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96751. * IN total_samples > 0 # of samples in residual signal
  96752. * RETURN expected bits per sample
  96753. */
  96754. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96755. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96756. /*
  96757. * FLAC__lpc_compute_best_order()
  96758. * --------------------------------------------------------------------
  96759. * Compute the best order from the array of signal errors returned
  96760. * during coefficient computation.
  96761. *
  96762. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96763. * IN max_order > 0 max LP order
  96764. * IN total_samples > 0 # of samples in residual signal
  96765. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96766. * (includes warmup sample size and quantized LP coefficient)
  96767. * RETURN [1,max_order] best order
  96768. */
  96769. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96770. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96771. #endif
  96772. /*** End of inlined file: lpc.h ***/
  96773. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96774. #include <stdio.h>
  96775. #endif
  96776. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96777. #ifndef M_LN2
  96778. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96779. #define M_LN2 0.69314718055994530942
  96780. #endif
  96781. /* OPT: #undef'ing this may improve the speed on some architectures */
  96782. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96783. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96784. {
  96785. unsigned i;
  96786. for(i = 0; i < data_len; i++)
  96787. out[i] = in[i] * window[i];
  96788. }
  96789. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96790. {
  96791. /* a readable, but slower, version */
  96792. #if 0
  96793. FLAC__real d;
  96794. unsigned i;
  96795. FLAC__ASSERT(lag > 0);
  96796. FLAC__ASSERT(lag <= data_len);
  96797. /*
  96798. * Technically we should subtract the mean first like so:
  96799. * for(i = 0; i < data_len; i++)
  96800. * data[i] -= mean;
  96801. * but it appears not to make enough of a difference to matter, and
  96802. * most signals are already closely centered around zero
  96803. */
  96804. while(lag--) {
  96805. for(i = lag, d = 0.0; i < data_len; i++)
  96806. d += data[i] * data[i - lag];
  96807. autoc[lag] = d;
  96808. }
  96809. #endif
  96810. /*
  96811. * this version tends to run faster because of better data locality
  96812. * ('data_len' is usually much larger than 'lag')
  96813. */
  96814. FLAC__real d;
  96815. unsigned sample, coeff;
  96816. const unsigned limit = data_len - lag;
  96817. FLAC__ASSERT(lag > 0);
  96818. FLAC__ASSERT(lag <= data_len);
  96819. for(coeff = 0; coeff < lag; coeff++)
  96820. autoc[coeff] = 0.0;
  96821. for(sample = 0; sample <= limit; sample++) {
  96822. d = data[sample];
  96823. for(coeff = 0; coeff < lag; coeff++)
  96824. autoc[coeff] += d * data[sample+coeff];
  96825. }
  96826. for(; sample < data_len; sample++) {
  96827. d = data[sample];
  96828. for(coeff = 0; coeff < data_len - sample; coeff++)
  96829. autoc[coeff] += d * data[sample+coeff];
  96830. }
  96831. }
  96832. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96833. {
  96834. unsigned i, j;
  96835. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96836. FLAC__ASSERT(0 != max_order);
  96837. FLAC__ASSERT(0 < *max_order);
  96838. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96839. FLAC__ASSERT(autoc[0] != 0.0);
  96840. err = autoc[0];
  96841. for(i = 0; i < *max_order; i++) {
  96842. /* Sum up this iteration's reflection coefficient. */
  96843. r = -autoc[i+1];
  96844. for(j = 0; j < i; j++)
  96845. r -= lpc[j] * autoc[i-j];
  96846. ref[i] = (r/=err);
  96847. /* Update LPC coefficients and total error. */
  96848. lpc[i]=r;
  96849. for(j = 0; j < (i>>1); j++) {
  96850. FLAC__double tmp = lpc[j];
  96851. lpc[j] += r * lpc[i-1-j];
  96852. lpc[i-1-j] += r * tmp;
  96853. }
  96854. if(i & 1)
  96855. lpc[j] += lpc[j] * r;
  96856. err *= (1.0 - r * r);
  96857. /* save this order */
  96858. for(j = 0; j <= i; j++)
  96859. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96860. error[i] = err;
  96861. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96862. if(err == 0.0) {
  96863. *max_order = i+1;
  96864. return;
  96865. }
  96866. }
  96867. }
  96868. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96869. {
  96870. unsigned i;
  96871. FLAC__double cmax;
  96872. FLAC__int32 qmax, qmin;
  96873. FLAC__ASSERT(precision > 0);
  96874. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96875. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96876. precision--;
  96877. qmax = 1 << precision;
  96878. qmin = -qmax;
  96879. qmax--;
  96880. /* calc cmax = max( |lp_coeff[i]| ) */
  96881. cmax = 0.0;
  96882. for(i = 0; i < order; i++) {
  96883. const FLAC__double d = fabs(lp_coeff[i]);
  96884. if(d > cmax)
  96885. cmax = d;
  96886. }
  96887. if(cmax <= 0.0) {
  96888. /* => coefficients are all 0, which means our constant-detect didn't work */
  96889. return 2;
  96890. }
  96891. else {
  96892. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96893. const int min_shiftlimit = -max_shiftlimit - 1;
  96894. int log2cmax;
  96895. (void)frexp(cmax, &log2cmax);
  96896. log2cmax--;
  96897. *shift = (int)precision - log2cmax - 1;
  96898. if(*shift > max_shiftlimit)
  96899. *shift = max_shiftlimit;
  96900. else if(*shift < min_shiftlimit)
  96901. return 1;
  96902. }
  96903. if(*shift >= 0) {
  96904. FLAC__double error = 0.0;
  96905. FLAC__int32 q;
  96906. for(i = 0; i < order; i++) {
  96907. error += lp_coeff[i] * (1 << *shift);
  96908. #if 1 /* unfortunately lround() is C99 */
  96909. if(error >= 0.0)
  96910. q = (FLAC__int32)(error + 0.5);
  96911. else
  96912. q = (FLAC__int32)(error - 0.5);
  96913. #else
  96914. q = lround(error);
  96915. #endif
  96916. #ifdef FLAC__OVERFLOW_DETECT
  96917. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96918. 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]);
  96919. else if(q < qmin)
  96920. 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]);
  96921. #endif
  96922. if(q > qmax)
  96923. q = qmax;
  96924. else if(q < qmin)
  96925. q = qmin;
  96926. error -= q;
  96927. qlp_coeff[i] = q;
  96928. }
  96929. }
  96930. /* negative shift is very rare but due to design flaw, negative shift is
  96931. * a NOP in the decoder, so it must be handled specially by scaling down
  96932. * coeffs
  96933. */
  96934. else {
  96935. const int nshift = -(*shift);
  96936. FLAC__double error = 0.0;
  96937. FLAC__int32 q;
  96938. #ifdef DEBUG
  96939. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96940. #endif
  96941. for(i = 0; i < order; i++) {
  96942. error += lp_coeff[i] / (1 << nshift);
  96943. #if 1 /* unfortunately lround() is C99 */
  96944. if(error >= 0.0)
  96945. q = (FLAC__int32)(error + 0.5);
  96946. else
  96947. q = (FLAC__int32)(error - 0.5);
  96948. #else
  96949. q = lround(error);
  96950. #endif
  96951. #ifdef FLAC__OVERFLOW_DETECT
  96952. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96953. 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]);
  96954. else if(q < qmin)
  96955. 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]);
  96956. #endif
  96957. if(q > qmax)
  96958. q = qmax;
  96959. else if(q < qmin)
  96960. q = qmin;
  96961. error -= q;
  96962. qlp_coeff[i] = q;
  96963. }
  96964. *shift = 0;
  96965. }
  96966. return 0;
  96967. }
  96968. 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[])
  96969. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96970. {
  96971. FLAC__int64 sumo;
  96972. unsigned i, j;
  96973. FLAC__int32 sum;
  96974. const FLAC__int32 *history;
  96975. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96976. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96977. for(i=0;i<order;i++)
  96978. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96979. fprintf(stderr,"\n");
  96980. #endif
  96981. FLAC__ASSERT(order > 0);
  96982. for(i = 0; i < data_len; i++) {
  96983. sumo = 0;
  96984. sum = 0;
  96985. history = data;
  96986. for(j = 0; j < order; j++) {
  96987. sum += qlp_coeff[j] * (*(--history));
  96988. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96989. #if defined _MSC_VER
  96990. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96991. 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);
  96992. #else
  96993. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96994. 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);
  96995. #endif
  96996. }
  96997. *(residual++) = *(data++) - (sum >> lp_quantization);
  96998. }
  96999. /* Here's a slower but clearer version:
  97000. for(i = 0; i < data_len; i++) {
  97001. sum = 0;
  97002. for(j = 0; j < order; j++)
  97003. sum += qlp_coeff[j] * data[i-j-1];
  97004. residual[i] = data[i] - (sum >> lp_quantization);
  97005. }
  97006. */
  97007. }
  97008. #else /* fully unrolled version for normal use */
  97009. {
  97010. int i;
  97011. FLAC__int32 sum;
  97012. FLAC__ASSERT(order > 0);
  97013. FLAC__ASSERT(order <= 32);
  97014. /*
  97015. * We do unique versions up to 12th order since that's the subset limit.
  97016. * Also they are roughly ordered to match frequency of occurrence to
  97017. * minimize branching.
  97018. */
  97019. if(order <= 12) {
  97020. if(order > 8) {
  97021. if(order > 10) {
  97022. if(order == 12) {
  97023. for(i = 0; i < (int)data_len; i++) {
  97024. sum = 0;
  97025. sum += qlp_coeff[11] * data[i-12];
  97026. sum += qlp_coeff[10] * data[i-11];
  97027. sum += qlp_coeff[9] * data[i-10];
  97028. sum += qlp_coeff[8] * data[i-9];
  97029. sum += qlp_coeff[7] * data[i-8];
  97030. sum += qlp_coeff[6] * data[i-7];
  97031. sum += qlp_coeff[5] * data[i-6];
  97032. sum += qlp_coeff[4] * data[i-5];
  97033. sum += qlp_coeff[3] * data[i-4];
  97034. sum += qlp_coeff[2] * data[i-3];
  97035. sum += qlp_coeff[1] * data[i-2];
  97036. sum += qlp_coeff[0] * data[i-1];
  97037. residual[i] = data[i] - (sum >> lp_quantization);
  97038. }
  97039. }
  97040. else { /* order == 11 */
  97041. for(i = 0; i < (int)data_len; i++) {
  97042. sum = 0;
  97043. sum += qlp_coeff[10] * data[i-11];
  97044. sum += qlp_coeff[9] * data[i-10];
  97045. sum += qlp_coeff[8] * data[i-9];
  97046. sum += qlp_coeff[7] * data[i-8];
  97047. sum += qlp_coeff[6] * data[i-7];
  97048. sum += qlp_coeff[5] * data[i-6];
  97049. sum += qlp_coeff[4] * data[i-5];
  97050. sum += qlp_coeff[3] * data[i-4];
  97051. sum += qlp_coeff[2] * data[i-3];
  97052. sum += qlp_coeff[1] * data[i-2];
  97053. sum += qlp_coeff[0] * data[i-1];
  97054. residual[i] = data[i] - (sum >> lp_quantization);
  97055. }
  97056. }
  97057. }
  97058. else {
  97059. if(order == 10) {
  97060. for(i = 0; i < (int)data_len; i++) {
  97061. sum = 0;
  97062. sum += qlp_coeff[9] * data[i-10];
  97063. sum += qlp_coeff[8] * data[i-9];
  97064. sum += qlp_coeff[7] * data[i-8];
  97065. sum += qlp_coeff[6] * data[i-7];
  97066. sum += qlp_coeff[5] * data[i-6];
  97067. sum += qlp_coeff[4] * data[i-5];
  97068. sum += qlp_coeff[3] * data[i-4];
  97069. sum += qlp_coeff[2] * data[i-3];
  97070. sum += qlp_coeff[1] * data[i-2];
  97071. sum += qlp_coeff[0] * data[i-1];
  97072. residual[i] = data[i] - (sum >> lp_quantization);
  97073. }
  97074. }
  97075. else { /* order == 9 */
  97076. for(i = 0; i < (int)data_len; i++) {
  97077. sum = 0;
  97078. sum += qlp_coeff[8] * data[i-9];
  97079. sum += qlp_coeff[7] * data[i-8];
  97080. sum += qlp_coeff[6] * data[i-7];
  97081. sum += qlp_coeff[5] * data[i-6];
  97082. sum += qlp_coeff[4] * data[i-5];
  97083. sum += qlp_coeff[3] * data[i-4];
  97084. sum += qlp_coeff[2] * data[i-3];
  97085. sum += qlp_coeff[1] * data[i-2];
  97086. sum += qlp_coeff[0] * data[i-1];
  97087. residual[i] = data[i] - (sum >> lp_quantization);
  97088. }
  97089. }
  97090. }
  97091. }
  97092. else if(order > 4) {
  97093. if(order > 6) {
  97094. if(order == 8) {
  97095. for(i = 0; i < (int)data_len; i++) {
  97096. sum = 0;
  97097. sum += qlp_coeff[7] * data[i-8];
  97098. sum += qlp_coeff[6] * data[i-7];
  97099. sum += qlp_coeff[5] * data[i-6];
  97100. sum += qlp_coeff[4] * data[i-5];
  97101. sum += qlp_coeff[3] * data[i-4];
  97102. sum += qlp_coeff[2] * data[i-3];
  97103. sum += qlp_coeff[1] * data[i-2];
  97104. sum += qlp_coeff[0] * data[i-1];
  97105. residual[i] = data[i] - (sum >> lp_quantization);
  97106. }
  97107. }
  97108. else { /* order == 7 */
  97109. for(i = 0; i < (int)data_len; i++) {
  97110. sum = 0;
  97111. sum += qlp_coeff[6] * data[i-7];
  97112. sum += qlp_coeff[5] * data[i-6];
  97113. sum += qlp_coeff[4] * data[i-5];
  97114. sum += qlp_coeff[3] * data[i-4];
  97115. sum += qlp_coeff[2] * data[i-3];
  97116. sum += qlp_coeff[1] * data[i-2];
  97117. sum += qlp_coeff[0] * data[i-1];
  97118. residual[i] = data[i] - (sum >> lp_quantization);
  97119. }
  97120. }
  97121. }
  97122. else {
  97123. if(order == 6) {
  97124. for(i = 0; i < (int)data_len; i++) {
  97125. sum = 0;
  97126. sum += qlp_coeff[5] * data[i-6];
  97127. sum += qlp_coeff[4] * data[i-5];
  97128. sum += qlp_coeff[3] * data[i-4];
  97129. sum += qlp_coeff[2] * data[i-3];
  97130. sum += qlp_coeff[1] * data[i-2];
  97131. sum += qlp_coeff[0] * data[i-1];
  97132. residual[i] = data[i] - (sum >> lp_quantization);
  97133. }
  97134. }
  97135. else { /* order == 5 */
  97136. for(i = 0; i < (int)data_len; i++) {
  97137. sum = 0;
  97138. sum += qlp_coeff[4] * data[i-5];
  97139. sum += qlp_coeff[3] * data[i-4];
  97140. sum += qlp_coeff[2] * data[i-3];
  97141. sum += qlp_coeff[1] * data[i-2];
  97142. sum += qlp_coeff[0] * data[i-1];
  97143. residual[i] = data[i] - (sum >> lp_quantization);
  97144. }
  97145. }
  97146. }
  97147. }
  97148. else {
  97149. if(order > 2) {
  97150. if(order == 4) {
  97151. for(i = 0; i < (int)data_len; i++) {
  97152. sum = 0;
  97153. sum += qlp_coeff[3] * data[i-4];
  97154. sum += qlp_coeff[2] * data[i-3];
  97155. sum += qlp_coeff[1] * data[i-2];
  97156. sum += qlp_coeff[0] * data[i-1];
  97157. residual[i] = data[i] - (sum >> lp_quantization);
  97158. }
  97159. }
  97160. else { /* order == 3 */
  97161. for(i = 0; i < (int)data_len; i++) {
  97162. sum = 0;
  97163. sum += qlp_coeff[2] * data[i-3];
  97164. sum += qlp_coeff[1] * data[i-2];
  97165. sum += qlp_coeff[0] * data[i-1];
  97166. residual[i] = data[i] - (sum >> lp_quantization);
  97167. }
  97168. }
  97169. }
  97170. else {
  97171. if(order == 2) {
  97172. for(i = 0; i < (int)data_len; i++) {
  97173. sum = 0;
  97174. sum += qlp_coeff[1] * data[i-2];
  97175. sum += qlp_coeff[0] * data[i-1];
  97176. residual[i] = data[i] - (sum >> lp_quantization);
  97177. }
  97178. }
  97179. else { /* order == 1 */
  97180. for(i = 0; i < (int)data_len; i++)
  97181. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97182. }
  97183. }
  97184. }
  97185. }
  97186. else { /* order > 12 */
  97187. for(i = 0; i < (int)data_len; i++) {
  97188. sum = 0;
  97189. switch(order) {
  97190. case 32: sum += qlp_coeff[31] * data[i-32];
  97191. case 31: sum += qlp_coeff[30] * data[i-31];
  97192. case 30: sum += qlp_coeff[29] * data[i-30];
  97193. case 29: sum += qlp_coeff[28] * data[i-29];
  97194. case 28: sum += qlp_coeff[27] * data[i-28];
  97195. case 27: sum += qlp_coeff[26] * data[i-27];
  97196. case 26: sum += qlp_coeff[25] * data[i-26];
  97197. case 25: sum += qlp_coeff[24] * data[i-25];
  97198. case 24: sum += qlp_coeff[23] * data[i-24];
  97199. case 23: sum += qlp_coeff[22] * data[i-23];
  97200. case 22: sum += qlp_coeff[21] * data[i-22];
  97201. case 21: sum += qlp_coeff[20] * data[i-21];
  97202. case 20: sum += qlp_coeff[19] * data[i-20];
  97203. case 19: sum += qlp_coeff[18] * data[i-19];
  97204. case 18: sum += qlp_coeff[17] * data[i-18];
  97205. case 17: sum += qlp_coeff[16] * data[i-17];
  97206. case 16: sum += qlp_coeff[15] * data[i-16];
  97207. case 15: sum += qlp_coeff[14] * data[i-15];
  97208. case 14: sum += qlp_coeff[13] * data[i-14];
  97209. case 13: sum += qlp_coeff[12] * data[i-13];
  97210. sum += qlp_coeff[11] * data[i-12];
  97211. sum += qlp_coeff[10] * data[i-11];
  97212. sum += qlp_coeff[ 9] * data[i-10];
  97213. sum += qlp_coeff[ 8] * data[i- 9];
  97214. sum += qlp_coeff[ 7] * data[i- 8];
  97215. sum += qlp_coeff[ 6] * data[i- 7];
  97216. sum += qlp_coeff[ 5] * data[i- 6];
  97217. sum += qlp_coeff[ 4] * data[i- 5];
  97218. sum += qlp_coeff[ 3] * data[i- 4];
  97219. sum += qlp_coeff[ 2] * data[i- 3];
  97220. sum += qlp_coeff[ 1] * data[i- 2];
  97221. sum += qlp_coeff[ 0] * data[i- 1];
  97222. }
  97223. residual[i] = data[i] - (sum >> lp_quantization);
  97224. }
  97225. }
  97226. }
  97227. #endif
  97228. 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[])
  97229. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97230. {
  97231. unsigned i, j;
  97232. FLAC__int64 sum;
  97233. const FLAC__int32 *history;
  97234. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97235. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97236. for(i=0;i<order;i++)
  97237. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97238. fprintf(stderr,"\n");
  97239. #endif
  97240. FLAC__ASSERT(order > 0);
  97241. for(i = 0; i < data_len; i++) {
  97242. sum = 0;
  97243. history = data;
  97244. for(j = 0; j < order; j++)
  97245. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97246. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97247. #if defined _MSC_VER
  97248. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97249. #else
  97250. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97251. #endif
  97252. break;
  97253. }
  97254. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97255. #if defined _MSC_VER
  97256. 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));
  97257. #else
  97258. 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)));
  97259. #endif
  97260. break;
  97261. }
  97262. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97263. }
  97264. }
  97265. #else /* fully unrolled version for normal use */
  97266. {
  97267. int i;
  97268. FLAC__int64 sum;
  97269. FLAC__ASSERT(order > 0);
  97270. FLAC__ASSERT(order <= 32);
  97271. /*
  97272. * We do unique versions up to 12th order since that's the subset limit.
  97273. * Also they are roughly ordered to match frequency of occurrence to
  97274. * minimize branching.
  97275. */
  97276. if(order <= 12) {
  97277. if(order > 8) {
  97278. if(order > 10) {
  97279. if(order == 12) {
  97280. for(i = 0; i < (int)data_len; i++) {
  97281. sum = 0;
  97282. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97283. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97284. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97285. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97286. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97287. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97288. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97289. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97290. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97291. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97292. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97293. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97294. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97295. }
  97296. }
  97297. else { /* order == 11 */
  97298. for(i = 0; i < (int)data_len; i++) {
  97299. sum = 0;
  97300. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97301. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97302. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97303. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97304. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97305. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97306. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97307. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97308. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97309. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97310. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97311. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97312. }
  97313. }
  97314. }
  97315. else {
  97316. if(order == 10) {
  97317. for(i = 0; i < (int)data_len; i++) {
  97318. sum = 0;
  97319. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97320. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97321. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97322. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97323. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97324. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97325. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97326. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97327. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97328. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97329. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97330. }
  97331. }
  97332. else { /* order == 9 */
  97333. for(i = 0; i < (int)data_len; i++) {
  97334. sum = 0;
  97335. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97336. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97337. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97338. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97339. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97340. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97341. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97342. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97343. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97344. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97345. }
  97346. }
  97347. }
  97348. }
  97349. else if(order > 4) {
  97350. if(order > 6) {
  97351. if(order == 8) {
  97352. for(i = 0; i < (int)data_len; i++) {
  97353. sum = 0;
  97354. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97355. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97356. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97357. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97358. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97359. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97360. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97361. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97362. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97363. }
  97364. }
  97365. else { /* order == 7 */
  97366. for(i = 0; i < (int)data_len; i++) {
  97367. sum = 0;
  97368. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97369. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97370. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97371. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97372. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97373. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97374. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97375. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97376. }
  97377. }
  97378. }
  97379. else {
  97380. if(order == 6) {
  97381. for(i = 0; i < (int)data_len; i++) {
  97382. sum = 0;
  97383. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97384. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97385. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97386. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97387. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97388. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97389. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97390. }
  97391. }
  97392. else { /* order == 5 */
  97393. for(i = 0; i < (int)data_len; i++) {
  97394. sum = 0;
  97395. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97396. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97397. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97398. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97399. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97400. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97401. }
  97402. }
  97403. }
  97404. }
  97405. else {
  97406. if(order > 2) {
  97407. if(order == 4) {
  97408. for(i = 0; i < (int)data_len; i++) {
  97409. sum = 0;
  97410. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97411. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97412. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97413. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97414. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97415. }
  97416. }
  97417. else { /* order == 3 */
  97418. for(i = 0; i < (int)data_len; i++) {
  97419. sum = 0;
  97420. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97421. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97422. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97423. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97424. }
  97425. }
  97426. }
  97427. else {
  97428. if(order == 2) {
  97429. for(i = 0; i < (int)data_len; i++) {
  97430. sum = 0;
  97431. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97432. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97433. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97434. }
  97435. }
  97436. else { /* order == 1 */
  97437. for(i = 0; i < (int)data_len; i++)
  97438. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97439. }
  97440. }
  97441. }
  97442. }
  97443. else { /* order > 12 */
  97444. for(i = 0; i < (int)data_len; i++) {
  97445. sum = 0;
  97446. switch(order) {
  97447. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97448. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97449. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97450. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97451. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97452. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97453. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97454. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97455. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97456. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97457. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97458. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97459. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97460. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97461. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97462. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97463. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97464. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97465. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97466. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97467. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97468. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97469. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97470. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97471. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97472. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97473. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97474. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97475. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97476. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97477. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97478. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97479. }
  97480. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97481. }
  97482. }
  97483. }
  97484. #endif
  97485. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97486. 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[])
  97487. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97488. {
  97489. FLAC__int64 sumo;
  97490. unsigned i, j;
  97491. FLAC__int32 sum;
  97492. const FLAC__int32 *r = residual, *history;
  97493. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97494. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97495. for(i=0;i<order;i++)
  97496. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97497. fprintf(stderr,"\n");
  97498. #endif
  97499. FLAC__ASSERT(order > 0);
  97500. for(i = 0; i < data_len; i++) {
  97501. sumo = 0;
  97502. sum = 0;
  97503. history = data;
  97504. for(j = 0; j < order; j++) {
  97505. sum += qlp_coeff[j] * (*(--history));
  97506. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97507. #if defined _MSC_VER
  97508. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97509. 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);
  97510. #else
  97511. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97512. 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);
  97513. #endif
  97514. }
  97515. *(data++) = *(r++) + (sum >> lp_quantization);
  97516. }
  97517. /* Here's a slower but clearer version:
  97518. for(i = 0; i < data_len; i++) {
  97519. sum = 0;
  97520. for(j = 0; j < order; j++)
  97521. sum += qlp_coeff[j] * data[i-j-1];
  97522. data[i] = residual[i] + (sum >> lp_quantization);
  97523. }
  97524. */
  97525. }
  97526. #else /* fully unrolled version for normal use */
  97527. {
  97528. int i;
  97529. FLAC__int32 sum;
  97530. FLAC__ASSERT(order > 0);
  97531. FLAC__ASSERT(order <= 32);
  97532. /*
  97533. * We do unique versions up to 12th order since that's the subset limit.
  97534. * Also they are roughly ordered to match frequency of occurrence to
  97535. * minimize branching.
  97536. */
  97537. if(order <= 12) {
  97538. if(order > 8) {
  97539. if(order > 10) {
  97540. if(order == 12) {
  97541. for(i = 0; i < (int)data_len; i++) {
  97542. sum = 0;
  97543. sum += qlp_coeff[11] * data[i-12];
  97544. sum += qlp_coeff[10] * data[i-11];
  97545. sum += qlp_coeff[9] * data[i-10];
  97546. sum += qlp_coeff[8] * data[i-9];
  97547. sum += qlp_coeff[7] * data[i-8];
  97548. sum += qlp_coeff[6] * data[i-7];
  97549. sum += qlp_coeff[5] * data[i-6];
  97550. sum += qlp_coeff[4] * data[i-5];
  97551. sum += qlp_coeff[3] * data[i-4];
  97552. sum += qlp_coeff[2] * data[i-3];
  97553. sum += qlp_coeff[1] * data[i-2];
  97554. sum += qlp_coeff[0] * data[i-1];
  97555. data[i] = residual[i] + (sum >> lp_quantization);
  97556. }
  97557. }
  97558. else { /* order == 11 */
  97559. for(i = 0; i < (int)data_len; i++) {
  97560. sum = 0;
  97561. sum += qlp_coeff[10] * data[i-11];
  97562. sum += qlp_coeff[9] * data[i-10];
  97563. sum += qlp_coeff[8] * data[i-9];
  97564. sum += qlp_coeff[7] * data[i-8];
  97565. sum += qlp_coeff[6] * data[i-7];
  97566. sum += qlp_coeff[5] * data[i-6];
  97567. sum += qlp_coeff[4] * data[i-5];
  97568. sum += qlp_coeff[3] * data[i-4];
  97569. sum += qlp_coeff[2] * data[i-3];
  97570. sum += qlp_coeff[1] * data[i-2];
  97571. sum += qlp_coeff[0] * data[i-1];
  97572. data[i] = residual[i] + (sum >> lp_quantization);
  97573. }
  97574. }
  97575. }
  97576. else {
  97577. if(order == 10) {
  97578. for(i = 0; i < (int)data_len; i++) {
  97579. sum = 0;
  97580. sum += qlp_coeff[9] * data[i-10];
  97581. sum += qlp_coeff[8] * data[i-9];
  97582. sum += qlp_coeff[7] * data[i-8];
  97583. sum += qlp_coeff[6] * data[i-7];
  97584. sum += qlp_coeff[5] * data[i-6];
  97585. sum += qlp_coeff[4] * data[i-5];
  97586. sum += qlp_coeff[3] * data[i-4];
  97587. sum += qlp_coeff[2] * data[i-3];
  97588. sum += qlp_coeff[1] * data[i-2];
  97589. sum += qlp_coeff[0] * data[i-1];
  97590. data[i] = residual[i] + (sum >> lp_quantization);
  97591. }
  97592. }
  97593. else { /* order == 9 */
  97594. for(i = 0; i < (int)data_len; i++) {
  97595. sum = 0;
  97596. sum += qlp_coeff[8] * data[i-9];
  97597. sum += qlp_coeff[7] * data[i-8];
  97598. sum += qlp_coeff[6] * data[i-7];
  97599. sum += qlp_coeff[5] * data[i-6];
  97600. sum += qlp_coeff[4] * data[i-5];
  97601. sum += qlp_coeff[3] * data[i-4];
  97602. sum += qlp_coeff[2] * data[i-3];
  97603. sum += qlp_coeff[1] * data[i-2];
  97604. sum += qlp_coeff[0] * data[i-1];
  97605. data[i] = residual[i] + (sum >> lp_quantization);
  97606. }
  97607. }
  97608. }
  97609. }
  97610. else if(order > 4) {
  97611. if(order > 6) {
  97612. if(order == 8) {
  97613. for(i = 0; i < (int)data_len; i++) {
  97614. sum = 0;
  97615. sum += qlp_coeff[7] * data[i-8];
  97616. sum += qlp_coeff[6] * data[i-7];
  97617. sum += qlp_coeff[5] * data[i-6];
  97618. sum += qlp_coeff[4] * data[i-5];
  97619. sum += qlp_coeff[3] * data[i-4];
  97620. sum += qlp_coeff[2] * data[i-3];
  97621. sum += qlp_coeff[1] * data[i-2];
  97622. sum += qlp_coeff[0] * data[i-1];
  97623. data[i] = residual[i] + (sum >> lp_quantization);
  97624. }
  97625. }
  97626. else { /* order == 7 */
  97627. for(i = 0; i < (int)data_len; i++) {
  97628. sum = 0;
  97629. sum += qlp_coeff[6] * data[i-7];
  97630. sum += qlp_coeff[5] * data[i-6];
  97631. sum += qlp_coeff[4] * data[i-5];
  97632. sum += qlp_coeff[3] * data[i-4];
  97633. sum += qlp_coeff[2] * data[i-3];
  97634. sum += qlp_coeff[1] * data[i-2];
  97635. sum += qlp_coeff[0] * data[i-1];
  97636. data[i] = residual[i] + (sum >> lp_quantization);
  97637. }
  97638. }
  97639. }
  97640. else {
  97641. if(order == 6) {
  97642. for(i = 0; i < (int)data_len; i++) {
  97643. sum = 0;
  97644. sum += qlp_coeff[5] * data[i-6];
  97645. sum += qlp_coeff[4] * data[i-5];
  97646. sum += qlp_coeff[3] * data[i-4];
  97647. sum += qlp_coeff[2] * data[i-3];
  97648. sum += qlp_coeff[1] * data[i-2];
  97649. sum += qlp_coeff[0] * data[i-1];
  97650. data[i] = residual[i] + (sum >> lp_quantization);
  97651. }
  97652. }
  97653. else { /* order == 5 */
  97654. for(i = 0; i < (int)data_len; i++) {
  97655. sum = 0;
  97656. sum += qlp_coeff[4] * data[i-5];
  97657. sum += qlp_coeff[3] * data[i-4];
  97658. sum += qlp_coeff[2] * data[i-3];
  97659. sum += qlp_coeff[1] * data[i-2];
  97660. sum += qlp_coeff[0] * data[i-1];
  97661. data[i] = residual[i] + (sum >> lp_quantization);
  97662. }
  97663. }
  97664. }
  97665. }
  97666. else {
  97667. if(order > 2) {
  97668. if(order == 4) {
  97669. for(i = 0; i < (int)data_len; i++) {
  97670. sum = 0;
  97671. sum += qlp_coeff[3] * data[i-4];
  97672. sum += qlp_coeff[2] * data[i-3];
  97673. sum += qlp_coeff[1] * data[i-2];
  97674. sum += qlp_coeff[0] * data[i-1];
  97675. data[i] = residual[i] + (sum >> lp_quantization);
  97676. }
  97677. }
  97678. else { /* order == 3 */
  97679. for(i = 0; i < (int)data_len; i++) {
  97680. sum = 0;
  97681. sum += qlp_coeff[2] * data[i-3];
  97682. sum += qlp_coeff[1] * data[i-2];
  97683. sum += qlp_coeff[0] * data[i-1];
  97684. data[i] = residual[i] + (sum >> lp_quantization);
  97685. }
  97686. }
  97687. }
  97688. else {
  97689. if(order == 2) {
  97690. for(i = 0; i < (int)data_len; i++) {
  97691. sum = 0;
  97692. sum += qlp_coeff[1] * data[i-2];
  97693. sum += qlp_coeff[0] * data[i-1];
  97694. data[i] = residual[i] + (sum >> lp_quantization);
  97695. }
  97696. }
  97697. else { /* order == 1 */
  97698. for(i = 0; i < (int)data_len; i++)
  97699. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97700. }
  97701. }
  97702. }
  97703. }
  97704. else { /* order > 12 */
  97705. for(i = 0; i < (int)data_len; i++) {
  97706. sum = 0;
  97707. switch(order) {
  97708. case 32: sum += qlp_coeff[31] * data[i-32];
  97709. case 31: sum += qlp_coeff[30] * data[i-31];
  97710. case 30: sum += qlp_coeff[29] * data[i-30];
  97711. case 29: sum += qlp_coeff[28] * data[i-29];
  97712. case 28: sum += qlp_coeff[27] * data[i-28];
  97713. case 27: sum += qlp_coeff[26] * data[i-27];
  97714. case 26: sum += qlp_coeff[25] * data[i-26];
  97715. case 25: sum += qlp_coeff[24] * data[i-25];
  97716. case 24: sum += qlp_coeff[23] * data[i-24];
  97717. case 23: sum += qlp_coeff[22] * data[i-23];
  97718. case 22: sum += qlp_coeff[21] * data[i-22];
  97719. case 21: sum += qlp_coeff[20] * data[i-21];
  97720. case 20: sum += qlp_coeff[19] * data[i-20];
  97721. case 19: sum += qlp_coeff[18] * data[i-19];
  97722. case 18: sum += qlp_coeff[17] * data[i-18];
  97723. case 17: sum += qlp_coeff[16] * data[i-17];
  97724. case 16: sum += qlp_coeff[15] * data[i-16];
  97725. case 15: sum += qlp_coeff[14] * data[i-15];
  97726. case 14: sum += qlp_coeff[13] * data[i-14];
  97727. case 13: sum += qlp_coeff[12] * data[i-13];
  97728. sum += qlp_coeff[11] * data[i-12];
  97729. sum += qlp_coeff[10] * data[i-11];
  97730. sum += qlp_coeff[ 9] * data[i-10];
  97731. sum += qlp_coeff[ 8] * data[i- 9];
  97732. sum += qlp_coeff[ 7] * data[i- 8];
  97733. sum += qlp_coeff[ 6] * data[i- 7];
  97734. sum += qlp_coeff[ 5] * data[i- 6];
  97735. sum += qlp_coeff[ 4] * data[i- 5];
  97736. sum += qlp_coeff[ 3] * data[i- 4];
  97737. sum += qlp_coeff[ 2] * data[i- 3];
  97738. sum += qlp_coeff[ 1] * data[i- 2];
  97739. sum += qlp_coeff[ 0] * data[i- 1];
  97740. }
  97741. data[i] = residual[i] + (sum >> lp_quantization);
  97742. }
  97743. }
  97744. }
  97745. #endif
  97746. 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[])
  97747. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97748. {
  97749. unsigned i, j;
  97750. FLAC__int64 sum;
  97751. const FLAC__int32 *r = residual, *history;
  97752. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97753. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97754. for(i=0;i<order;i++)
  97755. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97756. fprintf(stderr,"\n");
  97757. #endif
  97758. FLAC__ASSERT(order > 0);
  97759. for(i = 0; i < data_len; i++) {
  97760. sum = 0;
  97761. history = data;
  97762. for(j = 0; j < order; j++)
  97763. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97764. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97765. #ifdef _MSC_VER
  97766. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97767. #else
  97768. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97769. #endif
  97770. break;
  97771. }
  97772. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97773. #ifdef _MSC_VER
  97774. 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));
  97775. #else
  97776. 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)));
  97777. #endif
  97778. break;
  97779. }
  97780. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97781. }
  97782. }
  97783. #else /* fully unrolled version for normal use */
  97784. {
  97785. int i;
  97786. FLAC__int64 sum;
  97787. FLAC__ASSERT(order > 0);
  97788. FLAC__ASSERT(order <= 32);
  97789. /*
  97790. * We do unique versions up to 12th order since that's the subset limit.
  97791. * Also they are roughly ordered to match frequency of occurrence to
  97792. * minimize branching.
  97793. */
  97794. if(order <= 12) {
  97795. if(order > 8) {
  97796. if(order > 10) {
  97797. if(order == 12) {
  97798. for(i = 0; i < (int)data_len; i++) {
  97799. sum = 0;
  97800. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97801. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97802. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97803. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97804. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97805. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97806. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97807. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97808. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97809. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97810. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97811. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97812. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97813. }
  97814. }
  97815. else { /* order == 11 */
  97816. for(i = 0; i < (int)data_len; i++) {
  97817. sum = 0;
  97818. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97819. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97820. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97821. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97822. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97823. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97824. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97825. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97826. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97827. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97828. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97829. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97830. }
  97831. }
  97832. }
  97833. else {
  97834. if(order == 10) {
  97835. for(i = 0; i < (int)data_len; i++) {
  97836. sum = 0;
  97837. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97838. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97839. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97840. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97841. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97842. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97843. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97844. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97845. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97846. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97847. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97848. }
  97849. }
  97850. else { /* order == 9 */
  97851. for(i = 0; i < (int)data_len; i++) {
  97852. sum = 0;
  97853. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97854. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97855. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97856. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97857. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97858. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97859. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97860. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97861. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97862. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97863. }
  97864. }
  97865. }
  97866. }
  97867. else if(order > 4) {
  97868. if(order > 6) {
  97869. if(order == 8) {
  97870. for(i = 0; i < (int)data_len; i++) {
  97871. sum = 0;
  97872. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97873. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97874. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97875. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97876. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97877. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97878. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97879. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97880. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97881. }
  97882. }
  97883. else { /* order == 7 */
  97884. for(i = 0; i < (int)data_len; i++) {
  97885. sum = 0;
  97886. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97887. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97888. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97889. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97890. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97891. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97892. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97893. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97894. }
  97895. }
  97896. }
  97897. else {
  97898. if(order == 6) {
  97899. for(i = 0; i < (int)data_len; i++) {
  97900. sum = 0;
  97901. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97902. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97903. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97904. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97905. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97906. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97907. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97908. }
  97909. }
  97910. else { /* order == 5 */
  97911. for(i = 0; i < (int)data_len; i++) {
  97912. sum = 0;
  97913. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97914. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97915. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97916. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97917. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97918. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97919. }
  97920. }
  97921. }
  97922. }
  97923. else {
  97924. if(order > 2) {
  97925. if(order == 4) {
  97926. for(i = 0; i < (int)data_len; i++) {
  97927. sum = 0;
  97928. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97929. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97930. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97931. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97932. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97933. }
  97934. }
  97935. else { /* order == 3 */
  97936. for(i = 0; i < (int)data_len; i++) {
  97937. sum = 0;
  97938. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97939. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97940. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97941. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97942. }
  97943. }
  97944. }
  97945. else {
  97946. if(order == 2) {
  97947. for(i = 0; i < (int)data_len; i++) {
  97948. sum = 0;
  97949. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97950. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97951. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97952. }
  97953. }
  97954. else { /* order == 1 */
  97955. for(i = 0; i < (int)data_len; i++)
  97956. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97957. }
  97958. }
  97959. }
  97960. }
  97961. else { /* order > 12 */
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. switch(order) {
  97965. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97966. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97967. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97968. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97969. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97970. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97971. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97972. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97973. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97974. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97975. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97976. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97977. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97978. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97979. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97980. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97981. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97982. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97983. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97984. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97985. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97986. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97987. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97988. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97989. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97990. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97991. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97992. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97993. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97994. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97995. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97996. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97997. }
  97998. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97999. }
  98000. }
  98001. }
  98002. #endif
  98003. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98004. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98005. {
  98006. FLAC__double error_scale;
  98007. FLAC__ASSERT(total_samples > 0);
  98008. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98009. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98010. }
  98011. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98012. {
  98013. if(lpc_error > 0.0) {
  98014. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98015. if(bps >= 0.0)
  98016. return bps;
  98017. else
  98018. return 0.0;
  98019. }
  98020. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98021. return 1e32;
  98022. }
  98023. else {
  98024. return 0.0;
  98025. }
  98026. }
  98027. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98028. {
  98029. 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 */
  98030. FLAC__double bits, best_bits, error_scale;
  98031. FLAC__ASSERT(max_order > 0);
  98032. FLAC__ASSERT(total_samples > 0);
  98033. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98034. best_index = 0;
  98035. best_bits = (unsigned)(-1);
  98036. for(index = 0, order = 1; index < max_order; index++, order++) {
  98037. 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);
  98038. if(bits < best_bits) {
  98039. best_index = index;
  98040. best_bits = bits;
  98041. }
  98042. }
  98043. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98044. }
  98045. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98046. #endif
  98047. /*** End of inlined file: lpc_flac.c ***/
  98048. /*** Start of inlined file: md5.c ***/
  98049. /*** Start of inlined file: juce_FlacHeader.h ***/
  98050. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98051. // tasks..
  98052. #define VERSION "1.2.1"
  98053. #define FLAC__NO_DLL 1
  98054. #if JUCE_MSVC
  98055. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98056. #endif
  98057. #if JUCE_MAC
  98058. #define FLAC__SYS_DARWIN 1
  98059. #endif
  98060. /*** End of inlined file: juce_FlacHeader.h ***/
  98061. #if JUCE_USE_FLAC
  98062. #if HAVE_CONFIG_H
  98063. # include <config.h>
  98064. #endif
  98065. #include <stdlib.h> /* for malloc() */
  98066. #include <string.h> /* for memcpy() */
  98067. /*** Start of inlined file: md5.h ***/
  98068. #ifndef FLAC__PRIVATE__MD5_H
  98069. #define FLAC__PRIVATE__MD5_H
  98070. /*
  98071. * This is the header file for the MD5 message-digest algorithm.
  98072. * The algorithm is due to Ron Rivest. This code was
  98073. * written by Colin Plumb in 1993, no copyright is claimed.
  98074. * This code is in the public domain; do with it what you wish.
  98075. *
  98076. * Equivalent code is available from RSA Data Security, Inc.
  98077. * This code has been tested against that, and is equivalent,
  98078. * except that you don't need to include two pages of legalese
  98079. * with every copy.
  98080. *
  98081. * To compute the message digest of a chunk of bytes, declare an
  98082. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98083. * needed on buffers full of bytes, and then call MD5Final, which
  98084. * will fill a supplied 16-byte array with the digest.
  98085. *
  98086. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98087. * header definitions; now uses stuff from dpkg's config.h
  98088. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98089. * Still in the public domain.
  98090. *
  98091. * Josh Coalson: made some changes to integrate with libFLAC.
  98092. * Still in the public domain, with no warranty.
  98093. */
  98094. typedef struct {
  98095. FLAC__uint32 in[16];
  98096. FLAC__uint32 buf[4];
  98097. FLAC__uint32 bytes[2];
  98098. FLAC__byte *internal_buf;
  98099. size_t capacity;
  98100. } FLAC__MD5Context;
  98101. void FLAC__MD5Init(FLAC__MD5Context *context);
  98102. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98103. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98104. #endif
  98105. /*** End of inlined file: md5.h ***/
  98106. #ifndef FLaC__INLINE
  98107. #define FLaC__INLINE
  98108. #endif
  98109. /*
  98110. * This code implements the MD5 message-digest algorithm.
  98111. * The algorithm is due to Ron Rivest. This code was
  98112. * written by Colin Plumb in 1993, no copyright is claimed.
  98113. * This code is in the public domain; do with it what you wish.
  98114. *
  98115. * Equivalent code is available from RSA Data Security, Inc.
  98116. * This code has been tested against that, and is equivalent,
  98117. * except that you don't need to include two pages of legalese
  98118. * with every copy.
  98119. *
  98120. * To compute the message digest of a chunk of bytes, declare an
  98121. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98122. * needed on buffers full of bytes, and then call MD5Final, which
  98123. * will fill a supplied 16-byte array with the digest.
  98124. *
  98125. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98126. * definitions; now uses stuff from dpkg's config.h.
  98127. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98128. * Still in the public domain.
  98129. *
  98130. * Josh Coalson: made some changes to integrate with libFLAC.
  98131. * Still in the public domain.
  98132. */
  98133. /* The four core functions - F1 is optimized somewhat */
  98134. /* #define F1(x, y, z) (x & y | ~x & z) */
  98135. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98136. #define F2(x, y, z) F1(z, x, y)
  98137. #define F3(x, y, z) (x ^ y ^ z)
  98138. #define F4(x, y, z) (y ^ (x | ~z))
  98139. /* This is the central step in the MD5 algorithm. */
  98140. #define MD5STEP(f,w,x,y,z,in,s) \
  98141. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98142. /*
  98143. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98144. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98145. * the data and converts bytes into longwords for this routine.
  98146. */
  98147. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98148. {
  98149. register FLAC__uint32 a, b, c, d;
  98150. a = buf[0];
  98151. b = buf[1];
  98152. c = buf[2];
  98153. d = buf[3];
  98154. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98155. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98156. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98157. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98158. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98159. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98160. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98161. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98162. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98163. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98164. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98165. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98166. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98167. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98168. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98169. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98170. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98171. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98172. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98173. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98174. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98175. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98176. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98177. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98178. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98179. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98180. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98181. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98182. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98183. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98184. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98185. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98186. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98187. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98188. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98189. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98190. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98191. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98192. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98193. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98194. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98195. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98196. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98197. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98198. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98199. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98200. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98201. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98202. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98203. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98204. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98205. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98206. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98207. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98208. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98209. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98210. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98211. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98212. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98213. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98214. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98215. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98216. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98217. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98218. buf[0] += a;
  98219. buf[1] += b;
  98220. buf[2] += c;
  98221. buf[3] += d;
  98222. }
  98223. #if WORDS_BIGENDIAN
  98224. //@@@@@@ OPT: use bswap/intrinsics
  98225. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98226. {
  98227. register FLAC__uint32 x;
  98228. do {
  98229. x = *buf;
  98230. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98231. *buf++ = (x >> 16) | (x << 16);
  98232. } while (--words);
  98233. }
  98234. static void byteSwapX16(FLAC__uint32 *buf)
  98235. {
  98236. register FLAC__uint32 x;
  98237. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98238. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98239. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98240. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98241. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98242. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98243. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98244. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98245. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98246. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98247. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98248. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98249. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98250. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98251. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98252. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98253. }
  98254. #else
  98255. #define byteSwap(buf, words)
  98256. #define byteSwapX16(buf)
  98257. #endif
  98258. /*
  98259. * Update context to reflect the concatenation of another buffer full
  98260. * of bytes.
  98261. */
  98262. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98263. {
  98264. FLAC__uint32 t;
  98265. /* Update byte count */
  98266. t = ctx->bytes[0];
  98267. if ((ctx->bytes[0] = t + len) < t)
  98268. ctx->bytes[1]++; /* Carry from low to high */
  98269. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98270. if (t > len) {
  98271. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98272. return;
  98273. }
  98274. /* First chunk is an odd size */
  98275. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98276. byteSwapX16(ctx->in);
  98277. FLAC__MD5Transform(ctx->buf, ctx->in);
  98278. buf += t;
  98279. len -= t;
  98280. /* Process data in 64-byte chunks */
  98281. while (len >= 64) {
  98282. memcpy(ctx->in, buf, 64);
  98283. byteSwapX16(ctx->in);
  98284. FLAC__MD5Transform(ctx->buf, ctx->in);
  98285. buf += 64;
  98286. len -= 64;
  98287. }
  98288. /* Handle any remaining bytes of data. */
  98289. memcpy(ctx->in, buf, len);
  98290. }
  98291. /*
  98292. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98293. * initialization constants.
  98294. */
  98295. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98296. {
  98297. ctx->buf[0] = 0x67452301;
  98298. ctx->buf[1] = 0xefcdab89;
  98299. ctx->buf[2] = 0x98badcfe;
  98300. ctx->buf[3] = 0x10325476;
  98301. ctx->bytes[0] = 0;
  98302. ctx->bytes[1] = 0;
  98303. ctx->internal_buf = 0;
  98304. ctx->capacity = 0;
  98305. }
  98306. /*
  98307. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98308. * 1 0* (64-bit count of bits processed, MSB-first)
  98309. */
  98310. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98311. {
  98312. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98313. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98314. /* Set the first char of padding to 0x80. There is always room. */
  98315. *p++ = 0x80;
  98316. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98317. count = 56 - 1 - count;
  98318. if (count < 0) { /* Padding forces an extra block */
  98319. memset(p, 0, count + 8);
  98320. byteSwapX16(ctx->in);
  98321. FLAC__MD5Transform(ctx->buf, ctx->in);
  98322. p = (FLAC__byte *)ctx->in;
  98323. count = 56;
  98324. }
  98325. memset(p, 0, count);
  98326. byteSwap(ctx->in, 14);
  98327. /* Append length in bits and transform */
  98328. ctx->in[14] = ctx->bytes[0] << 3;
  98329. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98330. FLAC__MD5Transform(ctx->buf, ctx->in);
  98331. byteSwap(ctx->buf, 4);
  98332. memcpy(digest, ctx->buf, 16);
  98333. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98334. if(0 != ctx->internal_buf) {
  98335. free(ctx->internal_buf);
  98336. ctx->internal_buf = 0;
  98337. ctx->capacity = 0;
  98338. }
  98339. }
  98340. /*
  98341. * Convert the incoming audio signal to a byte stream
  98342. */
  98343. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98344. {
  98345. unsigned channel, sample;
  98346. register FLAC__int32 a_word;
  98347. register FLAC__byte *buf_ = buf;
  98348. #if WORDS_BIGENDIAN
  98349. #else
  98350. if(channels == 2 && bytes_per_sample == 2) {
  98351. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98352. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98353. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98354. *buf1_ = (FLAC__int16)signal[1][sample];
  98355. }
  98356. else if(channels == 1 && bytes_per_sample == 2) {
  98357. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98358. for(sample = 0; sample < samples; sample++)
  98359. *buf1_++ = (FLAC__int16)signal[0][sample];
  98360. }
  98361. else
  98362. #endif
  98363. if(bytes_per_sample == 2) {
  98364. if(channels == 2) {
  98365. for(sample = 0; sample < samples; sample++) {
  98366. a_word = signal[0][sample];
  98367. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98368. *buf_++ = (FLAC__byte)a_word;
  98369. a_word = signal[1][sample];
  98370. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98371. *buf_++ = (FLAC__byte)a_word;
  98372. }
  98373. }
  98374. else if(channels == 1) {
  98375. for(sample = 0; sample < samples; sample++) {
  98376. a_word = signal[0][sample];
  98377. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98378. *buf_++ = (FLAC__byte)a_word;
  98379. }
  98380. }
  98381. else {
  98382. for(sample = 0; sample < samples; sample++) {
  98383. for(channel = 0; channel < channels; channel++) {
  98384. a_word = signal[channel][sample];
  98385. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98386. *buf_++ = (FLAC__byte)a_word;
  98387. }
  98388. }
  98389. }
  98390. }
  98391. else if(bytes_per_sample == 3) {
  98392. if(channels == 2) {
  98393. for(sample = 0; sample < samples; sample++) {
  98394. a_word = signal[0][sample];
  98395. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98396. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98397. *buf_++ = (FLAC__byte)a_word;
  98398. a_word = signal[1][sample];
  98399. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98400. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98401. *buf_++ = (FLAC__byte)a_word;
  98402. }
  98403. }
  98404. else if(channels == 1) {
  98405. for(sample = 0; sample < samples; sample++) {
  98406. a_word = signal[0][sample];
  98407. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98408. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98409. *buf_++ = (FLAC__byte)a_word;
  98410. }
  98411. }
  98412. else {
  98413. for(sample = 0; sample < samples; sample++) {
  98414. for(channel = 0; channel < channels; channel++) {
  98415. a_word = signal[channel][sample];
  98416. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98417. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98418. *buf_++ = (FLAC__byte)a_word;
  98419. }
  98420. }
  98421. }
  98422. }
  98423. else if(bytes_per_sample == 1) {
  98424. if(channels == 2) {
  98425. for(sample = 0; sample < samples; sample++) {
  98426. a_word = signal[0][sample];
  98427. *buf_++ = (FLAC__byte)a_word;
  98428. a_word = signal[1][sample];
  98429. *buf_++ = (FLAC__byte)a_word;
  98430. }
  98431. }
  98432. else if(channels == 1) {
  98433. for(sample = 0; sample < samples; sample++) {
  98434. a_word = signal[0][sample];
  98435. *buf_++ = (FLAC__byte)a_word;
  98436. }
  98437. }
  98438. else {
  98439. for(sample = 0; sample < samples; sample++) {
  98440. for(channel = 0; channel < channels; channel++) {
  98441. a_word = signal[channel][sample];
  98442. *buf_++ = (FLAC__byte)a_word;
  98443. }
  98444. }
  98445. }
  98446. }
  98447. else { /* bytes_per_sample == 4, maybe optimize more later */
  98448. for(sample = 0; sample < samples; sample++) {
  98449. for(channel = 0; channel < channels; channel++) {
  98450. a_word = signal[channel][sample];
  98451. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98452. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98453. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98454. *buf_++ = (FLAC__byte)a_word;
  98455. }
  98456. }
  98457. }
  98458. }
  98459. /*
  98460. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98461. */
  98462. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98463. {
  98464. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98465. /* overflow check */
  98466. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98467. return false;
  98468. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98469. return false;
  98470. if(ctx->capacity < bytes_needed) {
  98471. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98472. if(0 == tmp) {
  98473. free(ctx->internal_buf);
  98474. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98475. return false;
  98476. }
  98477. ctx->internal_buf = tmp;
  98478. ctx->capacity = bytes_needed;
  98479. }
  98480. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98481. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98482. return true;
  98483. }
  98484. #endif
  98485. /*** End of inlined file: md5.c ***/
  98486. /*** Start of inlined file: memory.c ***/
  98487. /*** Start of inlined file: juce_FlacHeader.h ***/
  98488. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98489. // tasks..
  98490. #define VERSION "1.2.1"
  98491. #define FLAC__NO_DLL 1
  98492. #if JUCE_MSVC
  98493. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98494. #endif
  98495. #if JUCE_MAC
  98496. #define FLAC__SYS_DARWIN 1
  98497. #endif
  98498. /*** End of inlined file: juce_FlacHeader.h ***/
  98499. #if JUCE_USE_FLAC
  98500. #if HAVE_CONFIG_H
  98501. # include <config.h>
  98502. #endif
  98503. /*** Start of inlined file: memory.h ***/
  98504. #ifndef FLAC__PRIVATE__MEMORY_H
  98505. #define FLAC__PRIVATE__MEMORY_H
  98506. #ifdef HAVE_CONFIG_H
  98507. #include <config.h>
  98508. #endif
  98509. #include <stdlib.h> /* for size_t */
  98510. /* Returns the unaligned address returned by malloc.
  98511. * Use free() on this address to deallocate.
  98512. */
  98513. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98514. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98515. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98516. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98517. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98518. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98519. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98520. #endif
  98521. #endif
  98522. /*** End of inlined file: memory.h ***/
  98523. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98524. {
  98525. void *x;
  98526. FLAC__ASSERT(0 != aligned_address);
  98527. #ifdef FLAC__ALIGN_MALLOC_DATA
  98528. /* align on 32-byte (256-bit) boundary */
  98529. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98530. #ifdef SIZEOF_VOIDP
  98531. #if SIZEOF_VOIDP == 4
  98532. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98533. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98534. #elif SIZEOF_VOIDP == 8
  98535. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98536. #else
  98537. # error Unsupported sizeof(void*)
  98538. #endif
  98539. #else
  98540. /* there's got to be a better way to do this right for all archs */
  98541. if(sizeof(void*) == sizeof(unsigned))
  98542. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98543. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98544. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98545. else
  98546. return 0;
  98547. #endif
  98548. #else
  98549. x = safe_malloc_(bytes);
  98550. *aligned_address = x;
  98551. #endif
  98552. return x;
  98553. }
  98554. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98555. {
  98556. FLAC__int32 *pu; /* unaligned pointer */
  98557. union { /* union needed to comply with C99 pointer aliasing rules */
  98558. FLAC__int32 *pa; /* aligned pointer */
  98559. void *pv; /* aligned pointer alias */
  98560. } u;
  98561. FLAC__ASSERT(elements > 0);
  98562. FLAC__ASSERT(0 != unaligned_pointer);
  98563. FLAC__ASSERT(0 != aligned_pointer);
  98564. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98565. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98566. if(0 == pu) {
  98567. return false;
  98568. }
  98569. else {
  98570. if(*unaligned_pointer != 0)
  98571. free(*unaligned_pointer);
  98572. *unaligned_pointer = pu;
  98573. *aligned_pointer = u.pa;
  98574. return true;
  98575. }
  98576. }
  98577. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98578. {
  98579. FLAC__uint32 *pu; /* unaligned pointer */
  98580. union { /* union needed to comply with C99 pointer aliasing rules */
  98581. FLAC__uint32 *pa; /* aligned pointer */
  98582. void *pv; /* aligned pointer alias */
  98583. } u;
  98584. FLAC__ASSERT(elements > 0);
  98585. FLAC__ASSERT(0 != unaligned_pointer);
  98586. FLAC__ASSERT(0 != aligned_pointer);
  98587. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98588. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98589. if(0 == pu) {
  98590. return false;
  98591. }
  98592. else {
  98593. if(*unaligned_pointer != 0)
  98594. free(*unaligned_pointer);
  98595. *unaligned_pointer = pu;
  98596. *aligned_pointer = u.pa;
  98597. return true;
  98598. }
  98599. }
  98600. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98601. {
  98602. FLAC__uint64 *pu; /* unaligned pointer */
  98603. union { /* union needed to comply with C99 pointer aliasing rules */
  98604. FLAC__uint64 *pa; /* aligned pointer */
  98605. void *pv; /* aligned pointer alias */
  98606. } u;
  98607. FLAC__ASSERT(elements > 0);
  98608. FLAC__ASSERT(0 != unaligned_pointer);
  98609. FLAC__ASSERT(0 != aligned_pointer);
  98610. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98611. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98612. if(0 == pu) {
  98613. return false;
  98614. }
  98615. else {
  98616. if(*unaligned_pointer != 0)
  98617. free(*unaligned_pointer);
  98618. *unaligned_pointer = pu;
  98619. *aligned_pointer = u.pa;
  98620. return true;
  98621. }
  98622. }
  98623. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98624. {
  98625. unsigned *pu; /* unaligned pointer */
  98626. union { /* union needed to comply with C99 pointer aliasing rules */
  98627. unsigned *pa; /* aligned pointer */
  98628. void *pv; /* aligned pointer alias */
  98629. } u;
  98630. FLAC__ASSERT(elements > 0);
  98631. FLAC__ASSERT(0 != unaligned_pointer);
  98632. FLAC__ASSERT(0 != aligned_pointer);
  98633. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98634. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98635. if(0 == pu) {
  98636. return false;
  98637. }
  98638. else {
  98639. if(*unaligned_pointer != 0)
  98640. free(*unaligned_pointer);
  98641. *unaligned_pointer = pu;
  98642. *aligned_pointer = u.pa;
  98643. return true;
  98644. }
  98645. }
  98646. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98647. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98648. {
  98649. FLAC__real *pu; /* unaligned pointer */
  98650. union { /* union needed to comply with C99 pointer aliasing rules */
  98651. FLAC__real *pa; /* aligned pointer */
  98652. void *pv; /* aligned pointer alias */
  98653. } u;
  98654. FLAC__ASSERT(elements > 0);
  98655. FLAC__ASSERT(0 != unaligned_pointer);
  98656. FLAC__ASSERT(0 != aligned_pointer);
  98657. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98658. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98659. if(0 == pu) {
  98660. return false;
  98661. }
  98662. else {
  98663. if(*unaligned_pointer != 0)
  98664. free(*unaligned_pointer);
  98665. *unaligned_pointer = pu;
  98666. *aligned_pointer = u.pa;
  98667. return true;
  98668. }
  98669. }
  98670. #endif
  98671. #endif
  98672. /*** End of inlined file: memory.c ***/
  98673. /*** Start of inlined file: stream_decoder.c ***/
  98674. /*** Start of inlined file: juce_FlacHeader.h ***/
  98675. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98676. // tasks..
  98677. #define VERSION "1.2.1"
  98678. #define FLAC__NO_DLL 1
  98679. #if JUCE_MSVC
  98680. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98681. #endif
  98682. #if JUCE_MAC
  98683. #define FLAC__SYS_DARWIN 1
  98684. #endif
  98685. /*** End of inlined file: juce_FlacHeader.h ***/
  98686. #if JUCE_USE_FLAC
  98687. #if HAVE_CONFIG_H
  98688. # include <config.h>
  98689. #endif
  98690. #if defined _MSC_VER || defined __MINGW32__
  98691. #include <io.h> /* for _setmode() */
  98692. #include <fcntl.h> /* for _O_BINARY */
  98693. #endif
  98694. #if defined __CYGWIN__ || defined __EMX__
  98695. #include <io.h> /* for setmode(), O_BINARY */
  98696. #include <fcntl.h> /* for _O_BINARY */
  98697. #endif
  98698. #include <stdio.h>
  98699. #include <stdlib.h> /* for malloc() */
  98700. #include <string.h> /* for memset/memcpy() */
  98701. #include <sys/stat.h> /* for stat() */
  98702. #include <sys/types.h> /* for off_t */
  98703. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98704. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98705. #define fseeko fseek
  98706. #define ftello ftell
  98707. #endif
  98708. #endif
  98709. /*** Start of inlined file: stream_decoder.h ***/
  98710. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98711. #define FLAC__PROTECTED__STREAM_DECODER_H
  98712. #if FLAC__HAS_OGG
  98713. #include "include/private/ogg_decoder_aspect.h"
  98714. #endif
  98715. typedef struct FLAC__StreamDecoderProtected {
  98716. FLAC__StreamDecoderState state;
  98717. unsigned channels;
  98718. FLAC__ChannelAssignment channel_assignment;
  98719. unsigned bits_per_sample;
  98720. unsigned sample_rate; /* in Hz */
  98721. unsigned blocksize; /* in samples (per channel) */
  98722. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98723. #if FLAC__HAS_OGG
  98724. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98725. #endif
  98726. } FLAC__StreamDecoderProtected;
  98727. /*
  98728. * return the number of input bytes consumed
  98729. */
  98730. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98731. #endif
  98732. /*** End of inlined file: stream_decoder.h ***/
  98733. #ifdef max
  98734. #undef max
  98735. #endif
  98736. #define max(a,b) ((a)>(b)?(a):(b))
  98737. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98738. #ifdef _MSC_VER
  98739. #define FLAC__U64L(x) x
  98740. #else
  98741. #define FLAC__U64L(x) x##LLU
  98742. #endif
  98743. /* technically this should be in an "export.c" but this is convenient enough */
  98744. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98745. #if FLAC__HAS_OGG
  98746. 1
  98747. #else
  98748. 0
  98749. #endif
  98750. ;
  98751. /***********************************************************************
  98752. *
  98753. * Private static data
  98754. *
  98755. ***********************************************************************/
  98756. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98757. /***********************************************************************
  98758. *
  98759. * Private class method prototypes
  98760. *
  98761. ***********************************************************************/
  98762. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98763. static FILE *get_binary_stdin_(void);
  98764. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98765. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98766. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98767. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98768. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98769. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98770. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98771. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98772. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98773. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98774. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98775. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98776. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98777. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98778. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98779. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98780. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98781. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98782. 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);
  98783. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98784. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98785. #if FLAC__HAS_OGG
  98786. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98787. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98788. #endif
  98789. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98790. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98791. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98792. #if FLAC__HAS_OGG
  98793. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98794. #endif
  98795. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98796. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98797. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98798. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98799. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98800. /***********************************************************************
  98801. *
  98802. * Private class data
  98803. *
  98804. ***********************************************************************/
  98805. typedef struct FLAC__StreamDecoderPrivate {
  98806. #if FLAC__HAS_OGG
  98807. FLAC__bool is_ogg;
  98808. #endif
  98809. FLAC__StreamDecoderReadCallback read_callback;
  98810. FLAC__StreamDecoderSeekCallback seek_callback;
  98811. FLAC__StreamDecoderTellCallback tell_callback;
  98812. FLAC__StreamDecoderLengthCallback length_callback;
  98813. FLAC__StreamDecoderEofCallback eof_callback;
  98814. FLAC__StreamDecoderWriteCallback write_callback;
  98815. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98816. FLAC__StreamDecoderErrorCallback error_callback;
  98817. /* generic 32-bit datapath: */
  98818. 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[]);
  98819. /* generic 64-bit datapath: */
  98820. 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[]);
  98821. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98822. 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[]);
  98823. /* 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: */
  98824. 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[]);
  98825. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98826. void *client_data;
  98827. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98828. FLAC__BitReader *input;
  98829. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98830. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98831. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98832. unsigned output_capacity, output_channels;
  98833. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98834. FLAC__uint64 samples_decoded;
  98835. FLAC__bool has_stream_info, has_seek_table;
  98836. FLAC__StreamMetadata stream_info;
  98837. FLAC__StreamMetadata seek_table;
  98838. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98839. FLAC__byte *metadata_filter_ids;
  98840. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98841. FLAC__Frame frame;
  98842. FLAC__bool cached; /* true if there is a byte in lookahead */
  98843. FLAC__CPUInfo cpuinfo;
  98844. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98845. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98846. /* unaligned (original) pointers to allocated data */
  98847. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98848. 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 */
  98849. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98850. FLAC__bool is_seeking;
  98851. FLAC__MD5Context md5context;
  98852. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98853. /* (the rest of these are only used for seeking) */
  98854. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98855. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98856. FLAC__uint64 target_sample;
  98857. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98858. #if FLAC__HAS_OGG
  98859. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98860. #endif
  98861. } FLAC__StreamDecoderPrivate;
  98862. /***********************************************************************
  98863. *
  98864. * Public static class data
  98865. *
  98866. ***********************************************************************/
  98867. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98868. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98869. "FLAC__STREAM_DECODER_READ_METADATA",
  98870. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98871. "FLAC__STREAM_DECODER_READ_FRAME",
  98872. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98873. "FLAC__STREAM_DECODER_OGG_ERROR",
  98874. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98875. "FLAC__STREAM_DECODER_ABORTED",
  98876. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98877. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98878. };
  98879. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98880. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98881. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98882. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98883. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98884. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98885. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98886. };
  98887. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98888. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98889. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98890. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98891. };
  98892. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98893. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98894. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98895. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98896. };
  98897. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98898. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98899. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98900. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98901. };
  98902. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98903. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98904. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98905. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98906. };
  98907. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98908. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98909. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98910. };
  98911. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98912. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98913. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98914. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98915. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98916. };
  98917. /***********************************************************************
  98918. *
  98919. * Class constructor/destructor
  98920. *
  98921. ***********************************************************************/
  98922. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98923. {
  98924. FLAC__StreamDecoder *decoder;
  98925. unsigned i;
  98926. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98927. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98928. if(decoder == 0) {
  98929. return 0;
  98930. }
  98931. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98932. if(decoder->protected_ == 0) {
  98933. free(decoder);
  98934. return 0;
  98935. }
  98936. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98937. if(decoder->private_ == 0) {
  98938. free(decoder->protected_);
  98939. free(decoder);
  98940. return 0;
  98941. }
  98942. decoder->private_->input = FLAC__bitreader_new();
  98943. if(decoder->private_->input == 0) {
  98944. free(decoder->private_);
  98945. free(decoder->protected_);
  98946. free(decoder);
  98947. return 0;
  98948. }
  98949. decoder->private_->metadata_filter_ids_capacity = 16;
  98950. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98951. FLAC__bitreader_delete(decoder->private_->input);
  98952. free(decoder->private_);
  98953. free(decoder->protected_);
  98954. free(decoder);
  98955. return 0;
  98956. }
  98957. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98958. decoder->private_->output[i] = 0;
  98959. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98960. }
  98961. decoder->private_->output_capacity = 0;
  98962. decoder->private_->output_channels = 0;
  98963. decoder->private_->has_seek_table = false;
  98964. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98965. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98966. decoder->private_->file = 0;
  98967. set_defaults_dec(decoder);
  98968. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98969. return decoder;
  98970. }
  98971. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98972. {
  98973. unsigned i;
  98974. FLAC__ASSERT(0 != decoder);
  98975. FLAC__ASSERT(0 != decoder->protected_);
  98976. FLAC__ASSERT(0 != decoder->private_);
  98977. FLAC__ASSERT(0 != decoder->private_->input);
  98978. (void)FLAC__stream_decoder_finish(decoder);
  98979. if(0 != decoder->private_->metadata_filter_ids)
  98980. free(decoder->private_->metadata_filter_ids);
  98981. FLAC__bitreader_delete(decoder->private_->input);
  98982. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98983. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98984. free(decoder->private_);
  98985. free(decoder->protected_);
  98986. free(decoder);
  98987. }
  98988. /***********************************************************************
  98989. *
  98990. * Public class methods
  98991. *
  98992. ***********************************************************************/
  98993. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98994. FLAC__StreamDecoder *decoder,
  98995. FLAC__StreamDecoderReadCallback read_callback,
  98996. FLAC__StreamDecoderSeekCallback seek_callback,
  98997. FLAC__StreamDecoderTellCallback tell_callback,
  98998. FLAC__StreamDecoderLengthCallback length_callback,
  98999. FLAC__StreamDecoderEofCallback eof_callback,
  99000. FLAC__StreamDecoderWriteCallback write_callback,
  99001. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99002. FLAC__StreamDecoderErrorCallback error_callback,
  99003. void *client_data,
  99004. FLAC__bool is_ogg
  99005. )
  99006. {
  99007. FLAC__ASSERT(0 != decoder);
  99008. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99009. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99010. #if !FLAC__HAS_OGG
  99011. if(is_ogg)
  99012. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99013. #endif
  99014. if(
  99015. 0 == read_callback ||
  99016. 0 == write_callback ||
  99017. 0 == error_callback ||
  99018. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99019. )
  99020. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99021. #if FLAC__HAS_OGG
  99022. decoder->private_->is_ogg = is_ogg;
  99023. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99024. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99025. #endif
  99026. /*
  99027. * get the CPU info and set the function pointers
  99028. */
  99029. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99030. /* first default to the non-asm routines */
  99031. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99032. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99033. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99034. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99035. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99036. /* now override with asm where appropriate */
  99037. #ifndef FLAC__NO_ASM
  99038. if(decoder->private_->cpuinfo.use_asm) {
  99039. #ifdef FLAC__CPU_IA32
  99040. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99041. #ifdef FLAC__HAS_NASM
  99042. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99043. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99044. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99045. #endif
  99046. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99047. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99048. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99049. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99050. }
  99051. else {
  99052. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99053. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99054. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99055. }
  99056. #endif
  99057. #elif defined FLAC__CPU_PPC
  99058. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99059. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99060. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99061. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99062. }
  99063. #endif
  99064. }
  99065. #endif
  99066. /* from here on, errors are fatal */
  99067. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99068. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99069. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99070. }
  99071. decoder->private_->read_callback = read_callback;
  99072. decoder->private_->seek_callback = seek_callback;
  99073. decoder->private_->tell_callback = tell_callback;
  99074. decoder->private_->length_callback = length_callback;
  99075. decoder->private_->eof_callback = eof_callback;
  99076. decoder->private_->write_callback = write_callback;
  99077. decoder->private_->metadata_callback = metadata_callback;
  99078. decoder->private_->error_callback = error_callback;
  99079. decoder->private_->client_data = client_data;
  99080. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99081. decoder->private_->samples_decoded = 0;
  99082. decoder->private_->has_stream_info = false;
  99083. decoder->private_->cached = false;
  99084. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99085. decoder->private_->is_seeking = false;
  99086. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99087. if(!FLAC__stream_decoder_reset(decoder)) {
  99088. /* above call sets the state for us */
  99089. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99090. }
  99091. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99092. }
  99093. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99094. FLAC__StreamDecoder *decoder,
  99095. FLAC__StreamDecoderReadCallback read_callback,
  99096. FLAC__StreamDecoderSeekCallback seek_callback,
  99097. FLAC__StreamDecoderTellCallback tell_callback,
  99098. FLAC__StreamDecoderLengthCallback length_callback,
  99099. FLAC__StreamDecoderEofCallback eof_callback,
  99100. FLAC__StreamDecoderWriteCallback write_callback,
  99101. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99102. FLAC__StreamDecoderErrorCallback error_callback,
  99103. void *client_data
  99104. )
  99105. {
  99106. return init_stream_internal_dec(
  99107. decoder,
  99108. read_callback,
  99109. seek_callback,
  99110. tell_callback,
  99111. length_callback,
  99112. eof_callback,
  99113. write_callback,
  99114. metadata_callback,
  99115. error_callback,
  99116. client_data,
  99117. /*is_ogg=*/false
  99118. );
  99119. }
  99120. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99121. FLAC__StreamDecoder *decoder,
  99122. FLAC__StreamDecoderReadCallback read_callback,
  99123. FLAC__StreamDecoderSeekCallback seek_callback,
  99124. FLAC__StreamDecoderTellCallback tell_callback,
  99125. FLAC__StreamDecoderLengthCallback length_callback,
  99126. FLAC__StreamDecoderEofCallback eof_callback,
  99127. FLAC__StreamDecoderWriteCallback write_callback,
  99128. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99129. FLAC__StreamDecoderErrorCallback error_callback,
  99130. void *client_data
  99131. )
  99132. {
  99133. return init_stream_internal_dec(
  99134. decoder,
  99135. read_callback,
  99136. seek_callback,
  99137. tell_callback,
  99138. length_callback,
  99139. eof_callback,
  99140. write_callback,
  99141. metadata_callback,
  99142. error_callback,
  99143. client_data,
  99144. /*is_ogg=*/true
  99145. );
  99146. }
  99147. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99148. FLAC__StreamDecoder *decoder,
  99149. FILE *file,
  99150. FLAC__StreamDecoderWriteCallback write_callback,
  99151. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99152. FLAC__StreamDecoderErrorCallback error_callback,
  99153. void *client_data,
  99154. FLAC__bool is_ogg
  99155. )
  99156. {
  99157. FLAC__ASSERT(0 != decoder);
  99158. FLAC__ASSERT(0 != file);
  99159. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99160. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99161. if(0 == write_callback || 0 == error_callback)
  99162. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99163. /*
  99164. * To make sure that our file does not go unclosed after an error, we
  99165. * must assign the FILE pointer before any further error can occur in
  99166. * this routine.
  99167. */
  99168. if(file == stdin)
  99169. file = get_binary_stdin_(); /* just to be safe */
  99170. decoder->private_->file = file;
  99171. return init_stream_internal_dec(
  99172. decoder,
  99173. file_read_callback_dec,
  99174. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99175. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99176. decoder->private_->file == stdin? 0: file_length_callback_,
  99177. file_eof_callback_,
  99178. write_callback,
  99179. metadata_callback,
  99180. error_callback,
  99181. client_data,
  99182. is_ogg
  99183. );
  99184. }
  99185. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99186. FLAC__StreamDecoder *decoder,
  99187. FILE *file,
  99188. FLAC__StreamDecoderWriteCallback write_callback,
  99189. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99190. FLAC__StreamDecoderErrorCallback error_callback,
  99191. void *client_data
  99192. )
  99193. {
  99194. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99195. }
  99196. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99197. FLAC__StreamDecoder *decoder,
  99198. FILE *file,
  99199. FLAC__StreamDecoderWriteCallback write_callback,
  99200. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99201. FLAC__StreamDecoderErrorCallback error_callback,
  99202. void *client_data
  99203. )
  99204. {
  99205. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99206. }
  99207. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99208. FLAC__StreamDecoder *decoder,
  99209. const char *filename,
  99210. FLAC__StreamDecoderWriteCallback write_callback,
  99211. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99212. FLAC__StreamDecoderErrorCallback error_callback,
  99213. void *client_data,
  99214. FLAC__bool is_ogg
  99215. )
  99216. {
  99217. FILE *file;
  99218. FLAC__ASSERT(0 != decoder);
  99219. /*
  99220. * To make sure that our file does not go unclosed after an error, we
  99221. * have to do the same entrance checks here that are later performed
  99222. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99223. */
  99224. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99225. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99226. if(0 == write_callback || 0 == error_callback)
  99227. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99228. file = filename? fopen(filename, "rb") : stdin;
  99229. if(0 == file)
  99230. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99231. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99232. }
  99233. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99234. FLAC__StreamDecoder *decoder,
  99235. const char *filename,
  99236. FLAC__StreamDecoderWriteCallback write_callback,
  99237. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99238. FLAC__StreamDecoderErrorCallback error_callback,
  99239. void *client_data
  99240. )
  99241. {
  99242. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99243. }
  99244. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99245. FLAC__StreamDecoder *decoder,
  99246. const char *filename,
  99247. FLAC__StreamDecoderWriteCallback write_callback,
  99248. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99249. FLAC__StreamDecoderErrorCallback error_callback,
  99250. void *client_data
  99251. )
  99252. {
  99253. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99254. }
  99255. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99256. {
  99257. FLAC__bool md5_failed = false;
  99258. unsigned i;
  99259. FLAC__ASSERT(0 != decoder);
  99260. FLAC__ASSERT(0 != decoder->private_);
  99261. FLAC__ASSERT(0 != decoder->protected_);
  99262. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99263. return true;
  99264. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99265. * always call FLAC__MD5Final()
  99266. */
  99267. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99268. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99269. free(decoder->private_->seek_table.data.seek_table.points);
  99270. decoder->private_->seek_table.data.seek_table.points = 0;
  99271. decoder->private_->has_seek_table = false;
  99272. }
  99273. FLAC__bitreader_free(decoder->private_->input);
  99274. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99275. /* WATCHOUT:
  99276. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99277. * output arrays have a buffer of up to 3 zeroes in front
  99278. * (at negative indices) for alignment purposes; we use 4
  99279. * to keep the data well-aligned.
  99280. */
  99281. if(0 != decoder->private_->output[i]) {
  99282. free(decoder->private_->output[i]-4);
  99283. decoder->private_->output[i] = 0;
  99284. }
  99285. if(0 != decoder->private_->residual_unaligned[i]) {
  99286. free(decoder->private_->residual_unaligned[i]);
  99287. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99288. }
  99289. }
  99290. decoder->private_->output_capacity = 0;
  99291. decoder->private_->output_channels = 0;
  99292. #if FLAC__HAS_OGG
  99293. if(decoder->private_->is_ogg)
  99294. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99295. #endif
  99296. if(0 != decoder->private_->file) {
  99297. if(decoder->private_->file != stdin)
  99298. fclose(decoder->private_->file);
  99299. decoder->private_->file = 0;
  99300. }
  99301. if(decoder->private_->do_md5_checking) {
  99302. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99303. md5_failed = true;
  99304. }
  99305. decoder->private_->is_seeking = false;
  99306. set_defaults_dec(decoder);
  99307. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99308. return !md5_failed;
  99309. }
  99310. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99311. {
  99312. FLAC__ASSERT(0 != decoder);
  99313. FLAC__ASSERT(0 != decoder->private_);
  99314. FLAC__ASSERT(0 != decoder->protected_);
  99315. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99316. return false;
  99317. #if FLAC__HAS_OGG
  99318. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99319. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99320. return true;
  99321. #else
  99322. (void)value;
  99323. return false;
  99324. #endif
  99325. }
  99326. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99327. {
  99328. FLAC__ASSERT(0 != decoder);
  99329. FLAC__ASSERT(0 != decoder->protected_);
  99330. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99331. return false;
  99332. decoder->protected_->md5_checking = value;
  99333. return true;
  99334. }
  99335. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99336. {
  99337. FLAC__ASSERT(0 != decoder);
  99338. FLAC__ASSERT(0 != decoder->private_);
  99339. FLAC__ASSERT(0 != decoder->protected_);
  99340. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99341. /* double protection */
  99342. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99343. return false;
  99344. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99345. return false;
  99346. decoder->private_->metadata_filter[type] = true;
  99347. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99348. decoder->private_->metadata_filter_ids_count = 0;
  99349. return true;
  99350. }
  99351. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99352. {
  99353. FLAC__ASSERT(0 != decoder);
  99354. FLAC__ASSERT(0 != decoder->private_);
  99355. FLAC__ASSERT(0 != decoder->protected_);
  99356. FLAC__ASSERT(0 != id);
  99357. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99358. return false;
  99359. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99360. return true;
  99361. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99362. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99363. 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))) {
  99364. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99365. return false;
  99366. }
  99367. decoder->private_->metadata_filter_ids_capacity *= 2;
  99368. }
  99369. 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));
  99370. decoder->private_->metadata_filter_ids_count++;
  99371. return true;
  99372. }
  99373. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99374. {
  99375. unsigned i;
  99376. FLAC__ASSERT(0 != decoder);
  99377. FLAC__ASSERT(0 != decoder->private_);
  99378. FLAC__ASSERT(0 != decoder->protected_);
  99379. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99380. return false;
  99381. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99382. decoder->private_->metadata_filter[i] = true;
  99383. decoder->private_->metadata_filter_ids_count = 0;
  99384. return true;
  99385. }
  99386. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99387. {
  99388. FLAC__ASSERT(0 != decoder);
  99389. FLAC__ASSERT(0 != decoder->private_);
  99390. FLAC__ASSERT(0 != decoder->protected_);
  99391. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99392. /* double protection */
  99393. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99394. return false;
  99395. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99396. return false;
  99397. decoder->private_->metadata_filter[type] = false;
  99398. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99399. decoder->private_->metadata_filter_ids_count = 0;
  99400. return true;
  99401. }
  99402. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99403. {
  99404. FLAC__ASSERT(0 != decoder);
  99405. FLAC__ASSERT(0 != decoder->private_);
  99406. FLAC__ASSERT(0 != decoder->protected_);
  99407. FLAC__ASSERT(0 != id);
  99408. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99409. return false;
  99410. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99411. return true;
  99412. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99413. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99414. 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))) {
  99415. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99416. return false;
  99417. }
  99418. decoder->private_->metadata_filter_ids_capacity *= 2;
  99419. }
  99420. 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));
  99421. decoder->private_->metadata_filter_ids_count++;
  99422. return true;
  99423. }
  99424. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99425. {
  99426. FLAC__ASSERT(0 != decoder);
  99427. FLAC__ASSERT(0 != decoder->private_);
  99428. FLAC__ASSERT(0 != decoder->protected_);
  99429. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99430. return false;
  99431. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99432. decoder->private_->metadata_filter_ids_count = 0;
  99433. return true;
  99434. }
  99435. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99436. {
  99437. FLAC__ASSERT(0 != decoder);
  99438. FLAC__ASSERT(0 != decoder->protected_);
  99439. return decoder->protected_->state;
  99440. }
  99441. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99442. {
  99443. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99444. }
  99445. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99446. {
  99447. FLAC__ASSERT(0 != decoder);
  99448. FLAC__ASSERT(0 != decoder->protected_);
  99449. return decoder->protected_->md5_checking;
  99450. }
  99451. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99452. {
  99453. FLAC__ASSERT(0 != decoder);
  99454. FLAC__ASSERT(0 != decoder->protected_);
  99455. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99456. }
  99457. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99458. {
  99459. FLAC__ASSERT(0 != decoder);
  99460. FLAC__ASSERT(0 != decoder->protected_);
  99461. return decoder->protected_->channels;
  99462. }
  99463. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99464. {
  99465. FLAC__ASSERT(0 != decoder);
  99466. FLAC__ASSERT(0 != decoder->protected_);
  99467. return decoder->protected_->channel_assignment;
  99468. }
  99469. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99470. {
  99471. FLAC__ASSERT(0 != decoder);
  99472. FLAC__ASSERT(0 != decoder->protected_);
  99473. return decoder->protected_->bits_per_sample;
  99474. }
  99475. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99476. {
  99477. FLAC__ASSERT(0 != decoder);
  99478. FLAC__ASSERT(0 != decoder->protected_);
  99479. return decoder->protected_->sample_rate;
  99480. }
  99481. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99482. {
  99483. FLAC__ASSERT(0 != decoder);
  99484. FLAC__ASSERT(0 != decoder->protected_);
  99485. return decoder->protected_->blocksize;
  99486. }
  99487. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99488. {
  99489. FLAC__ASSERT(0 != decoder);
  99490. FLAC__ASSERT(0 != decoder->private_);
  99491. FLAC__ASSERT(0 != position);
  99492. #if FLAC__HAS_OGG
  99493. if(decoder->private_->is_ogg)
  99494. return false;
  99495. #endif
  99496. if(0 == decoder->private_->tell_callback)
  99497. return false;
  99498. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99499. return false;
  99500. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99501. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99502. return false;
  99503. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99504. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99505. return true;
  99506. }
  99507. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99508. {
  99509. FLAC__ASSERT(0 != decoder);
  99510. FLAC__ASSERT(0 != decoder->private_);
  99511. FLAC__ASSERT(0 != decoder->protected_);
  99512. decoder->private_->samples_decoded = 0;
  99513. decoder->private_->do_md5_checking = false;
  99514. #if FLAC__HAS_OGG
  99515. if(decoder->private_->is_ogg)
  99516. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99517. #endif
  99518. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99519. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99520. return false;
  99521. }
  99522. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99523. return true;
  99524. }
  99525. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99526. {
  99527. FLAC__ASSERT(0 != decoder);
  99528. FLAC__ASSERT(0 != decoder->private_);
  99529. FLAC__ASSERT(0 != decoder->protected_);
  99530. if(!FLAC__stream_decoder_flush(decoder)) {
  99531. /* above call sets the state for us */
  99532. return false;
  99533. }
  99534. #if FLAC__HAS_OGG
  99535. /*@@@ could go in !internal_reset_hack block below */
  99536. if(decoder->private_->is_ogg)
  99537. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99538. #endif
  99539. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99540. * (internal_reset_hack) don't try to rewind since we are already at
  99541. * the beginning of the stream and don't want to fail if the input is
  99542. * not seekable.
  99543. */
  99544. if(!decoder->private_->internal_reset_hack) {
  99545. if(decoder->private_->file == stdin)
  99546. return false; /* can't rewind stdin, reset fails */
  99547. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99548. return false; /* seekable and seek fails, reset fails */
  99549. }
  99550. else
  99551. decoder->private_->internal_reset_hack = false;
  99552. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99553. decoder->private_->has_stream_info = false;
  99554. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99555. free(decoder->private_->seek_table.data.seek_table.points);
  99556. decoder->private_->seek_table.data.seek_table.points = 0;
  99557. decoder->private_->has_seek_table = false;
  99558. }
  99559. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99560. /*
  99561. * This goes in reset() and not flush() because according to the spec, a
  99562. * fixed-blocksize stream must stay that way through the whole stream.
  99563. */
  99564. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99565. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99566. * is because md5 checking may be turned on to start and then turned off if
  99567. * a seek occurs. So we init the context here and finalize it in
  99568. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99569. * properly.
  99570. */
  99571. FLAC__MD5Init(&decoder->private_->md5context);
  99572. decoder->private_->first_frame_offset = 0;
  99573. decoder->private_->unparseable_frame_count = 0;
  99574. return true;
  99575. }
  99576. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99577. {
  99578. FLAC__bool got_a_frame;
  99579. FLAC__ASSERT(0 != decoder);
  99580. FLAC__ASSERT(0 != decoder->protected_);
  99581. while(1) {
  99582. switch(decoder->protected_->state) {
  99583. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99584. if(!find_metadata_(decoder))
  99585. return false; /* above function sets the status for us */
  99586. break;
  99587. case FLAC__STREAM_DECODER_READ_METADATA:
  99588. if(!read_metadata_(decoder))
  99589. return false; /* above function sets the status for us */
  99590. else
  99591. return true;
  99592. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99593. if(!frame_sync_(decoder))
  99594. return true; /* above function sets the status for us */
  99595. break;
  99596. case FLAC__STREAM_DECODER_READ_FRAME:
  99597. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99598. return false; /* above function sets the status for us */
  99599. if(got_a_frame)
  99600. return true; /* above function sets the status for us */
  99601. break;
  99602. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99603. case FLAC__STREAM_DECODER_ABORTED:
  99604. return true;
  99605. default:
  99606. FLAC__ASSERT(0);
  99607. return false;
  99608. }
  99609. }
  99610. }
  99611. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99612. {
  99613. FLAC__ASSERT(0 != decoder);
  99614. FLAC__ASSERT(0 != decoder->protected_);
  99615. while(1) {
  99616. switch(decoder->protected_->state) {
  99617. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99618. if(!find_metadata_(decoder))
  99619. return false; /* above function sets the status for us */
  99620. break;
  99621. case FLAC__STREAM_DECODER_READ_METADATA:
  99622. if(!read_metadata_(decoder))
  99623. return false; /* above function sets the status for us */
  99624. break;
  99625. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99626. case FLAC__STREAM_DECODER_READ_FRAME:
  99627. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99628. case FLAC__STREAM_DECODER_ABORTED:
  99629. return true;
  99630. default:
  99631. FLAC__ASSERT(0);
  99632. return false;
  99633. }
  99634. }
  99635. }
  99636. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99637. {
  99638. FLAC__bool dummy;
  99639. FLAC__ASSERT(0 != decoder);
  99640. FLAC__ASSERT(0 != decoder->protected_);
  99641. while(1) {
  99642. switch(decoder->protected_->state) {
  99643. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99644. if(!find_metadata_(decoder))
  99645. return false; /* above function sets the status for us */
  99646. break;
  99647. case FLAC__STREAM_DECODER_READ_METADATA:
  99648. if(!read_metadata_(decoder))
  99649. return false; /* above function sets the status for us */
  99650. break;
  99651. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99652. if(!frame_sync_(decoder))
  99653. return true; /* above function sets the status for us */
  99654. break;
  99655. case FLAC__STREAM_DECODER_READ_FRAME:
  99656. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99657. return false; /* above function sets the status for us */
  99658. break;
  99659. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99660. case FLAC__STREAM_DECODER_ABORTED:
  99661. return true;
  99662. default:
  99663. FLAC__ASSERT(0);
  99664. return false;
  99665. }
  99666. }
  99667. }
  99668. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99669. {
  99670. FLAC__bool got_a_frame;
  99671. FLAC__ASSERT(0 != decoder);
  99672. FLAC__ASSERT(0 != decoder->protected_);
  99673. while(1) {
  99674. switch(decoder->protected_->state) {
  99675. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99676. case FLAC__STREAM_DECODER_READ_METADATA:
  99677. return false; /* above function sets the status for us */
  99678. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99679. if(!frame_sync_(decoder))
  99680. return true; /* above function sets the status for us */
  99681. break;
  99682. case FLAC__STREAM_DECODER_READ_FRAME:
  99683. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99684. return false; /* above function sets the status for us */
  99685. if(got_a_frame)
  99686. return true; /* above function sets the status for us */
  99687. break;
  99688. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99689. case FLAC__STREAM_DECODER_ABORTED:
  99690. return true;
  99691. default:
  99692. FLAC__ASSERT(0);
  99693. return false;
  99694. }
  99695. }
  99696. }
  99697. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99698. {
  99699. FLAC__uint64 length;
  99700. FLAC__ASSERT(0 != decoder);
  99701. if(
  99702. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99703. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99704. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99705. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99706. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99707. )
  99708. return false;
  99709. if(0 == decoder->private_->seek_callback)
  99710. return false;
  99711. FLAC__ASSERT(decoder->private_->seek_callback);
  99712. FLAC__ASSERT(decoder->private_->tell_callback);
  99713. FLAC__ASSERT(decoder->private_->length_callback);
  99714. FLAC__ASSERT(decoder->private_->eof_callback);
  99715. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99716. return false;
  99717. decoder->private_->is_seeking = true;
  99718. /* turn off md5 checking if a seek is attempted */
  99719. decoder->private_->do_md5_checking = false;
  99720. /* 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) */
  99721. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99722. decoder->private_->is_seeking = false;
  99723. return false;
  99724. }
  99725. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99726. if(
  99727. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99728. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99729. ) {
  99730. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99731. /* above call sets the state for us */
  99732. decoder->private_->is_seeking = false;
  99733. return false;
  99734. }
  99735. /* check this again in case we didn't know total_samples the first time */
  99736. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99737. decoder->private_->is_seeking = false;
  99738. return false;
  99739. }
  99740. }
  99741. {
  99742. const FLAC__bool ok =
  99743. #if FLAC__HAS_OGG
  99744. decoder->private_->is_ogg?
  99745. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99746. #endif
  99747. seek_to_absolute_sample_(decoder, length, sample)
  99748. ;
  99749. decoder->private_->is_seeking = false;
  99750. return ok;
  99751. }
  99752. }
  99753. /***********************************************************************
  99754. *
  99755. * Protected class methods
  99756. *
  99757. ***********************************************************************/
  99758. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99759. {
  99760. FLAC__ASSERT(0 != decoder);
  99761. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99762. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99763. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99764. }
  99765. /***********************************************************************
  99766. *
  99767. * Private class methods
  99768. *
  99769. ***********************************************************************/
  99770. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99771. {
  99772. #if FLAC__HAS_OGG
  99773. decoder->private_->is_ogg = false;
  99774. #endif
  99775. decoder->private_->read_callback = 0;
  99776. decoder->private_->seek_callback = 0;
  99777. decoder->private_->tell_callback = 0;
  99778. decoder->private_->length_callback = 0;
  99779. decoder->private_->eof_callback = 0;
  99780. decoder->private_->write_callback = 0;
  99781. decoder->private_->metadata_callback = 0;
  99782. decoder->private_->error_callback = 0;
  99783. decoder->private_->client_data = 0;
  99784. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99785. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99786. decoder->private_->metadata_filter_ids_count = 0;
  99787. decoder->protected_->md5_checking = false;
  99788. #if FLAC__HAS_OGG
  99789. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99790. #endif
  99791. }
  99792. /*
  99793. * This will forcibly set stdin to binary mode (for OSes that require it)
  99794. */
  99795. FILE *get_binary_stdin_(void)
  99796. {
  99797. /* if something breaks here it is probably due to the presence or
  99798. * absence of an underscore before the identifiers 'setmode',
  99799. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99800. */
  99801. #if defined _MSC_VER || defined __MINGW32__
  99802. _setmode(_fileno(stdin), _O_BINARY);
  99803. #elif defined __CYGWIN__
  99804. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99805. setmode(_fileno(stdin), _O_BINARY);
  99806. #elif defined __EMX__
  99807. setmode(fileno(stdin), O_BINARY);
  99808. #endif
  99809. return stdin;
  99810. }
  99811. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99812. {
  99813. unsigned i;
  99814. FLAC__int32 *tmp;
  99815. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99816. return true;
  99817. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99818. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99819. if(0 != decoder->private_->output[i]) {
  99820. free(decoder->private_->output[i]-4);
  99821. decoder->private_->output[i] = 0;
  99822. }
  99823. if(0 != decoder->private_->residual_unaligned[i]) {
  99824. free(decoder->private_->residual_unaligned[i]);
  99825. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99826. }
  99827. }
  99828. for(i = 0; i < channels; i++) {
  99829. /* WATCHOUT:
  99830. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99831. * output arrays have a buffer of up to 3 zeroes in front
  99832. * (at negative indices) for alignment purposes; we use 4
  99833. * to keep the data well-aligned.
  99834. */
  99835. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99836. if(tmp == 0) {
  99837. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99838. return false;
  99839. }
  99840. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99841. decoder->private_->output[i] = tmp + 4;
  99842. /* WATCHOUT:
  99843. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99844. */
  99845. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99846. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99847. return false;
  99848. }
  99849. }
  99850. decoder->private_->output_capacity = size;
  99851. decoder->private_->output_channels = channels;
  99852. return true;
  99853. }
  99854. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99855. {
  99856. size_t i;
  99857. FLAC__ASSERT(0 != decoder);
  99858. FLAC__ASSERT(0 != decoder->private_);
  99859. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99860. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99861. return true;
  99862. return false;
  99863. }
  99864. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99865. {
  99866. FLAC__uint32 x;
  99867. unsigned i, id_;
  99868. FLAC__bool first = true;
  99869. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99870. for(i = id_ = 0; i < 4; ) {
  99871. if(decoder->private_->cached) {
  99872. x = (FLAC__uint32)decoder->private_->lookahead;
  99873. decoder->private_->cached = false;
  99874. }
  99875. else {
  99876. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99877. return false; /* read_callback_ sets the state for us */
  99878. }
  99879. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99880. first = true;
  99881. i++;
  99882. id_ = 0;
  99883. continue;
  99884. }
  99885. if(x == ID3V2_TAG_[id_]) {
  99886. id_++;
  99887. i = 0;
  99888. if(id_ == 3) {
  99889. if(!skip_id3v2_tag_(decoder))
  99890. return false; /* skip_id3v2_tag_ sets the state for us */
  99891. }
  99892. continue;
  99893. }
  99894. id_ = 0;
  99895. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99896. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99897. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99898. return false; /* read_callback_ sets the state for us */
  99899. /* 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 */
  99900. /* else we have to check if the second byte is the end of a sync code */
  99901. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99902. decoder->private_->lookahead = (FLAC__byte)x;
  99903. decoder->private_->cached = true;
  99904. }
  99905. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99906. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99907. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99908. return true;
  99909. }
  99910. }
  99911. i = 0;
  99912. if(first) {
  99913. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99914. first = false;
  99915. }
  99916. }
  99917. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99918. return true;
  99919. }
  99920. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99921. {
  99922. FLAC__bool is_last;
  99923. FLAC__uint32 i, x, type, length;
  99924. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99925. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99926. return false; /* read_callback_ sets the state for us */
  99927. is_last = x? true : false;
  99928. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99929. return false; /* read_callback_ sets the state for us */
  99930. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99931. return false; /* read_callback_ sets the state for us */
  99932. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99933. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99934. return false;
  99935. decoder->private_->has_stream_info = true;
  99936. 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))
  99937. decoder->private_->do_md5_checking = false;
  99938. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99939. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99940. }
  99941. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99942. if(!read_metadata_seektable_(decoder, is_last, length))
  99943. return false;
  99944. decoder->private_->has_seek_table = true;
  99945. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99946. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99947. }
  99948. else {
  99949. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99950. unsigned real_length = length;
  99951. FLAC__StreamMetadata block;
  99952. block.is_last = is_last;
  99953. block.type = (FLAC__MetadataType)type;
  99954. block.length = length;
  99955. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99956. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99957. return false; /* read_callback_ sets the state for us */
  99958. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99959. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99960. return false;
  99961. }
  99962. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99963. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99964. skip_it = !skip_it;
  99965. }
  99966. if(skip_it) {
  99967. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99968. return false; /* read_callback_ sets the state for us */
  99969. }
  99970. else {
  99971. switch(type) {
  99972. case FLAC__METADATA_TYPE_PADDING:
  99973. /* skip the padding bytes */
  99974. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99975. return false; /* read_callback_ sets the state for us */
  99976. break;
  99977. case FLAC__METADATA_TYPE_APPLICATION:
  99978. /* remember, we read the ID already */
  99979. if(real_length > 0) {
  99980. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99981. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99982. return false;
  99983. }
  99984. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99985. return false; /* read_callback_ sets the state for us */
  99986. }
  99987. else
  99988. block.data.application.data = 0;
  99989. break;
  99990. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99991. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99992. return false;
  99993. break;
  99994. case FLAC__METADATA_TYPE_CUESHEET:
  99995. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99996. return false;
  99997. break;
  99998. case FLAC__METADATA_TYPE_PICTURE:
  99999. if(!read_metadata_picture_(decoder, &block.data.picture))
  100000. return false;
  100001. break;
  100002. case FLAC__METADATA_TYPE_STREAMINFO:
  100003. case FLAC__METADATA_TYPE_SEEKTABLE:
  100004. FLAC__ASSERT(0);
  100005. break;
  100006. default:
  100007. if(real_length > 0) {
  100008. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100009. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100010. return false;
  100011. }
  100012. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100013. return false; /* read_callback_ sets the state for us */
  100014. }
  100015. else
  100016. block.data.unknown.data = 0;
  100017. break;
  100018. }
  100019. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100020. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100021. /* now we have to free any malloc()ed data in the block */
  100022. switch(type) {
  100023. case FLAC__METADATA_TYPE_PADDING:
  100024. break;
  100025. case FLAC__METADATA_TYPE_APPLICATION:
  100026. if(0 != block.data.application.data)
  100027. free(block.data.application.data);
  100028. break;
  100029. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100030. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100031. free(block.data.vorbis_comment.vendor_string.entry);
  100032. if(block.data.vorbis_comment.num_comments > 0)
  100033. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100034. if(0 != block.data.vorbis_comment.comments[i].entry)
  100035. free(block.data.vorbis_comment.comments[i].entry);
  100036. if(0 != block.data.vorbis_comment.comments)
  100037. free(block.data.vorbis_comment.comments);
  100038. break;
  100039. case FLAC__METADATA_TYPE_CUESHEET:
  100040. if(block.data.cue_sheet.num_tracks > 0)
  100041. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100042. if(0 != block.data.cue_sheet.tracks[i].indices)
  100043. free(block.data.cue_sheet.tracks[i].indices);
  100044. if(0 != block.data.cue_sheet.tracks)
  100045. free(block.data.cue_sheet.tracks);
  100046. break;
  100047. case FLAC__METADATA_TYPE_PICTURE:
  100048. if(0 != block.data.picture.mime_type)
  100049. free(block.data.picture.mime_type);
  100050. if(0 != block.data.picture.description)
  100051. free(block.data.picture.description);
  100052. if(0 != block.data.picture.data)
  100053. free(block.data.picture.data);
  100054. break;
  100055. case FLAC__METADATA_TYPE_STREAMINFO:
  100056. case FLAC__METADATA_TYPE_SEEKTABLE:
  100057. FLAC__ASSERT(0);
  100058. default:
  100059. if(0 != block.data.unknown.data)
  100060. free(block.data.unknown.data);
  100061. break;
  100062. }
  100063. }
  100064. }
  100065. if(is_last) {
  100066. /* if this fails, it's OK, it's just a hint for the seek routine */
  100067. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100068. decoder->private_->first_frame_offset = 0;
  100069. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100070. }
  100071. return true;
  100072. }
  100073. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100074. {
  100075. FLAC__uint32 x;
  100076. unsigned bits, used_bits = 0;
  100077. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100078. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100079. decoder->private_->stream_info.is_last = is_last;
  100080. decoder->private_->stream_info.length = length;
  100081. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100082. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100083. return false; /* read_callback_ sets the state for us */
  100084. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100085. used_bits += bits;
  100086. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100087. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100088. return false; /* read_callback_ sets the state for us */
  100089. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100090. used_bits += bits;
  100091. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100092. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100093. return false; /* read_callback_ sets the state for us */
  100094. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100095. used_bits += bits;
  100096. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100097. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100098. return false; /* read_callback_ sets the state for us */
  100099. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100100. used_bits += bits;
  100101. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100102. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100103. return false; /* read_callback_ sets the state for us */
  100104. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100105. used_bits += bits;
  100106. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100107. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100108. return false; /* read_callback_ sets the state for us */
  100109. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100110. used_bits += bits;
  100111. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100112. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100113. return false; /* read_callback_ sets the state for us */
  100114. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100115. used_bits += bits;
  100116. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100117. 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))
  100118. return false; /* read_callback_ sets the state for us */
  100119. used_bits += bits;
  100120. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100121. return false; /* read_callback_ sets the state for us */
  100122. used_bits += 16*8;
  100123. /* skip the rest of the block */
  100124. FLAC__ASSERT(used_bits % 8 == 0);
  100125. length -= (used_bits / 8);
  100126. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100127. return false; /* read_callback_ sets the state for us */
  100128. return true;
  100129. }
  100130. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100131. {
  100132. FLAC__uint32 i, x;
  100133. FLAC__uint64 xx;
  100134. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100135. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100136. decoder->private_->seek_table.is_last = is_last;
  100137. decoder->private_->seek_table.length = length;
  100138. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100139. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100140. 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)))) {
  100141. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100142. return false;
  100143. }
  100144. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100145. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100146. return false; /* read_callback_ sets the state for us */
  100147. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100148. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100149. return false; /* read_callback_ sets the state for us */
  100150. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100151. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100152. return false; /* read_callback_ sets the state for us */
  100153. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100154. }
  100155. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100156. /* if there is a partial point left, skip over it */
  100157. if(length > 0) {
  100158. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100159. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100160. return false; /* read_callback_ sets the state for us */
  100161. }
  100162. return true;
  100163. }
  100164. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100165. {
  100166. FLAC__uint32 i;
  100167. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100168. /* read vendor string */
  100169. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100170. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100171. return false; /* read_callback_ sets the state for us */
  100172. if(obj->vendor_string.length > 0) {
  100173. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100174. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100175. return false;
  100176. }
  100177. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100178. return false; /* read_callback_ sets the state for us */
  100179. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100180. }
  100181. else
  100182. obj->vendor_string.entry = 0;
  100183. /* read num comments */
  100184. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100185. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100186. return false; /* read_callback_ sets the state for us */
  100187. /* read comments */
  100188. if(obj->num_comments > 0) {
  100189. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100190. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100191. return false;
  100192. }
  100193. for(i = 0; i < obj->num_comments; i++) {
  100194. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100195. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100196. return false; /* read_callback_ sets the state for us */
  100197. if(obj->comments[i].length > 0) {
  100198. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100199. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100200. return false;
  100201. }
  100202. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100203. return false; /* read_callback_ sets the state for us */
  100204. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100205. }
  100206. else
  100207. obj->comments[i].entry = 0;
  100208. }
  100209. }
  100210. else {
  100211. obj->comments = 0;
  100212. }
  100213. return true;
  100214. }
  100215. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100216. {
  100217. FLAC__uint32 i, j, x;
  100218. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100219. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100220. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100221. 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))
  100222. return false; /* read_callback_ sets the state for us */
  100223. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100224. return false; /* read_callback_ sets the state for us */
  100225. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100226. return false; /* read_callback_ sets the state for us */
  100227. obj->is_cd = x? true : false;
  100228. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100229. return false; /* read_callback_ sets the state for us */
  100230. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100231. return false; /* read_callback_ sets the state for us */
  100232. obj->num_tracks = x;
  100233. if(obj->num_tracks > 0) {
  100234. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100235. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100236. return false;
  100237. }
  100238. for(i = 0; i < obj->num_tracks; i++) {
  100239. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100240. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100241. return false; /* read_callback_ sets the state for us */
  100242. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100243. return false; /* read_callback_ sets the state for us */
  100244. track->number = (FLAC__byte)x;
  100245. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100246. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100247. return false; /* read_callback_ sets the state for us */
  100248. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100249. return false; /* read_callback_ sets the state for us */
  100250. track->type = x;
  100251. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100252. return false; /* read_callback_ sets the state for us */
  100253. track->pre_emphasis = x;
  100254. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100255. return false; /* read_callback_ sets the state for us */
  100256. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100257. return false; /* read_callback_ sets the state for us */
  100258. track->num_indices = (FLAC__byte)x;
  100259. if(track->num_indices > 0) {
  100260. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100261. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100262. return false;
  100263. }
  100264. for(j = 0; j < track->num_indices; j++) {
  100265. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100266. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100267. return false; /* read_callback_ sets the state for us */
  100268. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100269. return false; /* read_callback_ sets the state for us */
  100270. index->number = (FLAC__byte)x;
  100271. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100272. return false; /* read_callback_ sets the state for us */
  100273. }
  100274. }
  100275. }
  100276. }
  100277. return true;
  100278. }
  100279. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100280. {
  100281. FLAC__uint32 x;
  100282. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100283. /* read type */
  100284. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100285. return false; /* read_callback_ sets the state for us */
  100286. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100287. /* read MIME type */
  100288. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100289. return false; /* read_callback_ sets the state for us */
  100290. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100291. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100292. return false;
  100293. }
  100294. if(x > 0) {
  100295. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100296. return false; /* read_callback_ sets the state for us */
  100297. }
  100298. obj->mime_type[x] = '\0';
  100299. /* read description */
  100300. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100301. return false; /* read_callback_ sets the state for us */
  100302. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100303. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100304. return false;
  100305. }
  100306. if(x > 0) {
  100307. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100308. return false; /* read_callback_ sets the state for us */
  100309. }
  100310. obj->description[x] = '\0';
  100311. /* read width */
  100312. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100313. return false; /* read_callback_ sets the state for us */
  100314. /* read height */
  100315. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100316. return false; /* read_callback_ sets the state for us */
  100317. /* read depth */
  100318. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100319. return false; /* read_callback_ sets the state for us */
  100320. /* read colors */
  100321. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100322. return false; /* read_callback_ sets the state for us */
  100323. /* read data */
  100324. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100325. return false; /* read_callback_ sets the state for us */
  100326. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100327. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100328. return false;
  100329. }
  100330. if(obj->data_length > 0) {
  100331. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100332. return false; /* read_callback_ sets the state for us */
  100333. }
  100334. return true;
  100335. }
  100336. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100337. {
  100338. FLAC__uint32 x;
  100339. unsigned i, skip;
  100340. /* skip the version and flags bytes */
  100341. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100342. return false; /* read_callback_ sets the state for us */
  100343. /* get the size (in bytes) to skip */
  100344. skip = 0;
  100345. for(i = 0; i < 4; i++) {
  100346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100347. return false; /* read_callback_ sets the state for us */
  100348. skip <<= 7;
  100349. skip |= (x & 0x7f);
  100350. }
  100351. /* skip the rest of the tag */
  100352. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100353. return false; /* read_callback_ sets the state for us */
  100354. return true;
  100355. }
  100356. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100357. {
  100358. FLAC__uint32 x;
  100359. FLAC__bool first = true;
  100360. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100361. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100362. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100363. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100364. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100365. return true;
  100366. }
  100367. }
  100368. /* make sure we're byte aligned */
  100369. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100370. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100371. return false; /* read_callback_ sets the state for us */
  100372. }
  100373. while(1) {
  100374. if(decoder->private_->cached) {
  100375. x = (FLAC__uint32)decoder->private_->lookahead;
  100376. decoder->private_->cached = false;
  100377. }
  100378. else {
  100379. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100380. return false; /* read_callback_ sets the state for us */
  100381. }
  100382. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100383. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100384. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100385. return false; /* read_callback_ sets the state for us */
  100386. /* 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 */
  100387. /* else we have to check if the second byte is the end of a sync code */
  100388. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100389. decoder->private_->lookahead = (FLAC__byte)x;
  100390. decoder->private_->cached = true;
  100391. }
  100392. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100393. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100394. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100395. return true;
  100396. }
  100397. }
  100398. if(first) {
  100399. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100400. first = false;
  100401. }
  100402. }
  100403. return true;
  100404. }
  100405. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100406. {
  100407. unsigned channel;
  100408. unsigned i;
  100409. FLAC__int32 mid, side;
  100410. unsigned frame_crc; /* the one we calculate from the input stream */
  100411. FLAC__uint32 x;
  100412. *got_a_frame = false;
  100413. /* init the CRC */
  100414. frame_crc = 0;
  100415. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100416. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100417. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100418. if(!read_frame_header_(decoder))
  100419. return false;
  100420. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100421. return true;
  100422. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100423. return false;
  100424. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100425. /*
  100426. * first figure the correct bits-per-sample of the subframe
  100427. */
  100428. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100429. switch(decoder->private_->frame.header.channel_assignment) {
  100430. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100431. /* no adjustment needed */
  100432. break;
  100433. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100434. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100435. if(channel == 1)
  100436. bps++;
  100437. break;
  100438. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100439. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100440. if(channel == 0)
  100441. bps++;
  100442. break;
  100443. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100444. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100445. if(channel == 1)
  100446. bps++;
  100447. break;
  100448. default:
  100449. FLAC__ASSERT(0);
  100450. }
  100451. /*
  100452. * now read it
  100453. */
  100454. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100455. return false;
  100456. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100457. return true;
  100458. }
  100459. if(!read_zero_padding_(decoder))
  100460. return false;
  100461. 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) */
  100462. return true;
  100463. /*
  100464. * Read the frame CRC-16 from the footer and check
  100465. */
  100466. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100467. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100468. return false; /* read_callback_ sets the state for us */
  100469. if(frame_crc == x) {
  100470. if(do_full_decode) {
  100471. /* Undo any special channel coding */
  100472. switch(decoder->private_->frame.header.channel_assignment) {
  100473. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100474. /* do nothing */
  100475. break;
  100476. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100477. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100478. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100479. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100480. break;
  100481. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100482. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100483. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100484. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100485. break;
  100486. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100487. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100488. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100489. #if 1
  100490. mid = decoder->private_->output[0][i];
  100491. side = decoder->private_->output[1][i];
  100492. mid <<= 1;
  100493. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100494. decoder->private_->output[0][i] = (mid + side) >> 1;
  100495. decoder->private_->output[1][i] = (mid - side) >> 1;
  100496. #else
  100497. /* OPT: without 'side' temp variable */
  100498. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100499. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100500. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100501. #endif
  100502. }
  100503. break;
  100504. default:
  100505. FLAC__ASSERT(0);
  100506. break;
  100507. }
  100508. }
  100509. }
  100510. else {
  100511. /* Bad frame, emit error and zero the output signal */
  100512. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100513. if(do_full_decode) {
  100514. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100515. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100516. }
  100517. }
  100518. }
  100519. *got_a_frame = true;
  100520. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100521. if(decoder->private_->next_fixed_block_size)
  100522. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100523. /* put the latest values into the public section of the decoder instance */
  100524. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100525. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100526. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100527. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100528. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100529. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100530. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100531. /* write it */
  100532. if(do_full_decode) {
  100533. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100534. return false;
  100535. }
  100536. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100537. return true;
  100538. }
  100539. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100540. {
  100541. FLAC__uint32 x;
  100542. FLAC__uint64 xx;
  100543. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100544. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100545. unsigned raw_header_len;
  100546. FLAC__bool is_unparseable = false;
  100547. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100548. /* init the raw header with the saved bits from synchronization */
  100549. raw_header[0] = decoder->private_->header_warmup[0];
  100550. raw_header[1] = decoder->private_->header_warmup[1];
  100551. raw_header_len = 2;
  100552. /* check to make sure that reserved bit is 0 */
  100553. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100554. is_unparseable = true;
  100555. /*
  100556. * Note that along the way as we read the header, we look for a sync
  100557. * code inside. If we find one it would indicate that our original
  100558. * sync was bad since there cannot be a sync code in a valid header.
  100559. *
  100560. * Three kinds of things can go wrong when reading the frame header:
  100561. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100562. * If we don't find a sync code, it can end up looking like we read
  100563. * a valid but unparseable header, until getting to the frame header
  100564. * CRC. Even then we could get a false positive on the CRC.
  100565. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100566. * future encoder).
  100567. * 3) We may be on a damaged frame which appears valid but unparseable.
  100568. *
  100569. * For all these reasons, we try and read a complete frame header as
  100570. * long as it seems valid, even if unparseable, up until the frame
  100571. * header CRC.
  100572. */
  100573. /*
  100574. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100575. */
  100576. for(i = 0; i < 2; i++) {
  100577. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100578. return false; /* read_callback_ sets the state for us */
  100579. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100580. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100581. decoder->private_->lookahead = (FLAC__byte)x;
  100582. decoder->private_->cached = true;
  100583. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100584. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100585. return true;
  100586. }
  100587. raw_header[raw_header_len++] = (FLAC__byte)x;
  100588. }
  100589. switch(x = raw_header[2] >> 4) {
  100590. case 0:
  100591. is_unparseable = true;
  100592. break;
  100593. case 1:
  100594. decoder->private_->frame.header.blocksize = 192;
  100595. break;
  100596. case 2:
  100597. case 3:
  100598. case 4:
  100599. case 5:
  100600. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100601. break;
  100602. case 6:
  100603. case 7:
  100604. blocksize_hint = x;
  100605. break;
  100606. case 8:
  100607. case 9:
  100608. case 10:
  100609. case 11:
  100610. case 12:
  100611. case 13:
  100612. case 14:
  100613. case 15:
  100614. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100615. break;
  100616. default:
  100617. FLAC__ASSERT(0);
  100618. break;
  100619. }
  100620. switch(x = raw_header[2] & 0x0f) {
  100621. case 0:
  100622. if(decoder->private_->has_stream_info)
  100623. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100624. else
  100625. is_unparseable = true;
  100626. break;
  100627. case 1:
  100628. decoder->private_->frame.header.sample_rate = 88200;
  100629. break;
  100630. case 2:
  100631. decoder->private_->frame.header.sample_rate = 176400;
  100632. break;
  100633. case 3:
  100634. decoder->private_->frame.header.sample_rate = 192000;
  100635. break;
  100636. case 4:
  100637. decoder->private_->frame.header.sample_rate = 8000;
  100638. break;
  100639. case 5:
  100640. decoder->private_->frame.header.sample_rate = 16000;
  100641. break;
  100642. case 6:
  100643. decoder->private_->frame.header.sample_rate = 22050;
  100644. break;
  100645. case 7:
  100646. decoder->private_->frame.header.sample_rate = 24000;
  100647. break;
  100648. case 8:
  100649. decoder->private_->frame.header.sample_rate = 32000;
  100650. break;
  100651. case 9:
  100652. decoder->private_->frame.header.sample_rate = 44100;
  100653. break;
  100654. case 10:
  100655. decoder->private_->frame.header.sample_rate = 48000;
  100656. break;
  100657. case 11:
  100658. decoder->private_->frame.header.sample_rate = 96000;
  100659. break;
  100660. case 12:
  100661. case 13:
  100662. case 14:
  100663. sample_rate_hint = x;
  100664. break;
  100665. case 15:
  100666. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100667. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100668. return true;
  100669. default:
  100670. FLAC__ASSERT(0);
  100671. }
  100672. x = (unsigned)(raw_header[3] >> 4);
  100673. if(x & 8) {
  100674. decoder->private_->frame.header.channels = 2;
  100675. switch(x & 7) {
  100676. case 0:
  100677. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100678. break;
  100679. case 1:
  100680. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100681. break;
  100682. case 2:
  100683. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100684. break;
  100685. default:
  100686. is_unparseable = true;
  100687. break;
  100688. }
  100689. }
  100690. else {
  100691. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100692. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100693. }
  100694. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100695. case 0:
  100696. if(decoder->private_->has_stream_info)
  100697. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100698. else
  100699. is_unparseable = true;
  100700. break;
  100701. case 1:
  100702. decoder->private_->frame.header.bits_per_sample = 8;
  100703. break;
  100704. case 2:
  100705. decoder->private_->frame.header.bits_per_sample = 12;
  100706. break;
  100707. case 4:
  100708. decoder->private_->frame.header.bits_per_sample = 16;
  100709. break;
  100710. case 5:
  100711. decoder->private_->frame.header.bits_per_sample = 20;
  100712. break;
  100713. case 6:
  100714. decoder->private_->frame.header.bits_per_sample = 24;
  100715. break;
  100716. case 3:
  100717. case 7:
  100718. is_unparseable = true;
  100719. break;
  100720. default:
  100721. FLAC__ASSERT(0);
  100722. break;
  100723. }
  100724. /* check to make sure that reserved bit is 0 */
  100725. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100726. is_unparseable = true;
  100727. /* read the frame's starting sample number (or frame number as the case may be) */
  100728. if(
  100729. raw_header[1] & 0x01 ||
  100730. /*@@@ 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 */
  100731. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100732. ) { /* variable blocksize */
  100733. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100734. return false; /* read_callback_ sets the state for us */
  100735. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100736. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100737. decoder->private_->cached = true;
  100738. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100739. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100740. return true;
  100741. }
  100742. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100743. decoder->private_->frame.header.number.sample_number = xx;
  100744. }
  100745. else { /* fixed blocksize */
  100746. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100747. return false; /* read_callback_ sets the state for us */
  100748. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100749. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100750. decoder->private_->cached = true;
  100751. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100752. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100753. return true;
  100754. }
  100755. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100756. decoder->private_->frame.header.number.frame_number = x;
  100757. }
  100758. if(blocksize_hint) {
  100759. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100760. return false; /* read_callback_ sets the state for us */
  100761. raw_header[raw_header_len++] = (FLAC__byte)x;
  100762. if(blocksize_hint == 7) {
  100763. FLAC__uint32 _x;
  100764. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100765. return false; /* read_callback_ sets the state for us */
  100766. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100767. x = (x << 8) | _x;
  100768. }
  100769. decoder->private_->frame.header.blocksize = x+1;
  100770. }
  100771. if(sample_rate_hint) {
  100772. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100773. return false; /* read_callback_ sets the state for us */
  100774. raw_header[raw_header_len++] = (FLAC__byte)x;
  100775. if(sample_rate_hint != 12) {
  100776. FLAC__uint32 _x;
  100777. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100778. return false; /* read_callback_ sets the state for us */
  100779. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100780. x = (x << 8) | _x;
  100781. }
  100782. if(sample_rate_hint == 12)
  100783. decoder->private_->frame.header.sample_rate = x*1000;
  100784. else if(sample_rate_hint == 13)
  100785. decoder->private_->frame.header.sample_rate = x;
  100786. else
  100787. decoder->private_->frame.header.sample_rate = x*10;
  100788. }
  100789. /* read the CRC-8 byte */
  100790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100791. return false; /* read_callback_ sets the state for us */
  100792. crc8 = (FLAC__byte)x;
  100793. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100794. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100795. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100796. return true;
  100797. }
  100798. /* calculate the sample number from the frame number if needed */
  100799. decoder->private_->next_fixed_block_size = 0;
  100800. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100801. x = decoder->private_->frame.header.number.frame_number;
  100802. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100803. if(decoder->private_->fixed_block_size)
  100804. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100805. else if(decoder->private_->has_stream_info) {
  100806. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100807. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100808. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100809. }
  100810. else
  100811. is_unparseable = true;
  100812. }
  100813. else if(x == 0) {
  100814. decoder->private_->frame.header.number.sample_number = 0;
  100815. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100816. }
  100817. else {
  100818. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100819. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100820. }
  100821. }
  100822. if(is_unparseable) {
  100823. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100824. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100825. return true;
  100826. }
  100827. return true;
  100828. }
  100829. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100830. {
  100831. FLAC__uint32 x;
  100832. FLAC__bool wasted_bits;
  100833. unsigned i;
  100834. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100835. return false; /* read_callback_ sets the state for us */
  100836. wasted_bits = (x & 1);
  100837. x &= 0xfe;
  100838. if(wasted_bits) {
  100839. unsigned u;
  100840. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100841. return false; /* read_callback_ sets the state for us */
  100842. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100843. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100844. }
  100845. else
  100846. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100847. /*
  100848. * Lots of magic numbers here
  100849. */
  100850. if(x & 0x80) {
  100851. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100852. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100853. return true;
  100854. }
  100855. else if(x == 0) {
  100856. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100857. return false;
  100858. }
  100859. else if(x == 2) {
  100860. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100861. return false;
  100862. }
  100863. else if(x < 16) {
  100864. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100865. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100866. return true;
  100867. }
  100868. else if(x <= 24) {
  100869. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100870. return false;
  100871. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100872. return true;
  100873. }
  100874. else if(x < 64) {
  100875. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100876. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100877. return true;
  100878. }
  100879. else {
  100880. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100881. return false;
  100882. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100883. return true;
  100884. }
  100885. if(wasted_bits && do_full_decode) {
  100886. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100887. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100888. decoder->private_->output[channel][i] <<= x;
  100889. }
  100890. return true;
  100891. }
  100892. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100893. {
  100894. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100895. FLAC__int32 x;
  100896. unsigned i;
  100897. FLAC__int32 *output = decoder->private_->output[channel];
  100898. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100899. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100900. return false; /* read_callback_ sets the state for us */
  100901. subframe->value = x;
  100902. /* decode the subframe */
  100903. if(do_full_decode) {
  100904. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100905. output[i] = x;
  100906. }
  100907. return true;
  100908. }
  100909. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100910. {
  100911. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100912. FLAC__int32 i32;
  100913. FLAC__uint32 u32;
  100914. unsigned u;
  100915. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100916. subframe->residual = decoder->private_->residual[channel];
  100917. subframe->order = order;
  100918. /* read warm-up samples */
  100919. for(u = 0; u < order; u++) {
  100920. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100921. return false; /* read_callback_ sets the state for us */
  100922. subframe->warmup[u] = i32;
  100923. }
  100924. /* read entropy coding method info */
  100925. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100926. return false; /* read_callback_ sets the state for us */
  100927. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100928. switch(subframe->entropy_coding_method.type) {
  100929. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100930. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100931. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100932. return false; /* read_callback_ sets the state for us */
  100933. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100934. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100935. break;
  100936. default:
  100937. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100938. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100939. return true;
  100940. }
  100941. /* read residual */
  100942. switch(subframe->entropy_coding_method.type) {
  100943. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100944. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100945. 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))
  100946. return false;
  100947. break;
  100948. default:
  100949. FLAC__ASSERT(0);
  100950. }
  100951. /* decode the subframe */
  100952. if(do_full_decode) {
  100953. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100954. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100955. }
  100956. return true;
  100957. }
  100958. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100959. {
  100960. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100961. FLAC__int32 i32;
  100962. FLAC__uint32 u32;
  100963. unsigned u;
  100964. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100965. subframe->residual = decoder->private_->residual[channel];
  100966. subframe->order = order;
  100967. /* read warm-up samples */
  100968. for(u = 0; u < order; u++) {
  100969. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100970. return false; /* read_callback_ sets the state for us */
  100971. subframe->warmup[u] = i32;
  100972. }
  100973. /* read qlp coeff precision */
  100974. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100975. return false; /* read_callback_ sets the state for us */
  100976. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100977. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100978. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100979. return true;
  100980. }
  100981. subframe->qlp_coeff_precision = u32+1;
  100982. /* read qlp shift */
  100983. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100984. return false; /* read_callback_ sets the state for us */
  100985. subframe->quantization_level = i32;
  100986. /* read quantized lp coefficiencts */
  100987. for(u = 0; u < order; u++) {
  100988. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100989. return false; /* read_callback_ sets the state for us */
  100990. subframe->qlp_coeff[u] = i32;
  100991. }
  100992. /* read entropy coding method info */
  100993. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100994. return false; /* read_callback_ sets the state for us */
  100995. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100996. switch(subframe->entropy_coding_method.type) {
  100997. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100998. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100999. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101000. return false; /* read_callback_ sets the state for us */
  101001. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101002. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101003. break;
  101004. default:
  101005. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101006. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101007. return true;
  101008. }
  101009. /* read residual */
  101010. switch(subframe->entropy_coding_method.type) {
  101011. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101012. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101013. 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))
  101014. return false;
  101015. break;
  101016. default:
  101017. FLAC__ASSERT(0);
  101018. }
  101019. /* decode the subframe */
  101020. if(do_full_decode) {
  101021. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101022. /*@@@@@@ technically not pessimistic enough, should be more like
  101023. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101024. */
  101025. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101026. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101027. if(order <= 8)
  101028. 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);
  101029. else
  101030. 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);
  101031. }
  101032. else
  101033. 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);
  101034. else
  101035. 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);
  101036. }
  101037. return true;
  101038. }
  101039. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101040. {
  101041. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101042. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101043. unsigned i;
  101044. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101045. subframe->data = residual;
  101046. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101047. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101048. return false; /* read_callback_ sets the state for us */
  101049. residual[i] = x;
  101050. }
  101051. /* decode the subframe */
  101052. if(do_full_decode)
  101053. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101054. return true;
  101055. }
  101056. 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)
  101057. {
  101058. FLAC__uint32 rice_parameter;
  101059. int i;
  101060. unsigned partition, sample, u;
  101061. const unsigned partitions = 1u << partition_order;
  101062. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101063. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101064. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101065. /* sanity checks */
  101066. if(partition_order == 0) {
  101067. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101068. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101069. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101070. return true;
  101071. }
  101072. }
  101073. else {
  101074. if(partition_samples < predictor_order) {
  101075. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101076. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101077. return true;
  101078. }
  101079. }
  101080. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101081. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101082. return false;
  101083. }
  101084. sample = 0;
  101085. for(partition = 0; partition < partitions; partition++) {
  101086. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101087. return false; /* read_callback_ sets the state for us */
  101088. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101089. if(rice_parameter < pesc) {
  101090. partitioned_rice_contents->raw_bits[partition] = 0;
  101091. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101092. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101093. return false; /* read_callback_ sets the state for us */
  101094. sample += u;
  101095. }
  101096. else {
  101097. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101098. return false; /* read_callback_ sets the state for us */
  101099. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101100. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101101. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101102. return false; /* read_callback_ sets the state for us */
  101103. residual[sample] = i;
  101104. }
  101105. }
  101106. }
  101107. return true;
  101108. }
  101109. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101110. {
  101111. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101112. FLAC__uint32 zero = 0;
  101113. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101114. return false; /* read_callback_ sets the state for us */
  101115. if(zero != 0) {
  101116. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101117. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101118. }
  101119. }
  101120. return true;
  101121. }
  101122. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101123. {
  101124. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101125. if(
  101126. #if FLAC__HAS_OGG
  101127. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101128. !decoder->private_->is_ogg &&
  101129. #endif
  101130. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101131. ) {
  101132. *bytes = 0;
  101133. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101134. return false;
  101135. }
  101136. else if(*bytes > 0) {
  101137. /* While seeking, it is possible for our seek to land in the
  101138. * middle of audio data that looks exactly like a frame header
  101139. * from a future version of an encoder. When that happens, our
  101140. * error callback will get an
  101141. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101142. * unparseable_frame_count. But there is a remote possibility
  101143. * that it is properly synced at such a "future-codec frame",
  101144. * so to make sure, we wait to see many "unparseable" errors in
  101145. * a row before bailing out.
  101146. */
  101147. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101148. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101149. return false;
  101150. }
  101151. else {
  101152. const FLAC__StreamDecoderReadStatus status =
  101153. #if FLAC__HAS_OGG
  101154. decoder->private_->is_ogg?
  101155. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101156. #endif
  101157. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101158. ;
  101159. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101160. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101161. return false;
  101162. }
  101163. else if(*bytes == 0) {
  101164. if(
  101165. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101166. (
  101167. #if FLAC__HAS_OGG
  101168. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101169. !decoder->private_->is_ogg &&
  101170. #endif
  101171. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101172. )
  101173. ) {
  101174. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101175. return false;
  101176. }
  101177. else
  101178. return true;
  101179. }
  101180. else
  101181. return true;
  101182. }
  101183. }
  101184. else {
  101185. /* abort to avoid a deadlock */
  101186. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101187. return false;
  101188. }
  101189. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101190. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101191. * and at the same time hit the end of the stream (for example, seeking
  101192. * to a point that is after the beginning of the last Ogg page). There
  101193. * is no way to report an Ogg sync loss through the callbacks (see note
  101194. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101195. * So to keep the decoder from stopping at this point we gate the call
  101196. * to the eof_callback and let the Ogg decoder aspect set the
  101197. * end-of-stream state when it is needed.
  101198. */
  101199. }
  101200. #if FLAC__HAS_OGG
  101201. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101202. {
  101203. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101204. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101205. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101206. /* we don't really have a way to handle lost sync via read
  101207. * callback so we'll let it pass and let the underlying
  101208. * FLAC decoder catch the error
  101209. */
  101210. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101211. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101212. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101213. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101214. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101215. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101216. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101217. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101218. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101219. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101220. default:
  101221. FLAC__ASSERT(0);
  101222. /* double protection */
  101223. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101224. }
  101225. }
  101226. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101227. {
  101228. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101229. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101230. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101231. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101232. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101233. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101234. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101235. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101236. default:
  101237. /* double protection: */
  101238. FLAC__ASSERT(0);
  101239. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101240. }
  101241. }
  101242. #endif
  101243. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101244. {
  101245. if(decoder->private_->is_seeking) {
  101246. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101247. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101248. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101249. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101250. #if FLAC__HAS_OGG
  101251. decoder->private_->got_a_frame = true;
  101252. #endif
  101253. decoder->private_->last_frame = *frame; /* save the frame */
  101254. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101255. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101256. /* kick out of seek mode */
  101257. decoder->private_->is_seeking = false;
  101258. /* shift out the samples before target_sample */
  101259. if(delta > 0) {
  101260. unsigned channel;
  101261. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101262. for(channel = 0; channel < frame->header.channels; channel++)
  101263. newbuffer[channel] = buffer[channel] + delta;
  101264. decoder->private_->last_frame.header.blocksize -= delta;
  101265. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101266. /* write the relevant samples */
  101267. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101268. }
  101269. else {
  101270. /* write the relevant samples */
  101271. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101272. }
  101273. }
  101274. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101275. }
  101276. /*
  101277. * If we never got STREAMINFO, turn off MD5 checking to save
  101278. * cycles since we don't have a sum to compare to anyway
  101279. */
  101280. if(!decoder->private_->has_stream_info)
  101281. decoder->private_->do_md5_checking = false;
  101282. if(decoder->private_->do_md5_checking) {
  101283. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101284. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101285. }
  101286. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101287. }
  101288. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101289. {
  101290. if(!decoder->private_->is_seeking)
  101291. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101292. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101293. decoder->private_->unparseable_frame_count++;
  101294. }
  101295. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101296. {
  101297. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101298. FLAC__int64 pos = -1;
  101299. int i;
  101300. unsigned approx_bytes_per_frame;
  101301. FLAC__bool first_seek = true;
  101302. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101303. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101304. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101305. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101306. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101307. /* take these from the current frame in case they've changed mid-stream */
  101308. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101309. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101310. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101311. /* use values from stream info if we didn't decode a frame */
  101312. if(channels == 0)
  101313. channels = decoder->private_->stream_info.data.stream_info.channels;
  101314. if(bps == 0)
  101315. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101316. /* we are just guessing here */
  101317. if(max_framesize > 0)
  101318. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101319. /*
  101320. * Check if it's a known fixed-blocksize stream. Note that though
  101321. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101322. * never get a STREAMINFO block when decoding so the value of
  101323. * min_blocksize might be zero.
  101324. */
  101325. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101326. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101327. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101328. }
  101329. else
  101330. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101331. /*
  101332. * First, we set an upper and lower bound on where in the
  101333. * stream we will search. For now we assume the worst case
  101334. * scenario, which is our best guess at the beginning of
  101335. * the first frame and end of the stream.
  101336. */
  101337. lower_bound = first_frame_offset;
  101338. lower_bound_sample = 0;
  101339. upper_bound = stream_length;
  101340. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101341. /*
  101342. * Now we refine the bounds if we have a seektable with
  101343. * suitable points. Note that according to the spec they
  101344. * must be ordered by ascending sample number.
  101345. *
  101346. * Note: to protect against invalid seek tables we will ignore points
  101347. * that have frame_samples==0 or sample_number>=total_samples
  101348. */
  101349. if(seek_table) {
  101350. FLAC__uint64 new_lower_bound = lower_bound;
  101351. FLAC__uint64 new_upper_bound = upper_bound;
  101352. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101353. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101354. /* find the closest seek point <= target_sample, if it exists */
  101355. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101356. if(
  101357. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101358. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101359. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101360. seek_table->points[i].sample_number <= target_sample
  101361. )
  101362. break;
  101363. }
  101364. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101365. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101366. new_lower_bound_sample = seek_table->points[i].sample_number;
  101367. }
  101368. /* find the closest seek point > target_sample, if it exists */
  101369. for(i = 0; i < (int)seek_table->num_points; i++) {
  101370. if(
  101371. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101372. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101373. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101374. seek_table->points[i].sample_number > target_sample
  101375. )
  101376. break;
  101377. }
  101378. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101379. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101380. new_upper_bound_sample = seek_table->points[i].sample_number;
  101381. }
  101382. /* final protection against unsorted seek tables; keep original values if bogus */
  101383. if(new_upper_bound >= new_lower_bound) {
  101384. lower_bound = new_lower_bound;
  101385. upper_bound = new_upper_bound;
  101386. lower_bound_sample = new_lower_bound_sample;
  101387. upper_bound_sample = new_upper_bound_sample;
  101388. }
  101389. }
  101390. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101391. /* there are 2 insidious ways that the following equality occurs, which
  101392. * we need to fix:
  101393. * 1) total_samples is 0 (unknown) and target_sample is 0
  101394. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101395. * exactly equal to the last seek point in the seek table; this
  101396. * means there is no seek point above it, and upper_bound_samples
  101397. * remains equal to the estimate (of target_samples) we made above
  101398. * in either case it does not hurt to move upper_bound_sample up by 1
  101399. */
  101400. if(upper_bound_sample == lower_bound_sample)
  101401. upper_bound_sample++;
  101402. decoder->private_->target_sample = target_sample;
  101403. while(1) {
  101404. /* check if the bounds are still ok */
  101405. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101406. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101407. return false;
  101408. }
  101409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101410. #if defined _MSC_VER || defined __MINGW32__
  101411. /* with VC++ you have to spoon feed it the casting */
  101412. 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;
  101413. #else
  101414. 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;
  101415. #endif
  101416. #else
  101417. /* a little less accurate: */
  101418. if(upper_bound - lower_bound < 0xffffffff)
  101419. 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;
  101420. else /* @@@ WATCHOUT, ~2TB limit */
  101421. 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;
  101422. #endif
  101423. if(pos >= (FLAC__int64)upper_bound)
  101424. pos = (FLAC__int64)upper_bound - 1;
  101425. if(pos < (FLAC__int64)lower_bound)
  101426. pos = (FLAC__int64)lower_bound;
  101427. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101428. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101429. return false;
  101430. }
  101431. if(!FLAC__stream_decoder_flush(decoder)) {
  101432. /* above call sets the state for us */
  101433. return false;
  101434. }
  101435. /* Now we need to get a frame. First we need to reset our
  101436. * unparseable_frame_count; if we get too many unparseable
  101437. * frames in a row, the read callback will return
  101438. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101439. * FLAC__stream_decoder_process_single() to return false.
  101440. */
  101441. decoder->private_->unparseable_frame_count = 0;
  101442. if(!FLAC__stream_decoder_process_single(decoder)) {
  101443. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101444. return false;
  101445. }
  101446. /* our write callback will change the state when it gets to the target frame */
  101447. /* 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 */
  101448. #if 0
  101449. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101450. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101451. break;
  101452. #endif
  101453. if(!decoder->private_->is_seeking)
  101454. break;
  101455. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101456. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101457. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101458. if (pos == (FLAC__int64)lower_bound) {
  101459. /* can't move back any more than the first frame, something is fatally wrong */
  101460. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101461. return false;
  101462. }
  101463. /* our last move backwards wasn't big enough, try again */
  101464. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101465. continue;
  101466. }
  101467. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101468. first_seek = false;
  101469. /* make sure we are not seeking in corrupted stream */
  101470. if (this_frame_sample < lower_bound_sample) {
  101471. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101472. return false;
  101473. }
  101474. /* we need to narrow the search */
  101475. if(target_sample < this_frame_sample) {
  101476. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101477. /*@@@@@@ what will decode position be if at end of stream? */
  101478. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101479. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101480. return false;
  101481. }
  101482. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101483. }
  101484. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101485. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101486. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101487. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101488. return false;
  101489. }
  101490. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101491. }
  101492. }
  101493. return true;
  101494. }
  101495. #if FLAC__HAS_OGG
  101496. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101497. {
  101498. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101499. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101500. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101501. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101502. FLAC__bool did_a_seek;
  101503. unsigned iteration = 0;
  101504. /* In the first iterations, we will calculate the target byte position
  101505. * by the distance from the target sample to left_sample and
  101506. * right_sample (let's call it "proportional search"). After that, we
  101507. * will switch to binary search.
  101508. */
  101509. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101510. /* We will switch to a linear search once our current sample is less
  101511. * than this number of samples ahead of the target sample
  101512. */
  101513. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101514. /* If the total number of samples is unknown, use a large value, and
  101515. * force binary search immediately.
  101516. */
  101517. if(right_sample == 0) {
  101518. right_sample = (FLAC__uint64)(-1);
  101519. BINARY_SEARCH_AFTER_ITERATION = 0;
  101520. }
  101521. decoder->private_->target_sample = target_sample;
  101522. for( ; ; iteration++) {
  101523. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101524. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101525. pos = (right_pos + left_pos) / 2;
  101526. }
  101527. else {
  101528. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101529. #if defined _MSC_VER || defined __MINGW32__
  101530. /* with MSVC you have to spoon feed it the casting */
  101531. 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));
  101532. #else
  101533. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101534. #endif
  101535. #else
  101536. /* a little less accurate: */
  101537. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101538. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101539. else /* @@@ WATCHOUT, ~2TB limit */
  101540. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101541. #endif
  101542. /* @@@ TODO: might want to limit pos to some distance
  101543. * before EOF, to make sure we land before the last frame,
  101544. * thereby getting a this_frame_sample and so having a better
  101545. * estimate.
  101546. */
  101547. }
  101548. /* physical seek */
  101549. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101550. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101551. return false;
  101552. }
  101553. if(!FLAC__stream_decoder_flush(decoder)) {
  101554. /* above call sets the state for us */
  101555. return false;
  101556. }
  101557. did_a_seek = true;
  101558. }
  101559. else
  101560. did_a_seek = false;
  101561. decoder->private_->got_a_frame = false;
  101562. if(!FLAC__stream_decoder_process_single(decoder)) {
  101563. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101564. return false;
  101565. }
  101566. if(!decoder->private_->got_a_frame) {
  101567. if(did_a_seek) {
  101568. /* this can happen if we seek to a point after the last frame; we drop
  101569. * to binary search right away in this case to avoid any wasted
  101570. * iterations of proportional search.
  101571. */
  101572. right_pos = pos;
  101573. BINARY_SEARCH_AFTER_ITERATION = 0;
  101574. }
  101575. else {
  101576. /* this can probably only happen if total_samples is unknown and the
  101577. * target_sample is past the end of the stream
  101578. */
  101579. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101580. return false;
  101581. }
  101582. }
  101583. /* our write callback will change the state when it gets to the target frame */
  101584. else if(!decoder->private_->is_seeking) {
  101585. break;
  101586. }
  101587. else {
  101588. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101589. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101590. if (did_a_seek) {
  101591. if (this_frame_sample <= target_sample) {
  101592. /* The 'equal' case should not happen, since
  101593. * FLAC__stream_decoder_process_single()
  101594. * should recognize that it has hit the
  101595. * target sample and we would exit through
  101596. * the 'break' above.
  101597. */
  101598. FLAC__ASSERT(this_frame_sample != target_sample);
  101599. left_sample = this_frame_sample;
  101600. /* sanity check to avoid infinite loop */
  101601. if (left_pos == pos) {
  101602. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101603. return false;
  101604. }
  101605. left_pos = pos;
  101606. }
  101607. else if(this_frame_sample > target_sample) {
  101608. right_sample = this_frame_sample;
  101609. /* sanity check to avoid infinite loop */
  101610. if (right_pos == pos) {
  101611. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101612. return false;
  101613. }
  101614. right_pos = pos;
  101615. }
  101616. }
  101617. }
  101618. }
  101619. return true;
  101620. }
  101621. #endif
  101622. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101623. {
  101624. (void)client_data;
  101625. if(*bytes > 0) {
  101626. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101627. if(ferror(decoder->private_->file))
  101628. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101629. else if(*bytes == 0)
  101630. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101631. else
  101632. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101633. }
  101634. else
  101635. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101636. }
  101637. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101638. {
  101639. (void)client_data;
  101640. if(decoder->private_->file == stdin)
  101641. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101642. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101643. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101644. else
  101645. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101646. }
  101647. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101648. {
  101649. off_t pos;
  101650. (void)client_data;
  101651. if(decoder->private_->file == stdin)
  101652. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101653. else if((pos = ftello(decoder->private_->file)) < 0)
  101654. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101655. else {
  101656. *absolute_byte_offset = (FLAC__uint64)pos;
  101657. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101658. }
  101659. }
  101660. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101661. {
  101662. struct stat filestats;
  101663. (void)client_data;
  101664. if(decoder->private_->file == stdin)
  101665. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101666. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101667. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101668. else {
  101669. *stream_length = (FLAC__uint64)filestats.st_size;
  101670. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101671. }
  101672. }
  101673. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101674. {
  101675. (void)client_data;
  101676. return feof(decoder->private_->file)? true : false;
  101677. }
  101678. #endif
  101679. /*** End of inlined file: stream_decoder.c ***/
  101680. /*** Start of inlined file: stream_encoder.c ***/
  101681. /*** Start of inlined file: juce_FlacHeader.h ***/
  101682. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101683. // tasks..
  101684. #define VERSION "1.2.1"
  101685. #define FLAC__NO_DLL 1
  101686. #if JUCE_MSVC
  101687. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101688. #endif
  101689. #if JUCE_MAC
  101690. #define FLAC__SYS_DARWIN 1
  101691. #endif
  101692. /*** End of inlined file: juce_FlacHeader.h ***/
  101693. #if JUCE_USE_FLAC
  101694. #if HAVE_CONFIG_H
  101695. # include <config.h>
  101696. #endif
  101697. #if defined _MSC_VER || defined __MINGW32__
  101698. #include <io.h> /* for _setmode() */
  101699. #include <fcntl.h> /* for _O_BINARY */
  101700. #endif
  101701. #if defined __CYGWIN__ || defined __EMX__
  101702. #include <io.h> /* for setmode(), O_BINARY */
  101703. #include <fcntl.h> /* for _O_BINARY */
  101704. #endif
  101705. #include <limits.h>
  101706. #include <stdio.h>
  101707. #include <stdlib.h> /* for malloc() */
  101708. #include <string.h> /* for memcpy() */
  101709. #include <sys/types.h> /* for off_t */
  101710. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101711. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101712. #define fseeko fseek
  101713. #define ftello ftell
  101714. #endif
  101715. #endif
  101716. /*** Start of inlined file: stream_encoder.h ***/
  101717. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101718. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101719. #if FLAC__HAS_OGG
  101720. #include "private/ogg_encoder_aspect.h"
  101721. #endif
  101722. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101723. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101724. typedef enum {
  101725. FLAC__APODIZATION_BARTLETT,
  101726. FLAC__APODIZATION_BARTLETT_HANN,
  101727. FLAC__APODIZATION_BLACKMAN,
  101728. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101729. FLAC__APODIZATION_CONNES,
  101730. FLAC__APODIZATION_FLATTOP,
  101731. FLAC__APODIZATION_GAUSS,
  101732. FLAC__APODIZATION_HAMMING,
  101733. FLAC__APODIZATION_HANN,
  101734. FLAC__APODIZATION_KAISER_BESSEL,
  101735. FLAC__APODIZATION_NUTTALL,
  101736. FLAC__APODIZATION_RECTANGLE,
  101737. FLAC__APODIZATION_TRIANGLE,
  101738. FLAC__APODIZATION_TUKEY,
  101739. FLAC__APODIZATION_WELCH
  101740. } FLAC__ApodizationFunction;
  101741. typedef struct {
  101742. FLAC__ApodizationFunction type;
  101743. union {
  101744. struct {
  101745. FLAC__real stddev;
  101746. } gauss;
  101747. struct {
  101748. FLAC__real p;
  101749. } tukey;
  101750. } parameters;
  101751. } FLAC__ApodizationSpecification;
  101752. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101753. typedef struct FLAC__StreamEncoderProtected {
  101754. FLAC__StreamEncoderState state;
  101755. FLAC__bool verify;
  101756. FLAC__bool streamable_subset;
  101757. FLAC__bool do_md5;
  101758. FLAC__bool do_mid_side_stereo;
  101759. FLAC__bool loose_mid_side_stereo;
  101760. unsigned channels;
  101761. unsigned bits_per_sample;
  101762. unsigned sample_rate;
  101763. unsigned blocksize;
  101764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101765. unsigned num_apodizations;
  101766. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101767. #endif
  101768. unsigned max_lpc_order;
  101769. unsigned qlp_coeff_precision;
  101770. FLAC__bool do_qlp_coeff_prec_search;
  101771. FLAC__bool do_exhaustive_model_search;
  101772. FLAC__bool do_escape_coding;
  101773. unsigned min_residual_partition_order;
  101774. unsigned max_residual_partition_order;
  101775. unsigned rice_parameter_search_dist;
  101776. FLAC__uint64 total_samples_estimate;
  101777. FLAC__StreamMetadata **metadata;
  101778. unsigned num_metadata_blocks;
  101779. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101780. #if FLAC__HAS_OGG
  101781. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101782. #endif
  101783. } FLAC__StreamEncoderProtected;
  101784. #endif
  101785. /*** End of inlined file: stream_encoder.h ***/
  101786. #if FLAC__HAS_OGG
  101787. #include "include/private/ogg_helper.h"
  101788. #include "include/private/ogg_mapping.h"
  101789. #endif
  101790. /*** Start of inlined file: stream_encoder_framing.h ***/
  101791. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101792. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101793. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101794. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101795. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101796. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101797. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101798. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101799. #endif
  101800. /*** End of inlined file: stream_encoder_framing.h ***/
  101801. /*** Start of inlined file: window.h ***/
  101802. #ifndef FLAC__PRIVATE__WINDOW_H
  101803. #define FLAC__PRIVATE__WINDOW_H
  101804. #ifdef HAVE_CONFIG_H
  101805. #include <config.h>
  101806. #endif
  101807. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101808. /*
  101809. * FLAC__window_*()
  101810. * --------------------------------------------------------------------
  101811. * Calculates window coefficients according to different apodization
  101812. * functions.
  101813. *
  101814. * OUT window[0,L-1]
  101815. * IN L (number of points in window)
  101816. */
  101817. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101818. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101819. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101820. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101821. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101822. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101823. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101824. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101825. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101826. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101827. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101828. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101829. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101830. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101831. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101832. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101833. #endif
  101834. /*** End of inlined file: window.h ***/
  101835. #ifndef FLaC__INLINE
  101836. #define FLaC__INLINE
  101837. #endif
  101838. #ifdef min
  101839. #undef min
  101840. #endif
  101841. #define min(x,y) ((x)<(y)?(x):(y))
  101842. #ifdef max
  101843. #undef max
  101844. #endif
  101845. #define max(x,y) ((x)>(y)?(x):(y))
  101846. /* Exact Rice codeword length calculation is off by default. The simple
  101847. * (and fast) estimation (of how many bits a residual value will be
  101848. * encoded with) in this encoder is very good, almost always yielding
  101849. * compression within 0.1% of exact calculation.
  101850. */
  101851. #undef EXACT_RICE_BITS_CALCULATION
  101852. /* Rice parameter searching is off by default. The simple (and fast)
  101853. * parameter estimation in this encoder is very good, almost always
  101854. * yielding compression within 0.1% of the optimal parameters.
  101855. */
  101856. #undef ENABLE_RICE_PARAMETER_SEARCH
  101857. typedef struct {
  101858. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101859. unsigned size; /* of each data[] in samples */
  101860. unsigned tail;
  101861. } verify_input_fifo;
  101862. typedef struct {
  101863. const FLAC__byte *data;
  101864. unsigned capacity;
  101865. unsigned bytes;
  101866. } verify_output;
  101867. typedef enum {
  101868. ENCODER_IN_MAGIC = 0,
  101869. ENCODER_IN_METADATA = 1,
  101870. ENCODER_IN_AUDIO = 2
  101871. } EncoderStateHint;
  101872. static struct CompressionLevels {
  101873. FLAC__bool do_mid_side_stereo;
  101874. FLAC__bool loose_mid_side_stereo;
  101875. unsigned max_lpc_order;
  101876. unsigned qlp_coeff_precision;
  101877. FLAC__bool do_qlp_coeff_prec_search;
  101878. FLAC__bool do_escape_coding;
  101879. FLAC__bool do_exhaustive_model_search;
  101880. unsigned min_residual_partition_order;
  101881. unsigned max_residual_partition_order;
  101882. unsigned rice_parameter_search_dist;
  101883. } compression_levels_[] = {
  101884. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101885. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101886. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101887. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101888. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101889. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101890. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101891. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101892. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101893. };
  101894. /***********************************************************************
  101895. *
  101896. * Private class method prototypes
  101897. *
  101898. ***********************************************************************/
  101899. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101900. static void free_(FLAC__StreamEncoder *encoder);
  101901. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101902. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101903. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101904. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101905. #if FLAC__HAS_OGG
  101906. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101907. #endif
  101908. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101909. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101910. static FLAC__bool process_subframe_(
  101911. FLAC__StreamEncoder *encoder,
  101912. unsigned min_partition_order,
  101913. unsigned max_partition_order,
  101914. const FLAC__FrameHeader *frame_header,
  101915. unsigned subframe_bps,
  101916. const FLAC__int32 integer_signal[],
  101917. FLAC__Subframe *subframe[2],
  101918. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101919. FLAC__int32 *residual[2],
  101920. unsigned *best_subframe,
  101921. unsigned *best_bits
  101922. );
  101923. static FLAC__bool add_subframe_(
  101924. FLAC__StreamEncoder *encoder,
  101925. unsigned blocksize,
  101926. unsigned subframe_bps,
  101927. const FLAC__Subframe *subframe,
  101928. FLAC__BitWriter *frame
  101929. );
  101930. static unsigned evaluate_constant_subframe_(
  101931. FLAC__StreamEncoder *encoder,
  101932. const FLAC__int32 signal,
  101933. unsigned blocksize,
  101934. unsigned subframe_bps,
  101935. FLAC__Subframe *subframe
  101936. );
  101937. static unsigned evaluate_fixed_subframe_(
  101938. FLAC__StreamEncoder *encoder,
  101939. const FLAC__int32 signal[],
  101940. FLAC__int32 residual[],
  101941. FLAC__uint64 abs_residual_partition_sums[],
  101942. unsigned raw_bits_per_partition[],
  101943. unsigned blocksize,
  101944. unsigned subframe_bps,
  101945. unsigned order,
  101946. unsigned rice_parameter,
  101947. unsigned rice_parameter_limit,
  101948. unsigned min_partition_order,
  101949. unsigned max_partition_order,
  101950. FLAC__bool do_escape_coding,
  101951. unsigned rice_parameter_search_dist,
  101952. FLAC__Subframe *subframe,
  101953. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101954. );
  101955. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101956. static unsigned evaluate_lpc_subframe_(
  101957. FLAC__StreamEncoder *encoder,
  101958. const FLAC__int32 signal[],
  101959. FLAC__int32 residual[],
  101960. FLAC__uint64 abs_residual_partition_sums[],
  101961. unsigned raw_bits_per_partition[],
  101962. const FLAC__real lp_coeff[],
  101963. unsigned blocksize,
  101964. unsigned subframe_bps,
  101965. unsigned order,
  101966. unsigned qlp_coeff_precision,
  101967. unsigned rice_parameter,
  101968. unsigned rice_parameter_limit,
  101969. unsigned min_partition_order,
  101970. unsigned max_partition_order,
  101971. FLAC__bool do_escape_coding,
  101972. unsigned rice_parameter_search_dist,
  101973. FLAC__Subframe *subframe,
  101974. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101975. );
  101976. #endif
  101977. static unsigned evaluate_verbatim_subframe_(
  101978. FLAC__StreamEncoder *encoder,
  101979. const FLAC__int32 signal[],
  101980. unsigned blocksize,
  101981. unsigned subframe_bps,
  101982. FLAC__Subframe *subframe
  101983. );
  101984. static unsigned find_best_partition_order_(
  101985. struct FLAC__StreamEncoderPrivate *private_,
  101986. const FLAC__int32 residual[],
  101987. FLAC__uint64 abs_residual_partition_sums[],
  101988. unsigned raw_bits_per_partition[],
  101989. unsigned residual_samples,
  101990. unsigned predictor_order,
  101991. unsigned rice_parameter,
  101992. unsigned rice_parameter_limit,
  101993. unsigned min_partition_order,
  101994. unsigned max_partition_order,
  101995. unsigned bps,
  101996. FLAC__bool do_escape_coding,
  101997. unsigned rice_parameter_search_dist,
  101998. FLAC__EntropyCodingMethod *best_ecm
  101999. );
  102000. static void precompute_partition_info_sums_(
  102001. const FLAC__int32 residual[],
  102002. FLAC__uint64 abs_residual_partition_sums[],
  102003. unsigned residual_samples,
  102004. unsigned predictor_order,
  102005. unsigned min_partition_order,
  102006. unsigned max_partition_order,
  102007. unsigned bps
  102008. );
  102009. static void precompute_partition_info_escapes_(
  102010. const FLAC__int32 residual[],
  102011. unsigned raw_bits_per_partition[],
  102012. unsigned residual_samples,
  102013. unsigned predictor_order,
  102014. unsigned min_partition_order,
  102015. unsigned max_partition_order
  102016. );
  102017. static FLAC__bool set_partitioned_rice_(
  102018. #ifdef EXACT_RICE_BITS_CALCULATION
  102019. const FLAC__int32 residual[],
  102020. #endif
  102021. const FLAC__uint64 abs_residual_partition_sums[],
  102022. const unsigned raw_bits_per_partition[],
  102023. const unsigned residual_samples,
  102024. const unsigned predictor_order,
  102025. const unsigned suggested_rice_parameter,
  102026. const unsigned rice_parameter_limit,
  102027. const unsigned rice_parameter_search_dist,
  102028. const unsigned partition_order,
  102029. const FLAC__bool search_for_escapes,
  102030. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102031. unsigned *bits
  102032. );
  102033. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102034. /* verify-related routines: */
  102035. static void append_to_verify_fifo_(
  102036. verify_input_fifo *fifo,
  102037. const FLAC__int32 * const input[],
  102038. unsigned input_offset,
  102039. unsigned channels,
  102040. unsigned wide_samples
  102041. );
  102042. static void append_to_verify_fifo_interleaved_(
  102043. verify_input_fifo *fifo,
  102044. const FLAC__int32 input[],
  102045. unsigned input_offset,
  102046. unsigned channels,
  102047. unsigned wide_samples
  102048. );
  102049. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102050. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102051. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102052. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102053. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102054. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102055. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102056. 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);
  102057. static FILE *get_binary_stdout_(void);
  102058. /***********************************************************************
  102059. *
  102060. * Private class data
  102061. *
  102062. ***********************************************************************/
  102063. typedef struct FLAC__StreamEncoderPrivate {
  102064. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102065. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102066. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102068. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102069. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102070. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102071. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102072. #endif
  102073. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102074. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102075. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102076. FLAC__int32 *residual_workspace_mid_side[2][2];
  102077. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102078. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102079. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102080. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102081. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102082. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102083. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102084. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102085. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102086. unsigned best_subframe_mid_side[2];
  102087. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102088. unsigned best_subframe_bits_mid_side[2];
  102089. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102090. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102091. FLAC__BitWriter *frame; /* the current frame being worked on */
  102092. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102093. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102094. FLAC__ChannelAssignment last_channel_assignment;
  102095. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102096. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102097. unsigned current_sample_number;
  102098. unsigned current_frame_number;
  102099. FLAC__MD5Context md5context;
  102100. FLAC__CPUInfo cpuinfo;
  102101. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102102. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102103. #else
  102104. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102105. #endif
  102106. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102107. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102108. 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[]);
  102109. 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[]);
  102110. 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[]);
  102111. #endif
  102112. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102113. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102114. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102115. FLAC__bool disable_constant_subframes;
  102116. FLAC__bool disable_fixed_subframes;
  102117. FLAC__bool disable_verbatim_subframes;
  102118. #if FLAC__HAS_OGG
  102119. FLAC__bool is_ogg;
  102120. #endif
  102121. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102122. FLAC__StreamEncoderSeekCallback seek_callback;
  102123. FLAC__StreamEncoderTellCallback tell_callback;
  102124. FLAC__StreamEncoderWriteCallback write_callback;
  102125. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102126. FLAC__StreamEncoderProgressCallback progress_callback;
  102127. void *client_data;
  102128. unsigned first_seekpoint_to_check;
  102129. FILE *file; /* only used when encoding to a file */
  102130. FLAC__uint64 bytes_written;
  102131. FLAC__uint64 samples_written;
  102132. unsigned frames_written;
  102133. unsigned total_frames_estimate;
  102134. /* unaligned (original) pointers to allocated data */
  102135. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102136. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102137. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102138. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102139. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102140. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102141. FLAC__real *windowed_signal_unaligned;
  102142. #endif
  102143. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102144. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102145. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102146. unsigned *raw_bits_per_partition_unaligned;
  102147. /*
  102148. * These fields have been moved here from private function local
  102149. * declarations merely to save stack space during encoding.
  102150. */
  102151. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102152. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102153. #endif
  102154. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102155. /*
  102156. * The data for the verify section
  102157. */
  102158. struct {
  102159. FLAC__StreamDecoder *decoder;
  102160. EncoderStateHint state_hint;
  102161. FLAC__bool needs_magic_hack;
  102162. verify_input_fifo input_fifo;
  102163. verify_output output;
  102164. struct {
  102165. FLAC__uint64 absolute_sample;
  102166. unsigned frame_number;
  102167. unsigned channel;
  102168. unsigned sample;
  102169. FLAC__int32 expected;
  102170. FLAC__int32 got;
  102171. } error_stats;
  102172. } verify;
  102173. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102174. } FLAC__StreamEncoderPrivate;
  102175. /***********************************************************************
  102176. *
  102177. * Public static class data
  102178. *
  102179. ***********************************************************************/
  102180. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102181. "FLAC__STREAM_ENCODER_OK",
  102182. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102183. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102184. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102185. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102186. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102187. "FLAC__STREAM_ENCODER_IO_ERROR",
  102188. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102189. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102190. };
  102191. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102192. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102193. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102194. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102195. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102196. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102197. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102198. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102199. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102200. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102201. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102202. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102203. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102204. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102205. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102206. };
  102207. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102208. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102209. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102210. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102211. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102212. };
  102213. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102214. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102215. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102216. };
  102217. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102218. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102219. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102220. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102221. };
  102222. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102223. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102224. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102225. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102226. };
  102227. /* Number of samples that will be overread to watch for end of stream. By
  102228. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102229. * always try to read blocksize+1 samples before encoding a block, so that
  102230. * even if the stream has a total sample count that is an integral multiple
  102231. * of the blocksize, we will still notice when we are encoding the last
  102232. * block. This is needed, for example, to correctly set the end-of-stream
  102233. * marker in Ogg FLAC.
  102234. *
  102235. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102236. * not really any reason to change it.
  102237. */
  102238. static const unsigned OVERREAD_ = 1;
  102239. /***********************************************************************
  102240. *
  102241. * Class constructor/destructor
  102242. *
  102243. */
  102244. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102245. {
  102246. FLAC__StreamEncoder *encoder;
  102247. unsigned i;
  102248. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102249. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102250. if(encoder == 0) {
  102251. return 0;
  102252. }
  102253. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102254. if(encoder->protected_ == 0) {
  102255. free(encoder);
  102256. return 0;
  102257. }
  102258. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102259. if(encoder->private_ == 0) {
  102260. free(encoder->protected_);
  102261. free(encoder);
  102262. return 0;
  102263. }
  102264. encoder->private_->frame = FLAC__bitwriter_new();
  102265. if(encoder->private_->frame == 0) {
  102266. free(encoder->private_);
  102267. free(encoder->protected_);
  102268. free(encoder);
  102269. return 0;
  102270. }
  102271. encoder->private_->file = 0;
  102272. set_defaults_enc(encoder);
  102273. encoder->private_->is_being_deleted = false;
  102274. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102275. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102276. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102277. }
  102278. for(i = 0; i < 2; i++) {
  102279. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102280. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102281. }
  102282. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102283. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102284. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102285. }
  102286. for(i = 0; i < 2; i++) {
  102287. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102288. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102289. }
  102290. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102291. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102292. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102293. }
  102294. for(i = 0; i < 2; i++) {
  102295. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102296. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102297. }
  102298. for(i = 0; i < 2; i++)
  102299. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102300. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102301. return encoder;
  102302. }
  102303. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102304. {
  102305. unsigned i;
  102306. FLAC__ASSERT(0 != encoder);
  102307. FLAC__ASSERT(0 != encoder->protected_);
  102308. FLAC__ASSERT(0 != encoder->private_);
  102309. FLAC__ASSERT(0 != encoder->private_->frame);
  102310. encoder->private_->is_being_deleted = true;
  102311. (void)FLAC__stream_encoder_finish(encoder);
  102312. if(0 != encoder->private_->verify.decoder)
  102313. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102314. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102315. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102316. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102317. }
  102318. for(i = 0; i < 2; i++) {
  102319. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102320. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102321. }
  102322. for(i = 0; i < 2; i++)
  102323. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102324. FLAC__bitwriter_delete(encoder->private_->frame);
  102325. free(encoder->private_);
  102326. free(encoder->protected_);
  102327. free(encoder);
  102328. }
  102329. /***********************************************************************
  102330. *
  102331. * Public class methods
  102332. *
  102333. ***********************************************************************/
  102334. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102335. FLAC__StreamEncoder *encoder,
  102336. FLAC__StreamEncoderReadCallback read_callback,
  102337. FLAC__StreamEncoderWriteCallback write_callback,
  102338. FLAC__StreamEncoderSeekCallback seek_callback,
  102339. FLAC__StreamEncoderTellCallback tell_callback,
  102340. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102341. void *client_data,
  102342. FLAC__bool is_ogg
  102343. )
  102344. {
  102345. unsigned i;
  102346. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102347. FLAC__ASSERT(0 != encoder);
  102348. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102349. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102350. #if !FLAC__HAS_OGG
  102351. if(is_ogg)
  102352. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102353. #endif
  102354. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102355. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102356. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102357. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102358. if(encoder->protected_->channels != 2) {
  102359. encoder->protected_->do_mid_side_stereo = false;
  102360. encoder->protected_->loose_mid_side_stereo = false;
  102361. }
  102362. else if(!encoder->protected_->do_mid_side_stereo)
  102363. encoder->protected_->loose_mid_side_stereo = false;
  102364. if(encoder->protected_->bits_per_sample >= 32)
  102365. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102366. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102367. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102368. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102369. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102370. if(encoder->protected_->blocksize == 0) {
  102371. if(encoder->protected_->max_lpc_order == 0)
  102372. encoder->protected_->blocksize = 1152;
  102373. else
  102374. encoder->protected_->blocksize = 4096;
  102375. }
  102376. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102377. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102378. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102379. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102380. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102381. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102382. if(encoder->protected_->qlp_coeff_precision == 0) {
  102383. if(encoder->protected_->bits_per_sample < 16) {
  102384. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102385. /* @@@ until then we'll make a guess */
  102386. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102387. }
  102388. else if(encoder->protected_->bits_per_sample == 16) {
  102389. if(encoder->protected_->blocksize <= 192)
  102390. encoder->protected_->qlp_coeff_precision = 7;
  102391. else if(encoder->protected_->blocksize <= 384)
  102392. encoder->protected_->qlp_coeff_precision = 8;
  102393. else if(encoder->protected_->blocksize <= 576)
  102394. encoder->protected_->qlp_coeff_precision = 9;
  102395. else if(encoder->protected_->blocksize <= 1152)
  102396. encoder->protected_->qlp_coeff_precision = 10;
  102397. else if(encoder->protected_->blocksize <= 2304)
  102398. encoder->protected_->qlp_coeff_precision = 11;
  102399. else if(encoder->protected_->blocksize <= 4608)
  102400. encoder->protected_->qlp_coeff_precision = 12;
  102401. else
  102402. encoder->protected_->qlp_coeff_precision = 13;
  102403. }
  102404. else {
  102405. if(encoder->protected_->blocksize <= 384)
  102406. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102407. else if(encoder->protected_->blocksize <= 1152)
  102408. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102409. else
  102410. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102411. }
  102412. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102413. }
  102414. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102415. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102416. if(encoder->protected_->streamable_subset) {
  102417. if(
  102418. encoder->protected_->blocksize != 192 &&
  102419. encoder->protected_->blocksize != 576 &&
  102420. encoder->protected_->blocksize != 1152 &&
  102421. encoder->protected_->blocksize != 2304 &&
  102422. encoder->protected_->blocksize != 4608 &&
  102423. encoder->protected_->blocksize != 256 &&
  102424. encoder->protected_->blocksize != 512 &&
  102425. encoder->protected_->blocksize != 1024 &&
  102426. encoder->protected_->blocksize != 2048 &&
  102427. encoder->protected_->blocksize != 4096 &&
  102428. encoder->protected_->blocksize != 8192 &&
  102429. encoder->protected_->blocksize != 16384
  102430. )
  102431. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102432. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102433. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102434. if(
  102435. encoder->protected_->bits_per_sample != 8 &&
  102436. encoder->protected_->bits_per_sample != 12 &&
  102437. encoder->protected_->bits_per_sample != 16 &&
  102438. encoder->protected_->bits_per_sample != 20 &&
  102439. encoder->protected_->bits_per_sample != 24
  102440. )
  102441. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102442. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102443. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102444. if(
  102445. encoder->protected_->sample_rate <= 48000 &&
  102446. (
  102447. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102448. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102449. )
  102450. ) {
  102451. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102452. }
  102453. }
  102454. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102455. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102456. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102457. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102458. #if FLAC__HAS_OGG
  102459. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102460. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102461. unsigned i;
  102462. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102463. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102464. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102465. for( ; i > 0; i--)
  102466. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102467. encoder->protected_->metadata[0] = vc;
  102468. break;
  102469. }
  102470. }
  102471. }
  102472. #endif
  102473. /* keep track of any SEEKTABLE block */
  102474. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102475. unsigned i;
  102476. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102477. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102478. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102479. break; /* take only the first one */
  102480. }
  102481. }
  102482. }
  102483. /* validate metadata */
  102484. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102485. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102486. metadata_has_seektable = false;
  102487. metadata_has_vorbis_comment = false;
  102488. metadata_picture_has_type1 = false;
  102489. metadata_picture_has_type2 = false;
  102490. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102491. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102492. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102493. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102494. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102495. if(metadata_has_seektable) /* only one is allowed */
  102496. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102497. metadata_has_seektable = true;
  102498. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102499. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102500. }
  102501. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102502. if(metadata_has_vorbis_comment) /* only one is allowed */
  102503. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102504. metadata_has_vorbis_comment = true;
  102505. }
  102506. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102507. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102508. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102509. }
  102510. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102511. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102512. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102513. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102514. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102515. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102516. metadata_picture_has_type1 = true;
  102517. /* standard icon must be 32x32 pixel PNG */
  102518. if(
  102519. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102520. (
  102521. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102522. m->data.picture.width != 32 ||
  102523. m->data.picture.height != 32
  102524. )
  102525. )
  102526. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102527. }
  102528. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102529. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102530. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102531. metadata_picture_has_type2 = true;
  102532. }
  102533. }
  102534. }
  102535. encoder->private_->input_capacity = 0;
  102536. for(i = 0; i < encoder->protected_->channels; i++) {
  102537. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102538. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102539. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102540. #endif
  102541. }
  102542. for(i = 0; i < 2; i++) {
  102543. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102544. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102545. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102546. #endif
  102547. }
  102548. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102549. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102550. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102551. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102552. #endif
  102553. for(i = 0; i < encoder->protected_->channels; i++) {
  102554. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102555. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102556. encoder->private_->best_subframe[i] = 0;
  102557. }
  102558. for(i = 0; i < 2; i++) {
  102559. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102560. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102561. encoder->private_->best_subframe_mid_side[i] = 0;
  102562. }
  102563. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102564. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102565. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102566. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102567. #else
  102568. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102569. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102570. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102571. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102572. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102573. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102574. 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);
  102575. #endif
  102576. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102577. encoder->private_->loose_mid_side_stereo_frames = 1;
  102578. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102579. encoder->private_->current_sample_number = 0;
  102580. encoder->private_->current_frame_number = 0;
  102581. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102582. 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? */
  102583. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102584. /*
  102585. * get the CPU info and set the function pointers
  102586. */
  102587. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102588. /* first default to the non-asm routines */
  102589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102590. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102591. #endif
  102592. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102593. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102594. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102595. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102596. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102597. #endif
  102598. /* now override with asm where appropriate */
  102599. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102600. # ifndef FLAC__NO_ASM
  102601. if(encoder->private_->cpuinfo.use_asm) {
  102602. # ifdef FLAC__CPU_IA32
  102603. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102604. # ifdef FLAC__HAS_NASM
  102605. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102606. if(encoder->protected_->max_lpc_order < 4)
  102607. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102608. else if(encoder->protected_->max_lpc_order < 8)
  102609. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102610. else if(encoder->protected_->max_lpc_order < 12)
  102611. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102612. else
  102613. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102614. }
  102615. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102616. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102617. else
  102618. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102619. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102620. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102621. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102622. }
  102623. else {
  102624. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102625. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102626. }
  102627. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102628. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102629. # endif /* FLAC__HAS_NASM */
  102630. # endif /* FLAC__CPU_IA32 */
  102631. }
  102632. # endif /* !FLAC__NO_ASM */
  102633. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102634. /* finally override based on wide-ness if necessary */
  102635. if(encoder->private_->use_wide_by_block) {
  102636. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102637. }
  102638. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102639. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102640. #if FLAC__HAS_OGG
  102641. encoder->private_->is_ogg = is_ogg;
  102642. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102643. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102644. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102645. }
  102646. #endif
  102647. encoder->private_->read_callback = read_callback;
  102648. encoder->private_->write_callback = write_callback;
  102649. encoder->private_->seek_callback = seek_callback;
  102650. encoder->private_->tell_callback = tell_callback;
  102651. encoder->private_->metadata_callback = metadata_callback;
  102652. encoder->private_->client_data = client_data;
  102653. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102654. /* the above function sets the state for us in case of an error */
  102655. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102656. }
  102657. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102658. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102659. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102660. }
  102661. /*
  102662. * Set up the verify stuff if necessary
  102663. */
  102664. if(encoder->protected_->verify) {
  102665. /*
  102666. * First, set up the fifo which will hold the
  102667. * original signal to compare against
  102668. */
  102669. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102670. for(i = 0; i < encoder->protected_->channels; i++) {
  102671. 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))) {
  102672. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102673. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102674. }
  102675. }
  102676. encoder->private_->verify.input_fifo.tail = 0;
  102677. /*
  102678. * Now set up a stream decoder for verification
  102679. */
  102680. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102681. if(0 == encoder->private_->verify.decoder) {
  102682. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102683. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102684. }
  102685. 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) {
  102686. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102687. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102688. }
  102689. }
  102690. encoder->private_->verify.error_stats.absolute_sample = 0;
  102691. encoder->private_->verify.error_stats.frame_number = 0;
  102692. encoder->private_->verify.error_stats.channel = 0;
  102693. encoder->private_->verify.error_stats.sample = 0;
  102694. encoder->private_->verify.error_stats.expected = 0;
  102695. encoder->private_->verify.error_stats.got = 0;
  102696. /*
  102697. * These must be done before we write any metadata, because that
  102698. * calls the write_callback, which uses these values.
  102699. */
  102700. encoder->private_->first_seekpoint_to_check = 0;
  102701. encoder->private_->samples_written = 0;
  102702. encoder->protected_->streaminfo_offset = 0;
  102703. encoder->protected_->seektable_offset = 0;
  102704. encoder->protected_->audio_offset = 0;
  102705. /*
  102706. * write the stream header
  102707. */
  102708. if(encoder->protected_->verify)
  102709. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102710. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102711. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102712. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102713. }
  102714. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102715. /* the above function sets the state for us in case of an error */
  102716. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102717. }
  102718. /*
  102719. * write the STREAMINFO metadata block
  102720. */
  102721. if(encoder->protected_->verify)
  102722. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102723. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102724. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102725. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102726. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102727. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102728. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102729. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102730. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102731. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102732. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102733. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102734. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102735. if(encoder->protected_->do_md5)
  102736. FLAC__MD5Init(&encoder->private_->md5context);
  102737. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102738. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102739. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102740. }
  102741. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102742. /* the above function sets the state for us in case of an error */
  102743. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102744. }
  102745. /*
  102746. * Now that the STREAMINFO block is written, we can init this to an
  102747. * absurdly-high value...
  102748. */
  102749. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102750. /* ... and clear this to 0 */
  102751. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102752. /*
  102753. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102754. * if not, we will write an empty one (FLAC__add_metadata_block()
  102755. * automatically supplies the vendor string).
  102756. *
  102757. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102758. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102759. * true it will have already insured that the metadata list is properly
  102760. * ordered.)
  102761. */
  102762. if(!metadata_has_vorbis_comment) {
  102763. FLAC__StreamMetadata vorbis_comment;
  102764. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102765. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102766. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102767. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102768. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102769. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102770. vorbis_comment.data.vorbis_comment.comments = 0;
  102771. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102772. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102773. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102774. }
  102775. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102776. /* the above function sets the state for us in case of an error */
  102777. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102778. }
  102779. }
  102780. /*
  102781. * write the user's metadata blocks
  102782. */
  102783. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102784. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102785. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102786. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102787. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102788. }
  102789. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102790. /* the above function sets the state for us in case of an error */
  102791. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102792. }
  102793. }
  102794. /* now that all the metadata is written, we save the stream offset */
  102795. 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 */
  102796. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102797. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102798. }
  102799. if(encoder->protected_->verify)
  102800. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102801. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102802. }
  102803. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102804. FLAC__StreamEncoder *encoder,
  102805. FLAC__StreamEncoderWriteCallback write_callback,
  102806. FLAC__StreamEncoderSeekCallback seek_callback,
  102807. FLAC__StreamEncoderTellCallback tell_callback,
  102808. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102809. void *client_data
  102810. )
  102811. {
  102812. return init_stream_internal_enc(
  102813. encoder,
  102814. /*read_callback=*/0,
  102815. write_callback,
  102816. seek_callback,
  102817. tell_callback,
  102818. metadata_callback,
  102819. client_data,
  102820. /*is_ogg=*/false
  102821. );
  102822. }
  102823. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102824. FLAC__StreamEncoder *encoder,
  102825. FLAC__StreamEncoderReadCallback read_callback,
  102826. FLAC__StreamEncoderWriteCallback write_callback,
  102827. FLAC__StreamEncoderSeekCallback seek_callback,
  102828. FLAC__StreamEncoderTellCallback tell_callback,
  102829. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102830. void *client_data
  102831. )
  102832. {
  102833. return init_stream_internal_enc(
  102834. encoder,
  102835. read_callback,
  102836. write_callback,
  102837. seek_callback,
  102838. tell_callback,
  102839. metadata_callback,
  102840. client_data,
  102841. /*is_ogg=*/true
  102842. );
  102843. }
  102844. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102845. FLAC__StreamEncoder *encoder,
  102846. FILE *file,
  102847. FLAC__StreamEncoderProgressCallback progress_callback,
  102848. void *client_data,
  102849. FLAC__bool is_ogg
  102850. )
  102851. {
  102852. FLAC__StreamEncoderInitStatus init_status;
  102853. FLAC__ASSERT(0 != encoder);
  102854. FLAC__ASSERT(0 != file);
  102855. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102856. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102857. /* double protection */
  102858. if(file == 0) {
  102859. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102860. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102861. }
  102862. /*
  102863. * To make sure that our file does not go unclosed after an error, we
  102864. * must assign the FILE pointer before any further error can occur in
  102865. * this routine.
  102866. */
  102867. if(file == stdout)
  102868. file = get_binary_stdout_(); /* just to be safe */
  102869. encoder->private_->file = file;
  102870. encoder->private_->progress_callback = progress_callback;
  102871. encoder->private_->bytes_written = 0;
  102872. encoder->private_->samples_written = 0;
  102873. encoder->private_->frames_written = 0;
  102874. init_status = init_stream_internal_enc(
  102875. encoder,
  102876. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102877. file_write_callback_,
  102878. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102879. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102880. /*metadata_callback=*/0,
  102881. client_data,
  102882. is_ogg
  102883. );
  102884. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102885. /* the above function sets the state for us in case of an error */
  102886. return init_status;
  102887. }
  102888. {
  102889. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102890. FLAC__ASSERT(blocksize != 0);
  102891. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102892. }
  102893. return init_status;
  102894. }
  102895. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102896. FLAC__StreamEncoder *encoder,
  102897. FILE *file,
  102898. FLAC__StreamEncoderProgressCallback progress_callback,
  102899. void *client_data
  102900. )
  102901. {
  102902. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102903. }
  102904. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102905. FLAC__StreamEncoder *encoder,
  102906. FILE *file,
  102907. FLAC__StreamEncoderProgressCallback progress_callback,
  102908. void *client_data
  102909. )
  102910. {
  102911. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102912. }
  102913. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102914. FLAC__StreamEncoder *encoder,
  102915. const char *filename,
  102916. FLAC__StreamEncoderProgressCallback progress_callback,
  102917. void *client_data,
  102918. FLAC__bool is_ogg
  102919. )
  102920. {
  102921. FILE *file;
  102922. FLAC__ASSERT(0 != encoder);
  102923. /*
  102924. * To make sure that our file does not go unclosed after an error, we
  102925. * have to do the same entrance checks here that are later performed
  102926. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102927. */
  102928. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102929. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102930. file = filename? fopen(filename, "w+b") : stdout;
  102931. if(file == 0) {
  102932. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102933. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102934. }
  102935. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102936. }
  102937. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102938. FLAC__StreamEncoder *encoder,
  102939. const char *filename,
  102940. FLAC__StreamEncoderProgressCallback progress_callback,
  102941. void *client_data
  102942. )
  102943. {
  102944. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102945. }
  102946. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102947. FLAC__StreamEncoder *encoder,
  102948. const char *filename,
  102949. FLAC__StreamEncoderProgressCallback progress_callback,
  102950. void *client_data
  102951. )
  102952. {
  102953. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102954. }
  102955. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102956. {
  102957. FLAC__bool error = false;
  102958. FLAC__ASSERT(0 != encoder);
  102959. FLAC__ASSERT(0 != encoder->private_);
  102960. FLAC__ASSERT(0 != encoder->protected_);
  102961. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102962. return true;
  102963. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102964. if(encoder->private_->current_sample_number != 0) {
  102965. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102966. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102967. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102968. error = true;
  102969. }
  102970. }
  102971. if(encoder->protected_->do_md5)
  102972. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102973. if(!encoder->private_->is_being_deleted) {
  102974. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102975. if(encoder->private_->seek_callback) {
  102976. #if FLAC__HAS_OGG
  102977. if(encoder->private_->is_ogg)
  102978. update_ogg_metadata_(encoder);
  102979. else
  102980. #endif
  102981. update_metadata_(encoder);
  102982. /* check if an error occurred while updating metadata */
  102983. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102984. error = true;
  102985. }
  102986. if(encoder->private_->metadata_callback)
  102987. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102988. }
  102989. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102990. if(!error)
  102991. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102992. error = true;
  102993. }
  102994. }
  102995. if(0 != encoder->private_->file) {
  102996. if(encoder->private_->file != stdout)
  102997. fclose(encoder->private_->file);
  102998. encoder->private_->file = 0;
  102999. }
  103000. #if FLAC__HAS_OGG
  103001. if(encoder->private_->is_ogg)
  103002. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103003. #endif
  103004. free_(encoder);
  103005. set_defaults_enc(encoder);
  103006. if(!error)
  103007. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103008. return !error;
  103009. }
  103010. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103011. {
  103012. FLAC__ASSERT(0 != encoder);
  103013. FLAC__ASSERT(0 != encoder->private_);
  103014. FLAC__ASSERT(0 != encoder->protected_);
  103015. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103016. return false;
  103017. #if FLAC__HAS_OGG
  103018. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103019. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103020. return true;
  103021. #else
  103022. (void)value;
  103023. return false;
  103024. #endif
  103025. }
  103026. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103027. {
  103028. FLAC__ASSERT(0 != encoder);
  103029. FLAC__ASSERT(0 != encoder->private_);
  103030. FLAC__ASSERT(0 != encoder->protected_);
  103031. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103032. return false;
  103033. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103034. encoder->protected_->verify = value;
  103035. #endif
  103036. return true;
  103037. }
  103038. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103039. {
  103040. FLAC__ASSERT(0 != encoder);
  103041. FLAC__ASSERT(0 != encoder->private_);
  103042. FLAC__ASSERT(0 != encoder->protected_);
  103043. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103044. return false;
  103045. encoder->protected_->streamable_subset = value;
  103046. return true;
  103047. }
  103048. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103049. {
  103050. FLAC__ASSERT(0 != encoder);
  103051. FLAC__ASSERT(0 != encoder->private_);
  103052. FLAC__ASSERT(0 != encoder->protected_);
  103053. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103054. return false;
  103055. encoder->protected_->do_md5 = value;
  103056. return true;
  103057. }
  103058. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103059. {
  103060. FLAC__ASSERT(0 != encoder);
  103061. FLAC__ASSERT(0 != encoder->private_);
  103062. FLAC__ASSERT(0 != encoder->protected_);
  103063. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103064. return false;
  103065. encoder->protected_->channels = value;
  103066. return true;
  103067. }
  103068. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103069. {
  103070. FLAC__ASSERT(0 != encoder);
  103071. FLAC__ASSERT(0 != encoder->private_);
  103072. FLAC__ASSERT(0 != encoder->protected_);
  103073. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103074. return false;
  103075. encoder->protected_->bits_per_sample = value;
  103076. return true;
  103077. }
  103078. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103079. {
  103080. FLAC__ASSERT(0 != encoder);
  103081. FLAC__ASSERT(0 != encoder->private_);
  103082. FLAC__ASSERT(0 != encoder->protected_);
  103083. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103084. return false;
  103085. encoder->protected_->sample_rate = value;
  103086. return true;
  103087. }
  103088. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103089. {
  103090. FLAC__bool ok = true;
  103091. FLAC__ASSERT(0 != encoder);
  103092. FLAC__ASSERT(0 != encoder->private_);
  103093. FLAC__ASSERT(0 != encoder->protected_);
  103094. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103095. return false;
  103096. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103097. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103098. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103099. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103100. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103101. #if 0
  103102. /* was: */
  103103. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103104. /* but it's too hard to specify the string in a locale-specific way */
  103105. #else
  103106. encoder->protected_->num_apodizations = 1;
  103107. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103108. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103109. #endif
  103110. #endif
  103111. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103112. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103113. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103114. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103115. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103116. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103117. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103118. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103119. return ok;
  103120. }
  103121. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103122. {
  103123. FLAC__ASSERT(0 != encoder);
  103124. FLAC__ASSERT(0 != encoder->private_);
  103125. FLAC__ASSERT(0 != encoder->protected_);
  103126. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103127. return false;
  103128. encoder->protected_->blocksize = value;
  103129. return true;
  103130. }
  103131. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103132. {
  103133. FLAC__ASSERT(0 != encoder);
  103134. FLAC__ASSERT(0 != encoder->private_);
  103135. FLAC__ASSERT(0 != encoder->protected_);
  103136. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103137. return false;
  103138. encoder->protected_->do_mid_side_stereo = value;
  103139. return true;
  103140. }
  103141. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103142. {
  103143. FLAC__ASSERT(0 != encoder);
  103144. FLAC__ASSERT(0 != encoder->private_);
  103145. FLAC__ASSERT(0 != encoder->protected_);
  103146. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103147. return false;
  103148. encoder->protected_->loose_mid_side_stereo = value;
  103149. return true;
  103150. }
  103151. /*@@@@add to tests*/
  103152. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103153. {
  103154. FLAC__ASSERT(0 != encoder);
  103155. FLAC__ASSERT(0 != encoder->private_);
  103156. FLAC__ASSERT(0 != encoder->protected_);
  103157. FLAC__ASSERT(0 != specification);
  103158. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103159. return false;
  103160. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103161. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103162. #else
  103163. encoder->protected_->num_apodizations = 0;
  103164. while(1) {
  103165. const char *s = strchr(specification, ';');
  103166. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103167. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103168. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103169. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103170. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103171. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103172. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103173. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103174. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103175. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103176. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103177. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103178. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103179. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103180. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103181. if (stddev > 0.0 && stddev <= 0.5) {
  103182. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103183. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103184. }
  103185. }
  103186. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103187. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103188. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103189. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103190. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103191. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103192. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103193. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103194. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103195. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103196. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103197. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103198. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103199. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103200. if (p >= 0.0 && p <= 1.0) {
  103201. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103202. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103203. }
  103204. }
  103205. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103206. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103207. if (encoder->protected_->num_apodizations == 32)
  103208. break;
  103209. if (s)
  103210. specification = s+1;
  103211. else
  103212. break;
  103213. }
  103214. if(encoder->protected_->num_apodizations == 0) {
  103215. encoder->protected_->num_apodizations = 1;
  103216. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103217. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103218. }
  103219. #endif
  103220. return true;
  103221. }
  103222. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103223. {
  103224. FLAC__ASSERT(0 != encoder);
  103225. FLAC__ASSERT(0 != encoder->private_);
  103226. FLAC__ASSERT(0 != encoder->protected_);
  103227. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103228. return false;
  103229. encoder->protected_->max_lpc_order = value;
  103230. return true;
  103231. }
  103232. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103233. {
  103234. FLAC__ASSERT(0 != encoder);
  103235. FLAC__ASSERT(0 != encoder->private_);
  103236. FLAC__ASSERT(0 != encoder->protected_);
  103237. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103238. return false;
  103239. encoder->protected_->qlp_coeff_precision = value;
  103240. return true;
  103241. }
  103242. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103243. {
  103244. FLAC__ASSERT(0 != encoder);
  103245. FLAC__ASSERT(0 != encoder->private_);
  103246. FLAC__ASSERT(0 != encoder->protected_);
  103247. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103248. return false;
  103249. encoder->protected_->do_qlp_coeff_prec_search = value;
  103250. return true;
  103251. }
  103252. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103253. {
  103254. FLAC__ASSERT(0 != encoder);
  103255. FLAC__ASSERT(0 != encoder->private_);
  103256. FLAC__ASSERT(0 != encoder->protected_);
  103257. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103258. return false;
  103259. #if 0
  103260. /*@@@ deprecated: */
  103261. encoder->protected_->do_escape_coding = value;
  103262. #else
  103263. (void)value;
  103264. #endif
  103265. return true;
  103266. }
  103267. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103268. {
  103269. FLAC__ASSERT(0 != encoder);
  103270. FLAC__ASSERT(0 != encoder->private_);
  103271. FLAC__ASSERT(0 != encoder->protected_);
  103272. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103273. return false;
  103274. encoder->protected_->do_exhaustive_model_search = value;
  103275. return true;
  103276. }
  103277. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103278. {
  103279. FLAC__ASSERT(0 != encoder);
  103280. FLAC__ASSERT(0 != encoder->private_);
  103281. FLAC__ASSERT(0 != encoder->protected_);
  103282. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103283. return false;
  103284. encoder->protected_->min_residual_partition_order = value;
  103285. return true;
  103286. }
  103287. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103288. {
  103289. FLAC__ASSERT(0 != encoder);
  103290. FLAC__ASSERT(0 != encoder->private_);
  103291. FLAC__ASSERT(0 != encoder->protected_);
  103292. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103293. return false;
  103294. encoder->protected_->max_residual_partition_order = value;
  103295. return true;
  103296. }
  103297. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103298. {
  103299. FLAC__ASSERT(0 != encoder);
  103300. FLAC__ASSERT(0 != encoder->private_);
  103301. FLAC__ASSERT(0 != encoder->protected_);
  103302. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103303. return false;
  103304. #if 0
  103305. /*@@@ deprecated: */
  103306. encoder->protected_->rice_parameter_search_dist = value;
  103307. #else
  103308. (void)value;
  103309. #endif
  103310. return true;
  103311. }
  103312. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103313. {
  103314. FLAC__ASSERT(0 != encoder);
  103315. FLAC__ASSERT(0 != encoder->private_);
  103316. FLAC__ASSERT(0 != encoder->protected_);
  103317. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103318. return false;
  103319. encoder->protected_->total_samples_estimate = value;
  103320. return true;
  103321. }
  103322. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103323. {
  103324. FLAC__ASSERT(0 != encoder);
  103325. FLAC__ASSERT(0 != encoder->private_);
  103326. FLAC__ASSERT(0 != encoder->protected_);
  103327. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103328. return false;
  103329. if(0 == metadata)
  103330. num_blocks = 0;
  103331. if(0 == num_blocks)
  103332. metadata = 0;
  103333. /* realloc() does not do exactly what we want so... */
  103334. if(encoder->protected_->metadata) {
  103335. free(encoder->protected_->metadata);
  103336. encoder->protected_->metadata = 0;
  103337. encoder->protected_->num_metadata_blocks = 0;
  103338. }
  103339. if(num_blocks) {
  103340. FLAC__StreamMetadata **m;
  103341. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103342. return false;
  103343. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103344. encoder->protected_->metadata = m;
  103345. encoder->protected_->num_metadata_blocks = num_blocks;
  103346. }
  103347. #if FLAC__HAS_OGG
  103348. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103349. return false;
  103350. #endif
  103351. return true;
  103352. }
  103353. /*
  103354. * These three functions are not static, but not publically exposed in
  103355. * include/FLAC/ either. They are used by the test suite.
  103356. */
  103357. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103358. {
  103359. FLAC__ASSERT(0 != encoder);
  103360. FLAC__ASSERT(0 != encoder->private_);
  103361. FLAC__ASSERT(0 != encoder->protected_);
  103362. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103363. return false;
  103364. encoder->private_->disable_constant_subframes = value;
  103365. return true;
  103366. }
  103367. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103368. {
  103369. FLAC__ASSERT(0 != encoder);
  103370. FLAC__ASSERT(0 != encoder->private_);
  103371. FLAC__ASSERT(0 != encoder->protected_);
  103372. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103373. return false;
  103374. encoder->private_->disable_fixed_subframes = value;
  103375. return true;
  103376. }
  103377. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103378. {
  103379. FLAC__ASSERT(0 != encoder);
  103380. FLAC__ASSERT(0 != encoder->private_);
  103381. FLAC__ASSERT(0 != encoder->protected_);
  103382. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103383. return false;
  103384. encoder->private_->disable_verbatim_subframes = value;
  103385. return true;
  103386. }
  103387. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103388. {
  103389. FLAC__ASSERT(0 != encoder);
  103390. FLAC__ASSERT(0 != encoder->private_);
  103391. FLAC__ASSERT(0 != encoder->protected_);
  103392. return encoder->protected_->state;
  103393. }
  103394. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103395. {
  103396. FLAC__ASSERT(0 != encoder);
  103397. FLAC__ASSERT(0 != encoder->private_);
  103398. FLAC__ASSERT(0 != encoder->protected_);
  103399. if(encoder->protected_->verify)
  103400. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103401. else
  103402. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103403. }
  103404. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103405. {
  103406. FLAC__ASSERT(0 != encoder);
  103407. FLAC__ASSERT(0 != encoder->private_);
  103408. FLAC__ASSERT(0 != encoder->protected_);
  103409. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103410. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103411. else
  103412. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103413. }
  103414. 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)
  103415. {
  103416. FLAC__ASSERT(0 != encoder);
  103417. FLAC__ASSERT(0 != encoder->private_);
  103418. FLAC__ASSERT(0 != encoder->protected_);
  103419. if(0 != absolute_sample)
  103420. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103421. if(0 != frame_number)
  103422. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103423. if(0 != channel)
  103424. *channel = encoder->private_->verify.error_stats.channel;
  103425. if(0 != sample)
  103426. *sample = encoder->private_->verify.error_stats.sample;
  103427. if(0 != expected)
  103428. *expected = encoder->private_->verify.error_stats.expected;
  103429. if(0 != got)
  103430. *got = encoder->private_->verify.error_stats.got;
  103431. }
  103432. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103433. {
  103434. FLAC__ASSERT(0 != encoder);
  103435. FLAC__ASSERT(0 != encoder->private_);
  103436. FLAC__ASSERT(0 != encoder->protected_);
  103437. return encoder->protected_->verify;
  103438. }
  103439. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103440. {
  103441. FLAC__ASSERT(0 != encoder);
  103442. FLAC__ASSERT(0 != encoder->private_);
  103443. FLAC__ASSERT(0 != encoder->protected_);
  103444. return encoder->protected_->streamable_subset;
  103445. }
  103446. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103447. {
  103448. FLAC__ASSERT(0 != encoder);
  103449. FLAC__ASSERT(0 != encoder->private_);
  103450. FLAC__ASSERT(0 != encoder->protected_);
  103451. return encoder->protected_->do_md5;
  103452. }
  103453. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103454. {
  103455. FLAC__ASSERT(0 != encoder);
  103456. FLAC__ASSERT(0 != encoder->private_);
  103457. FLAC__ASSERT(0 != encoder->protected_);
  103458. return encoder->protected_->channels;
  103459. }
  103460. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103461. {
  103462. FLAC__ASSERT(0 != encoder);
  103463. FLAC__ASSERT(0 != encoder->private_);
  103464. FLAC__ASSERT(0 != encoder->protected_);
  103465. return encoder->protected_->bits_per_sample;
  103466. }
  103467. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103468. {
  103469. FLAC__ASSERT(0 != encoder);
  103470. FLAC__ASSERT(0 != encoder->private_);
  103471. FLAC__ASSERT(0 != encoder->protected_);
  103472. return encoder->protected_->sample_rate;
  103473. }
  103474. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103475. {
  103476. FLAC__ASSERT(0 != encoder);
  103477. FLAC__ASSERT(0 != encoder->private_);
  103478. FLAC__ASSERT(0 != encoder->protected_);
  103479. return encoder->protected_->blocksize;
  103480. }
  103481. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103482. {
  103483. FLAC__ASSERT(0 != encoder);
  103484. FLAC__ASSERT(0 != encoder->private_);
  103485. FLAC__ASSERT(0 != encoder->protected_);
  103486. return encoder->protected_->do_mid_side_stereo;
  103487. }
  103488. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103489. {
  103490. FLAC__ASSERT(0 != encoder);
  103491. FLAC__ASSERT(0 != encoder->private_);
  103492. FLAC__ASSERT(0 != encoder->protected_);
  103493. return encoder->protected_->loose_mid_side_stereo;
  103494. }
  103495. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103496. {
  103497. FLAC__ASSERT(0 != encoder);
  103498. FLAC__ASSERT(0 != encoder->private_);
  103499. FLAC__ASSERT(0 != encoder->protected_);
  103500. return encoder->protected_->max_lpc_order;
  103501. }
  103502. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103503. {
  103504. FLAC__ASSERT(0 != encoder);
  103505. FLAC__ASSERT(0 != encoder->private_);
  103506. FLAC__ASSERT(0 != encoder->protected_);
  103507. return encoder->protected_->qlp_coeff_precision;
  103508. }
  103509. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103510. {
  103511. FLAC__ASSERT(0 != encoder);
  103512. FLAC__ASSERT(0 != encoder->private_);
  103513. FLAC__ASSERT(0 != encoder->protected_);
  103514. return encoder->protected_->do_qlp_coeff_prec_search;
  103515. }
  103516. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103517. {
  103518. FLAC__ASSERT(0 != encoder);
  103519. FLAC__ASSERT(0 != encoder->private_);
  103520. FLAC__ASSERT(0 != encoder->protected_);
  103521. return encoder->protected_->do_escape_coding;
  103522. }
  103523. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103524. {
  103525. FLAC__ASSERT(0 != encoder);
  103526. FLAC__ASSERT(0 != encoder->private_);
  103527. FLAC__ASSERT(0 != encoder->protected_);
  103528. return encoder->protected_->do_exhaustive_model_search;
  103529. }
  103530. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103531. {
  103532. FLAC__ASSERT(0 != encoder);
  103533. FLAC__ASSERT(0 != encoder->private_);
  103534. FLAC__ASSERT(0 != encoder->protected_);
  103535. return encoder->protected_->min_residual_partition_order;
  103536. }
  103537. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103538. {
  103539. FLAC__ASSERT(0 != encoder);
  103540. FLAC__ASSERT(0 != encoder->private_);
  103541. FLAC__ASSERT(0 != encoder->protected_);
  103542. return encoder->protected_->max_residual_partition_order;
  103543. }
  103544. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103545. {
  103546. FLAC__ASSERT(0 != encoder);
  103547. FLAC__ASSERT(0 != encoder->private_);
  103548. FLAC__ASSERT(0 != encoder->protected_);
  103549. return encoder->protected_->rice_parameter_search_dist;
  103550. }
  103551. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103552. {
  103553. FLAC__ASSERT(0 != encoder);
  103554. FLAC__ASSERT(0 != encoder->private_);
  103555. FLAC__ASSERT(0 != encoder->protected_);
  103556. return encoder->protected_->total_samples_estimate;
  103557. }
  103558. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103559. {
  103560. unsigned i, j = 0, channel;
  103561. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103562. FLAC__ASSERT(0 != encoder);
  103563. FLAC__ASSERT(0 != encoder->private_);
  103564. FLAC__ASSERT(0 != encoder->protected_);
  103565. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103566. do {
  103567. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103568. if(encoder->protected_->verify)
  103569. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103570. for(channel = 0; channel < channels; channel++)
  103571. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103572. if(encoder->protected_->do_mid_side_stereo) {
  103573. FLAC__ASSERT(channels == 2);
  103574. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103575. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103576. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103577. 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' ! */
  103578. }
  103579. }
  103580. else
  103581. j += n;
  103582. encoder->private_->current_sample_number += n;
  103583. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103584. if(encoder->private_->current_sample_number > blocksize) {
  103585. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103586. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103587. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103588. return false;
  103589. /* move unprocessed overread samples to beginnings of arrays */
  103590. for(channel = 0; channel < channels; channel++)
  103591. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103592. if(encoder->protected_->do_mid_side_stereo) {
  103593. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103594. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103595. }
  103596. encoder->private_->current_sample_number = 1;
  103597. }
  103598. } while(j < samples);
  103599. return true;
  103600. }
  103601. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103602. {
  103603. unsigned i, j, k, channel;
  103604. FLAC__int32 x, mid, side;
  103605. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103606. FLAC__ASSERT(0 != encoder);
  103607. FLAC__ASSERT(0 != encoder->private_);
  103608. FLAC__ASSERT(0 != encoder->protected_);
  103609. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103610. j = k = 0;
  103611. /*
  103612. * we have several flavors of the same basic loop, optimized for
  103613. * different conditions:
  103614. */
  103615. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103616. /*
  103617. * stereo coding: unroll channel loop
  103618. */
  103619. do {
  103620. if(encoder->protected_->verify)
  103621. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103622. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103623. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103624. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103625. x = buffer[k++];
  103626. encoder->private_->integer_signal[1][i] = x;
  103627. mid += x;
  103628. side -= x;
  103629. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103630. encoder->private_->integer_signal_mid_side[1][i] = side;
  103631. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103632. }
  103633. encoder->private_->current_sample_number = i;
  103634. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103635. if(i > blocksize) {
  103636. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103637. return false;
  103638. /* move unprocessed overread samples to beginnings of arrays */
  103639. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103640. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103641. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103642. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103643. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103644. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103645. encoder->private_->current_sample_number = 1;
  103646. }
  103647. } while(j < samples);
  103648. }
  103649. else {
  103650. /*
  103651. * independent channel coding: buffer each channel in inner loop
  103652. */
  103653. do {
  103654. if(encoder->protected_->verify)
  103655. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103656. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103657. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103658. for(channel = 0; channel < channels; channel++)
  103659. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103660. }
  103661. encoder->private_->current_sample_number = i;
  103662. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103663. if(i > blocksize) {
  103664. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103665. return false;
  103666. /* move unprocessed overread samples to beginnings of arrays */
  103667. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103668. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103669. for(channel = 0; channel < channels; channel++)
  103670. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103671. encoder->private_->current_sample_number = 1;
  103672. }
  103673. } while(j < samples);
  103674. }
  103675. return true;
  103676. }
  103677. /***********************************************************************
  103678. *
  103679. * Private class methods
  103680. *
  103681. ***********************************************************************/
  103682. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103683. {
  103684. FLAC__ASSERT(0 != encoder);
  103685. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103686. encoder->protected_->verify = true;
  103687. #else
  103688. encoder->protected_->verify = false;
  103689. #endif
  103690. encoder->protected_->streamable_subset = true;
  103691. encoder->protected_->do_md5 = true;
  103692. encoder->protected_->do_mid_side_stereo = false;
  103693. encoder->protected_->loose_mid_side_stereo = false;
  103694. encoder->protected_->channels = 2;
  103695. encoder->protected_->bits_per_sample = 16;
  103696. encoder->protected_->sample_rate = 44100;
  103697. encoder->protected_->blocksize = 0;
  103698. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103699. encoder->protected_->num_apodizations = 1;
  103700. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103701. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103702. #endif
  103703. encoder->protected_->max_lpc_order = 0;
  103704. encoder->protected_->qlp_coeff_precision = 0;
  103705. encoder->protected_->do_qlp_coeff_prec_search = false;
  103706. encoder->protected_->do_exhaustive_model_search = false;
  103707. encoder->protected_->do_escape_coding = false;
  103708. encoder->protected_->min_residual_partition_order = 0;
  103709. encoder->protected_->max_residual_partition_order = 0;
  103710. encoder->protected_->rice_parameter_search_dist = 0;
  103711. encoder->protected_->total_samples_estimate = 0;
  103712. encoder->protected_->metadata = 0;
  103713. encoder->protected_->num_metadata_blocks = 0;
  103714. encoder->private_->seek_table = 0;
  103715. encoder->private_->disable_constant_subframes = false;
  103716. encoder->private_->disable_fixed_subframes = false;
  103717. encoder->private_->disable_verbatim_subframes = false;
  103718. #if FLAC__HAS_OGG
  103719. encoder->private_->is_ogg = false;
  103720. #endif
  103721. encoder->private_->read_callback = 0;
  103722. encoder->private_->write_callback = 0;
  103723. encoder->private_->seek_callback = 0;
  103724. encoder->private_->tell_callback = 0;
  103725. encoder->private_->metadata_callback = 0;
  103726. encoder->private_->progress_callback = 0;
  103727. encoder->private_->client_data = 0;
  103728. #if FLAC__HAS_OGG
  103729. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103730. #endif
  103731. }
  103732. void free_(FLAC__StreamEncoder *encoder)
  103733. {
  103734. unsigned i, channel;
  103735. FLAC__ASSERT(0 != encoder);
  103736. if(encoder->protected_->metadata) {
  103737. free(encoder->protected_->metadata);
  103738. encoder->protected_->metadata = 0;
  103739. encoder->protected_->num_metadata_blocks = 0;
  103740. }
  103741. for(i = 0; i < encoder->protected_->channels; i++) {
  103742. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103743. free(encoder->private_->integer_signal_unaligned[i]);
  103744. encoder->private_->integer_signal_unaligned[i] = 0;
  103745. }
  103746. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103747. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103748. free(encoder->private_->real_signal_unaligned[i]);
  103749. encoder->private_->real_signal_unaligned[i] = 0;
  103750. }
  103751. #endif
  103752. }
  103753. for(i = 0; i < 2; i++) {
  103754. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103755. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103756. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103757. }
  103758. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103759. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103760. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103761. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103762. }
  103763. #endif
  103764. }
  103765. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103766. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103767. if(0 != encoder->private_->window_unaligned[i]) {
  103768. free(encoder->private_->window_unaligned[i]);
  103769. encoder->private_->window_unaligned[i] = 0;
  103770. }
  103771. }
  103772. if(0 != encoder->private_->windowed_signal_unaligned) {
  103773. free(encoder->private_->windowed_signal_unaligned);
  103774. encoder->private_->windowed_signal_unaligned = 0;
  103775. }
  103776. #endif
  103777. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103778. for(i = 0; i < 2; i++) {
  103779. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103780. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103781. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103782. }
  103783. }
  103784. }
  103785. for(channel = 0; channel < 2; channel++) {
  103786. for(i = 0; i < 2; i++) {
  103787. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103788. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103789. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103790. }
  103791. }
  103792. }
  103793. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103794. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103795. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103796. }
  103797. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103798. free(encoder->private_->raw_bits_per_partition_unaligned);
  103799. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103800. }
  103801. if(encoder->protected_->verify) {
  103802. for(i = 0; i < encoder->protected_->channels; i++) {
  103803. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103804. free(encoder->private_->verify.input_fifo.data[i]);
  103805. encoder->private_->verify.input_fifo.data[i] = 0;
  103806. }
  103807. }
  103808. }
  103809. FLAC__bitwriter_free(encoder->private_->frame);
  103810. }
  103811. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103812. {
  103813. FLAC__bool ok;
  103814. unsigned i, channel;
  103815. FLAC__ASSERT(new_blocksize > 0);
  103816. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103817. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103818. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103819. if(new_blocksize <= encoder->private_->input_capacity)
  103820. return true;
  103821. ok = true;
  103822. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103823. * requires that the input arrays (in our case the integer signals)
  103824. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103825. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103826. */
  103827. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103828. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103829. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103830. encoder->private_->integer_signal[i] += 4;
  103831. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103832. #if 0 /* @@@ currently unused */
  103833. if(encoder->protected_->max_lpc_order > 0)
  103834. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103835. #endif
  103836. #endif
  103837. }
  103838. for(i = 0; ok && i < 2; i++) {
  103839. 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]);
  103840. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103841. encoder->private_->integer_signal_mid_side[i] += 4;
  103842. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103843. #if 0 /* @@@ currently unused */
  103844. if(encoder->protected_->max_lpc_order > 0)
  103845. 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]);
  103846. #endif
  103847. #endif
  103848. }
  103849. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103850. if(ok && encoder->protected_->max_lpc_order > 0) {
  103851. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103852. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103853. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103854. }
  103855. #endif
  103856. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103857. for(i = 0; ok && i < 2; i++) {
  103858. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103859. }
  103860. }
  103861. for(channel = 0; ok && channel < 2; channel++) {
  103862. for(i = 0; ok && i < 2; i++) {
  103863. 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]);
  103864. }
  103865. }
  103866. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103867. /*@@@ 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) */
  103868. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103869. if(encoder->protected_->do_escape_coding)
  103870. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103871. /* now adjust the windows if the blocksize has changed */
  103872. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103873. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103874. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103875. switch(encoder->protected_->apodizations[i].type) {
  103876. case FLAC__APODIZATION_BARTLETT:
  103877. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103878. break;
  103879. case FLAC__APODIZATION_BARTLETT_HANN:
  103880. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103881. break;
  103882. case FLAC__APODIZATION_BLACKMAN:
  103883. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103884. break;
  103885. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103886. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103887. break;
  103888. case FLAC__APODIZATION_CONNES:
  103889. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103890. break;
  103891. case FLAC__APODIZATION_FLATTOP:
  103892. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103893. break;
  103894. case FLAC__APODIZATION_GAUSS:
  103895. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103896. break;
  103897. case FLAC__APODIZATION_HAMMING:
  103898. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103899. break;
  103900. case FLAC__APODIZATION_HANN:
  103901. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103902. break;
  103903. case FLAC__APODIZATION_KAISER_BESSEL:
  103904. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103905. break;
  103906. case FLAC__APODIZATION_NUTTALL:
  103907. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103908. break;
  103909. case FLAC__APODIZATION_RECTANGLE:
  103910. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103911. break;
  103912. case FLAC__APODIZATION_TRIANGLE:
  103913. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103914. break;
  103915. case FLAC__APODIZATION_TUKEY:
  103916. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103917. break;
  103918. case FLAC__APODIZATION_WELCH:
  103919. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103920. break;
  103921. default:
  103922. FLAC__ASSERT(0);
  103923. /* double protection */
  103924. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103925. break;
  103926. }
  103927. }
  103928. }
  103929. #endif
  103930. if(ok)
  103931. encoder->private_->input_capacity = new_blocksize;
  103932. else
  103933. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103934. return ok;
  103935. }
  103936. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103937. {
  103938. const FLAC__byte *buffer;
  103939. size_t bytes;
  103940. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103941. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103942. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103943. return false;
  103944. }
  103945. if(encoder->protected_->verify) {
  103946. encoder->private_->verify.output.data = buffer;
  103947. encoder->private_->verify.output.bytes = bytes;
  103948. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103949. encoder->private_->verify.needs_magic_hack = true;
  103950. }
  103951. else {
  103952. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103953. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103954. FLAC__bitwriter_clear(encoder->private_->frame);
  103955. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103956. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103957. return false;
  103958. }
  103959. }
  103960. }
  103961. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103962. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103963. FLAC__bitwriter_clear(encoder->private_->frame);
  103964. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103965. return false;
  103966. }
  103967. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103968. FLAC__bitwriter_clear(encoder->private_->frame);
  103969. if(samples > 0) {
  103970. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103971. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103972. }
  103973. return true;
  103974. }
  103975. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103976. {
  103977. FLAC__StreamEncoderWriteStatus status;
  103978. FLAC__uint64 output_position = 0;
  103979. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103980. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103981. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103982. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103983. }
  103984. /*
  103985. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103986. */
  103987. if(samples == 0) {
  103988. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103989. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103990. encoder->protected_->streaminfo_offset = output_position;
  103991. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103992. encoder->protected_->seektable_offset = output_position;
  103993. }
  103994. /*
  103995. * Mark the current seek point if hit (if audio_offset == 0 that
  103996. * means we're still writing metadata and haven't hit the first
  103997. * frame yet)
  103998. */
  103999. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104000. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104001. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104002. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104003. FLAC__uint64 test_sample;
  104004. unsigned i;
  104005. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104006. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104007. if(test_sample > frame_last_sample) {
  104008. break;
  104009. }
  104010. else if(test_sample >= frame_first_sample) {
  104011. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104012. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104013. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104014. encoder->private_->first_seekpoint_to_check++;
  104015. /* DO NOT: "break;" and here's why:
  104016. * The seektable template may contain more than one target
  104017. * sample for any given frame; we will keep looping, generating
  104018. * duplicate seekpoints for them, and we'll clean it up later,
  104019. * just before writing the seektable back to the metadata.
  104020. */
  104021. }
  104022. else {
  104023. encoder->private_->first_seekpoint_to_check++;
  104024. }
  104025. }
  104026. }
  104027. #if FLAC__HAS_OGG
  104028. if(encoder->private_->is_ogg) {
  104029. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104030. &encoder->protected_->ogg_encoder_aspect,
  104031. buffer,
  104032. bytes,
  104033. samples,
  104034. encoder->private_->current_frame_number,
  104035. is_last_block,
  104036. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104037. encoder,
  104038. encoder->private_->client_data
  104039. );
  104040. }
  104041. else
  104042. #endif
  104043. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104044. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104045. encoder->private_->bytes_written += bytes;
  104046. encoder->private_->samples_written += samples;
  104047. /* we keep a high watermark on the number of frames written because
  104048. * when the encoder goes back to write metadata, 'current_frame'
  104049. * will drop back to 0.
  104050. */
  104051. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104052. }
  104053. else
  104054. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104055. return status;
  104056. }
  104057. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104058. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104059. {
  104060. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104061. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104062. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104063. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104064. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104065. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104066. FLAC__StreamEncoderSeekStatus seek_status;
  104067. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104068. /* All this is based on intimate knowledge of the stream header
  104069. * layout, but a change to the header format that would break this
  104070. * would also break all streams encoded in the previous format.
  104071. */
  104072. /*
  104073. * Write MD5 signature
  104074. */
  104075. {
  104076. const unsigned md5_offset =
  104077. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104078. (
  104079. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104080. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104081. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104082. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104083. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104084. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104085. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104086. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104087. ) / 8;
  104088. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104089. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104090. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104091. return;
  104092. }
  104093. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104094. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104095. return;
  104096. }
  104097. }
  104098. /*
  104099. * Write total samples
  104100. */
  104101. {
  104102. const unsigned total_samples_byte_offset =
  104103. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104104. (
  104105. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104106. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104107. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104108. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104109. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104110. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104111. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104112. - 4
  104113. ) / 8;
  104114. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104115. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104116. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104117. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104118. b[4] = (FLAC__byte)(samples & 0xFF);
  104119. 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) {
  104120. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104121. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104122. return;
  104123. }
  104124. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104125. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104126. return;
  104127. }
  104128. }
  104129. /*
  104130. * Write min/max framesize
  104131. */
  104132. {
  104133. const unsigned min_framesize_offset =
  104134. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104135. (
  104136. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104137. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104138. ) / 8;
  104139. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104140. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104141. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104142. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104143. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104144. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104145. 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) {
  104146. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104147. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104148. return;
  104149. }
  104150. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104151. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104152. return;
  104153. }
  104154. }
  104155. /*
  104156. * Write seektable
  104157. */
  104158. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104159. unsigned i;
  104160. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104161. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104162. 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) {
  104163. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104164. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104165. return;
  104166. }
  104167. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104168. FLAC__uint64 xx;
  104169. unsigned x;
  104170. xx = encoder->private_->seek_table->points[i].sample_number;
  104171. b[7] = (FLAC__byte)xx; xx >>= 8;
  104172. b[6] = (FLAC__byte)xx; xx >>= 8;
  104173. b[5] = (FLAC__byte)xx; xx >>= 8;
  104174. b[4] = (FLAC__byte)xx; xx >>= 8;
  104175. b[3] = (FLAC__byte)xx; xx >>= 8;
  104176. b[2] = (FLAC__byte)xx; xx >>= 8;
  104177. b[1] = (FLAC__byte)xx; xx >>= 8;
  104178. b[0] = (FLAC__byte)xx; xx >>= 8;
  104179. xx = encoder->private_->seek_table->points[i].stream_offset;
  104180. b[15] = (FLAC__byte)xx; xx >>= 8;
  104181. b[14] = (FLAC__byte)xx; xx >>= 8;
  104182. b[13] = (FLAC__byte)xx; xx >>= 8;
  104183. b[12] = (FLAC__byte)xx; xx >>= 8;
  104184. b[11] = (FLAC__byte)xx; xx >>= 8;
  104185. b[10] = (FLAC__byte)xx; xx >>= 8;
  104186. b[9] = (FLAC__byte)xx; xx >>= 8;
  104187. b[8] = (FLAC__byte)xx; xx >>= 8;
  104188. x = encoder->private_->seek_table->points[i].frame_samples;
  104189. b[17] = (FLAC__byte)x; x >>= 8;
  104190. b[16] = (FLAC__byte)x; x >>= 8;
  104191. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104192. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104193. return;
  104194. }
  104195. }
  104196. }
  104197. }
  104198. #if FLAC__HAS_OGG
  104199. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104200. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104201. {
  104202. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104203. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104204. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104205. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104206. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104207. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104208. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104209. FLAC__STREAM_SYNC_LENGTH
  104210. ;
  104211. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104212. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104213. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104214. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104215. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104216. ogg_page page;
  104217. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104218. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104219. /* Pre-check that client supports seeking, since we don't want the
  104220. * ogg_helper code to ever have to deal with this condition.
  104221. */
  104222. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104223. return;
  104224. /* All this is based on intimate knowledge of the stream header
  104225. * layout, but a change to the header format that would break this
  104226. * would also break all streams encoded in the previous format.
  104227. */
  104228. /**
  104229. ** Write STREAMINFO stats
  104230. **/
  104231. simple_ogg_page__init(&page);
  104232. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104233. simple_ogg_page__clear(&page);
  104234. return; /* state already set */
  104235. }
  104236. /*
  104237. * Write MD5 signature
  104238. */
  104239. {
  104240. const unsigned md5_offset =
  104241. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104242. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104243. (
  104244. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104245. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104246. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104247. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104248. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104249. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104250. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104251. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104252. ) / 8;
  104253. if(md5_offset + 16 > (unsigned)page.body_len) {
  104254. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104255. simple_ogg_page__clear(&page);
  104256. return;
  104257. }
  104258. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104259. }
  104260. /*
  104261. * Write total samples
  104262. */
  104263. {
  104264. const unsigned total_samples_byte_offset =
  104265. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104266. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104267. (
  104268. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104269. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104270. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104271. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104272. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104273. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104274. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104275. - 4
  104276. ) / 8;
  104277. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104278. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104279. simple_ogg_page__clear(&page);
  104280. return;
  104281. }
  104282. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104283. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104284. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104285. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104286. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104287. b[4] = (FLAC__byte)(samples & 0xFF);
  104288. memcpy(page.body + total_samples_byte_offset, b, 5);
  104289. }
  104290. /*
  104291. * Write min/max framesize
  104292. */
  104293. {
  104294. const unsigned min_framesize_offset =
  104295. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104296. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104297. (
  104298. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104299. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104300. ) / 8;
  104301. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104302. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104303. simple_ogg_page__clear(&page);
  104304. return;
  104305. }
  104306. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104307. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104308. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104309. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104310. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104311. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104312. memcpy(page.body + min_framesize_offset, b, 6);
  104313. }
  104314. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104315. simple_ogg_page__clear(&page);
  104316. return; /* state already set */
  104317. }
  104318. simple_ogg_page__clear(&page);
  104319. /*
  104320. * Write seektable
  104321. */
  104322. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104323. unsigned i;
  104324. FLAC__byte *p;
  104325. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104326. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104327. simple_ogg_page__init(&page);
  104328. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104329. simple_ogg_page__clear(&page);
  104330. return; /* state already set */
  104331. }
  104332. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104333. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104334. simple_ogg_page__clear(&page);
  104335. return;
  104336. }
  104337. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104338. FLAC__uint64 xx;
  104339. unsigned x;
  104340. xx = encoder->private_->seek_table->points[i].sample_number;
  104341. b[7] = (FLAC__byte)xx; xx >>= 8;
  104342. b[6] = (FLAC__byte)xx; xx >>= 8;
  104343. b[5] = (FLAC__byte)xx; xx >>= 8;
  104344. b[4] = (FLAC__byte)xx; xx >>= 8;
  104345. b[3] = (FLAC__byte)xx; xx >>= 8;
  104346. b[2] = (FLAC__byte)xx; xx >>= 8;
  104347. b[1] = (FLAC__byte)xx; xx >>= 8;
  104348. b[0] = (FLAC__byte)xx; xx >>= 8;
  104349. xx = encoder->private_->seek_table->points[i].stream_offset;
  104350. b[15] = (FLAC__byte)xx; xx >>= 8;
  104351. b[14] = (FLAC__byte)xx; xx >>= 8;
  104352. b[13] = (FLAC__byte)xx; xx >>= 8;
  104353. b[12] = (FLAC__byte)xx; xx >>= 8;
  104354. b[11] = (FLAC__byte)xx; xx >>= 8;
  104355. b[10] = (FLAC__byte)xx; xx >>= 8;
  104356. b[9] = (FLAC__byte)xx; xx >>= 8;
  104357. b[8] = (FLAC__byte)xx; xx >>= 8;
  104358. x = encoder->private_->seek_table->points[i].frame_samples;
  104359. b[17] = (FLAC__byte)x; x >>= 8;
  104360. b[16] = (FLAC__byte)x; x >>= 8;
  104361. memcpy(p, b, 18);
  104362. }
  104363. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104364. simple_ogg_page__clear(&page);
  104365. return; /* state already set */
  104366. }
  104367. simple_ogg_page__clear(&page);
  104368. }
  104369. }
  104370. #endif
  104371. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104372. {
  104373. FLAC__uint16 crc;
  104374. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104375. /*
  104376. * Accumulate raw signal to the MD5 signature
  104377. */
  104378. 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)) {
  104379. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104380. return false;
  104381. }
  104382. /*
  104383. * Process the frame header and subframes into the frame bitbuffer
  104384. */
  104385. if(!process_subframes_(encoder, is_fractional_block)) {
  104386. /* the above function sets the state for us in case of an error */
  104387. return false;
  104388. }
  104389. /*
  104390. * Zero-pad the frame to a byte_boundary
  104391. */
  104392. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104393. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104394. return false;
  104395. }
  104396. /*
  104397. * CRC-16 the whole thing
  104398. */
  104399. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104400. if(
  104401. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104402. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104403. ) {
  104404. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104405. return false;
  104406. }
  104407. /*
  104408. * Write it
  104409. */
  104410. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104411. /* the above function sets the state for us in case of an error */
  104412. return false;
  104413. }
  104414. /*
  104415. * Get ready for the next frame
  104416. */
  104417. encoder->private_->current_sample_number = 0;
  104418. encoder->private_->current_frame_number++;
  104419. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104420. return true;
  104421. }
  104422. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104423. {
  104424. FLAC__FrameHeader frame_header;
  104425. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104426. FLAC__bool do_independent, do_mid_side;
  104427. /*
  104428. * Calculate the min,max Rice partition orders
  104429. */
  104430. if(is_fractional_block) {
  104431. max_partition_order = 0;
  104432. }
  104433. else {
  104434. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104435. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104436. }
  104437. min_partition_order = min(min_partition_order, max_partition_order);
  104438. /*
  104439. * Setup the frame
  104440. */
  104441. frame_header.blocksize = encoder->protected_->blocksize;
  104442. frame_header.sample_rate = encoder->protected_->sample_rate;
  104443. frame_header.channels = encoder->protected_->channels;
  104444. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104445. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104446. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104447. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104448. /*
  104449. * Figure out what channel assignments to try
  104450. */
  104451. if(encoder->protected_->do_mid_side_stereo) {
  104452. if(encoder->protected_->loose_mid_side_stereo) {
  104453. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104454. do_independent = true;
  104455. do_mid_side = true;
  104456. }
  104457. else {
  104458. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104459. do_mid_side = !do_independent;
  104460. }
  104461. }
  104462. else {
  104463. do_independent = true;
  104464. do_mid_side = true;
  104465. }
  104466. }
  104467. else {
  104468. do_independent = true;
  104469. do_mid_side = false;
  104470. }
  104471. FLAC__ASSERT(do_independent || do_mid_side);
  104472. /*
  104473. * Check for wasted bits; set effective bps for each subframe
  104474. */
  104475. if(do_independent) {
  104476. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104477. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104478. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104479. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104480. }
  104481. }
  104482. if(do_mid_side) {
  104483. FLAC__ASSERT(encoder->protected_->channels == 2);
  104484. for(channel = 0; channel < 2; channel++) {
  104485. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104486. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104487. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104488. }
  104489. }
  104490. /*
  104491. * First do a normal encoding pass of each independent channel
  104492. */
  104493. if(do_independent) {
  104494. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104495. if(!
  104496. process_subframe_(
  104497. encoder,
  104498. min_partition_order,
  104499. max_partition_order,
  104500. &frame_header,
  104501. encoder->private_->subframe_bps[channel],
  104502. encoder->private_->integer_signal[channel],
  104503. encoder->private_->subframe_workspace_ptr[channel],
  104504. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104505. encoder->private_->residual_workspace[channel],
  104506. encoder->private_->best_subframe+channel,
  104507. encoder->private_->best_subframe_bits+channel
  104508. )
  104509. )
  104510. return false;
  104511. }
  104512. }
  104513. /*
  104514. * Now do mid and side channels if requested
  104515. */
  104516. if(do_mid_side) {
  104517. FLAC__ASSERT(encoder->protected_->channels == 2);
  104518. for(channel = 0; channel < 2; channel++) {
  104519. if(!
  104520. process_subframe_(
  104521. encoder,
  104522. min_partition_order,
  104523. max_partition_order,
  104524. &frame_header,
  104525. encoder->private_->subframe_bps_mid_side[channel],
  104526. encoder->private_->integer_signal_mid_side[channel],
  104527. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104528. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104529. encoder->private_->residual_workspace_mid_side[channel],
  104530. encoder->private_->best_subframe_mid_side+channel,
  104531. encoder->private_->best_subframe_bits_mid_side+channel
  104532. )
  104533. )
  104534. return false;
  104535. }
  104536. }
  104537. /*
  104538. * Compose the frame bitbuffer
  104539. */
  104540. if(do_mid_side) {
  104541. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104542. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104543. FLAC__ChannelAssignment channel_assignment;
  104544. FLAC__ASSERT(encoder->protected_->channels == 2);
  104545. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104546. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104547. }
  104548. else {
  104549. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104550. unsigned min_bits;
  104551. int ca;
  104552. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104553. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104554. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104555. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104556. FLAC__ASSERT(do_independent && do_mid_side);
  104557. /* We have to figure out which channel assignent results in the smallest frame */
  104558. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104559. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104560. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104561. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104562. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104563. min_bits = bits[channel_assignment];
  104564. for(ca = 1; ca <= 3; ca++) {
  104565. if(bits[ca] < min_bits) {
  104566. min_bits = bits[ca];
  104567. channel_assignment = (FLAC__ChannelAssignment)ca;
  104568. }
  104569. }
  104570. }
  104571. frame_header.channel_assignment = channel_assignment;
  104572. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104573. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104574. return false;
  104575. }
  104576. switch(channel_assignment) {
  104577. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104578. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104579. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104580. break;
  104581. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104582. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104583. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104584. break;
  104585. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104586. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104587. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104588. break;
  104589. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104590. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104591. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104592. break;
  104593. default:
  104594. FLAC__ASSERT(0);
  104595. }
  104596. switch(channel_assignment) {
  104597. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104598. left_bps = encoder->private_->subframe_bps [0];
  104599. right_bps = encoder->private_->subframe_bps [1];
  104600. break;
  104601. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104602. left_bps = encoder->private_->subframe_bps [0];
  104603. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104604. break;
  104605. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104606. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104607. right_bps = encoder->private_->subframe_bps [1];
  104608. break;
  104609. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104610. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104611. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104612. break;
  104613. default:
  104614. FLAC__ASSERT(0);
  104615. }
  104616. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104617. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104618. return false;
  104619. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104620. return false;
  104621. }
  104622. else {
  104623. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104624. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104625. return false;
  104626. }
  104627. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104628. 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)) {
  104629. /* the above function sets the state for us in case of an error */
  104630. return false;
  104631. }
  104632. }
  104633. }
  104634. if(encoder->protected_->loose_mid_side_stereo) {
  104635. encoder->private_->loose_mid_side_stereo_frame_count++;
  104636. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104637. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104638. }
  104639. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104640. return true;
  104641. }
  104642. FLAC__bool process_subframe_(
  104643. FLAC__StreamEncoder *encoder,
  104644. unsigned min_partition_order,
  104645. unsigned max_partition_order,
  104646. const FLAC__FrameHeader *frame_header,
  104647. unsigned subframe_bps,
  104648. const FLAC__int32 integer_signal[],
  104649. FLAC__Subframe *subframe[2],
  104650. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104651. FLAC__int32 *residual[2],
  104652. unsigned *best_subframe,
  104653. unsigned *best_bits
  104654. )
  104655. {
  104656. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104657. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104658. #else
  104659. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104660. #endif
  104661. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104662. FLAC__double lpc_residual_bits_per_sample;
  104663. 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 */
  104664. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104665. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104666. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104667. #endif
  104668. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104669. unsigned rice_parameter;
  104670. unsigned _candidate_bits, _best_bits;
  104671. unsigned _best_subframe;
  104672. /* only use RICE2 partitions if stream bps > 16 */
  104673. 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;
  104674. FLAC__ASSERT(frame_header->blocksize > 0);
  104675. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104676. _best_subframe = 0;
  104677. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104678. _best_bits = UINT_MAX;
  104679. else
  104680. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104681. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104682. unsigned signal_is_constant = false;
  104683. 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);
  104684. /* check for constant subframe */
  104685. if(
  104686. !encoder->private_->disable_constant_subframes &&
  104687. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104688. fixed_residual_bits_per_sample[1] == 0.0
  104689. #else
  104690. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104691. #endif
  104692. ) {
  104693. /* the above means it's possible all samples are the same value; now double-check it: */
  104694. unsigned i;
  104695. signal_is_constant = true;
  104696. for(i = 1; i < frame_header->blocksize; i++) {
  104697. if(integer_signal[0] != integer_signal[i]) {
  104698. signal_is_constant = false;
  104699. break;
  104700. }
  104701. }
  104702. }
  104703. if(signal_is_constant) {
  104704. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104705. if(_candidate_bits < _best_bits) {
  104706. _best_subframe = !_best_subframe;
  104707. _best_bits = _candidate_bits;
  104708. }
  104709. }
  104710. else {
  104711. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104712. /* encode fixed */
  104713. if(encoder->protected_->do_exhaustive_model_search) {
  104714. min_fixed_order = 0;
  104715. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104716. }
  104717. else {
  104718. min_fixed_order = max_fixed_order = guess_fixed_order;
  104719. }
  104720. if(max_fixed_order >= frame_header->blocksize)
  104721. max_fixed_order = frame_header->blocksize - 1;
  104722. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104723. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104724. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104725. continue; /* don't even try */
  104726. 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 */
  104727. #else
  104728. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104729. continue; /* don't even try */
  104730. 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 */
  104731. #endif
  104732. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104733. if(rice_parameter >= rice_parameter_limit) {
  104734. #ifdef DEBUG_VERBOSE
  104735. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104736. #endif
  104737. rice_parameter = rice_parameter_limit - 1;
  104738. }
  104739. _candidate_bits =
  104740. evaluate_fixed_subframe_(
  104741. encoder,
  104742. integer_signal,
  104743. residual[!_best_subframe],
  104744. encoder->private_->abs_residual_partition_sums,
  104745. encoder->private_->raw_bits_per_partition,
  104746. frame_header->blocksize,
  104747. subframe_bps,
  104748. fixed_order,
  104749. rice_parameter,
  104750. rice_parameter_limit,
  104751. min_partition_order,
  104752. max_partition_order,
  104753. encoder->protected_->do_escape_coding,
  104754. encoder->protected_->rice_parameter_search_dist,
  104755. subframe[!_best_subframe],
  104756. partitioned_rice_contents[!_best_subframe]
  104757. );
  104758. if(_candidate_bits < _best_bits) {
  104759. _best_subframe = !_best_subframe;
  104760. _best_bits = _candidate_bits;
  104761. }
  104762. }
  104763. }
  104764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104765. /* encode lpc */
  104766. if(encoder->protected_->max_lpc_order > 0) {
  104767. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104768. max_lpc_order = frame_header->blocksize-1;
  104769. else
  104770. max_lpc_order = encoder->protected_->max_lpc_order;
  104771. if(max_lpc_order > 0) {
  104772. unsigned a;
  104773. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104774. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104775. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104776. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104777. if(autoc[0] != 0.0) {
  104778. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104779. if(encoder->protected_->do_exhaustive_model_search) {
  104780. min_lpc_order = 1;
  104781. }
  104782. else {
  104783. const unsigned guess_lpc_order =
  104784. FLAC__lpc_compute_best_order(
  104785. lpc_error,
  104786. max_lpc_order,
  104787. frame_header->blocksize,
  104788. subframe_bps + (
  104789. encoder->protected_->do_qlp_coeff_prec_search?
  104790. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104791. encoder->protected_->qlp_coeff_precision
  104792. )
  104793. );
  104794. min_lpc_order = max_lpc_order = guess_lpc_order;
  104795. }
  104796. if(max_lpc_order >= frame_header->blocksize)
  104797. max_lpc_order = frame_header->blocksize - 1;
  104798. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104799. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104800. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104801. continue; /* don't even try */
  104802. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104803. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104804. if(rice_parameter >= rice_parameter_limit) {
  104805. #ifdef DEBUG_VERBOSE
  104806. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104807. #endif
  104808. rice_parameter = rice_parameter_limit - 1;
  104809. }
  104810. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104811. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104812. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104813. if(subframe_bps <= 17) {
  104814. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104815. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104816. }
  104817. else
  104818. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104819. }
  104820. else {
  104821. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104822. }
  104823. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104824. _candidate_bits =
  104825. evaluate_lpc_subframe_(
  104826. encoder,
  104827. integer_signal,
  104828. residual[!_best_subframe],
  104829. encoder->private_->abs_residual_partition_sums,
  104830. encoder->private_->raw_bits_per_partition,
  104831. encoder->private_->lp_coeff[lpc_order-1],
  104832. frame_header->blocksize,
  104833. subframe_bps,
  104834. lpc_order,
  104835. qlp_coeff_precision,
  104836. rice_parameter,
  104837. rice_parameter_limit,
  104838. min_partition_order,
  104839. max_partition_order,
  104840. encoder->protected_->do_escape_coding,
  104841. encoder->protected_->rice_parameter_search_dist,
  104842. subframe[!_best_subframe],
  104843. partitioned_rice_contents[!_best_subframe]
  104844. );
  104845. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104846. if(_candidate_bits < _best_bits) {
  104847. _best_subframe = !_best_subframe;
  104848. _best_bits = _candidate_bits;
  104849. }
  104850. }
  104851. }
  104852. }
  104853. }
  104854. }
  104855. }
  104856. }
  104857. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104858. }
  104859. }
  104860. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104861. if(_best_bits == UINT_MAX) {
  104862. FLAC__ASSERT(_best_subframe == 0);
  104863. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104864. }
  104865. *best_subframe = _best_subframe;
  104866. *best_bits = _best_bits;
  104867. return true;
  104868. }
  104869. FLAC__bool add_subframe_(
  104870. FLAC__StreamEncoder *encoder,
  104871. unsigned blocksize,
  104872. unsigned subframe_bps,
  104873. const FLAC__Subframe *subframe,
  104874. FLAC__BitWriter *frame
  104875. )
  104876. {
  104877. switch(subframe->type) {
  104878. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104879. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104880. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104881. return false;
  104882. }
  104883. break;
  104884. case FLAC__SUBFRAME_TYPE_FIXED:
  104885. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104886. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104887. return false;
  104888. }
  104889. break;
  104890. case FLAC__SUBFRAME_TYPE_LPC:
  104891. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104892. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104893. return false;
  104894. }
  104895. break;
  104896. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104897. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104898. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104899. return false;
  104900. }
  104901. break;
  104902. default:
  104903. FLAC__ASSERT(0);
  104904. }
  104905. return true;
  104906. }
  104907. #define SPOTCHECK_ESTIMATE 0
  104908. #if SPOTCHECK_ESTIMATE
  104909. static void spotcheck_subframe_estimate_(
  104910. FLAC__StreamEncoder *encoder,
  104911. unsigned blocksize,
  104912. unsigned subframe_bps,
  104913. const FLAC__Subframe *subframe,
  104914. unsigned estimate
  104915. )
  104916. {
  104917. FLAC__bool ret;
  104918. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104919. if(frame == 0) {
  104920. fprintf(stderr, "EST: can't allocate frame\n");
  104921. return;
  104922. }
  104923. if(!FLAC__bitwriter_init(frame)) {
  104924. fprintf(stderr, "EST: can't init frame\n");
  104925. return;
  104926. }
  104927. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104928. FLAC__ASSERT(ret);
  104929. {
  104930. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104931. if(estimate != actual)
  104932. 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);
  104933. }
  104934. FLAC__bitwriter_delete(frame);
  104935. }
  104936. #endif
  104937. unsigned evaluate_constant_subframe_(
  104938. FLAC__StreamEncoder *encoder,
  104939. const FLAC__int32 signal,
  104940. unsigned blocksize,
  104941. unsigned subframe_bps,
  104942. FLAC__Subframe *subframe
  104943. )
  104944. {
  104945. unsigned estimate;
  104946. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104947. subframe->data.constant.value = signal;
  104948. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104949. #if SPOTCHECK_ESTIMATE
  104950. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104951. #else
  104952. (void)encoder, (void)blocksize;
  104953. #endif
  104954. return estimate;
  104955. }
  104956. unsigned evaluate_fixed_subframe_(
  104957. FLAC__StreamEncoder *encoder,
  104958. const FLAC__int32 signal[],
  104959. FLAC__int32 residual[],
  104960. FLAC__uint64 abs_residual_partition_sums[],
  104961. unsigned raw_bits_per_partition[],
  104962. unsigned blocksize,
  104963. unsigned subframe_bps,
  104964. unsigned order,
  104965. unsigned rice_parameter,
  104966. unsigned rice_parameter_limit,
  104967. unsigned min_partition_order,
  104968. unsigned max_partition_order,
  104969. FLAC__bool do_escape_coding,
  104970. unsigned rice_parameter_search_dist,
  104971. FLAC__Subframe *subframe,
  104972. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104973. )
  104974. {
  104975. unsigned i, residual_bits, estimate;
  104976. const unsigned residual_samples = blocksize - order;
  104977. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104978. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104979. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104980. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104981. subframe->data.fixed.residual = residual;
  104982. residual_bits =
  104983. find_best_partition_order_(
  104984. encoder->private_,
  104985. residual,
  104986. abs_residual_partition_sums,
  104987. raw_bits_per_partition,
  104988. residual_samples,
  104989. order,
  104990. rice_parameter,
  104991. rice_parameter_limit,
  104992. min_partition_order,
  104993. max_partition_order,
  104994. subframe_bps,
  104995. do_escape_coding,
  104996. rice_parameter_search_dist,
  104997. &subframe->data.fixed.entropy_coding_method
  104998. );
  104999. subframe->data.fixed.order = order;
  105000. for(i = 0; i < order; i++)
  105001. subframe->data.fixed.warmup[i] = signal[i];
  105002. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105003. #if SPOTCHECK_ESTIMATE
  105004. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105005. #endif
  105006. return estimate;
  105007. }
  105008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105009. unsigned evaluate_lpc_subframe_(
  105010. FLAC__StreamEncoder *encoder,
  105011. const FLAC__int32 signal[],
  105012. FLAC__int32 residual[],
  105013. FLAC__uint64 abs_residual_partition_sums[],
  105014. unsigned raw_bits_per_partition[],
  105015. const FLAC__real lp_coeff[],
  105016. unsigned blocksize,
  105017. unsigned subframe_bps,
  105018. unsigned order,
  105019. unsigned qlp_coeff_precision,
  105020. unsigned rice_parameter,
  105021. unsigned rice_parameter_limit,
  105022. unsigned min_partition_order,
  105023. unsigned max_partition_order,
  105024. FLAC__bool do_escape_coding,
  105025. unsigned rice_parameter_search_dist,
  105026. FLAC__Subframe *subframe,
  105027. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105028. )
  105029. {
  105030. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105031. unsigned i, residual_bits, estimate;
  105032. int quantization, ret;
  105033. const unsigned residual_samples = blocksize - order;
  105034. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105035. if(subframe_bps <= 16) {
  105036. FLAC__ASSERT(order > 0);
  105037. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105038. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105039. }
  105040. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105041. if(ret != 0)
  105042. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105043. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105044. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105045. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105046. else
  105047. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105048. else
  105049. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105050. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105051. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105052. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105053. subframe->data.lpc.residual = residual;
  105054. residual_bits =
  105055. find_best_partition_order_(
  105056. encoder->private_,
  105057. residual,
  105058. abs_residual_partition_sums,
  105059. raw_bits_per_partition,
  105060. residual_samples,
  105061. order,
  105062. rice_parameter,
  105063. rice_parameter_limit,
  105064. min_partition_order,
  105065. max_partition_order,
  105066. subframe_bps,
  105067. do_escape_coding,
  105068. rice_parameter_search_dist,
  105069. &subframe->data.lpc.entropy_coding_method
  105070. );
  105071. subframe->data.lpc.order = order;
  105072. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105073. subframe->data.lpc.quantization_level = quantization;
  105074. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105075. for(i = 0; i < order; i++)
  105076. subframe->data.lpc.warmup[i] = signal[i];
  105077. 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;
  105078. #if SPOTCHECK_ESTIMATE
  105079. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105080. #endif
  105081. return estimate;
  105082. }
  105083. #endif
  105084. unsigned evaluate_verbatim_subframe_(
  105085. FLAC__StreamEncoder *encoder,
  105086. const FLAC__int32 signal[],
  105087. unsigned blocksize,
  105088. unsigned subframe_bps,
  105089. FLAC__Subframe *subframe
  105090. )
  105091. {
  105092. unsigned estimate;
  105093. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105094. subframe->data.verbatim.data = signal;
  105095. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105096. #if SPOTCHECK_ESTIMATE
  105097. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105098. #else
  105099. (void)encoder;
  105100. #endif
  105101. return estimate;
  105102. }
  105103. unsigned find_best_partition_order_(
  105104. FLAC__StreamEncoderPrivate *private_,
  105105. const FLAC__int32 residual[],
  105106. FLAC__uint64 abs_residual_partition_sums[],
  105107. unsigned raw_bits_per_partition[],
  105108. unsigned residual_samples,
  105109. unsigned predictor_order,
  105110. unsigned rice_parameter,
  105111. unsigned rice_parameter_limit,
  105112. unsigned min_partition_order,
  105113. unsigned max_partition_order,
  105114. unsigned bps,
  105115. FLAC__bool do_escape_coding,
  105116. unsigned rice_parameter_search_dist,
  105117. FLAC__EntropyCodingMethod *best_ecm
  105118. )
  105119. {
  105120. unsigned residual_bits, best_residual_bits = 0;
  105121. unsigned best_parameters_index = 0;
  105122. unsigned best_partition_order = 0;
  105123. const unsigned blocksize = residual_samples + predictor_order;
  105124. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105125. min_partition_order = min(min_partition_order, max_partition_order);
  105126. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105127. if(do_escape_coding)
  105128. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105129. {
  105130. int partition_order;
  105131. unsigned sum;
  105132. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105133. if(!
  105134. set_partitioned_rice_(
  105135. #ifdef EXACT_RICE_BITS_CALCULATION
  105136. residual,
  105137. #endif
  105138. abs_residual_partition_sums+sum,
  105139. raw_bits_per_partition+sum,
  105140. residual_samples,
  105141. predictor_order,
  105142. rice_parameter,
  105143. rice_parameter_limit,
  105144. rice_parameter_search_dist,
  105145. (unsigned)partition_order,
  105146. do_escape_coding,
  105147. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105148. &residual_bits
  105149. )
  105150. )
  105151. {
  105152. FLAC__ASSERT(best_residual_bits != 0);
  105153. break;
  105154. }
  105155. sum += 1u << partition_order;
  105156. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105157. best_residual_bits = residual_bits;
  105158. best_parameters_index = !best_parameters_index;
  105159. best_partition_order = partition_order;
  105160. }
  105161. }
  105162. }
  105163. best_ecm->data.partitioned_rice.order = best_partition_order;
  105164. {
  105165. /*
  105166. * We are allowed to de-const the pointer based on our special
  105167. * knowledge; it is const to the outside world.
  105168. */
  105169. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105170. unsigned partition;
  105171. /* save best parameters and raw_bits */
  105172. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105173. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105174. if(do_escape_coding)
  105175. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105176. /*
  105177. * Now need to check if the type should be changed to
  105178. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105179. * size of the rice parameters.
  105180. */
  105181. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105182. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105183. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105184. break;
  105185. }
  105186. }
  105187. }
  105188. return best_residual_bits;
  105189. }
  105190. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105191. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105192. const FLAC__int32 residual[],
  105193. FLAC__uint64 abs_residual_partition_sums[],
  105194. unsigned blocksize,
  105195. unsigned predictor_order,
  105196. unsigned min_partition_order,
  105197. unsigned max_partition_order
  105198. );
  105199. #endif
  105200. void precompute_partition_info_sums_(
  105201. const FLAC__int32 residual[],
  105202. FLAC__uint64 abs_residual_partition_sums[],
  105203. unsigned residual_samples,
  105204. unsigned predictor_order,
  105205. unsigned min_partition_order,
  105206. unsigned max_partition_order,
  105207. unsigned bps
  105208. )
  105209. {
  105210. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105211. unsigned partitions = 1u << max_partition_order;
  105212. FLAC__ASSERT(default_partition_samples > predictor_order);
  105213. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105214. /* slightly pessimistic but still catches all common cases */
  105215. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105216. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105217. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105218. return;
  105219. }
  105220. #endif
  105221. /* first do max_partition_order */
  105222. {
  105223. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105224. /* slightly pessimistic but still catches all common cases */
  105225. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105226. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105227. FLAC__uint32 abs_residual_partition_sum;
  105228. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105229. end += default_partition_samples;
  105230. abs_residual_partition_sum = 0;
  105231. for( ; residual_sample < end; residual_sample++)
  105232. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105233. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105234. }
  105235. }
  105236. else { /* have to pessimistically use 64 bits for accumulator */
  105237. FLAC__uint64 abs_residual_partition_sum;
  105238. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105239. end += default_partition_samples;
  105240. abs_residual_partition_sum = 0;
  105241. for( ; residual_sample < end; residual_sample++)
  105242. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105243. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105244. }
  105245. }
  105246. }
  105247. /* now merge partitions for lower orders */
  105248. {
  105249. unsigned from_partition = 0, to_partition = partitions;
  105250. int partition_order;
  105251. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105252. unsigned i;
  105253. partitions >>= 1;
  105254. for(i = 0; i < partitions; i++) {
  105255. abs_residual_partition_sums[to_partition++] =
  105256. abs_residual_partition_sums[from_partition ] +
  105257. abs_residual_partition_sums[from_partition+1];
  105258. from_partition += 2;
  105259. }
  105260. }
  105261. }
  105262. }
  105263. void precompute_partition_info_escapes_(
  105264. const FLAC__int32 residual[],
  105265. unsigned raw_bits_per_partition[],
  105266. unsigned residual_samples,
  105267. unsigned predictor_order,
  105268. unsigned min_partition_order,
  105269. unsigned max_partition_order
  105270. )
  105271. {
  105272. int partition_order;
  105273. unsigned from_partition, to_partition = 0;
  105274. const unsigned blocksize = residual_samples + predictor_order;
  105275. /* first do max_partition_order */
  105276. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105277. FLAC__int32 r;
  105278. FLAC__uint32 rmax;
  105279. unsigned partition, partition_sample, partition_samples, residual_sample;
  105280. const unsigned partitions = 1u << partition_order;
  105281. const unsigned default_partition_samples = blocksize >> partition_order;
  105282. FLAC__ASSERT(default_partition_samples > predictor_order);
  105283. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105284. partition_samples = default_partition_samples;
  105285. if(partition == 0)
  105286. partition_samples -= predictor_order;
  105287. rmax = 0;
  105288. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105289. r = residual[residual_sample++];
  105290. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105291. if(r < 0)
  105292. rmax |= ~r;
  105293. else
  105294. rmax |= r;
  105295. }
  105296. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105297. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105298. }
  105299. to_partition = partitions;
  105300. break; /*@@@ yuck, should remove the 'for' loop instead */
  105301. }
  105302. /* now merge partitions for lower orders */
  105303. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105304. unsigned m;
  105305. unsigned i;
  105306. const unsigned partitions = 1u << partition_order;
  105307. for(i = 0; i < partitions; i++) {
  105308. m = raw_bits_per_partition[from_partition];
  105309. from_partition++;
  105310. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105311. from_partition++;
  105312. to_partition++;
  105313. }
  105314. }
  105315. }
  105316. #ifdef EXACT_RICE_BITS_CALCULATION
  105317. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105318. const unsigned rice_parameter,
  105319. const unsigned partition_samples,
  105320. const FLAC__int32 *residual
  105321. )
  105322. {
  105323. unsigned i, partition_bits =
  105324. 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 */
  105325. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105326. ;
  105327. for(i = 0; i < partition_samples; i++)
  105328. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105329. return partition_bits;
  105330. }
  105331. #else
  105332. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105333. const unsigned rice_parameter,
  105334. const unsigned partition_samples,
  105335. const FLAC__uint64 abs_residual_partition_sum
  105336. )
  105337. {
  105338. return
  105339. 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 */
  105340. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105341. (
  105342. rice_parameter?
  105343. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105344. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105345. )
  105346. - (partition_samples >> 1)
  105347. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105348. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105349. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105350. * So the subtraction term tries to guess how many extra bits were contributed.
  105351. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105352. */
  105353. ;
  105354. }
  105355. #endif
  105356. FLAC__bool set_partitioned_rice_(
  105357. #ifdef EXACT_RICE_BITS_CALCULATION
  105358. const FLAC__int32 residual[],
  105359. #endif
  105360. const FLAC__uint64 abs_residual_partition_sums[],
  105361. const unsigned raw_bits_per_partition[],
  105362. const unsigned residual_samples,
  105363. const unsigned predictor_order,
  105364. const unsigned suggested_rice_parameter,
  105365. const unsigned rice_parameter_limit,
  105366. const unsigned rice_parameter_search_dist,
  105367. const unsigned partition_order,
  105368. const FLAC__bool search_for_escapes,
  105369. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105370. unsigned *bits
  105371. )
  105372. {
  105373. unsigned rice_parameter, partition_bits;
  105374. unsigned best_partition_bits, best_rice_parameter = 0;
  105375. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105376. unsigned *parameters, *raw_bits;
  105377. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105378. unsigned min_rice_parameter, max_rice_parameter;
  105379. #else
  105380. (void)rice_parameter_search_dist;
  105381. #endif
  105382. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105383. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105384. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105385. parameters = partitioned_rice_contents->parameters;
  105386. raw_bits = partitioned_rice_contents->raw_bits;
  105387. if(partition_order == 0) {
  105388. best_partition_bits = (unsigned)(-1);
  105389. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105390. if(rice_parameter_search_dist) {
  105391. if(suggested_rice_parameter < rice_parameter_search_dist)
  105392. min_rice_parameter = 0;
  105393. else
  105394. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105395. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105396. if(max_rice_parameter >= rice_parameter_limit) {
  105397. #ifdef DEBUG_VERBOSE
  105398. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105399. #endif
  105400. max_rice_parameter = rice_parameter_limit - 1;
  105401. }
  105402. }
  105403. else
  105404. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105405. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105406. #else
  105407. rice_parameter = suggested_rice_parameter;
  105408. #endif
  105409. #ifdef EXACT_RICE_BITS_CALCULATION
  105410. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105411. #else
  105412. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105413. #endif
  105414. if(partition_bits < best_partition_bits) {
  105415. best_rice_parameter = rice_parameter;
  105416. best_partition_bits = partition_bits;
  105417. }
  105418. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105419. }
  105420. #endif
  105421. if(search_for_escapes) {
  105422. 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;
  105423. if(partition_bits <= best_partition_bits) {
  105424. raw_bits[0] = raw_bits_per_partition[0];
  105425. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105426. best_partition_bits = partition_bits;
  105427. }
  105428. else
  105429. raw_bits[0] = 0;
  105430. }
  105431. parameters[0] = best_rice_parameter;
  105432. bits_ += best_partition_bits;
  105433. }
  105434. else {
  105435. unsigned partition, residual_sample;
  105436. unsigned partition_samples;
  105437. FLAC__uint64 mean, k;
  105438. const unsigned partitions = 1u << partition_order;
  105439. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105440. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105441. if(partition == 0) {
  105442. if(partition_samples <= predictor_order)
  105443. return false;
  105444. else
  105445. partition_samples -= predictor_order;
  105446. }
  105447. mean = abs_residual_partition_sums[partition];
  105448. /* we are basically calculating the size in bits of the
  105449. * average residual magnitude in the partition:
  105450. * rice_parameter = floor(log2(mean/partition_samples))
  105451. * 'mean' is not a good name for the variable, it is
  105452. * actually the sum of magnitudes of all residual values
  105453. * in the partition, so the actual mean is
  105454. * mean/partition_samples
  105455. */
  105456. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105457. ;
  105458. if(rice_parameter >= rice_parameter_limit) {
  105459. #ifdef DEBUG_VERBOSE
  105460. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105461. #endif
  105462. rice_parameter = rice_parameter_limit - 1;
  105463. }
  105464. best_partition_bits = (unsigned)(-1);
  105465. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105466. if(rice_parameter_search_dist) {
  105467. if(rice_parameter < rice_parameter_search_dist)
  105468. min_rice_parameter = 0;
  105469. else
  105470. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105471. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105472. if(max_rice_parameter >= rice_parameter_limit) {
  105473. #ifdef DEBUG_VERBOSE
  105474. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105475. #endif
  105476. max_rice_parameter = rice_parameter_limit - 1;
  105477. }
  105478. }
  105479. else
  105480. min_rice_parameter = max_rice_parameter = rice_parameter;
  105481. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105482. #endif
  105483. #ifdef EXACT_RICE_BITS_CALCULATION
  105484. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105485. #else
  105486. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105487. #endif
  105488. if(partition_bits < best_partition_bits) {
  105489. best_rice_parameter = rice_parameter;
  105490. best_partition_bits = partition_bits;
  105491. }
  105492. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105493. }
  105494. #endif
  105495. if(search_for_escapes) {
  105496. 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;
  105497. if(partition_bits <= best_partition_bits) {
  105498. raw_bits[partition] = raw_bits_per_partition[partition];
  105499. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105500. best_partition_bits = partition_bits;
  105501. }
  105502. else
  105503. raw_bits[partition] = 0;
  105504. }
  105505. parameters[partition] = best_rice_parameter;
  105506. bits_ += best_partition_bits;
  105507. residual_sample += partition_samples;
  105508. }
  105509. }
  105510. *bits = bits_;
  105511. return true;
  105512. }
  105513. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105514. {
  105515. unsigned i, shift;
  105516. FLAC__int32 x = 0;
  105517. for(i = 0; i < samples && !(x&1); i++)
  105518. x |= signal[i];
  105519. if(x == 0) {
  105520. shift = 0;
  105521. }
  105522. else {
  105523. for(shift = 0; !(x&1); shift++)
  105524. x >>= 1;
  105525. }
  105526. if(shift > 0) {
  105527. for(i = 0; i < samples; i++)
  105528. signal[i] >>= shift;
  105529. }
  105530. return shift;
  105531. }
  105532. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105533. {
  105534. unsigned channel;
  105535. for(channel = 0; channel < channels; channel++)
  105536. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105537. fifo->tail += wide_samples;
  105538. FLAC__ASSERT(fifo->tail <= fifo->size);
  105539. }
  105540. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105541. {
  105542. unsigned channel;
  105543. unsigned sample, wide_sample;
  105544. unsigned tail = fifo->tail;
  105545. sample = input_offset * channels;
  105546. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105547. for(channel = 0; channel < channels; channel++)
  105548. fifo->data[channel][tail] = input[sample++];
  105549. tail++;
  105550. }
  105551. fifo->tail = tail;
  105552. FLAC__ASSERT(fifo->tail <= fifo->size);
  105553. }
  105554. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105555. {
  105556. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105557. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105558. (void)decoder;
  105559. if(encoder->private_->verify.needs_magic_hack) {
  105560. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105561. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105562. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105563. encoder->private_->verify.needs_magic_hack = false;
  105564. }
  105565. else {
  105566. if(encoded_bytes == 0) {
  105567. /*
  105568. * If we get here, a FIFO underflow has occurred,
  105569. * which means there is a bug somewhere.
  105570. */
  105571. FLAC__ASSERT(0);
  105572. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105573. }
  105574. else if(encoded_bytes < *bytes)
  105575. *bytes = encoded_bytes;
  105576. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105577. encoder->private_->verify.output.data += *bytes;
  105578. encoder->private_->verify.output.bytes -= *bytes;
  105579. }
  105580. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105581. }
  105582. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105583. {
  105584. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105585. unsigned channel;
  105586. const unsigned channels = frame->header.channels;
  105587. const unsigned blocksize = frame->header.blocksize;
  105588. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105589. (void)decoder;
  105590. for(channel = 0; channel < channels; channel++) {
  105591. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105592. unsigned i, sample = 0;
  105593. FLAC__int32 expect = 0, got = 0;
  105594. for(i = 0; i < blocksize; i++) {
  105595. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105596. sample = i;
  105597. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105598. got = (FLAC__int32)buffer[channel][i];
  105599. break;
  105600. }
  105601. }
  105602. FLAC__ASSERT(i < blocksize);
  105603. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105604. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105605. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105606. encoder->private_->verify.error_stats.channel = channel;
  105607. encoder->private_->verify.error_stats.sample = sample;
  105608. encoder->private_->verify.error_stats.expected = expect;
  105609. encoder->private_->verify.error_stats.got = got;
  105610. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105611. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105612. }
  105613. }
  105614. /* dequeue the frame from the fifo */
  105615. encoder->private_->verify.input_fifo.tail -= blocksize;
  105616. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105617. for(channel = 0; channel < channels; channel++)
  105618. 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]));
  105619. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105620. }
  105621. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105622. {
  105623. (void)decoder, (void)metadata, (void)client_data;
  105624. }
  105625. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105626. {
  105627. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105628. (void)decoder, (void)status;
  105629. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105630. }
  105631. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105632. {
  105633. (void)client_data;
  105634. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105635. if (*bytes == 0) {
  105636. if (feof(encoder->private_->file))
  105637. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105638. else if (ferror(encoder->private_->file))
  105639. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105640. }
  105641. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105642. }
  105643. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105644. {
  105645. (void)client_data;
  105646. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105647. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105648. else
  105649. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105650. }
  105651. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105652. {
  105653. off_t offset;
  105654. (void)client_data;
  105655. offset = ftello(encoder->private_->file);
  105656. if(offset < 0) {
  105657. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105658. }
  105659. else {
  105660. *absolute_byte_offset = (FLAC__uint64)offset;
  105661. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105662. }
  105663. }
  105664. #ifdef FLAC__VALGRIND_TESTING
  105665. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105666. {
  105667. size_t ret = fwrite(ptr, size, nmemb, stream);
  105668. if(!ferror(stream))
  105669. fflush(stream);
  105670. return ret;
  105671. }
  105672. #else
  105673. #define local__fwrite fwrite
  105674. #endif
  105675. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105676. {
  105677. (void)client_data, (void)current_frame;
  105678. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105679. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105680. #if FLAC__HAS_OGG
  105681. /* We would like to be able to use 'samples > 0' in the
  105682. * clause here but currently because of the nature of our
  105683. * Ogg writing implementation, 'samples' is always 0 (see
  105684. * ogg_encoder_aspect.c). The downside is extra progress
  105685. * callbacks.
  105686. */
  105687. encoder->private_->is_ogg? true :
  105688. #endif
  105689. samples > 0
  105690. );
  105691. if(call_it) {
  105692. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105693. * because at this point in the callback chain, the stats
  105694. * have not been updated. Only after we return and control
  105695. * gets back to write_frame_() are the stats updated
  105696. */
  105697. 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);
  105698. }
  105699. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105700. }
  105701. else
  105702. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105703. }
  105704. /*
  105705. * This will forcibly set stdout to binary mode (for OSes that require it)
  105706. */
  105707. FILE *get_binary_stdout_(void)
  105708. {
  105709. /* if something breaks here it is probably due to the presence or
  105710. * absence of an underscore before the identifiers 'setmode',
  105711. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105712. */
  105713. #if defined _MSC_VER || defined __MINGW32__
  105714. _setmode(_fileno(stdout), _O_BINARY);
  105715. #elif defined __CYGWIN__
  105716. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105717. setmode(_fileno(stdout), _O_BINARY);
  105718. #elif defined __EMX__
  105719. setmode(fileno(stdout), O_BINARY);
  105720. #endif
  105721. return stdout;
  105722. }
  105723. #endif
  105724. /*** End of inlined file: stream_encoder.c ***/
  105725. /*** Start of inlined file: stream_encoder_framing.c ***/
  105726. /*** Start of inlined file: juce_FlacHeader.h ***/
  105727. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105728. // tasks..
  105729. #define VERSION "1.2.1"
  105730. #define FLAC__NO_DLL 1
  105731. #if JUCE_MSVC
  105732. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105733. #endif
  105734. #if JUCE_MAC
  105735. #define FLAC__SYS_DARWIN 1
  105736. #endif
  105737. /*** End of inlined file: juce_FlacHeader.h ***/
  105738. #if JUCE_USE_FLAC
  105739. #if HAVE_CONFIG_H
  105740. # include <config.h>
  105741. #endif
  105742. #include <stdio.h>
  105743. #include <string.h> /* for strlen() */
  105744. #ifdef max
  105745. #undef max
  105746. #endif
  105747. #define max(x,y) ((x)>(y)?(x):(y))
  105748. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105749. 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);
  105750. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105751. {
  105752. unsigned i, j;
  105753. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105754. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105755. return false;
  105756. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105757. return false;
  105758. /*
  105759. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105760. */
  105761. i = metadata->length;
  105762. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105763. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105764. i -= metadata->data.vorbis_comment.vendor_string.length;
  105765. i += vendor_string_length;
  105766. }
  105767. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105768. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105769. return false;
  105770. switch(metadata->type) {
  105771. case FLAC__METADATA_TYPE_STREAMINFO:
  105772. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105773. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105774. return false;
  105775. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105776. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105777. return false;
  105778. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105779. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105780. return false;
  105781. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105782. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105783. return false;
  105784. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105785. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105786. return false;
  105787. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105788. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105789. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105790. return false;
  105791. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105792. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105793. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105794. return false;
  105795. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105796. return false;
  105797. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105798. return false;
  105799. break;
  105800. case FLAC__METADATA_TYPE_PADDING:
  105801. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105802. return false;
  105803. break;
  105804. case FLAC__METADATA_TYPE_APPLICATION:
  105805. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105806. return false;
  105807. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105808. return false;
  105809. break;
  105810. case FLAC__METADATA_TYPE_SEEKTABLE:
  105811. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105812. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105813. return false;
  105814. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105815. return false;
  105816. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105817. return false;
  105818. }
  105819. break;
  105820. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105821. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105822. return false;
  105823. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105824. return false;
  105825. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105826. return false;
  105827. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105828. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105829. return false;
  105830. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105831. return false;
  105832. }
  105833. break;
  105834. case FLAC__METADATA_TYPE_CUESHEET:
  105835. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105836. 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))
  105837. return false;
  105838. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105839. return false;
  105840. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105841. return false;
  105842. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105843. return false;
  105844. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105845. return false;
  105846. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105847. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105848. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105849. return false;
  105850. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105851. return false;
  105852. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105853. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105854. return false;
  105855. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105856. return false;
  105857. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105858. return false;
  105859. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105860. return false;
  105861. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105862. return false;
  105863. for(j = 0; j < track->num_indices; j++) {
  105864. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105865. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105866. return false;
  105867. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105868. return false;
  105869. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105870. return false;
  105871. }
  105872. }
  105873. break;
  105874. case FLAC__METADATA_TYPE_PICTURE:
  105875. {
  105876. size_t len;
  105877. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105878. return false;
  105879. len = strlen(metadata->data.picture.mime_type);
  105880. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105881. return false;
  105882. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105883. return false;
  105884. len = strlen((const char *)metadata->data.picture.description);
  105885. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105886. return false;
  105887. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105888. return false;
  105889. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105890. return false;
  105891. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105892. return false;
  105893. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105894. return false;
  105895. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105896. return false;
  105897. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105898. return false;
  105899. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105900. return false;
  105901. }
  105902. break;
  105903. default:
  105904. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105905. return false;
  105906. break;
  105907. }
  105908. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105909. return true;
  105910. }
  105911. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105912. {
  105913. unsigned u, blocksize_hint, sample_rate_hint;
  105914. FLAC__byte crc;
  105915. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105916. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105917. return false;
  105918. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105919. return false;
  105920. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105921. return false;
  105922. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105923. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105924. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105925. blocksize_hint = 0;
  105926. switch(header->blocksize) {
  105927. case 192: u = 1; break;
  105928. case 576: u = 2; break;
  105929. case 1152: u = 3; break;
  105930. case 2304: u = 4; break;
  105931. case 4608: u = 5; break;
  105932. case 256: u = 8; break;
  105933. case 512: u = 9; break;
  105934. case 1024: u = 10; break;
  105935. case 2048: u = 11; break;
  105936. case 4096: u = 12; break;
  105937. case 8192: u = 13; break;
  105938. case 16384: u = 14; break;
  105939. case 32768: u = 15; break;
  105940. default:
  105941. if(header->blocksize <= 0x100)
  105942. blocksize_hint = u = 6;
  105943. else
  105944. blocksize_hint = u = 7;
  105945. break;
  105946. }
  105947. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105948. return false;
  105949. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105950. sample_rate_hint = 0;
  105951. switch(header->sample_rate) {
  105952. case 88200: u = 1; break;
  105953. case 176400: u = 2; break;
  105954. case 192000: u = 3; break;
  105955. case 8000: u = 4; break;
  105956. case 16000: u = 5; break;
  105957. case 22050: u = 6; break;
  105958. case 24000: u = 7; break;
  105959. case 32000: u = 8; break;
  105960. case 44100: u = 9; break;
  105961. case 48000: u = 10; break;
  105962. case 96000: u = 11; break;
  105963. default:
  105964. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105965. sample_rate_hint = u = 12;
  105966. else if(header->sample_rate % 10 == 0)
  105967. sample_rate_hint = u = 14;
  105968. else if(header->sample_rate <= 0xffff)
  105969. sample_rate_hint = u = 13;
  105970. else
  105971. u = 0;
  105972. break;
  105973. }
  105974. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105975. return false;
  105976. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105977. switch(header->channel_assignment) {
  105978. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105979. u = header->channels - 1;
  105980. break;
  105981. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105982. FLAC__ASSERT(header->channels == 2);
  105983. u = 8;
  105984. break;
  105985. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105986. FLAC__ASSERT(header->channels == 2);
  105987. u = 9;
  105988. break;
  105989. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105990. FLAC__ASSERT(header->channels == 2);
  105991. u = 10;
  105992. break;
  105993. default:
  105994. FLAC__ASSERT(0);
  105995. }
  105996. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105997. return false;
  105998. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105999. switch(header->bits_per_sample) {
  106000. case 8 : u = 1; break;
  106001. case 12: u = 2; break;
  106002. case 16: u = 4; break;
  106003. case 20: u = 5; break;
  106004. case 24: u = 6; break;
  106005. default: u = 0; break;
  106006. }
  106007. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106008. return false;
  106009. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106010. return false;
  106011. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106012. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106013. return false;
  106014. }
  106015. else {
  106016. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106017. return false;
  106018. }
  106019. if(blocksize_hint)
  106020. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106021. return false;
  106022. switch(sample_rate_hint) {
  106023. case 12:
  106024. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106025. return false;
  106026. break;
  106027. case 13:
  106028. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106029. return false;
  106030. break;
  106031. case 14:
  106032. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106033. return false;
  106034. break;
  106035. }
  106036. /* write the CRC */
  106037. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106038. return false;
  106039. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106040. return false;
  106041. return true;
  106042. }
  106043. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106044. {
  106045. FLAC__bool ok;
  106046. ok =
  106047. 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) &&
  106048. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106049. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106050. ;
  106051. return ok;
  106052. }
  106053. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106054. {
  106055. unsigned i;
  106056. 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))
  106057. return false;
  106058. if(wasted_bits)
  106059. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106060. return false;
  106061. for(i = 0; i < subframe->order; i++)
  106062. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106063. return false;
  106064. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106065. return false;
  106066. switch(subframe->entropy_coding_method.type) {
  106067. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106068. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106069. if(!add_residual_partitioned_rice_(
  106070. bw,
  106071. subframe->residual,
  106072. residual_samples,
  106073. subframe->order,
  106074. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106075. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106076. subframe->entropy_coding_method.data.partitioned_rice.order,
  106077. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106078. ))
  106079. return false;
  106080. break;
  106081. default:
  106082. FLAC__ASSERT(0);
  106083. }
  106084. return true;
  106085. }
  106086. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106087. {
  106088. unsigned i;
  106089. 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))
  106090. return false;
  106091. if(wasted_bits)
  106092. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106093. return false;
  106094. for(i = 0; i < subframe->order; i++)
  106095. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106096. return false;
  106097. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106098. return false;
  106099. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106100. return false;
  106101. for(i = 0; i < subframe->order; i++)
  106102. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106103. return false;
  106104. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106105. return false;
  106106. switch(subframe->entropy_coding_method.type) {
  106107. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106108. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106109. if(!add_residual_partitioned_rice_(
  106110. bw,
  106111. subframe->residual,
  106112. residual_samples,
  106113. subframe->order,
  106114. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106115. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106116. subframe->entropy_coding_method.data.partitioned_rice.order,
  106117. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106118. ))
  106119. return false;
  106120. break;
  106121. default:
  106122. FLAC__ASSERT(0);
  106123. }
  106124. return true;
  106125. }
  106126. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106127. {
  106128. unsigned i;
  106129. const FLAC__int32 *signal = subframe->data;
  106130. 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))
  106131. return false;
  106132. if(wasted_bits)
  106133. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106134. return false;
  106135. for(i = 0; i < samples; i++)
  106136. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106137. return false;
  106138. return true;
  106139. }
  106140. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106141. {
  106142. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106143. return false;
  106144. switch(method->type) {
  106145. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106146. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106147. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106148. return false;
  106149. break;
  106150. default:
  106151. FLAC__ASSERT(0);
  106152. }
  106153. return true;
  106154. }
  106155. 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)
  106156. {
  106157. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106158. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106159. if(partition_order == 0) {
  106160. unsigned i;
  106161. if(raw_bits[0] == 0) {
  106162. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106163. return false;
  106164. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106165. return false;
  106166. }
  106167. else {
  106168. FLAC__ASSERT(rice_parameters[0] == 0);
  106169. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106170. return false;
  106171. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106172. return false;
  106173. for(i = 0; i < residual_samples; i++) {
  106174. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106175. return false;
  106176. }
  106177. }
  106178. return true;
  106179. }
  106180. else {
  106181. unsigned i, j, k = 0, k_last = 0;
  106182. unsigned partition_samples;
  106183. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106184. for(i = 0; i < (1u<<partition_order); i++) {
  106185. partition_samples = default_partition_samples;
  106186. if(i == 0)
  106187. partition_samples -= predictor_order;
  106188. k += partition_samples;
  106189. if(raw_bits[i] == 0) {
  106190. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106191. return false;
  106192. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106193. return false;
  106194. }
  106195. else {
  106196. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106197. return false;
  106198. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106199. return false;
  106200. for(j = k_last; j < k; j++) {
  106201. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106202. return false;
  106203. }
  106204. }
  106205. k_last = k;
  106206. }
  106207. return true;
  106208. }
  106209. }
  106210. #endif
  106211. /*** End of inlined file: stream_encoder_framing.c ***/
  106212. /*** Start of inlined file: window_flac.c ***/
  106213. /*** Start of inlined file: juce_FlacHeader.h ***/
  106214. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106215. // tasks..
  106216. #define VERSION "1.2.1"
  106217. #define FLAC__NO_DLL 1
  106218. #if JUCE_MSVC
  106219. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106220. #endif
  106221. #if JUCE_MAC
  106222. #define FLAC__SYS_DARWIN 1
  106223. #endif
  106224. /*** End of inlined file: juce_FlacHeader.h ***/
  106225. #if JUCE_USE_FLAC
  106226. #if HAVE_CONFIG_H
  106227. # include <config.h>
  106228. #endif
  106229. #include <math.h>
  106230. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106231. #ifndef M_PI
  106232. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106233. #define M_PI 3.14159265358979323846
  106234. #endif
  106235. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106236. {
  106237. const FLAC__int32 N = L - 1;
  106238. FLAC__int32 n;
  106239. if (L & 1) {
  106240. for (n = 0; n <= N/2; n++)
  106241. window[n] = 2.0f * n / (float)N;
  106242. for (; n <= N; n++)
  106243. window[n] = 2.0f - 2.0f * n / (float)N;
  106244. }
  106245. else {
  106246. for (n = 0; n <= L/2-1; n++)
  106247. window[n] = 2.0f * n / (float)N;
  106248. for (; n <= N; n++)
  106249. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106250. }
  106251. }
  106252. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106253. {
  106254. const FLAC__int32 N = L - 1;
  106255. FLAC__int32 n;
  106256. for (n = 0; n < L; n++)
  106257. 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)));
  106258. }
  106259. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106260. {
  106261. const FLAC__int32 N = L - 1;
  106262. FLAC__int32 n;
  106263. for (n = 0; n < L; n++)
  106264. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106265. }
  106266. /* 4-term -92dB side-lobe */
  106267. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106268. {
  106269. const FLAC__int32 N = L - 1;
  106270. FLAC__int32 n;
  106271. for (n = 0; n <= N; n++)
  106272. 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));
  106273. }
  106274. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106275. {
  106276. const FLAC__int32 N = L - 1;
  106277. const double N2 = (double)N / 2.;
  106278. FLAC__int32 n;
  106279. for (n = 0; n <= N; n++) {
  106280. double k = ((double)n - N2) / N2;
  106281. k = 1.0f - k * k;
  106282. window[n] = (FLAC__real)(k * k);
  106283. }
  106284. }
  106285. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106286. {
  106287. const FLAC__int32 N = L - 1;
  106288. FLAC__int32 n;
  106289. for (n = 0; n < L; n++)
  106290. 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));
  106291. }
  106292. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106293. {
  106294. const FLAC__int32 N = L - 1;
  106295. const double N2 = (double)N / 2.;
  106296. FLAC__int32 n;
  106297. for (n = 0; n <= N; n++) {
  106298. const double k = ((double)n - N2) / (stddev * N2);
  106299. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106300. }
  106301. }
  106302. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106303. {
  106304. const FLAC__int32 N = L - 1;
  106305. FLAC__int32 n;
  106306. for (n = 0; n < L; n++)
  106307. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106308. }
  106309. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106310. {
  106311. const FLAC__int32 N = L - 1;
  106312. FLAC__int32 n;
  106313. for (n = 0; n < L; n++)
  106314. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106315. }
  106316. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106317. {
  106318. const FLAC__int32 N = L - 1;
  106319. FLAC__int32 n;
  106320. for (n = 0; n < L; n++)
  106321. 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));
  106322. }
  106323. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106324. {
  106325. const FLAC__int32 N = L - 1;
  106326. FLAC__int32 n;
  106327. for (n = 0; n < L; n++)
  106328. 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));
  106329. }
  106330. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106331. {
  106332. FLAC__int32 n;
  106333. for (n = 0; n < L; n++)
  106334. window[n] = 1.0f;
  106335. }
  106336. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106337. {
  106338. FLAC__int32 n;
  106339. if (L & 1) {
  106340. for (n = 1; n <= L+1/2; n++)
  106341. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106342. for (; n <= L; n++)
  106343. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106344. }
  106345. else {
  106346. for (n = 1; n <= L/2; n++)
  106347. window[n-1] = 2.0f * n / (float)L;
  106348. for (; n <= L; n++)
  106349. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106350. }
  106351. }
  106352. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106353. {
  106354. if (p <= 0.0)
  106355. FLAC__window_rectangle(window, L);
  106356. else if (p >= 1.0)
  106357. FLAC__window_hann(window, L);
  106358. else {
  106359. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106360. FLAC__int32 n;
  106361. /* start with rectangle... */
  106362. FLAC__window_rectangle(window, L);
  106363. /* ...replace ends with hann */
  106364. if (Np > 0) {
  106365. for (n = 0; n <= Np; n++) {
  106366. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106367. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106368. }
  106369. }
  106370. }
  106371. }
  106372. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106373. {
  106374. const FLAC__int32 N = L - 1;
  106375. const double N2 = (double)N / 2.;
  106376. FLAC__int32 n;
  106377. for (n = 0; n <= N; n++) {
  106378. const double k = ((double)n - N2) / N2;
  106379. window[n] = (FLAC__real)(1.0f - k * k);
  106380. }
  106381. }
  106382. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106383. #endif
  106384. /*** End of inlined file: window_flac.c ***/
  106385. #else
  106386. #include <FLAC/all.h>
  106387. #endif
  106388. }
  106389. #undef max
  106390. #undef min
  106391. BEGIN_JUCE_NAMESPACE
  106392. static const char* const flacFormatName = "FLAC file";
  106393. static const char* const flacExtensions[] = { ".flac", 0 };
  106394. class FlacReader : public AudioFormatReader
  106395. {
  106396. public:
  106397. FlacReader (InputStream* const in)
  106398. : AudioFormatReader (in, TRANS (flacFormatName)),
  106399. reservoir (2, 0),
  106400. reservoirStart (0),
  106401. samplesInReservoir (0),
  106402. scanningForLength (false)
  106403. {
  106404. using namespace FlacNamespace;
  106405. lengthInSamples = 0;
  106406. decoder = FLAC__stream_decoder_new();
  106407. ok = FLAC__stream_decoder_init_stream (decoder,
  106408. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106409. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106410. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106411. if (ok)
  106412. {
  106413. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106414. if (lengthInSamples == 0 && sampleRate > 0)
  106415. {
  106416. // the length hasn't been stored in the metadata, so we'll need to
  106417. // work it out the length the hard way, by scanning the whole file..
  106418. scanningForLength = true;
  106419. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106420. scanningForLength = false;
  106421. const int64 tempLength = lengthInSamples;
  106422. FLAC__stream_decoder_reset (decoder);
  106423. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106424. lengthInSamples = tempLength;
  106425. }
  106426. }
  106427. }
  106428. ~FlacReader()
  106429. {
  106430. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106431. }
  106432. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106433. {
  106434. sampleRate = info.sample_rate;
  106435. bitsPerSample = info.bits_per_sample;
  106436. lengthInSamples = (unsigned int) info.total_samples;
  106437. numChannels = info.channels;
  106438. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106439. }
  106440. // returns the number of samples read
  106441. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106442. int64 startSampleInFile, int numSamples)
  106443. {
  106444. using namespace FlacNamespace;
  106445. if (! ok)
  106446. return false;
  106447. while (numSamples > 0)
  106448. {
  106449. if (startSampleInFile >= reservoirStart
  106450. && startSampleInFile < reservoirStart + samplesInReservoir)
  106451. {
  106452. const int num = (int) jmin ((int64) numSamples,
  106453. reservoirStart + samplesInReservoir - startSampleInFile);
  106454. jassert (num > 0);
  106455. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106456. if (destSamples[i] != 0)
  106457. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106458. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106459. sizeof (int) * num);
  106460. startOffsetInDestBuffer += num;
  106461. startSampleInFile += num;
  106462. numSamples -= num;
  106463. }
  106464. else
  106465. {
  106466. if (startSampleInFile >= (int) lengthInSamples)
  106467. {
  106468. samplesInReservoir = 0;
  106469. }
  106470. else if (startSampleInFile < reservoirStart
  106471. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106472. {
  106473. // had some problems with flac crashing if the read pos is aligned more
  106474. // accurately than this. Probably fixed in newer versions of the library, though.
  106475. reservoirStart = (int) (startSampleInFile & ~511);
  106476. samplesInReservoir = 0;
  106477. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106478. }
  106479. else
  106480. {
  106481. reservoirStart += samplesInReservoir;
  106482. samplesInReservoir = 0;
  106483. FLAC__stream_decoder_process_single (decoder);
  106484. }
  106485. if (samplesInReservoir == 0)
  106486. break;
  106487. }
  106488. }
  106489. if (numSamples > 0)
  106490. {
  106491. for (int i = numDestChannels; --i >= 0;)
  106492. if (destSamples[i] != 0)
  106493. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106494. sizeof (int) * numSamples);
  106495. }
  106496. return true;
  106497. }
  106498. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106499. {
  106500. if (scanningForLength)
  106501. {
  106502. lengthInSamples += numSamples;
  106503. }
  106504. else
  106505. {
  106506. if (numSamples > reservoir.getNumSamples())
  106507. reservoir.setSize (numChannels, numSamples, false, false, true);
  106508. const int bitsToShift = 32 - bitsPerSample;
  106509. for (int i = 0; i < (int) numChannels; ++i)
  106510. {
  106511. const FlacNamespace::FLAC__int32* src = buffer[i];
  106512. int n = i;
  106513. while (src == 0 && n > 0)
  106514. src = buffer [--n];
  106515. if (src != 0)
  106516. {
  106517. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106518. for (int j = 0; j < numSamples; ++j)
  106519. dest[j] = src[j] << bitsToShift;
  106520. }
  106521. }
  106522. samplesInReservoir = numSamples;
  106523. }
  106524. }
  106525. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106526. {
  106527. using namespace FlacNamespace;
  106528. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106529. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106530. }
  106531. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106532. {
  106533. using namespace FlacNamespace;
  106534. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106535. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106536. }
  106537. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106538. {
  106539. using namespace FlacNamespace;
  106540. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106541. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106542. }
  106543. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106544. {
  106545. using namespace FlacNamespace;
  106546. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106547. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106548. }
  106549. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106550. {
  106551. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106552. }
  106553. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106554. const FlacNamespace::FLAC__Frame* frame,
  106555. const FlacNamespace::FLAC__int32* const buffer[],
  106556. void* client_data)
  106557. {
  106558. using namespace FlacNamespace;
  106559. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106560. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106561. }
  106562. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106563. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106564. void* client_data)
  106565. {
  106566. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106567. }
  106568. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106569. {
  106570. }
  106571. private:
  106572. FlacNamespace::FLAC__StreamDecoder* decoder;
  106573. AudioSampleBuffer reservoir;
  106574. int reservoirStart, samplesInReservoir;
  106575. bool ok, scanningForLength;
  106576. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106577. };
  106578. class FlacWriter : public AudioFormatWriter
  106579. {
  106580. public:
  106581. FlacWriter (OutputStream* const out, double sampleRate_,
  106582. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106583. : AudioFormatWriter (out, TRANS (flacFormatName),
  106584. sampleRate_, numChannels_, bitsPerSample_)
  106585. {
  106586. using namespace FlacNamespace;
  106587. encoder = FLAC__stream_encoder_new();
  106588. if (qualityOptionIndex > 0)
  106589. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106590. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106591. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106592. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106593. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106594. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106595. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106596. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106597. ok = FLAC__stream_encoder_init_stream (encoder,
  106598. encodeWriteCallback, encodeSeekCallback,
  106599. encodeTellCallback, encodeMetadataCallback,
  106600. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106601. }
  106602. ~FlacWriter()
  106603. {
  106604. if (ok)
  106605. {
  106606. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106607. output->flush();
  106608. }
  106609. else
  106610. {
  106611. output = 0; // to stop the base class deleting this, as it needs to be returned
  106612. // to the caller of createWriter()
  106613. }
  106614. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106615. }
  106616. bool write (const int** samplesToWrite, int numSamples)
  106617. {
  106618. using namespace FlacNamespace;
  106619. if (! ok)
  106620. return false;
  106621. int* buf[3];
  106622. HeapBlock<int> temp;
  106623. const int bitsToShift = 32 - bitsPerSample;
  106624. if (bitsToShift > 0)
  106625. {
  106626. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106627. temp.malloc (numSamples * numChannelsToWrite);
  106628. buf[0] = temp.getData();
  106629. buf[1] = temp.getData() + numSamples;
  106630. buf[2] = 0;
  106631. for (int i = numChannelsToWrite; --i >= 0;)
  106632. if (samplesToWrite[i] != 0)
  106633. for (int j = 0; j < numSamples; ++j)
  106634. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106635. samplesToWrite = const_cast<const int**> (buf);
  106636. }
  106637. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106638. }
  106639. bool writeData (const void* const data, const int size) const
  106640. {
  106641. return output->write (data, size);
  106642. }
  106643. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106644. {
  106645. using namespace FlacNamespace;
  106646. b += bytes;
  106647. for (int i = 0; i < bytes; ++i)
  106648. {
  106649. *(--b) = (FLAC__byte) (val & 0xff);
  106650. val >>= 8;
  106651. }
  106652. }
  106653. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106654. {
  106655. using namespace FlacNamespace;
  106656. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106657. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106658. const unsigned int channelsMinus1 = info.channels - 1;
  106659. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106660. packUint32 (info.min_blocksize, buffer, 2);
  106661. packUint32 (info.max_blocksize, buffer + 2, 2);
  106662. packUint32 (info.min_framesize, buffer + 4, 3);
  106663. packUint32 (info.max_framesize, buffer + 7, 3);
  106664. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106665. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106666. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106667. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106668. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106669. memcpy (buffer + 18, info.md5sum, 16);
  106670. const bool seekOk = output->setPosition (4);
  106671. (void) seekOk;
  106672. // if this fails, you've given it an output stream that can't seek! It needs
  106673. // to be able to seek back to write the header
  106674. jassert (seekOk);
  106675. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106676. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106677. }
  106678. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106679. const FlacNamespace::FLAC__byte buffer[],
  106680. size_t bytes,
  106681. unsigned int /*samples*/,
  106682. unsigned int /*current_frame*/,
  106683. void* client_data)
  106684. {
  106685. using namespace FlacNamespace;
  106686. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106687. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106688. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106689. }
  106690. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106691. {
  106692. using namespace FlacNamespace;
  106693. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106694. }
  106695. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106696. {
  106697. using namespace FlacNamespace;
  106698. if (client_data == 0)
  106699. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106700. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106701. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106702. }
  106703. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106704. {
  106705. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106706. }
  106707. bool ok;
  106708. private:
  106709. FlacNamespace::FLAC__StreamEncoder* encoder;
  106710. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106711. };
  106712. FlacAudioFormat::FlacAudioFormat()
  106713. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106714. {
  106715. }
  106716. FlacAudioFormat::~FlacAudioFormat()
  106717. {
  106718. }
  106719. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106720. {
  106721. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106722. return Array <int> (rates);
  106723. }
  106724. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106725. {
  106726. const int depths[] = { 16, 24, 0 };
  106727. return Array <int> (depths);
  106728. }
  106729. bool FlacAudioFormat::canDoStereo() { return true; }
  106730. bool FlacAudioFormat::canDoMono() { return true; }
  106731. bool FlacAudioFormat::isCompressed() { return true; }
  106732. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106733. const bool deleteStreamIfOpeningFails)
  106734. {
  106735. ScopedPointer<FlacReader> r (new FlacReader (in));
  106736. if (r->sampleRate != 0)
  106737. return r.release();
  106738. if (! deleteStreamIfOpeningFails)
  106739. r->input = 0;
  106740. return 0;
  106741. }
  106742. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106743. double sampleRate,
  106744. unsigned int numberOfChannels,
  106745. int bitsPerSample,
  106746. const StringPairArray& /*metadataValues*/,
  106747. int qualityOptionIndex)
  106748. {
  106749. if (getPossibleBitDepths().contains (bitsPerSample))
  106750. {
  106751. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  106752. if (w->ok)
  106753. return w.release();
  106754. }
  106755. return 0;
  106756. }
  106757. END_JUCE_NAMESPACE
  106758. #endif
  106759. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106760. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106761. #if JUCE_USE_OGGVORBIS
  106762. #if JUCE_MAC
  106763. #define __MACOSX__ 1
  106764. #endif
  106765. namespace OggVorbisNamespace
  106766. {
  106767. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106768. /*** Start of inlined file: vorbisenc.h ***/
  106769. #ifndef _OV_ENC_H_
  106770. #define _OV_ENC_H_
  106771. #ifdef __cplusplus
  106772. extern "C"
  106773. {
  106774. #endif /* __cplusplus */
  106775. /*** Start of inlined file: codec.h ***/
  106776. #ifndef _vorbis_codec_h_
  106777. #define _vorbis_codec_h_
  106778. #ifdef __cplusplus
  106779. extern "C"
  106780. {
  106781. #endif /* __cplusplus */
  106782. /*** Start of inlined file: ogg.h ***/
  106783. #ifndef _OGG_H
  106784. #define _OGG_H
  106785. #ifdef __cplusplus
  106786. extern "C" {
  106787. #endif
  106788. /*** Start of inlined file: os_types.h ***/
  106789. #ifndef _OS_TYPES_H
  106790. #define _OS_TYPES_H
  106791. /* make it easy on the folks that want to compile the libs with a
  106792. different malloc than stdlib */
  106793. #define _ogg_malloc malloc
  106794. #define _ogg_calloc calloc
  106795. #define _ogg_realloc realloc
  106796. #define _ogg_free free
  106797. #if defined(_WIN32)
  106798. # if defined(__CYGWIN__)
  106799. # include <_G_config.h>
  106800. typedef _G_int64_t ogg_int64_t;
  106801. typedef _G_int32_t ogg_int32_t;
  106802. typedef _G_uint32_t ogg_uint32_t;
  106803. typedef _G_int16_t ogg_int16_t;
  106804. typedef _G_uint16_t ogg_uint16_t;
  106805. # elif defined(__MINGW32__)
  106806. typedef short ogg_int16_t;
  106807. typedef unsigned short ogg_uint16_t;
  106808. typedef int ogg_int32_t;
  106809. typedef unsigned int ogg_uint32_t;
  106810. typedef long long ogg_int64_t;
  106811. typedef unsigned long long ogg_uint64_t;
  106812. # elif defined(__MWERKS__)
  106813. typedef long long ogg_int64_t;
  106814. typedef int ogg_int32_t;
  106815. typedef unsigned int ogg_uint32_t;
  106816. typedef short ogg_int16_t;
  106817. typedef unsigned short ogg_uint16_t;
  106818. # else
  106819. /* MSVC/Borland */
  106820. typedef __int64 ogg_int64_t;
  106821. typedef __int32 ogg_int32_t;
  106822. typedef unsigned __int32 ogg_uint32_t;
  106823. typedef __int16 ogg_int16_t;
  106824. typedef unsigned __int16 ogg_uint16_t;
  106825. # endif
  106826. #elif defined(__MACOS__)
  106827. # include <sys/types.h>
  106828. typedef SInt16 ogg_int16_t;
  106829. typedef UInt16 ogg_uint16_t;
  106830. typedef SInt32 ogg_int32_t;
  106831. typedef UInt32 ogg_uint32_t;
  106832. typedef SInt64 ogg_int64_t;
  106833. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106834. # include <sys/types.h>
  106835. typedef int16_t ogg_int16_t;
  106836. typedef u_int16_t ogg_uint16_t;
  106837. typedef int32_t ogg_int32_t;
  106838. typedef u_int32_t ogg_uint32_t;
  106839. typedef int64_t ogg_int64_t;
  106840. #elif defined(__BEOS__)
  106841. /* Be */
  106842. # include <inttypes.h>
  106843. typedef int16_t ogg_int16_t;
  106844. typedef u_int16_t ogg_uint16_t;
  106845. typedef int32_t ogg_int32_t;
  106846. typedef u_int32_t ogg_uint32_t;
  106847. typedef int64_t ogg_int64_t;
  106848. #elif defined (__EMX__)
  106849. /* OS/2 GCC */
  106850. typedef short ogg_int16_t;
  106851. typedef unsigned short ogg_uint16_t;
  106852. typedef int ogg_int32_t;
  106853. typedef unsigned int ogg_uint32_t;
  106854. typedef long long ogg_int64_t;
  106855. #elif defined (DJGPP)
  106856. /* DJGPP */
  106857. typedef short ogg_int16_t;
  106858. typedef int ogg_int32_t;
  106859. typedef unsigned int ogg_uint32_t;
  106860. typedef long long ogg_int64_t;
  106861. #elif defined(R5900)
  106862. /* PS2 EE */
  106863. typedef long ogg_int64_t;
  106864. typedef int ogg_int32_t;
  106865. typedef unsigned ogg_uint32_t;
  106866. typedef short ogg_int16_t;
  106867. #elif defined(__SYMBIAN32__)
  106868. /* Symbian GCC */
  106869. typedef signed short ogg_int16_t;
  106870. typedef unsigned short ogg_uint16_t;
  106871. typedef signed int ogg_int32_t;
  106872. typedef unsigned int ogg_uint32_t;
  106873. typedef long long int ogg_int64_t;
  106874. #else
  106875. # include <sys/types.h>
  106876. /*** Start of inlined file: config_types.h ***/
  106877. #ifndef __CONFIG_TYPES_H__
  106878. #define __CONFIG_TYPES_H__
  106879. typedef int16_t ogg_int16_t;
  106880. typedef unsigned short ogg_uint16_t;
  106881. typedef int32_t ogg_int32_t;
  106882. typedef unsigned int ogg_uint32_t;
  106883. typedef int64_t ogg_int64_t;
  106884. #endif
  106885. /*** End of inlined file: config_types.h ***/
  106886. #endif
  106887. #endif /* _OS_TYPES_H */
  106888. /*** End of inlined file: os_types.h ***/
  106889. typedef struct {
  106890. long endbyte;
  106891. int endbit;
  106892. unsigned char *buffer;
  106893. unsigned char *ptr;
  106894. long storage;
  106895. } oggpack_buffer;
  106896. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106897. typedef struct {
  106898. unsigned char *header;
  106899. long header_len;
  106900. unsigned char *body;
  106901. long body_len;
  106902. } ogg_page;
  106903. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106904. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106905. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106906. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106907. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106908. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106909. }
  106910. /* ogg_stream_state contains the current encode/decode state of a logical
  106911. Ogg bitstream **********************************************************/
  106912. typedef struct {
  106913. unsigned char *body_data; /* bytes from packet bodies */
  106914. long body_storage; /* storage elements allocated */
  106915. long body_fill; /* elements stored; fill mark */
  106916. long body_returned; /* elements of fill returned */
  106917. int *lacing_vals; /* The values that will go to the segment table */
  106918. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106919. this way, but it is simple coupled to the
  106920. lacing fifo */
  106921. long lacing_storage;
  106922. long lacing_fill;
  106923. long lacing_packet;
  106924. long lacing_returned;
  106925. unsigned char header[282]; /* working space for header encode */
  106926. int header_fill;
  106927. int e_o_s; /* set when we have buffered the last packet in the
  106928. logical bitstream */
  106929. int b_o_s; /* set after we've written the initial page
  106930. of a logical bitstream */
  106931. long serialno;
  106932. long pageno;
  106933. ogg_int64_t packetno; /* sequence number for decode; the framing
  106934. knows where there's a hole in the data,
  106935. but we need coupling so that the codec
  106936. (which is in a seperate abstraction
  106937. layer) also knows about the gap */
  106938. ogg_int64_t granulepos;
  106939. } ogg_stream_state;
  106940. /* ogg_packet is used to encapsulate the data and metadata belonging
  106941. to a single raw Ogg/Vorbis packet *************************************/
  106942. typedef struct {
  106943. unsigned char *packet;
  106944. long bytes;
  106945. long b_o_s;
  106946. long e_o_s;
  106947. ogg_int64_t granulepos;
  106948. ogg_int64_t packetno; /* sequence number for decode; the framing
  106949. knows where there's a hole in the data,
  106950. but we need coupling so that the codec
  106951. (which is in a seperate abstraction
  106952. layer) also knows about the gap */
  106953. } ogg_packet;
  106954. typedef struct {
  106955. unsigned char *data;
  106956. int storage;
  106957. int fill;
  106958. int returned;
  106959. int unsynced;
  106960. int headerbytes;
  106961. int bodybytes;
  106962. } ogg_sync_state;
  106963. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106964. extern void oggpack_writeinit(oggpack_buffer *b);
  106965. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106966. extern void oggpack_writealign(oggpack_buffer *b);
  106967. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106968. extern void oggpack_reset(oggpack_buffer *b);
  106969. extern void oggpack_writeclear(oggpack_buffer *b);
  106970. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106971. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106972. extern long oggpack_look(oggpack_buffer *b,int bits);
  106973. extern long oggpack_look1(oggpack_buffer *b);
  106974. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106975. extern void oggpack_adv1(oggpack_buffer *b);
  106976. extern long oggpack_read(oggpack_buffer *b,int bits);
  106977. extern long oggpack_read1(oggpack_buffer *b);
  106978. extern long oggpack_bytes(oggpack_buffer *b);
  106979. extern long oggpack_bits(oggpack_buffer *b);
  106980. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106981. extern void oggpackB_writeinit(oggpack_buffer *b);
  106982. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106983. extern void oggpackB_writealign(oggpack_buffer *b);
  106984. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106985. extern void oggpackB_reset(oggpack_buffer *b);
  106986. extern void oggpackB_writeclear(oggpack_buffer *b);
  106987. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106988. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106989. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106990. extern long oggpackB_look1(oggpack_buffer *b);
  106991. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106992. extern void oggpackB_adv1(oggpack_buffer *b);
  106993. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106994. extern long oggpackB_read1(oggpack_buffer *b);
  106995. extern long oggpackB_bytes(oggpack_buffer *b);
  106996. extern long oggpackB_bits(oggpack_buffer *b);
  106997. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106998. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106999. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107000. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107001. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107002. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107003. extern int ogg_sync_init(ogg_sync_state *oy);
  107004. extern int ogg_sync_clear(ogg_sync_state *oy);
  107005. extern int ogg_sync_reset(ogg_sync_state *oy);
  107006. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107007. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107008. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107009. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107010. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107011. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107012. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107013. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107014. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107015. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107016. extern int ogg_stream_clear(ogg_stream_state *os);
  107017. extern int ogg_stream_reset(ogg_stream_state *os);
  107018. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107019. extern int ogg_stream_destroy(ogg_stream_state *os);
  107020. extern int ogg_stream_eos(ogg_stream_state *os);
  107021. extern void ogg_page_checksum_set(ogg_page *og);
  107022. extern int ogg_page_version(ogg_page *og);
  107023. extern int ogg_page_continued(ogg_page *og);
  107024. extern int ogg_page_bos(ogg_page *og);
  107025. extern int ogg_page_eos(ogg_page *og);
  107026. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107027. extern int ogg_page_serialno(ogg_page *og);
  107028. extern long ogg_page_pageno(ogg_page *og);
  107029. extern int ogg_page_packets(ogg_page *og);
  107030. extern void ogg_packet_clear(ogg_packet *op);
  107031. #ifdef __cplusplus
  107032. }
  107033. #endif
  107034. #endif /* _OGG_H */
  107035. /*** End of inlined file: ogg.h ***/
  107036. typedef struct vorbis_info{
  107037. int version;
  107038. int channels;
  107039. long rate;
  107040. /* The below bitrate declarations are *hints*.
  107041. Combinations of the three values carry the following implications:
  107042. all three set to the same value:
  107043. implies a fixed rate bitstream
  107044. only nominal set:
  107045. implies a VBR stream that averages the nominal bitrate. No hard
  107046. upper/lower limit
  107047. upper and or lower set:
  107048. implies a VBR bitstream that obeys the bitrate limits. nominal
  107049. may also be set to give a nominal rate.
  107050. none set:
  107051. the coder does not care to speculate.
  107052. */
  107053. long bitrate_upper;
  107054. long bitrate_nominal;
  107055. long bitrate_lower;
  107056. long bitrate_window;
  107057. void *codec_setup;
  107058. } vorbis_info;
  107059. /* vorbis_dsp_state buffers the current vorbis audio
  107060. analysis/synthesis state. The DSP state belongs to a specific
  107061. logical bitstream ****************************************************/
  107062. typedef struct vorbis_dsp_state{
  107063. int analysisp;
  107064. vorbis_info *vi;
  107065. float **pcm;
  107066. float **pcmret;
  107067. int pcm_storage;
  107068. int pcm_current;
  107069. int pcm_returned;
  107070. int preextrapolate;
  107071. int eofflag;
  107072. long lW;
  107073. long W;
  107074. long nW;
  107075. long centerW;
  107076. ogg_int64_t granulepos;
  107077. ogg_int64_t sequence;
  107078. ogg_int64_t glue_bits;
  107079. ogg_int64_t time_bits;
  107080. ogg_int64_t floor_bits;
  107081. ogg_int64_t res_bits;
  107082. void *backend_state;
  107083. } vorbis_dsp_state;
  107084. typedef struct vorbis_block{
  107085. /* necessary stream state for linking to the framing abstraction */
  107086. float **pcm; /* this is a pointer into local storage */
  107087. oggpack_buffer opb;
  107088. long lW;
  107089. long W;
  107090. long nW;
  107091. int pcmend;
  107092. int mode;
  107093. int eofflag;
  107094. ogg_int64_t granulepos;
  107095. ogg_int64_t sequence;
  107096. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107097. /* local storage to avoid remallocing; it's up to the mapping to
  107098. structure it */
  107099. void *localstore;
  107100. long localtop;
  107101. long localalloc;
  107102. long totaluse;
  107103. struct alloc_chain *reap;
  107104. /* bitmetrics for the frame */
  107105. long glue_bits;
  107106. long time_bits;
  107107. long floor_bits;
  107108. long res_bits;
  107109. void *internal;
  107110. } vorbis_block;
  107111. /* vorbis_block is a single block of data to be processed as part of
  107112. the analysis/synthesis stream; it belongs to a specific logical
  107113. bitstream, but is independant from other vorbis_blocks belonging to
  107114. that logical bitstream. *************************************************/
  107115. struct alloc_chain{
  107116. void *ptr;
  107117. struct alloc_chain *next;
  107118. };
  107119. /* vorbis_info contains all the setup information specific to the
  107120. specific compression/decompression mode in progress (eg,
  107121. psychoacoustic settings, channel setup, options, codebook
  107122. etc). vorbis_info and substructures are in backends.h.
  107123. *********************************************************************/
  107124. /* the comments are not part of vorbis_info so that vorbis_info can be
  107125. static storage */
  107126. typedef struct vorbis_comment{
  107127. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107128. whatever vendor is set to in encode */
  107129. char **user_comments;
  107130. int *comment_lengths;
  107131. int comments;
  107132. char *vendor;
  107133. } vorbis_comment;
  107134. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107135. and produce a packet (see docs/analysis.txt). The packet is then
  107136. coded into a framed OggSquish bitstream by the second layer (see
  107137. docs/framing.txt). Decode is the reverse process; we sync/frame
  107138. the bitstream and extract individual packets, then decode the
  107139. packet back into PCM audio.
  107140. The extra framing/packetizing is used in streaming formats, such as
  107141. files. Over the net (such as with UDP), the framing and
  107142. packetization aren't necessary as they're provided by the transport
  107143. and the streaming layer is not used */
  107144. /* Vorbis PRIMITIVES: general ***************************************/
  107145. extern void vorbis_info_init(vorbis_info *vi);
  107146. extern void vorbis_info_clear(vorbis_info *vi);
  107147. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107148. extern void vorbis_comment_init(vorbis_comment *vc);
  107149. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107150. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107151. const char *tag, char *contents);
  107152. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107153. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107154. extern void vorbis_comment_clear(vorbis_comment *vc);
  107155. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107156. extern int vorbis_block_clear(vorbis_block *vb);
  107157. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107158. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107159. ogg_int64_t granulepos);
  107160. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107161. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107162. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107163. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107164. vorbis_comment *vc,
  107165. ogg_packet *op,
  107166. ogg_packet *op_comm,
  107167. ogg_packet *op_code);
  107168. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107169. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107170. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107171. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107172. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107173. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107174. ogg_packet *op);
  107175. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107176. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107177. ogg_packet *op);
  107178. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107179. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107180. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107181. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107182. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107183. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107184. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107185. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107186. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107187. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107188. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107189. /* Vorbis ERRORS and return codes ***********************************/
  107190. #define OV_FALSE -1
  107191. #define OV_EOF -2
  107192. #define OV_HOLE -3
  107193. #define OV_EREAD -128
  107194. #define OV_EFAULT -129
  107195. #define OV_EIMPL -130
  107196. #define OV_EINVAL -131
  107197. #define OV_ENOTVORBIS -132
  107198. #define OV_EBADHEADER -133
  107199. #define OV_EVERSION -134
  107200. #define OV_ENOTAUDIO -135
  107201. #define OV_EBADPACKET -136
  107202. #define OV_EBADLINK -137
  107203. #define OV_ENOSEEK -138
  107204. #ifdef __cplusplus
  107205. }
  107206. #endif /* __cplusplus */
  107207. #endif
  107208. /*** End of inlined file: codec.h ***/
  107209. extern int vorbis_encode_init(vorbis_info *vi,
  107210. long channels,
  107211. long rate,
  107212. long max_bitrate,
  107213. long nominal_bitrate,
  107214. long min_bitrate);
  107215. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107216. long channels,
  107217. long rate,
  107218. long max_bitrate,
  107219. long nominal_bitrate,
  107220. long min_bitrate);
  107221. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107222. long channels,
  107223. long rate,
  107224. float quality /* quality level from 0. (lo) to 1. (hi) */
  107225. );
  107226. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107227. long channels,
  107228. long rate,
  107229. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107230. );
  107231. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107232. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107233. /* deprecated rate management supported only for compatability */
  107234. #define OV_ECTL_RATEMANAGE_GET 0x10
  107235. #define OV_ECTL_RATEMANAGE_SET 0x11
  107236. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107237. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107238. struct ovectl_ratemanage_arg {
  107239. int management_active;
  107240. long bitrate_hard_min;
  107241. long bitrate_hard_max;
  107242. double bitrate_hard_window;
  107243. long bitrate_av_lo;
  107244. long bitrate_av_hi;
  107245. double bitrate_av_window;
  107246. double bitrate_av_window_center;
  107247. };
  107248. /* new rate setup */
  107249. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107250. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107251. struct ovectl_ratemanage2_arg {
  107252. int management_active;
  107253. long bitrate_limit_min_kbps;
  107254. long bitrate_limit_max_kbps;
  107255. long bitrate_limit_reservoir_bits;
  107256. double bitrate_limit_reservoir_bias;
  107257. long bitrate_average_kbps;
  107258. double bitrate_average_damping;
  107259. };
  107260. #define OV_ECTL_LOWPASS_GET 0x20
  107261. #define OV_ECTL_LOWPASS_SET 0x21
  107262. #define OV_ECTL_IBLOCK_GET 0x30
  107263. #define OV_ECTL_IBLOCK_SET 0x31
  107264. #ifdef __cplusplus
  107265. }
  107266. #endif /* __cplusplus */
  107267. #endif
  107268. /*** End of inlined file: vorbisenc.h ***/
  107269. /*** Start of inlined file: vorbisfile.h ***/
  107270. #ifndef _OV_FILE_H_
  107271. #define _OV_FILE_H_
  107272. #ifdef __cplusplus
  107273. extern "C"
  107274. {
  107275. #endif /* __cplusplus */
  107276. #include <stdio.h>
  107277. /* The function prototypes for the callbacks are basically the same as for
  107278. * the stdio functions fread, fseek, fclose, ftell.
  107279. * The one difference is that the FILE * arguments have been replaced with
  107280. * a void * - this is to be used as a pointer to whatever internal data these
  107281. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107282. *
  107283. * If you use other functions, check the docs for these functions and return
  107284. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107285. * unseekable
  107286. */
  107287. typedef struct {
  107288. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107289. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107290. int (*close_func) (void *datasource);
  107291. long (*tell_func) (void *datasource);
  107292. } ov_callbacks;
  107293. #define NOTOPEN 0
  107294. #define PARTOPEN 1
  107295. #define OPENED 2
  107296. #define STREAMSET 3
  107297. #define INITSET 4
  107298. typedef struct OggVorbis_File {
  107299. void *datasource; /* Pointer to a FILE *, etc. */
  107300. int seekable;
  107301. ogg_int64_t offset;
  107302. ogg_int64_t end;
  107303. ogg_sync_state oy;
  107304. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107305. stream appears */
  107306. int links;
  107307. ogg_int64_t *offsets;
  107308. ogg_int64_t *dataoffsets;
  107309. long *serialnos;
  107310. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107311. compatability; x2 size, stores both
  107312. beginning and end values */
  107313. vorbis_info *vi;
  107314. vorbis_comment *vc;
  107315. /* Decoding working state local storage */
  107316. ogg_int64_t pcm_offset;
  107317. int ready_state;
  107318. long current_serialno;
  107319. int current_link;
  107320. double bittrack;
  107321. double samptrack;
  107322. ogg_stream_state os; /* take physical pages, weld into a logical
  107323. stream of packets */
  107324. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107325. vorbis_block vb; /* local working space for packet->PCM decode */
  107326. ov_callbacks callbacks;
  107327. } OggVorbis_File;
  107328. extern int ov_clear(OggVorbis_File *vf);
  107329. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107330. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107331. char *initial, long ibytes, ov_callbacks callbacks);
  107332. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107333. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107334. char *initial, long ibytes, ov_callbacks callbacks);
  107335. extern int ov_test_open(OggVorbis_File *vf);
  107336. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107337. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107338. extern long ov_streams(OggVorbis_File *vf);
  107339. extern long ov_seekable(OggVorbis_File *vf);
  107340. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107341. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107342. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107343. extern double ov_time_total(OggVorbis_File *vf,int i);
  107344. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107345. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107346. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107347. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107348. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107349. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107350. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107351. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107352. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107353. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107354. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107355. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107356. extern double ov_time_tell(OggVorbis_File *vf);
  107357. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107358. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107359. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107360. int *bitstream);
  107361. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107362. int bigendianp,int word,int sgned,int *bitstream);
  107363. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107364. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107365. extern int ov_halfrate_p(OggVorbis_File *vf);
  107366. #ifdef __cplusplus
  107367. }
  107368. #endif /* __cplusplus */
  107369. #endif
  107370. /*** End of inlined file: vorbisfile.h ***/
  107371. /*** Start of inlined file: bitwise.c ***/
  107372. /* We're 'LSb' endian; if we write a word but read individual bits,
  107373. then we'll read the lsb first */
  107374. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107375. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107376. // tasks..
  107377. #if JUCE_MSVC
  107378. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107379. #endif
  107380. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107381. #if JUCE_USE_OGGVORBIS
  107382. #include <string.h>
  107383. #include <stdlib.h>
  107384. #define BUFFER_INCREMENT 256
  107385. static const unsigned long mask[]=
  107386. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107387. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107388. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107389. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107390. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107391. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107392. 0x3fffffff,0x7fffffff,0xffffffff };
  107393. static const unsigned int mask8B[]=
  107394. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107395. void oggpack_writeinit(oggpack_buffer *b){
  107396. memset(b,0,sizeof(*b));
  107397. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107398. b->buffer[0]='\0';
  107399. b->storage=BUFFER_INCREMENT;
  107400. }
  107401. void oggpackB_writeinit(oggpack_buffer *b){
  107402. oggpack_writeinit(b);
  107403. }
  107404. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107405. long bytes=bits>>3;
  107406. bits-=bytes*8;
  107407. b->ptr=b->buffer+bytes;
  107408. b->endbit=bits;
  107409. b->endbyte=bytes;
  107410. *b->ptr&=mask[bits];
  107411. }
  107412. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107413. long bytes=bits>>3;
  107414. bits-=bytes*8;
  107415. b->ptr=b->buffer+bytes;
  107416. b->endbit=bits;
  107417. b->endbyte=bytes;
  107418. *b->ptr&=mask8B[bits];
  107419. }
  107420. /* Takes only up to 32 bits. */
  107421. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107422. if(b->endbyte+4>=b->storage){
  107423. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107424. b->storage+=BUFFER_INCREMENT;
  107425. b->ptr=b->buffer+b->endbyte;
  107426. }
  107427. value&=mask[bits];
  107428. bits+=b->endbit;
  107429. b->ptr[0]|=value<<b->endbit;
  107430. if(bits>=8){
  107431. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107432. if(bits>=16){
  107433. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107434. if(bits>=24){
  107435. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107436. if(bits>=32){
  107437. if(b->endbit)
  107438. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107439. else
  107440. b->ptr[4]=0;
  107441. }
  107442. }
  107443. }
  107444. }
  107445. b->endbyte+=bits/8;
  107446. b->ptr+=bits/8;
  107447. b->endbit=bits&7;
  107448. }
  107449. /* Takes only up to 32 bits. */
  107450. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107451. if(b->endbyte+4>=b->storage){
  107452. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107453. b->storage+=BUFFER_INCREMENT;
  107454. b->ptr=b->buffer+b->endbyte;
  107455. }
  107456. value=(value&mask[bits])<<(32-bits);
  107457. bits+=b->endbit;
  107458. b->ptr[0]|=value>>(24+b->endbit);
  107459. if(bits>=8){
  107460. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107461. if(bits>=16){
  107462. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107463. if(bits>=24){
  107464. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107465. if(bits>=32){
  107466. if(b->endbit)
  107467. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107468. else
  107469. b->ptr[4]=0;
  107470. }
  107471. }
  107472. }
  107473. }
  107474. b->endbyte+=bits/8;
  107475. b->ptr+=bits/8;
  107476. b->endbit=bits&7;
  107477. }
  107478. void oggpack_writealign(oggpack_buffer *b){
  107479. int bits=8-b->endbit;
  107480. if(bits<8)
  107481. oggpack_write(b,0,bits);
  107482. }
  107483. void oggpackB_writealign(oggpack_buffer *b){
  107484. int bits=8-b->endbit;
  107485. if(bits<8)
  107486. oggpackB_write(b,0,bits);
  107487. }
  107488. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107489. void *source,
  107490. long bits,
  107491. void (*w)(oggpack_buffer *,
  107492. unsigned long,
  107493. int),
  107494. int msb){
  107495. unsigned char *ptr=(unsigned char *)source;
  107496. long bytes=bits/8;
  107497. bits-=bytes*8;
  107498. if(b->endbit){
  107499. int i;
  107500. /* unaligned copy. Do it the hard way. */
  107501. for(i=0;i<bytes;i++)
  107502. w(b,(unsigned long)(ptr[i]),8);
  107503. }else{
  107504. /* aligned block copy */
  107505. if(b->endbyte+bytes+1>=b->storage){
  107506. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107507. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107508. b->ptr=b->buffer+b->endbyte;
  107509. }
  107510. memmove(b->ptr,source,bytes);
  107511. b->ptr+=bytes;
  107512. b->endbyte+=bytes;
  107513. *b->ptr=0;
  107514. }
  107515. if(bits){
  107516. if(msb)
  107517. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107518. else
  107519. w(b,(unsigned long)(ptr[bytes]),bits);
  107520. }
  107521. }
  107522. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107523. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107524. }
  107525. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107526. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107527. }
  107528. void oggpack_reset(oggpack_buffer *b){
  107529. b->ptr=b->buffer;
  107530. b->buffer[0]=0;
  107531. b->endbit=b->endbyte=0;
  107532. }
  107533. void oggpackB_reset(oggpack_buffer *b){
  107534. oggpack_reset(b);
  107535. }
  107536. void oggpack_writeclear(oggpack_buffer *b){
  107537. _ogg_free(b->buffer);
  107538. memset(b,0,sizeof(*b));
  107539. }
  107540. void oggpackB_writeclear(oggpack_buffer *b){
  107541. oggpack_writeclear(b);
  107542. }
  107543. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107544. memset(b,0,sizeof(*b));
  107545. b->buffer=b->ptr=buf;
  107546. b->storage=bytes;
  107547. }
  107548. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107549. oggpack_readinit(b,buf,bytes);
  107550. }
  107551. /* Read in bits without advancing the bitptr; bits <= 32 */
  107552. long oggpack_look(oggpack_buffer *b,int bits){
  107553. unsigned long ret;
  107554. unsigned long m=mask[bits];
  107555. bits+=b->endbit;
  107556. if(b->endbyte+4>=b->storage){
  107557. /* not the main path */
  107558. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107559. }
  107560. ret=b->ptr[0]>>b->endbit;
  107561. if(bits>8){
  107562. ret|=b->ptr[1]<<(8-b->endbit);
  107563. if(bits>16){
  107564. ret|=b->ptr[2]<<(16-b->endbit);
  107565. if(bits>24){
  107566. ret|=b->ptr[3]<<(24-b->endbit);
  107567. if(bits>32 && b->endbit)
  107568. ret|=b->ptr[4]<<(32-b->endbit);
  107569. }
  107570. }
  107571. }
  107572. return(m&ret);
  107573. }
  107574. /* Read in bits without advancing the bitptr; bits <= 32 */
  107575. long oggpackB_look(oggpack_buffer *b,int bits){
  107576. unsigned long ret;
  107577. int m=32-bits;
  107578. bits+=b->endbit;
  107579. if(b->endbyte+4>=b->storage){
  107580. /* not the main path */
  107581. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107582. }
  107583. ret=b->ptr[0]<<(24+b->endbit);
  107584. if(bits>8){
  107585. ret|=b->ptr[1]<<(16+b->endbit);
  107586. if(bits>16){
  107587. ret|=b->ptr[2]<<(8+b->endbit);
  107588. if(bits>24){
  107589. ret|=b->ptr[3]<<(b->endbit);
  107590. if(bits>32 && b->endbit)
  107591. ret|=b->ptr[4]>>(8-b->endbit);
  107592. }
  107593. }
  107594. }
  107595. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107596. }
  107597. long oggpack_look1(oggpack_buffer *b){
  107598. if(b->endbyte>=b->storage)return(-1);
  107599. return((b->ptr[0]>>b->endbit)&1);
  107600. }
  107601. long oggpackB_look1(oggpack_buffer *b){
  107602. if(b->endbyte>=b->storage)return(-1);
  107603. return((b->ptr[0]>>(7-b->endbit))&1);
  107604. }
  107605. void oggpack_adv(oggpack_buffer *b,int bits){
  107606. bits+=b->endbit;
  107607. b->ptr+=bits/8;
  107608. b->endbyte+=bits/8;
  107609. b->endbit=bits&7;
  107610. }
  107611. void oggpackB_adv(oggpack_buffer *b,int bits){
  107612. oggpack_adv(b,bits);
  107613. }
  107614. void oggpack_adv1(oggpack_buffer *b){
  107615. if(++(b->endbit)>7){
  107616. b->endbit=0;
  107617. b->ptr++;
  107618. b->endbyte++;
  107619. }
  107620. }
  107621. void oggpackB_adv1(oggpack_buffer *b){
  107622. oggpack_adv1(b);
  107623. }
  107624. /* bits <= 32 */
  107625. long oggpack_read(oggpack_buffer *b,int bits){
  107626. long ret;
  107627. unsigned long m=mask[bits];
  107628. bits+=b->endbit;
  107629. if(b->endbyte+4>=b->storage){
  107630. /* not the main path */
  107631. ret=-1L;
  107632. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107633. }
  107634. ret=b->ptr[0]>>b->endbit;
  107635. if(bits>8){
  107636. ret|=b->ptr[1]<<(8-b->endbit);
  107637. if(bits>16){
  107638. ret|=b->ptr[2]<<(16-b->endbit);
  107639. if(bits>24){
  107640. ret|=b->ptr[3]<<(24-b->endbit);
  107641. if(bits>32 && b->endbit){
  107642. ret|=b->ptr[4]<<(32-b->endbit);
  107643. }
  107644. }
  107645. }
  107646. }
  107647. ret&=m;
  107648. overflow:
  107649. b->ptr+=bits/8;
  107650. b->endbyte+=bits/8;
  107651. b->endbit=bits&7;
  107652. return(ret);
  107653. }
  107654. /* bits <= 32 */
  107655. long oggpackB_read(oggpack_buffer *b,int bits){
  107656. long ret;
  107657. long m=32-bits;
  107658. bits+=b->endbit;
  107659. if(b->endbyte+4>=b->storage){
  107660. /* not the main path */
  107661. ret=-1L;
  107662. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107663. }
  107664. ret=b->ptr[0]<<(24+b->endbit);
  107665. if(bits>8){
  107666. ret|=b->ptr[1]<<(16+b->endbit);
  107667. if(bits>16){
  107668. ret|=b->ptr[2]<<(8+b->endbit);
  107669. if(bits>24){
  107670. ret|=b->ptr[3]<<(b->endbit);
  107671. if(bits>32 && b->endbit)
  107672. ret|=b->ptr[4]>>(8-b->endbit);
  107673. }
  107674. }
  107675. }
  107676. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107677. overflow:
  107678. b->ptr+=bits/8;
  107679. b->endbyte+=bits/8;
  107680. b->endbit=bits&7;
  107681. return(ret);
  107682. }
  107683. long oggpack_read1(oggpack_buffer *b){
  107684. long ret;
  107685. if(b->endbyte>=b->storage){
  107686. /* not the main path */
  107687. ret=-1L;
  107688. goto overflow;
  107689. }
  107690. ret=(b->ptr[0]>>b->endbit)&1;
  107691. overflow:
  107692. b->endbit++;
  107693. if(b->endbit>7){
  107694. b->endbit=0;
  107695. b->ptr++;
  107696. b->endbyte++;
  107697. }
  107698. return(ret);
  107699. }
  107700. long oggpackB_read1(oggpack_buffer *b){
  107701. long ret;
  107702. if(b->endbyte>=b->storage){
  107703. /* not the main path */
  107704. ret=-1L;
  107705. goto overflow;
  107706. }
  107707. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107708. overflow:
  107709. b->endbit++;
  107710. if(b->endbit>7){
  107711. b->endbit=0;
  107712. b->ptr++;
  107713. b->endbyte++;
  107714. }
  107715. return(ret);
  107716. }
  107717. long oggpack_bytes(oggpack_buffer *b){
  107718. return(b->endbyte+(b->endbit+7)/8);
  107719. }
  107720. long oggpack_bits(oggpack_buffer *b){
  107721. return(b->endbyte*8+b->endbit);
  107722. }
  107723. long oggpackB_bytes(oggpack_buffer *b){
  107724. return oggpack_bytes(b);
  107725. }
  107726. long oggpackB_bits(oggpack_buffer *b){
  107727. return oggpack_bits(b);
  107728. }
  107729. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107730. return(b->buffer);
  107731. }
  107732. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107733. return oggpack_get_buffer(b);
  107734. }
  107735. /* Self test of the bitwise routines; everything else is based on
  107736. them, so they damned well better be solid. */
  107737. #ifdef _V_SELFTEST
  107738. #include <stdio.h>
  107739. static int ilog(unsigned int v){
  107740. int ret=0;
  107741. while(v){
  107742. ret++;
  107743. v>>=1;
  107744. }
  107745. return(ret);
  107746. }
  107747. oggpack_buffer o;
  107748. oggpack_buffer r;
  107749. void report(char *in){
  107750. fprintf(stderr,"%s",in);
  107751. exit(1);
  107752. }
  107753. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107754. long bytes,i;
  107755. unsigned char *buffer;
  107756. oggpack_reset(&o);
  107757. for(i=0;i<vals;i++)
  107758. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107759. buffer=oggpack_get_buffer(&o);
  107760. bytes=oggpack_bytes(&o);
  107761. if(bytes!=compsize)report("wrong number of bytes!\n");
  107762. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107763. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107764. report("wrote incorrect value!\n");
  107765. }
  107766. oggpack_readinit(&r,buffer,bytes);
  107767. for(i=0;i<vals;i++){
  107768. int tbit=bits?bits:ilog(b[i]);
  107769. if(oggpack_look(&r,tbit)==-1)
  107770. report("out of data!\n");
  107771. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107772. report("looked at incorrect value!\n");
  107773. if(tbit==1)
  107774. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107775. report("looked at single bit incorrect value!\n");
  107776. if(tbit==1){
  107777. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107778. report("read incorrect single bit value!\n");
  107779. }else{
  107780. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107781. report("read incorrect value!\n");
  107782. }
  107783. }
  107784. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107785. }
  107786. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107787. long bytes,i;
  107788. unsigned char *buffer;
  107789. oggpackB_reset(&o);
  107790. for(i=0;i<vals;i++)
  107791. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107792. buffer=oggpackB_get_buffer(&o);
  107793. bytes=oggpackB_bytes(&o);
  107794. if(bytes!=compsize)report("wrong number of bytes!\n");
  107795. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107796. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107797. report("wrote incorrect value!\n");
  107798. }
  107799. oggpackB_readinit(&r,buffer,bytes);
  107800. for(i=0;i<vals;i++){
  107801. int tbit=bits?bits:ilog(b[i]);
  107802. if(oggpackB_look(&r,tbit)==-1)
  107803. report("out of data!\n");
  107804. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107805. report("looked at incorrect value!\n");
  107806. if(tbit==1)
  107807. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107808. report("looked at single bit incorrect value!\n");
  107809. if(tbit==1){
  107810. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107811. report("read incorrect single bit value!\n");
  107812. }else{
  107813. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107814. report("read incorrect value!\n");
  107815. }
  107816. }
  107817. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107818. }
  107819. int main(void){
  107820. unsigned char *buffer;
  107821. long bytes,i;
  107822. static unsigned long testbuffer1[]=
  107823. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107824. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107825. int test1size=43;
  107826. static unsigned long testbuffer2[]=
  107827. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107828. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107829. 85525151,0,12321,1,349528352};
  107830. int test2size=21;
  107831. static unsigned long testbuffer3[]=
  107832. {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,
  107833. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107834. int test3size=56;
  107835. static unsigned long large[]=
  107836. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107837. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107838. 85525151,0,12321,1,2146528352};
  107839. int onesize=33;
  107840. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107841. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107842. 223,4};
  107843. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107844. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107845. 245,251,128};
  107846. int twosize=6;
  107847. static int two[6]={61,255,255,251,231,29};
  107848. static int twoB[6]={247,63,255,253,249,120};
  107849. int threesize=54;
  107850. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107851. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107852. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107853. 100,52,4,14,18,86,77,1};
  107854. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107855. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107856. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107857. 200,20,254,4,58,106,176,144,0};
  107858. int foursize=38;
  107859. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107860. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107861. 28,2,133,0,1};
  107862. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107863. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107864. 129,10,4,32};
  107865. int fivesize=45;
  107866. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107867. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107868. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107869. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107870. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107871. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107872. int sixsize=7;
  107873. static int six[7]={17,177,170,242,169,19,148};
  107874. static int sixB[7]={136,141,85,79,149,200,41};
  107875. /* Test read/write together */
  107876. /* Later we test against pregenerated bitstreams */
  107877. oggpack_writeinit(&o);
  107878. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107879. cliptest(testbuffer1,test1size,0,one,onesize);
  107880. fprintf(stderr,"ok.");
  107881. fprintf(stderr,"\nNull bit call (LSb): ");
  107882. cliptest(testbuffer3,test3size,0,two,twosize);
  107883. fprintf(stderr,"ok.");
  107884. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107885. cliptest(testbuffer2,test2size,0,three,threesize);
  107886. fprintf(stderr,"ok.");
  107887. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107888. oggpack_reset(&o);
  107889. for(i=0;i<test2size;i++)
  107890. oggpack_write(&o,large[i],32);
  107891. buffer=oggpack_get_buffer(&o);
  107892. bytes=oggpack_bytes(&o);
  107893. oggpack_readinit(&r,buffer,bytes);
  107894. for(i=0;i<test2size;i++){
  107895. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107896. if(oggpack_look(&r,32)!=large[i]){
  107897. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107898. oggpack_look(&r,32),large[i]);
  107899. report("read incorrect value!\n");
  107900. }
  107901. oggpack_adv(&r,32);
  107902. }
  107903. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107904. fprintf(stderr,"ok.");
  107905. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107906. cliptest(testbuffer1,test1size,7,four,foursize);
  107907. fprintf(stderr,"ok.");
  107908. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107909. cliptest(testbuffer2,test2size,17,five,fivesize);
  107910. fprintf(stderr,"ok.");
  107911. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107912. cliptest(testbuffer3,test3size,1,six,sixsize);
  107913. fprintf(stderr,"ok.");
  107914. fprintf(stderr,"\nTesting read past end (LSb): ");
  107915. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107916. for(i=0;i<64;i++){
  107917. if(oggpack_read(&r,1)!=0){
  107918. fprintf(stderr,"failed; got -1 prematurely.\n");
  107919. exit(1);
  107920. }
  107921. }
  107922. if(oggpack_look(&r,1)!=-1 ||
  107923. oggpack_read(&r,1)!=-1){
  107924. fprintf(stderr,"failed; read past end without -1.\n");
  107925. exit(1);
  107926. }
  107927. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107928. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107929. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107930. exit(1);
  107931. }
  107932. if(oggpack_look(&r,18)!=0 ||
  107933. oggpack_look(&r,18)!=0){
  107934. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107935. exit(1);
  107936. }
  107937. if(oggpack_look(&r,19)!=-1 ||
  107938. oggpack_look(&r,19)!=-1){
  107939. fprintf(stderr,"failed; read past end without -1.\n");
  107940. exit(1);
  107941. }
  107942. if(oggpack_look(&r,32)!=-1 ||
  107943. oggpack_look(&r,32)!=-1){
  107944. fprintf(stderr,"failed; read past end without -1.\n");
  107945. exit(1);
  107946. }
  107947. oggpack_writeclear(&o);
  107948. fprintf(stderr,"ok.\n");
  107949. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107950. /* Test read/write together */
  107951. /* Later we test against pregenerated bitstreams */
  107952. oggpackB_writeinit(&o);
  107953. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107954. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107955. fprintf(stderr,"ok.");
  107956. fprintf(stderr,"\nNull bit call (MSb): ");
  107957. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107958. fprintf(stderr,"ok.");
  107959. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107960. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107961. fprintf(stderr,"ok.");
  107962. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107963. oggpackB_reset(&o);
  107964. for(i=0;i<test2size;i++)
  107965. oggpackB_write(&o,large[i],32);
  107966. buffer=oggpackB_get_buffer(&o);
  107967. bytes=oggpackB_bytes(&o);
  107968. oggpackB_readinit(&r,buffer,bytes);
  107969. for(i=0;i<test2size;i++){
  107970. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107971. if(oggpackB_look(&r,32)!=large[i]){
  107972. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107973. oggpackB_look(&r,32),large[i]);
  107974. report("read incorrect value!\n");
  107975. }
  107976. oggpackB_adv(&r,32);
  107977. }
  107978. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107979. fprintf(stderr,"ok.");
  107980. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107981. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107982. fprintf(stderr,"ok.");
  107983. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107984. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107985. fprintf(stderr,"ok.");
  107986. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107987. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107988. fprintf(stderr,"ok.");
  107989. fprintf(stderr,"\nTesting read past end (MSb): ");
  107990. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107991. for(i=0;i<64;i++){
  107992. if(oggpackB_read(&r,1)!=0){
  107993. fprintf(stderr,"failed; got -1 prematurely.\n");
  107994. exit(1);
  107995. }
  107996. }
  107997. if(oggpackB_look(&r,1)!=-1 ||
  107998. oggpackB_read(&r,1)!=-1){
  107999. fprintf(stderr,"failed; read past end without -1.\n");
  108000. exit(1);
  108001. }
  108002. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108003. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108004. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108005. exit(1);
  108006. }
  108007. if(oggpackB_look(&r,18)!=0 ||
  108008. oggpackB_look(&r,18)!=0){
  108009. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108010. exit(1);
  108011. }
  108012. if(oggpackB_look(&r,19)!=-1 ||
  108013. oggpackB_look(&r,19)!=-1){
  108014. fprintf(stderr,"failed; read past end without -1.\n");
  108015. exit(1);
  108016. }
  108017. if(oggpackB_look(&r,32)!=-1 ||
  108018. oggpackB_look(&r,32)!=-1){
  108019. fprintf(stderr,"failed; read past end without -1.\n");
  108020. exit(1);
  108021. }
  108022. oggpackB_writeclear(&o);
  108023. fprintf(stderr,"ok.\n\n");
  108024. return(0);
  108025. }
  108026. #endif /* _V_SELFTEST */
  108027. #undef BUFFER_INCREMENT
  108028. #endif
  108029. /*** End of inlined file: bitwise.c ***/
  108030. /*** Start of inlined file: framing.c ***/
  108031. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108032. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108033. // tasks..
  108034. #if JUCE_MSVC
  108035. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108036. #endif
  108037. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108038. #if JUCE_USE_OGGVORBIS
  108039. #include <stdlib.h>
  108040. #include <string.h>
  108041. /* A complete description of Ogg framing exists in docs/framing.html */
  108042. int ogg_page_version(ogg_page *og){
  108043. return((int)(og->header[4]));
  108044. }
  108045. int ogg_page_continued(ogg_page *og){
  108046. return((int)(og->header[5]&0x01));
  108047. }
  108048. int ogg_page_bos(ogg_page *og){
  108049. return((int)(og->header[5]&0x02));
  108050. }
  108051. int ogg_page_eos(ogg_page *og){
  108052. return((int)(og->header[5]&0x04));
  108053. }
  108054. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108055. unsigned char *page=og->header;
  108056. ogg_int64_t granulepos=page[13]&(0xff);
  108057. granulepos= (granulepos<<8)|(page[12]&0xff);
  108058. granulepos= (granulepos<<8)|(page[11]&0xff);
  108059. granulepos= (granulepos<<8)|(page[10]&0xff);
  108060. granulepos= (granulepos<<8)|(page[9]&0xff);
  108061. granulepos= (granulepos<<8)|(page[8]&0xff);
  108062. granulepos= (granulepos<<8)|(page[7]&0xff);
  108063. granulepos= (granulepos<<8)|(page[6]&0xff);
  108064. return(granulepos);
  108065. }
  108066. int ogg_page_serialno(ogg_page *og){
  108067. return(og->header[14] |
  108068. (og->header[15]<<8) |
  108069. (og->header[16]<<16) |
  108070. (og->header[17]<<24));
  108071. }
  108072. long ogg_page_pageno(ogg_page *og){
  108073. return(og->header[18] |
  108074. (og->header[19]<<8) |
  108075. (og->header[20]<<16) |
  108076. (og->header[21]<<24));
  108077. }
  108078. /* returns the number of packets that are completed on this page (if
  108079. the leading packet is begun on a previous page, but ends on this
  108080. page, it's counted */
  108081. /* NOTE:
  108082. If a page consists of a packet begun on a previous page, and a new
  108083. packet begun (but not completed) on this page, the return will be:
  108084. ogg_page_packets(page) ==1,
  108085. ogg_page_continued(page) !=0
  108086. If a page happens to be a single packet that was begun on a
  108087. previous page, and spans to the next page (in the case of a three or
  108088. more page packet), the return will be:
  108089. ogg_page_packets(page) ==0,
  108090. ogg_page_continued(page) !=0
  108091. */
  108092. int ogg_page_packets(ogg_page *og){
  108093. int i,n=og->header[26],count=0;
  108094. for(i=0;i<n;i++)
  108095. if(og->header[27+i]<255)count++;
  108096. return(count);
  108097. }
  108098. #if 0
  108099. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108100. use the static init below) */
  108101. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108102. int i;
  108103. unsigned long r;
  108104. r = index << 24;
  108105. for (i=0; i<8; i++)
  108106. if (r & 0x80000000UL)
  108107. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108108. polynomial, although we use an
  108109. unreflected alg and an init/final
  108110. of 0, not 0xffffffff */
  108111. else
  108112. r<<=1;
  108113. return (r & 0xffffffffUL);
  108114. }
  108115. #endif
  108116. static const ogg_uint32_t crc_lookup[256]={
  108117. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108118. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108119. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108120. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108121. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108122. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108123. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108124. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108125. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108126. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108127. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108128. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108129. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108130. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108131. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108132. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108133. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108134. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108135. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108136. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108137. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108138. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108139. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108140. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108141. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108142. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108143. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108144. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108145. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108146. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108147. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108148. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108149. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108150. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108151. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108152. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108153. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108154. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108155. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108156. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108157. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108158. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108159. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108160. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108161. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108162. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108163. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108164. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108165. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108166. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108167. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108168. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108169. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108170. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108171. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108172. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108173. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108174. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108175. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108176. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108177. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108178. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108179. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108180. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108181. /* init the encode/decode logical stream state */
  108182. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108183. if(os){
  108184. memset(os,0,sizeof(*os));
  108185. os->body_storage=16*1024;
  108186. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108187. os->lacing_storage=1024;
  108188. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108189. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108190. os->serialno=serialno;
  108191. return(0);
  108192. }
  108193. return(-1);
  108194. }
  108195. /* _clear does not free os, only the non-flat storage within */
  108196. int ogg_stream_clear(ogg_stream_state *os){
  108197. if(os){
  108198. if(os->body_data)_ogg_free(os->body_data);
  108199. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108200. if(os->granule_vals)_ogg_free(os->granule_vals);
  108201. memset(os,0,sizeof(*os));
  108202. }
  108203. return(0);
  108204. }
  108205. int ogg_stream_destroy(ogg_stream_state *os){
  108206. if(os){
  108207. ogg_stream_clear(os);
  108208. _ogg_free(os);
  108209. }
  108210. return(0);
  108211. }
  108212. /* Helpers for ogg_stream_encode; this keeps the structure and
  108213. what's happening fairly clear */
  108214. static void _os_body_expand(ogg_stream_state *os,int needed){
  108215. if(os->body_storage<=os->body_fill+needed){
  108216. os->body_storage+=(needed+1024);
  108217. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108218. }
  108219. }
  108220. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108221. if(os->lacing_storage<=os->lacing_fill+needed){
  108222. os->lacing_storage+=(needed+32);
  108223. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108224. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108225. }
  108226. }
  108227. /* checksum the page */
  108228. /* Direct table CRC; note that this will be faster in the future if we
  108229. perform the checksum silmultaneously with other copies */
  108230. void ogg_page_checksum_set(ogg_page *og){
  108231. if(og){
  108232. ogg_uint32_t crc_reg=0;
  108233. int i;
  108234. /* safety; needed for API behavior, but not framing code */
  108235. og->header[22]=0;
  108236. og->header[23]=0;
  108237. og->header[24]=0;
  108238. og->header[25]=0;
  108239. for(i=0;i<og->header_len;i++)
  108240. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108241. for(i=0;i<og->body_len;i++)
  108242. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108243. og->header[22]=(unsigned char)(crc_reg&0xff);
  108244. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108245. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108246. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108247. }
  108248. }
  108249. /* submit data to the internal buffer of the framing engine */
  108250. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108251. int lacing_vals=op->bytes/255+1,i;
  108252. if(os->body_returned){
  108253. /* advance packet data according to the body_returned pointer. We
  108254. had to keep it around to return a pointer into the buffer last
  108255. call */
  108256. os->body_fill-=os->body_returned;
  108257. if(os->body_fill)
  108258. memmove(os->body_data,os->body_data+os->body_returned,
  108259. os->body_fill);
  108260. os->body_returned=0;
  108261. }
  108262. /* make sure we have the buffer storage */
  108263. _os_body_expand(os,op->bytes);
  108264. _os_lacing_expand(os,lacing_vals);
  108265. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108266. the liability of overly clean abstraction for the time being. It
  108267. will actually be fairly easy to eliminate the extra copy in the
  108268. future */
  108269. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108270. os->body_fill+=op->bytes;
  108271. /* Store lacing vals for this packet */
  108272. for(i=0;i<lacing_vals-1;i++){
  108273. os->lacing_vals[os->lacing_fill+i]=255;
  108274. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108275. }
  108276. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108277. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108278. /* flag the first segment as the beginning of the packet */
  108279. os->lacing_vals[os->lacing_fill]|= 0x100;
  108280. os->lacing_fill+=lacing_vals;
  108281. /* for the sake of completeness */
  108282. os->packetno++;
  108283. if(op->e_o_s)os->e_o_s=1;
  108284. return(0);
  108285. }
  108286. /* This will flush remaining packets into a page (returning nonzero),
  108287. even if there is not enough data to trigger a flush normally
  108288. (undersized page). If there are no packets or partial packets to
  108289. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108290. try to flush a normal sized page like ogg_stream_pageout; a call to
  108291. ogg_stream_flush does not guarantee that all packets have flushed.
  108292. Only a return value of 0 from ogg_stream_flush indicates all packet
  108293. data is flushed into pages.
  108294. since ogg_stream_flush will flush the last page in a stream even if
  108295. it's undersized, you almost certainly want to use ogg_stream_pageout
  108296. (and *not* ogg_stream_flush) unless you specifically need to flush
  108297. an page regardless of size in the middle of a stream. */
  108298. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108299. int i;
  108300. int vals=0;
  108301. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108302. int bytes=0;
  108303. long acc=0;
  108304. ogg_int64_t granule_pos=-1;
  108305. if(maxvals==0)return(0);
  108306. /* construct a page */
  108307. /* decide how many segments to include */
  108308. /* If this is the initial header case, the first page must only include
  108309. the initial header packet */
  108310. if(os->b_o_s==0){ /* 'initial header page' case */
  108311. granule_pos=0;
  108312. for(vals=0;vals<maxvals;vals++){
  108313. if((os->lacing_vals[vals]&0x0ff)<255){
  108314. vals++;
  108315. break;
  108316. }
  108317. }
  108318. }else{
  108319. for(vals=0;vals<maxvals;vals++){
  108320. if(acc>4096)break;
  108321. acc+=os->lacing_vals[vals]&0x0ff;
  108322. if((os->lacing_vals[vals]&0xff)<255)
  108323. granule_pos=os->granule_vals[vals];
  108324. }
  108325. }
  108326. /* construct the header in temp storage */
  108327. memcpy(os->header,"OggS",4);
  108328. /* stream structure version */
  108329. os->header[4]=0x00;
  108330. /* continued packet flag? */
  108331. os->header[5]=0x00;
  108332. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108333. /* first page flag? */
  108334. if(os->b_o_s==0)os->header[5]|=0x02;
  108335. /* last page flag? */
  108336. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108337. os->b_o_s=1;
  108338. /* 64 bits of PCM position */
  108339. for(i=6;i<14;i++){
  108340. os->header[i]=(unsigned char)(granule_pos&0xff);
  108341. granule_pos>>=8;
  108342. }
  108343. /* 32 bits of stream serial number */
  108344. {
  108345. long serialno=os->serialno;
  108346. for(i=14;i<18;i++){
  108347. os->header[i]=(unsigned char)(serialno&0xff);
  108348. serialno>>=8;
  108349. }
  108350. }
  108351. /* 32 bits of page counter (we have both counter and page header
  108352. because this val can roll over) */
  108353. if(os->pageno==-1)os->pageno=0; /* because someone called
  108354. stream_reset; this would be a
  108355. strange thing to do in an
  108356. encode stream, but it has
  108357. plausible uses */
  108358. {
  108359. long pageno=os->pageno++;
  108360. for(i=18;i<22;i++){
  108361. os->header[i]=(unsigned char)(pageno&0xff);
  108362. pageno>>=8;
  108363. }
  108364. }
  108365. /* zero for computation; filled in later */
  108366. os->header[22]=0;
  108367. os->header[23]=0;
  108368. os->header[24]=0;
  108369. os->header[25]=0;
  108370. /* segment table */
  108371. os->header[26]=(unsigned char)(vals&0xff);
  108372. for(i=0;i<vals;i++)
  108373. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108374. /* set pointers in the ogg_page struct */
  108375. og->header=os->header;
  108376. og->header_len=os->header_fill=vals+27;
  108377. og->body=os->body_data+os->body_returned;
  108378. og->body_len=bytes;
  108379. /* advance the lacing data and set the body_returned pointer */
  108380. os->lacing_fill-=vals;
  108381. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108382. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108383. os->body_returned+=bytes;
  108384. /* calculate the checksum */
  108385. ogg_page_checksum_set(og);
  108386. /* done */
  108387. return(1);
  108388. }
  108389. /* This constructs pages from buffered packet segments. The pointers
  108390. returned are to static buffers; do not free. The returned buffers are
  108391. good only until the next call (using the same ogg_stream_state) */
  108392. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108393. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108394. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108395. os->lacing_fill>=255 || /* 'segment table full' case */
  108396. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108397. return(ogg_stream_flush(os,og));
  108398. }
  108399. /* not enough data to construct a page and not end of stream */
  108400. return(0);
  108401. }
  108402. int ogg_stream_eos(ogg_stream_state *os){
  108403. return os->e_o_s;
  108404. }
  108405. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108406. /* This has two layers to place more of the multi-serialno and paging
  108407. control in the application's hands. First, we expose a data buffer
  108408. using ogg_sync_buffer(). The app either copies into the
  108409. buffer, or passes it directly to read(), etc. We then call
  108410. ogg_sync_wrote() to tell how many bytes we just added.
  108411. Pages are returned (pointers into the buffer in ogg_sync_state)
  108412. by ogg_sync_pageout(). The page is then submitted to
  108413. ogg_stream_pagein() along with the appropriate
  108414. ogg_stream_state* (ie, matching serialno). We then get raw
  108415. packets out calling ogg_stream_packetout() with a
  108416. ogg_stream_state. */
  108417. /* initialize the struct to a known state */
  108418. int ogg_sync_init(ogg_sync_state *oy){
  108419. if(oy){
  108420. memset(oy,0,sizeof(*oy));
  108421. }
  108422. return(0);
  108423. }
  108424. /* clear non-flat storage within */
  108425. int ogg_sync_clear(ogg_sync_state *oy){
  108426. if(oy){
  108427. if(oy->data)_ogg_free(oy->data);
  108428. ogg_sync_init(oy);
  108429. }
  108430. return(0);
  108431. }
  108432. int ogg_sync_destroy(ogg_sync_state *oy){
  108433. if(oy){
  108434. ogg_sync_clear(oy);
  108435. _ogg_free(oy);
  108436. }
  108437. return(0);
  108438. }
  108439. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108440. /* first, clear out any space that has been previously returned */
  108441. if(oy->returned){
  108442. oy->fill-=oy->returned;
  108443. if(oy->fill>0)
  108444. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108445. oy->returned=0;
  108446. }
  108447. if(size>oy->storage-oy->fill){
  108448. /* We need to extend the internal buffer */
  108449. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108450. if(oy->data)
  108451. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108452. else
  108453. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108454. oy->storage=newsize;
  108455. }
  108456. /* expose a segment at least as large as requested at the fill mark */
  108457. return((char *)oy->data+oy->fill);
  108458. }
  108459. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108460. if(oy->fill+bytes>oy->storage)return(-1);
  108461. oy->fill+=bytes;
  108462. return(0);
  108463. }
  108464. /* sync the stream. This is meant to be useful for finding page
  108465. boundaries.
  108466. return values for this:
  108467. -n) skipped n bytes
  108468. 0) page not ready; more data (no bytes skipped)
  108469. n) page synced at current location; page length n bytes
  108470. */
  108471. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108472. unsigned char *page=oy->data+oy->returned;
  108473. unsigned char *next;
  108474. long bytes=oy->fill-oy->returned;
  108475. if(oy->headerbytes==0){
  108476. int headerbytes,i;
  108477. if(bytes<27)return(0); /* not enough for a header */
  108478. /* verify capture pattern */
  108479. if(memcmp(page,"OggS",4))goto sync_fail;
  108480. headerbytes=page[26]+27;
  108481. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108482. /* count up body length in the segment table */
  108483. for(i=0;i<page[26];i++)
  108484. oy->bodybytes+=page[27+i];
  108485. oy->headerbytes=headerbytes;
  108486. }
  108487. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108488. /* The whole test page is buffered. Verify the checksum */
  108489. {
  108490. /* Grab the checksum bytes, set the header field to zero */
  108491. char chksum[4];
  108492. ogg_page log;
  108493. memcpy(chksum,page+22,4);
  108494. memset(page+22,0,4);
  108495. /* set up a temp page struct and recompute the checksum */
  108496. log.header=page;
  108497. log.header_len=oy->headerbytes;
  108498. log.body=page+oy->headerbytes;
  108499. log.body_len=oy->bodybytes;
  108500. ogg_page_checksum_set(&log);
  108501. /* Compare */
  108502. if(memcmp(chksum,page+22,4)){
  108503. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108504. at all) */
  108505. /* replace the computed checksum with the one actually read in */
  108506. memcpy(page+22,chksum,4);
  108507. /* Bad checksum. Lose sync */
  108508. goto sync_fail;
  108509. }
  108510. }
  108511. /* yes, have a whole page all ready to go */
  108512. {
  108513. unsigned char *page=oy->data+oy->returned;
  108514. long bytes;
  108515. if(og){
  108516. og->header=page;
  108517. og->header_len=oy->headerbytes;
  108518. og->body=page+oy->headerbytes;
  108519. og->body_len=oy->bodybytes;
  108520. }
  108521. oy->unsynced=0;
  108522. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108523. oy->headerbytes=0;
  108524. oy->bodybytes=0;
  108525. return(bytes);
  108526. }
  108527. sync_fail:
  108528. oy->headerbytes=0;
  108529. oy->bodybytes=0;
  108530. /* search for possible capture */
  108531. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108532. if(!next)
  108533. next=oy->data+oy->fill;
  108534. oy->returned=next-oy->data;
  108535. return(-(next-page));
  108536. }
  108537. /* sync the stream and get a page. Keep trying until we find a page.
  108538. Supress 'sync errors' after reporting the first.
  108539. return values:
  108540. -1) recapture (hole in data)
  108541. 0) need more data
  108542. 1) page returned
  108543. Returns pointers into buffered data; invalidated by next call to
  108544. _stream, _clear, _init, or _buffer */
  108545. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108546. /* all we need to do is verify a page at the head of the stream
  108547. buffer. If it doesn't verify, we look for the next potential
  108548. frame */
  108549. for(;;){
  108550. long ret=ogg_sync_pageseek(oy,og);
  108551. if(ret>0){
  108552. /* have a page */
  108553. return(1);
  108554. }
  108555. if(ret==0){
  108556. /* need more data */
  108557. return(0);
  108558. }
  108559. /* head did not start a synced page... skipped some bytes */
  108560. if(!oy->unsynced){
  108561. oy->unsynced=1;
  108562. return(-1);
  108563. }
  108564. /* loop. keep looking */
  108565. }
  108566. }
  108567. /* add the incoming page to the stream state; we decompose the page
  108568. into packet segments here as well. */
  108569. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108570. unsigned char *header=og->header;
  108571. unsigned char *body=og->body;
  108572. long bodysize=og->body_len;
  108573. int segptr=0;
  108574. int version=ogg_page_version(og);
  108575. int continued=ogg_page_continued(og);
  108576. int bos=ogg_page_bos(og);
  108577. int eos=ogg_page_eos(og);
  108578. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108579. int serialno=ogg_page_serialno(og);
  108580. long pageno=ogg_page_pageno(og);
  108581. int segments=header[26];
  108582. /* clean up 'returned data' */
  108583. {
  108584. long lr=os->lacing_returned;
  108585. long br=os->body_returned;
  108586. /* body data */
  108587. if(br){
  108588. os->body_fill-=br;
  108589. if(os->body_fill)
  108590. memmove(os->body_data,os->body_data+br,os->body_fill);
  108591. os->body_returned=0;
  108592. }
  108593. if(lr){
  108594. /* segment table */
  108595. if(os->lacing_fill-lr){
  108596. memmove(os->lacing_vals,os->lacing_vals+lr,
  108597. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108598. memmove(os->granule_vals,os->granule_vals+lr,
  108599. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108600. }
  108601. os->lacing_fill-=lr;
  108602. os->lacing_packet-=lr;
  108603. os->lacing_returned=0;
  108604. }
  108605. }
  108606. /* check the serial number */
  108607. if(serialno!=os->serialno)return(-1);
  108608. if(version>0)return(-1);
  108609. _os_lacing_expand(os,segments+1);
  108610. /* are we in sequence? */
  108611. if(pageno!=os->pageno){
  108612. int i;
  108613. /* unroll previous partial packet (if any) */
  108614. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108615. os->body_fill-=os->lacing_vals[i]&0xff;
  108616. os->lacing_fill=os->lacing_packet;
  108617. /* make a note of dropped data in segment table */
  108618. if(os->pageno!=-1){
  108619. os->lacing_vals[os->lacing_fill++]=0x400;
  108620. os->lacing_packet++;
  108621. }
  108622. }
  108623. /* are we a 'continued packet' page? If so, we may need to skip
  108624. some segments */
  108625. if(continued){
  108626. if(os->lacing_fill<1 ||
  108627. os->lacing_vals[os->lacing_fill-1]==0x400){
  108628. bos=0;
  108629. for(;segptr<segments;segptr++){
  108630. int val=header[27+segptr];
  108631. body+=val;
  108632. bodysize-=val;
  108633. if(val<255){
  108634. segptr++;
  108635. break;
  108636. }
  108637. }
  108638. }
  108639. }
  108640. if(bodysize){
  108641. _os_body_expand(os,bodysize);
  108642. memcpy(os->body_data+os->body_fill,body,bodysize);
  108643. os->body_fill+=bodysize;
  108644. }
  108645. {
  108646. int saved=-1;
  108647. while(segptr<segments){
  108648. int val=header[27+segptr];
  108649. os->lacing_vals[os->lacing_fill]=val;
  108650. os->granule_vals[os->lacing_fill]=-1;
  108651. if(bos){
  108652. os->lacing_vals[os->lacing_fill]|=0x100;
  108653. bos=0;
  108654. }
  108655. if(val<255)saved=os->lacing_fill;
  108656. os->lacing_fill++;
  108657. segptr++;
  108658. if(val<255)os->lacing_packet=os->lacing_fill;
  108659. }
  108660. /* set the granulepos on the last granuleval of the last full packet */
  108661. if(saved!=-1){
  108662. os->granule_vals[saved]=granulepos;
  108663. }
  108664. }
  108665. if(eos){
  108666. os->e_o_s=1;
  108667. if(os->lacing_fill>0)
  108668. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108669. }
  108670. os->pageno=pageno+1;
  108671. return(0);
  108672. }
  108673. /* clear things to an initial state. Good to call, eg, before seeking */
  108674. int ogg_sync_reset(ogg_sync_state *oy){
  108675. oy->fill=0;
  108676. oy->returned=0;
  108677. oy->unsynced=0;
  108678. oy->headerbytes=0;
  108679. oy->bodybytes=0;
  108680. return(0);
  108681. }
  108682. int ogg_stream_reset(ogg_stream_state *os){
  108683. os->body_fill=0;
  108684. os->body_returned=0;
  108685. os->lacing_fill=0;
  108686. os->lacing_packet=0;
  108687. os->lacing_returned=0;
  108688. os->header_fill=0;
  108689. os->e_o_s=0;
  108690. os->b_o_s=0;
  108691. os->pageno=-1;
  108692. os->packetno=0;
  108693. os->granulepos=0;
  108694. return(0);
  108695. }
  108696. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108697. ogg_stream_reset(os);
  108698. os->serialno=serialno;
  108699. return(0);
  108700. }
  108701. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108702. /* The last part of decode. We have the stream broken into packet
  108703. segments. Now we need to group them into packets (or return the
  108704. out of sync markers) */
  108705. int ptr=os->lacing_returned;
  108706. if(os->lacing_packet<=ptr)return(0);
  108707. if(os->lacing_vals[ptr]&0x400){
  108708. /* we need to tell the codec there's a gap; it might need to
  108709. handle previous packet dependencies. */
  108710. os->lacing_returned++;
  108711. os->packetno++;
  108712. return(-1);
  108713. }
  108714. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108715. to ask if there's a whole packet
  108716. waiting */
  108717. /* Gather the whole packet. We'll have no holes or a partial packet */
  108718. {
  108719. int size=os->lacing_vals[ptr]&0xff;
  108720. int bytes=size;
  108721. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108722. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108723. while(size==255){
  108724. int val=os->lacing_vals[++ptr];
  108725. size=val&0xff;
  108726. if(val&0x200)eos=0x200;
  108727. bytes+=size;
  108728. }
  108729. if(op){
  108730. op->e_o_s=eos;
  108731. op->b_o_s=bos;
  108732. op->packet=os->body_data+os->body_returned;
  108733. op->packetno=os->packetno;
  108734. op->granulepos=os->granule_vals[ptr];
  108735. op->bytes=bytes;
  108736. }
  108737. if(adv){
  108738. os->body_returned+=bytes;
  108739. os->lacing_returned=ptr+1;
  108740. os->packetno++;
  108741. }
  108742. }
  108743. return(1);
  108744. }
  108745. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108746. return _packetout(os,op,1);
  108747. }
  108748. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108749. return _packetout(os,op,0);
  108750. }
  108751. void ogg_packet_clear(ogg_packet *op) {
  108752. _ogg_free(op->packet);
  108753. memset(op, 0, sizeof(*op));
  108754. }
  108755. #ifdef _V_SELFTEST
  108756. #include <stdio.h>
  108757. ogg_stream_state os_en, os_de;
  108758. ogg_sync_state oy;
  108759. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108760. long j;
  108761. static int sequence=0;
  108762. static int lastno=0;
  108763. if(op->bytes!=len){
  108764. fprintf(stderr,"incorrect packet length!\n");
  108765. exit(1);
  108766. }
  108767. if(op->granulepos!=pos){
  108768. fprintf(stderr,"incorrect packet position!\n");
  108769. exit(1);
  108770. }
  108771. /* packet number just follows sequence/gap; adjust the input number
  108772. for that */
  108773. if(no==0){
  108774. sequence=0;
  108775. }else{
  108776. sequence++;
  108777. if(no>lastno+1)
  108778. sequence++;
  108779. }
  108780. lastno=no;
  108781. if(op->packetno!=sequence){
  108782. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108783. (long)(op->packetno),sequence);
  108784. exit(1);
  108785. }
  108786. /* Test data */
  108787. for(j=0;j<op->bytes;j++)
  108788. if(op->packet[j]!=((j+no)&0xff)){
  108789. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108790. j,op->packet[j],(j+no)&0xff);
  108791. exit(1);
  108792. }
  108793. }
  108794. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108795. long j;
  108796. /* Test data */
  108797. for(j=0;j<og->body_len;j++)
  108798. if(og->body[j]!=data[j]){
  108799. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108800. j,data[j],og->body[j]);
  108801. exit(1);
  108802. }
  108803. /* Test header */
  108804. for(j=0;j<og->header_len;j++){
  108805. if(og->header[j]!=header[j]){
  108806. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108807. for(j=0;j<header[26]+27;j++)
  108808. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108809. fprintf(stderr,"\n");
  108810. exit(1);
  108811. }
  108812. }
  108813. if(og->header_len!=header[26]+27){
  108814. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108815. og->header_len,header[26]+27);
  108816. exit(1);
  108817. }
  108818. }
  108819. void print_header(ogg_page *og){
  108820. int j;
  108821. fprintf(stderr,"\nHEADER:\n");
  108822. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108823. og->header[0],og->header[1],og->header[2],og->header[3],
  108824. (int)og->header[4],(int)og->header[5]);
  108825. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108826. (og->header[9]<<24)|(og->header[8]<<16)|
  108827. (og->header[7]<<8)|og->header[6],
  108828. (og->header[17]<<24)|(og->header[16]<<16)|
  108829. (og->header[15]<<8)|og->header[14],
  108830. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108831. (og->header[19]<<8)|og->header[18]);
  108832. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108833. (int)og->header[22],(int)og->header[23],
  108834. (int)og->header[24],(int)og->header[25],
  108835. (int)og->header[26]);
  108836. for(j=27;j<og->header_len;j++)
  108837. fprintf(stderr,"%d ",(int)og->header[j]);
  108838. fprintf(stderr,")\n\n");
  108839. }
  108840. void copy_page(ogg_page *og){
  108841. unsigned char *temp=_ogg_malloc(og->header_len);
  108842. memcpy(temp,og->header,og->header_len);
  108843. og->header=temp;
  108844. temp=_ogg_malloc(og->body_len);
  108845. memcpy(temp,og->body,og->body_len);
  108846. og->body=temp;
  108847. }
  108848. void free_page(ogg_page *og){
  108849. _ogg_free (og->header);
  108850. _ogg_free (og->body);
  108851. }
  108852. void error(void){
  108853. fprintf(stderr,"error!\n");
  108854. exit(1);
  108855. }
  108856. /* 17 only */
  108857. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108858. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108859. 0x01,0x02,0x03,0x04,0,0,0,0,
  108860. 0x15,0xed,0xec,0x91,
  108861. 1,
  108862. 17};
  108863. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108864. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108865. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108866. 0x01,0x02,0x03,0x04,0,0,0,0,
  108867. 0x59,0x10,0x6c,0x2c,
  108868. 1,
  108869. 17};
  108870. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108871. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108872. 0x01,0x02,0x03,0x04,1,0,0,0,
  108873. 0x89,0x33,0x85,0xce,
  108874. 13,
  108875. 254,255,0,255,1,255,245,255,255,0,
  108876. 255,255,90};
  108877. /* nil packets; beginning,middle,end */
  108878. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108879. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108880. 0x01,0x02,0x03,0x04,0,0,0,0,
  108881. 0xff,0x7b,0x23,0x17,
  108882. 1,
  108883. 0};
  108884. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108885. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108886. 0x01,0x02,0x03,0x04,1,0,0,0,
  108887. 0x5c,0x3f,0x66,0xcb,
  108888. 17,
  108889. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108890. 255,255,90,0};
  108891. /* large initial packet */
  108892. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108893. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108894. 0x01,0x02,0x03,0x04,0,0,0,0,
  108895. 0x01,0x27,0x31,0xaa,
  108896. 18,
  108897. 255,255,255,255,255,255,255,255,
  108898. 255,255,255,255,255,255,255,255,255,10};
  108899. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108900. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108901. 0x01,0x02,0x03,0x04,1,0,0,0,
  108902. 0x7f,0x4e,0x8a,0xd2,
  108903. 4,
  108904. 255,4,255,0};
  108905. /* continuing packet test */
  108906. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108907. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108908. 0x01,0x02,0x03,0x04,0,0,0,0,
  108909. 0xff,0x7b,0x23,0x17,
  108910. 1,
  108911. 0};
  108912. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108913. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108914. 0x01,0x02,0x03,0x04,1,0,0,0,
  108915. 0x54,0x05,0x51,0xc8,
  108916. 17,
  108917. 255,255,255,255,255,255,255,255,
  108918. 255,255,255,255,255,255,255,255,255};
  108919. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108920. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108921. 0x01,0x02,0x03,0x04,2,0,0,0,
  108922. 0xc8,0xc3,0xcb,0xed,
  108923. 5,
  108924. 10,255,4,255,0};
  108925. /* page with the 255 segment limit */
  108926. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108927. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108928. 0x01,0x02,0x03,0x04,0,0,0,0,
  108929. 0xff,0x7b,0x23,0x17,
  108930. 1,
  108931. 0};
  108932. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108933. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108934. 0x01,0x02,0x03,0x04,1,0,0,0,
  108935. 0xed,0x2a,0x2e,0xa7,
  108936. 255,
  108937. 10,10,10,10,10,10,10,10,
  108938. 10,10,10,10,10,10,10,10,
  108939. 10,10,10,10,10,10,10,10,
  108940. 10,10,10,10,10,10,10,10,
  108941. 10,10,10,10,10,10,10,10,
  108942. 10,10,10,10,10,10,10,10,
  108943. 10,10,10,10,10,10,10,10,
  108944. 10,10,10,10,10,10,10,10,
  108945. 10,10,10,10,10,10,10,10,
  108946. 10,10,10,10,10,10,10,10,
  108947. 10,10,10,10,10,10,10,10,
  108948. 10,10,10,10,10,10,10,10,
  108949. 10,10,10,10,10,10,10,10,
  108950. 10,10,10,10,10,10,10,10,
  108951. 10,10,10,10,10,10,10,10,
  108952. 10,10,10,10,10,10,10,10,
  108953. 10,10,10,10,10,10,10,10,
  108954. 10,10,10,10,10,10,10,10,
  108955. 10,10,10,10,10,10,10,10,
  108956. 10,10,10,10,10,10,10,10,
  108957. 10,10,10,10,10,10,10,10,
  108958. 10,10,10,10,10,10,10,10,
  108959. 10,10,10,10,10,10,10,10,
  108960. 10,10,10,10,10,10,10,10,
  108961. 10,10,10,10,10,10,10,10,
  108962. 10,10,10,10,10,10,10,10,
  108963. 10,10,10,10,10,10,10,10,
  108964. 10,10,10,10,10,10,10,10,
  108965. 10,10,10,10,10,10,10,10,
  108966. 10,10,10,10,10,10,10,10,
  108967. 10,10,10,10,10,10,10,10,
  108968. 10,10,10,10,10,10,10};
  108969. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108970. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108971. 0x01,0x02,0x03,0x04,2,0,0,0,
  108972. 0x6c,0x3b,0x82,0x3d,
  108973. 1,
  108974. 50};
  108975. /* packet that overspans over an entire page */
  108976. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108977. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108978. 0x01,0x02,0x03,0x04,0,0,0,0,
  108979. 0xff,0x7b,0x23,0x17,
  108980. 1,
  108981. 0};
  108982. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108983. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108984. 0x01,0x02,0x03,0x04,1,0,0,0,
  108985. 0x3c,0xd9,0x4d,0x3f,
  108986. 17,
  108987. 100,255,255,255,255,255,255,255,255,
  108988. 255,255,255,255,255,255,255,255};
  108989. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108990. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108991. 0x01,0x02,0x03,0x04,2,0,0,0,
  108992. 0x01,0xd2,0xe5,0xe5,
  108993. 17,
  108994. 255,255,255,255,255,255,255,255,
  108995. 255,255,255,255,255,255,255,255,255};
  108996. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108997. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108998. 0x01,0x02,0x03,0x04,3,0,0,0,
  108999. 0xef,0xdd,0x88,0xde,
  109000. 7,
  109001. 255,255,75,255,4,255,0};
  109002. /* packet that overspans over an entire page */
  109003. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109004. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109005. 0x01,0x02,0x03,0x04,0,0,0,0,
  109006. 0xff,0x7b,0x23,0x17,
  109007. 1,
  109008. 0};
  109009. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109010. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109011. 0x01,0x02,0x03,0x04,1,0,0,0,
  109012. 0x3c,0xd9,0x4d,0x3f,
  109013. 17,
  109014. 100,255,255,255,255,255,255,255,255,
  109015. 255,255,255,255,255,255,255,255};
  109016. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109017. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109018. 0x01,0x02,0x03,0x04,2,0,0,0,
  109019. 0xd4,0xe0,0x60,0xe5,
  109020. 1,0};
  109021. void test_pack(const int *pl, const int **headers, int byteskip,
  109022. int pageskip, int packetskip){
  109023. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109024. long inptr=0;
  109025. long outptr=0;
  109026. long deptr=0;
  109027. long depacket=0;
  109028. long granule_pos=7,pageno=0;
  109029. int i,j,packets,pageout=pageskip;
  109030. int eosflag=0;
  109031. int bosflag=0;
  109032. int byteskipcount=0;
  109033. ogg_stream_reset(&os_en);
  109034. ogg_stream_reset(&os_de);
  109035. ogg_sync_reset(&oy);
  109036. for(packets=0;packets<packetskip;packets++)
  109037. depacket+=pl[packets];
  109038. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109039. for(i=0;i<packets;i++){
  109040. /* construct a test packet */
  109041. ogg_packet op;
  109042. int len=pl[i];
  109043. op.packet=data+inptr;
  109044. op.bytes=len;
  109045. op.e_o_s=(pl[i+1]<0?1:0);
  109046. op.granulepos=granule_pos;
  109047. granule_pos+=1024;
  109048. for(j=0;j<len;j++)data[inptr++]=i+j;
  109049. /* submit the test packet */
  109050. ogg_stream_packetin(&os_en,&op);
  109051. /* retrieve any finished pages */
  109052. {
  109053. ogg_page og;
  109054. while(ogg_stream_pageout(&os_en,&og)){
  109055. /* We have a page. Check it carefully */
  109056. fprintf(stderr,"%ld, ",pageno);
  109057. if(headers[pageno]==NULL){
  109058. fprintf(stderr,"coded too many pages!\n");
  109059. exit(1);
  109060. }
  109061. check_page(data+outptr,headers[pageno],&og);
  109062. outptr+=og.body_len;
  109063. pageno++;
  109064. if(pageskip){
  109065. bosflag=1;
  109066. pageskip--;
  109067. deptr+=og.body_len;
  109068. }
  109069. /* have a complete page; submit it to sync/decode */
  109070. {
  109071. ogg_page og_de;
  109072. ogg_packet op_de,op_de2;
  109073. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109074. char *next=buf;
  109075. byteskipcount+=og.header_len;
  109076. if(byteskipcount>byteskip){
  109077. memcpy(next,og.header,byteskipcount-byteskip);
  109078. next+=byteskipcount-byteskip;
  109079. byteskipcount=byteskip;
  109080. }
  109081. byteskipcount+=og.body_len;
  109082. if(byteskipcount>byteskip){
  109083. memcpy(next,og.body,byteskipcount-byteskip);
  109084. next+=byteskipcount-byteskip;
  109085. byteskipcount=byteskip;
  109086. }
  109087. ogg_sync_wrote(&oy,next-buf);
  109088. while(1){
  109089. int ret=ogg_sync_pageout(&oy,&og_de);
  109090. if(ret==0)break;
  109091. if(ret<0)continue;
  109092. /* got a page. Happy happy. Verify that it's good. */
  109093. fprintf(stderr,"(%ld), ",pageout);
  109094. check_page(data+deptr,headers[pageout],&og_de);
  109095. deptr+=og_de.body_len;
  109096. pageout++;
  109097. /* submit it to deconstitution */
  109098. ogg_stream_pagein(&os_de,&og_de);
  109099. /* packets out? */
  109100. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109101. ogg_stream_packetpeek(&os_de,NULL);
  109102. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109103. /* verify peek and out match */
  109104. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109105. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109106. depacket);
  109107. exit(1);
  109108. }
  109109. /* verify the packet! */
  109110. /* check data */
  109111. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109112. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109113. depacket);
  109114. exit(1);
  109115. }
  109116. /* check bos flag */
  109117. if(bosflag==0 && op_de.b_o_s==0){
  109118. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109119. exit(1);
  109120. }
  109121. if(bosflag && op_de.b_o_s){
  109122. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109123. exit(1);
  109124. }
  109125. bosflag=1;
  109126. depacket+=op_de.bytes;
  109127. /* check eos flag */
  109128. if(eosflag){
  109129. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109130. exit(1);
  109131. }
  109132. if(op_de.e_o_s)eosflag=1;
  109133. /* check granulepos flag */
  109134. if(op_de.granulepos!=-1){
  109135. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109136. }
  109137. }
  109138. }
  109139. }
  109140. }
  109141. }
  109142. }
  109143. _ogg_free(data);
  109144. if(headers[pageno]!=NULL){
  109145. fprintf(stderr,"did not write last page!\n");
  109146. exit(1);
  109147. }
  109148. if(headers[pageout]!=NULL){
  109149. fprintf(stderr,"did not decode last page!\n");
  109150. exit(1);
  109151. }
  109152. if(inptr!=outptr){
  109153. fprintf(stderr,"encoded page data incomplete!\n");
  109154. exit(1);
  109155. }
  109156. if(inptr!=deptr){
  109157. fprintf(stderr,"decoded page data incomplete!\n");
  109158. exit(1);
  109159. }
  109160. if(inptr!=depacket){
  109161. fprintf(stderr,"decoded packet data incomplete!\n");
  109162. exit(1);
  109163. }
  109164. if(!eosflag){
  109165. fprintf(stderr,"Never got a packet with EOS set!\n");
  109166. exit(1);
  109167. }
  109168. fprintf(stderr,"ok.\n");
  109169. }
  109170. int main(void){
  109171. ogg_stream_init(&os_en,0x04030201);
  109172. ogg_stream_init(&os_de,0x04030201);
  109173. ogg_sync_init(&oy);
  109174. /* Exercise each code path in the framing code. Also verify that
  109175. the checksums are working. */
  109176. {
  109177. /* 17 only */
  109178. const int packets[]={17, -1};
  109179. const int *headret[]={head1_0,NULL};
  109180. fprintf(stderr,"testing single page encoding... ");
  109181. test_pack(packets,headret,0,0,0);
  109182. }
  109183. {
  109184. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109185. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109186. const int *headret[]={head1_1,head2_1,NULL};
  109187. fprintf(stderr,"testing basic page encoding... ");
  109188. test_pack(packets,headret,0,0,0);
  109189. }
  109190. {
  109191. /* nil packets; beginning,middle,end */
  109192. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109193. const int *headret[]={head1_2,head2_2,NULL};
  109194. fprintf(stderr,"testing basic nil packets... ");
  109195. test_pack(packets,headret,0,0,0);
  109196. }
  109197. {
  109198. /* large initial packet */
  109199. const int packets[]={4345,259,255,-1};
  109200. const int *headret[]={head1_3,head2_3,NULL};
  109201. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109202. test_pack(packets,headret,0,0,0);
  109203. }
  109204. {
  109205. /* continuing packet test */
  109206. const int packets[]={0,4345,259,255,-1};
  109207. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109208. fprintf(stderr,"testing single packet page span... ");
  109209. test_pack(packets,headret,0,0,0);
  109210. }
  109211. /* page with the 255 segment limit */
  109212. {
  109213. const int packets[]={0,10,10,10,10,10,10,10,10,
  109214. 10,10,10,10,10,10,10,10,
  109215. 10,10,10,10,10,10,10,10,
  109216. 10,10,10,10,10,10,10,10,
  109217. 10,10,10,10,10,10,10,10,
  109218. 10,10,10,10,10,10,10,10,
  109219. 10,10,10,10,10,10,10,10,
  109220. 10,10,10,10,10,10,10,10,
  109221. 10,10,10,10,10,10,10,10,
  109222. 10,10,10,10,10,10,10,10,
  109223. 10,10,10,10,10,10,10,10,
  109224. 10,10,10,10,10,10,10,10,
  109225. 10,10,10,10,10,10,10,10,
  109226. 10,10,10,10,10,10,10,10,
  109227. 10,10,10,10,10,10,10,10,
  109228. 10,10,10,10,10,10,10,10,
  109229. 10,10,10,10,10,10,10,10,
  109230. 10,10,10,10,10,10,10,10,
  109231. 10,10,10,10,10,10,10,10,
  109232. 10,10,10,10,10,10,10,10,
  109233. 10,10,10,10,10,10,10,10,
  109234. 10,10,10,10,10,10,10,10,
  109235. 10,10,10,10,10,10,10,10,
  109236. 10,10,10,10,10,10,10,10,
  109237. 10,10,10,10,10,10,10,10,
  109238. 10,10,10,10,10,10,10,10,
  109239. 10,10,10,10,10,10,10,10,
  109240. 10,10,10,10,10,10,10,10,
  109241. 10,10,10,10,10,10,10,10,
  109242. 10,10,10,10,10,10,10,10,
  109243. 10,10,10,10,10,10,10,10,
  109244. 10,10,10,10,10,10,10,50,-1};
  109245. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109246. fprintf(stderr,"testing max packet segments... ");
  109247. test_pack(packets,headret,0,0,0);
  109248. }
  109249. {
  109250. /* packet that overspans over an entire page */
  109251. const int packets[]={0,100,9000,259,255,-1};
  109252. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109253. fprintf(stderr,"testing very large packets... ");
  109254. test_pack(packets,headret,0,0,0);
  109255. }
  109256. {
  109257. /* test for the libogg 1.1.1 resync in large continuation bug
  109258. found by Josh Coalson) */
  109259. const int packets[]={0,100,9000,259,255,-1};
  109260. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109261. fprintf(stderr,"testing continuation resync in very large packets... ");
  109262. test_pack(packets,headret,100,2,3);
  109263. }
  109264. {
  109265. /* term only page. why not? */
  109266. const int packets[]={0,100,4080,-1};
  109267. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109268. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109269. test_pack(packets,headret,0,0,0);
  109270. }
  109271. {
  109272. /* build a bunch of pages for testing */
  109273. unsigned char *data=_ogg_malloc(1024*1024);
  109274. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109275. int inptr=0,i,j;
  109276. ogg_page og[5];
  109277. ogg_stream_reset(&os_en);
  109278. for(i=0;pl[i]!=-1;i++){
  109279. ogg_packet op;
  109280. int len=pl[i];
  109281. op.packet=data+inptr;
  109282. op.bytes=len;
  109283. op.e_o_s=(pl[i+1]<0?1:0);
  109284. op.granulepos=(i+1)*1000;
  109285. for(j=0;j<len;j++)data[inptr++]=i+j;
  109286. ogg_stream_packetin(&os_en,&op);
  109287. }
  109288. _ogg_free(data);
  109289. /* retrieve finished pages */
  109290. for(i=0;i<5;i++){
  109291. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109292. fprintf(stderr,"Too few pages output building sync tests!\n");
  109293. exit(1);
  109294. }
  109295. copy_page(&og[i]);
  109296. }
  109297. /* Test lost pages on pagein/packetout: no rollback */
  109298. {
  109299. ogg_page temp;
  109300. ogg_packet test;
  109301. fprintf(stderr,"Testing loss of pages... ");
  109302. ogg_sync_reset(&oy);
  109303. ogg_stream_reset(&os_de);
  109304. for(i=0;i<5;i++){
  109305. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109306. og[i].header_len);
  109307. ogg_sync_wrote(&oy,og[i].header_len);
  109308. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109309. ogg_sync_wrote(&oy,og[i].body_len);
  109310. }
  109311. ogg_sync_pageout(&oy,&temp);
  109312. ogg_stream_pagein(&os_de,&temp);
  109313. ogg_sync_pageout(&oy,&temp);
  109314. ogg_stream_pagein(&os_de,&temp);
  109315. ogg_sync_pageout(&oy,&temp);
  109316. /* skip */
  109317. ogg_sync_pageout(&oy,&temp);
  109318. ogg_stream_pagein(&os_de,&temp);
  109319. /* do we get the expected results/packets? */
  109320. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109321. checkpacket(&test,0,0,0);
  109322. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109323. checkpacket(&test,100,1,-1);
  109324. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109325. checkpacket(&test,4079,2,3000);
  109326. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109327. fprintf(stderr,"Error: loss of page did not return error\n");
  109328. exit(1);
  109329. }
  109330. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109331. checkpacket(&test,76,5,-1);
  109332. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109333. checkpacket(&test,34,6,-1);
  109334. fprintf(stderr,"ok.\n");
  109335. }
  109336. /* Test lost pages on pagein/packetout: rollback with continuation */
  109337. {
  109338. ogg_page temp;
  109339. ogg_packet test;
  109340. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109341. ogg_sync_reset(&oy);
  109342. ogg_stream_reset(&os_de);
  109343. for(i=0;i<5;i++){
  109344. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109345. og[i].header_len);
  109346. ogg_sync_wrote(&oy,og[i].header_len);
  109347. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109348. ogg_sync_wrote(&oy,og[i].body_len);
  109349. }
  109350. ogg_sync_pageout(&oy,&temp);
  109351. ogg_stream_pagein(&os_de,&temp);
  109352. ogg_sync_pageout(&oy,&temp);
  109353. ogg_stream_pagein(&os_de,&temp);
  109354. ogg_sync_pageout(&oy,&temp);
  109355. ogg_stream_pagein(&os_de,&temp);
  109356. ogg_sync_pageout(&oy,&temp);
  109357. /* skip */
  109358. ogg_sync_pageout(&oy,&temp);
  109359. ogg_stream_pagein(&os_de,&temp);
  109360. /* do we get the expected results/packets? */
  109361. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109362. checkpacket(&test,0,0,0);
  109363. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109364. checkpacket(&test,100,1,-1);
  109365. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109366. checkpacket(&test,4079,2,3000);
  109367. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109368. checkpacket(&test,2956,3,4000);
  109369. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109370. fprintf(stderr,"Error: loss of page did not return error\n");
  109371. exit(1);
  109372. }
  109373. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109374. checkpacket(&test,300,13,14000);
  109375. fprintf(stderr,"ok.\n");
  109376. }
  109377. /* the rest only test sync */
  109378. {
  109379. ogg_page og_de;
  109380. /* Test fractional page inputs: incomplete capture */
  109381. fprintf(stderr,"Testing sync on partial inputs... ");
  109382. ogg_sync_reset(&oy);
  109383. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109384. 3);
  109385. ogg_sync_wrote(&oy,3);
  109386. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109387. /* Test fractional page inputs: incomplete fixed header */
  109388. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109389. 20);
  109390. ogg_sync_wrote(&oy,20);
  109391. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109392. /* Test fractional page inputs: incomplete header */
  109393. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109394. 5);
  109395. ogg_sync_wrote(&oy,5);
  109396. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109397. /* Test fractional page inputs: incomplete body */
  109398. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109399. og[1].header_len-28);
  109400. ogg_sync_wrote(&oy,og[1].header_len-28);
  109401. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109402. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109403. ogg_sync_wrote(&oy,1000);
  109404. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109405. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109406. og[1].body_len-1000);
  109407. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109408. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109409. fprintf(stderr,"ok.\n");
  109410. }
  109411. /* Test fractional page inputs: page + incomplete capture */
  109412. {
  109413. ogg_page og_de;
  109414. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109415. ogg_sync_reset(&oy);
  109416. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109417. og[1].header_len);
  109418. ogg_sync_wrote(&oy,og[1].header_len);
  109419. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109420. og[1].body_len);
  109421. ogg_sync_wrote(&oy,og[1].body_len);
  109422. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109423. 20);
  109424. ogg_sync_wrote(&oy,20);
  109425. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109426. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109427. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109428. og[1].header_len-20);
  109429. ogg_sync_wrote(&oy,og[1].header_len-20);
  109430. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109431. og[1].body_len);
  109432. ogg_sync_wrote(&oy,og[1].body_len);
  109433. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109434. fprintf(stderr,"ok.\n");
  109435. }
  109436. /* Test recapture: garbage + page */
  109437. {
  109438. ogg_page og_de;
  109439. fprintf(stderr,"Testing search for capture... ");
  109440. ogg_sync_reset(&oy);
  109441. /* 'garbage' */
  109442. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109443. og[1].body_len);
  109444. ogg_sync_wrote(&oy,og[1].body_len);
  109445. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109446. og[1].header_len);
  109447. ogg_sync_wrote(&oy,og[1].header_len);
  109448. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109449. og[1].body_len);
  109450. ogg_sync_wrote(&oy,og[1].body_len);
  109451. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109452. 20);
  109453. ogg_sync_wrote(&oy,20);
  109454. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109455. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109456. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109457. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109458. og[2].header_len-20);
  109459. ogg_sync_wrote(&oy,og[2].header_len-20);
  109460. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109461. og[2].body_len);
  109462. ogg_sync_wrote(&oy,og[2].body_len);
  109463. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109464. fprintf(stderr,"ok.\n");
  109465. }
  109466. /* Test recapture: page + garbage + page */
  109467. {
  109468. ogg_page og_de;
  109469. fprintf(stderr,"Testing recapture... ");
  109470. ogg_sync_reset(&oy);
  109471. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109472. og[1].header_len);
  109473. ogg_sync_wrote(&oy,og[1].header_len);
  109474. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109475. og[1].body_len);
  109476. ogg_sync_wrote(&oy,og[1].body_len);
  109477. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109478. og[2].header_len);
  109479. ogg_sync_wrote(&oy,og[2].header_len);
  109480. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109481. og[2].header_len);
  109482. ogg_sync_wrote(&oy,og[2].header_len);
  109483. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109484. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109485. og[2].body_len-5);
  109486. ogg_sync_wrote(&oy,og[2].body_len-5);
  109487. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109488. og[3].header_len);
  109489. ogg_sync_wrote(&oy,og[3].header_len);
  109490. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109491. og[3].body_len);
  109492. ogg_sync_wrote(&oy,og[3].body_len);
  109493. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109494. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109495. fprintf(stderr,"ok.\n");
  109496. }
  109497. /* Free page data that was previously copied */
  109498. {
  109499. for(i=0;i<5;i++){
  109500. free_page(&og[i]);
  109501. }
  109502. }
  109503. }
  109504. return(0);
  109505. }
  109506. #endif
  109507. #endif
  109508. /*** End of inlined file: framing.c ***/
  109509. /*** Start of inlined file: analysis.c ***/
  109510. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109511. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109512. // tasks..
  109513. #if JUCE_MSVC
  109514. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109515. #endif
  109516. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109517. #if JUCE_USE_OGGVORBIS
  109518. #include <stdio.h>
  109519. #include <string.h>
  109520. #include <math.h>
  109521. /*** Start of inlined file: codec_internal.h ***/
  109522. #ifndef _V_CODECI_H_
  109523. #define _V_CODECI_H_
  109524. /*** Start of inlined file: envelope.h ***/
  109525. #ifndef _V_ENVELOPE_
  109526. #define _V_ENVELOPE_
  109527. /*** Start of inlined file: mdct.h ***/
  109528. #ifndef _OGG_mdct_H_
  109529. #define _OGG_mdct_H_
  109530. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109531. #ifdef MDCT_INTEGERIZED
  109532. #define DATA_TYPE int
  109533. #define REG_TYPE register int
  109534. #define TRIGBITS 14
  109535. #define cPI3_8 6270
  109536. #define cPI2_8 11585
  109537. #define cPI1_8 15137
  109538. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109539. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109540. #define HALVE(x) ((x)>>1)
  109541. #else
  109542. #define DATA_TYPE float
  109543. #define REG_TYPE float
  109544. #define cPI3_8 .38268343236508977175F
  109545. #define cPI2_8 .70710678118654752441F
  109546. #define cPI1_8 .92387953251128675613F
  109547. #define FLOAT_CONV(x) (x)
  109548. #define MULT_NORM(x) (x)
  109549. #define HALVE(x) ((x)*.5f)
  109550. #endif
  109551. typedef struct {
  109552. int n;
  109553. int log2n;
  109554. DATA_TYPE *trig;
  109555. int *bitrev;
  109556. DATA_TYPE scale;
  109557. } mdct_lookup;
  109558. extern void mdct_init(mdct_lookup *lookup,int n);
  109559. extern void mdct_clear(mdct_lookup *l);
  109560. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109561. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109562. #endif
  109563. /*** End of inlined file: mdct.h ***/
  109564. #define VE_PRE 16
  109565. #define VE_WIN 4
  109566. #define VE_POST 2
  109567. #define VE_AMP (VE_PRE+VE_POST-1)
  109568. #define VE_BANDS 7
  109569. #define VE_NEARDC 15
  109570. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109571. #define VE_MAXSTRETCH 12 /* one-third full block */
  109572. typedef struct {
  109573. float ampbuf[VE_AMP];
  109574. int ampptr;
  109575. float nearDC[VE_NEARDC];
  109576. float nearDC_acc;
  109577. float nearDC_partialacc;
  109578. int nearptr;
  109579. } envelope_filter_state;
  109580. typedef struct {
  109581. int begin;
  109582. int end;
  109583. float *window;
  109584. float total;
  109585. } envelope_band;
  109586. typedef struct {
  109587. int ch;
  109588. int winlength;
  109589. int searchstep;
  109590. float minenergy;
  109591. mdct_lookup mdct;
  109592. float *mdct_win;
  109593. envelope_band band[VE_BANDS];
  109594. envelope_filter_state *filter;
  109595. int stretch;
  109596. int *mark;
  109597. long storage;
  109598. long current;
  109599. long curmark;
  109600. long cursor;
  109601. } envelope_lookup;
  109602. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109603. extern void _ve_envelope_clear(envelope_lookup *e);
  109604. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109605. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109606. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109607. #endif
  109608. /*** End of inlined file: envelope.h ***/
  109609. /*** Start of inlined file: codebook.h ***/
  109610. #ifndef _V_CODEBOOK_H_
  109611. #define _V_CODEBOOK_H_
  109612. /* This structure encapsulates huffman and VQ style encoding books; it
  109613. doesn't do anything specific to either.
  109614. valuelist/quantlist are nonNULL (and q_* significant) only if
  109615. there's entry->value mapping to be done.
  109616. If encode-side mapping must be done (and thus the entry needs to be
  109617. hunted), the auxiliary encode pointer will point to a decision
  109618. tree. This is true of both VQ and huffman, but is mostly useful
  109619. with VQ.
  109620. */
  109621. typedef struct static_codebook{
  109622. long dim; /* codebook dimensions (elements per vector) */
  109623. long entries; /* codebook entries */
  109624. long *lengthlist; /* codeword lengths in bits */
  109625. /* mapping ***************************************************************/
  109626. int maptype; /* 0=none
  109627. 1=implicitly populated values from map column
  109628. 2=listed arbitrary values */
  109629. /* The below does a linear, single monotonic sequence mapping. */
  109630. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109631. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109632. int q_quant; /* bits: 0 < quant <= 16 */
  109633. int q_sequencep; /* bitflag */
  109634. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109635. map == 2: list of dim*entries quantized entry vals
  109636. */
  109637. /* encode helpers ********************************************************/
  109638. struct encode_aux_nearestmatch *nearest_tree;
  109639. struct encode_aux_threshmatch *thresh_tree;
  109640. struct encode_aux_pigeonhole *pigeon_tree;
  109641. int allocedp;
  109642. } static_codebook;
  109643. /* this structures an arbitrary trained book to quickly find the
  109644. nearest cell match */
  109645. typedef struct encode_aux_nearestmatch{
  109646. /* pre-calculated partitioning tree */
  109647. long *ptr0;
  109648. long *ptr1;
  109649. long *p; /* decision points (each is an entry) */
  109650. long *q; /* decision points (each is an entry) */
  109651. long aux; /* number of tree entries */
  109652. long alloc;
  109653. } encode_aux_nearestmatch;
  109654. /* assumes a maptype of 1; encode side only, so that's OK */
  109655. typedef struct encode_aux_threshmatch{
  109656. float *quantthresh;
  109657. long *quantmap;
  109658. int quantvals;
  109659. int threshvals;
  109660. } encode_aux_threshmatch;
  109661. typedef struct encode_aux_pigeonhole{
  109662. float min;
  109663. float del;
  109664. int mapentries;
  109665. int quantvals;
  109666. long *pigeonmap;
  109667. long fittotal;
  109668. long *fitlist;
  109669. long *fitmap;
  109670. long *fitlength;
  109671. } encode_aux_pigeonhole;
  109672. typedef struct codebook{
  109673. long dim; /* codebook dimensions (elements per vector) */
  109674. long entries; /* codebook entries */
  109675. long used_entries; /* populated codebook entries */
  109676. const static_codebook *c;
  109677. /* for encode, the below are entry-ordered, fully populated */
  109678. /* for decode, the below are ordered by bitreversed codeword and only
  109679. used entries are populated */
  109680. float *valuelist; /* list of dim*entries actual entry values */
  109681. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109682. int *dec_index; /* only used if sparseness collapsed */
  109683. char *dec_codelengths;
  109684. ogg_uint32_t *dec_firsttable;
  109685. int dec_firsttablen;
  109686. int dec_maxlength;
  109687. } codebook;
  109688. extern void vorbis_staticbook_clear(static_codebook *b);
  109689. extern void vorbis_staticbook_destroy(static_codebook *b);
  109690. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109691. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109692. extern void vorbis_book_clear(codebook *b);
  109693. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109694. extern float *_book_logdist(const static_codebook *b,float *vals);
  109695. extern float _float32_unpack(long val);
  109696. extern long _float32_pack(float val);
  109697. extern int _best(codebook *book, float *a, int step);
  109698. extern int _ilog(unsigned int v);
  109699. extern long _book_maptype1_quantvals(const static_codebook *b);
  109700. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109701. extern long vorbis_book_codeword(codebook *book,int entry);
  109702. extern long vorbis_book_codelen(codebook *book,int entry);
  109703. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109704. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109705. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109706. extern int vorbis_book_errorv(codebook *book, float *a);
  109707. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109708. oggpack_buffer *b);
  109709. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109710. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109711. oggpack_buffer *b,int n);
  109712. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109713. oggpack_buffer *b,int n);
  109714. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109715. oggpack_buffer *b,int n);
  109716. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109717. long off,int ch,
  109718. oggpack_buffer *b,int n);
  109719. #endif
  109720. /*** End of inlined file: codebook.h ***/
  109721. #define BLOCKTYPE_IMPULSE 0
  109722. #define BLOCKTYPE_PADDING 1
  109723. #define BLOCKTYPE_TRANSITION 0
  109724. #define BLOCKTYPE_LONG 1
  109725. #define PACKETBLOBS 15
  109726. typedef struct vorbis_block_internal{
  109727. float **pcmdelay; /* this is a pointer into local storage */
  109728. float ampmax;
  109729. int blocktype;
  109730. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109731. blob [PACKETBLOBS/2] points to
  109732. the oggpack_buffer in the
  109733. main vorbis_block */
  109734. } vorbis_block_internal;
  109735. typedef void vorbis_look_floor;
  109736. typedef void vorbis_look_residue;
  109737. typedef void vorbis_look_transform;
  109738. /* mode ************************************************************/
  109739. typedef struct {
  109740. int blockflag;
  109741. int windowtype;
  109742. int transformtype;
  109743. int mapping;
  109744. } vorbis_info_mode;
  109745. typedef void vorbis_info_floor;
  109746. typedef void vorbis_info_residue;
  109747. typedef void vorbis_info_mapping;
  109748. /*** Start of inlined file: psy.h ***/
  109749. #ifndef _V_PSY_H_
  109750. #define _V_PSY_H_
  109751. /*** Start of inlined file: smallft.h ***/
  109752. #ifndef _V_SMFT_H_
  109753. #define _V_SMFT_H_
  109754. typedef struct {
  109755. int n;
  109756. float *trigcache;
  109757. int *splitcache;
  109758. } drft_lookup;
  109759. extern void drft_forward(drft_lookup *l,float *data);
  109760. extern void drft_backward(drft_lookup *l,float *data);
  109761. extern void drft_init(drft_lookup *l,int n);
  109762. extern void drft_clear(drft_lookup *l);
  109763. #endif
  109764. /*** End of inlined file: smallft.h ***/
  109765. /*** Start of inlined file: backends.h ***/
  109766. /* this is exposed up here because we need it for static modes.
  109767. Lookups for each backend aren't exposed because there's no reason
  109768. to do so */
  109769. #ifndef _vorbis_backend_h_
  109770. #define _vorbis_backend_h_
  109771. /* this would all be simpler/shorter with templates, but.... */
  109772. /* Floor backend generic *****************************************/
  109773. typedef struct{
  109774. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109775. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109776. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109777. void (*free_info) (vorbis_info_floor *);
  109778. void (*free_look) (vorbis_look_floor *);
  109779. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109780. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109781. void *buffer,float *);
  109782. } vorbis_func_floor;
  109783. typedef struct{
  109784. int order;
  109785. long rate;
  109786. long barkmap;
  109787. int ampbits;
  109788. int ampdB;
  109789. int numbooks; /* <= 16 */
  109790. int books[16];
  109791. float lessthan; /* encode-only config setting hacks for libvorbis */
  109792. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109793. } vorbis_info_floor0;
  109794. #define VIF_POSIT 63
  109795. #define VIF_CLASS 16
  109796. #define VIF_PARTS 31
  109797. typedef struct{
  109798. int partitions; /* 0 to 31 */
  109799. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109800. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109801. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109802. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109803. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109804. int mult; /* 1 2 3 or 4 */
  109805. int postlist[VIF_POSIT+2]; /* first two implicit */
  109806. /* encode side analysis parameters */
  109807. float maxover;
  109808. float maxunder;
  109809. float maxerr;
  109810. float twofitweight;
  109811. float twofitatten;
  109812. int n;
  109813. } vorbis_info_floor1;
  109814. /* Residue backend generic *****************************************/
  109815. typedef struct{
  109816. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109817. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109818. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109819. vorbis_info_residue *);
  109820. void (*free_info) (vorbis_info_residue *);
  109821. void (*free_look) (vorbis_look_residue *);
  109822. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109823. float **,int *,int);
  109824. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109825. vorbis_look_residue *,
  109826. float **,float **,int *,int,long **);
  109827. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109828. float **,int *,int);
  109829. } vorbis_func_residue;
  109830. typedef struct vorbis_info_residue0{
  109831. /* block-partitioned VQ coded straight residue */
  109832. long begin;
  109833. long end;
  109834. /* first stage (lossless partitioning) */
  109835. int grouping; /* group n vectors per partition */
  109836. int partitions; /* possible codebooks for a partition */
  109837. int groupbook; /* huffbook for partitioning */
  109838. int secondstages[64]; /* expanded out to pointers in lookup */
  109839. int booklist[256]; /* list of second stage books */
  109840. float classmetric1[64];
  109841. float classmetric2[64];
  109842. } vorbis_info_residue0;
  109843. /* Mapping backend generic *****************************************/
  109844. typedef struct{
  109845. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109846. oggpack_buffer *);
  109847. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109848. void (*free_info) (vorbis_info_mapping *);
  109849. int (*forward) (struct vorbis_block *vb);
  109850. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109851. } vorbis_func_mapping;
  109852. typedef struct vorbis_info_mapping0{
  109853. int submaps; /* <= 16 */
  109854. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109855. int floorsubmap[16]; /* [mux] submap to floors */
  109856. int residuesubmap[16]; /* [mux] submap to residue */
  109857. int coupling_steps;
  109858. int coupling_mag[256];
  109859. int coupling_ang[256];
  109860. } vorbis_info_mapping0;
  109861. #endif
  109862. /*** End of inlined file: backends.h ***/
  109863. #ifndef EHMER_MAX
  109864. #define EHMER_MAX 56
  109865. #endif
  109866. /* psychoacoustic setup ********************************************/
  109867. #define P_BANDS 17 /* 62Hz to 16kHz */
  109868. #define P_LEVELS 8 /* 30dB to 100dB */
  109869. #define P_LEVEL_0 30. /* 30 dB */
  109870. #define P_NOISECURVES 3
  109871. #define NOISE_COMPAND_LEVELS 40
  109872. typedef struct vorbis_info_psy{
  109873. int blockflag;
  109874. float ath_adjatt;
  109875. float ath_maxatt;
  109876. float tone_masteratt[P_NOISECURVES];
  109877. float tone_centerboost;
  109878. float tone_decay;
  109879. float tone_abs_limit;
  109880. float toneatt[P_BANDS];
  109881. int noisemaskp;
  109882. float noisemaxsupp;
  109883. float noisewindowlo;
  109884. float noisewindowhi;
  109885. int noisewindowlomin;
  109886. int noisewindowhimin;
  109887. int noisewindowfixed;
  109888. float noiseoff[P_NOISECURVES][P_BANDS];
  109889. float noisecompand[NOISE_COMPAND_LEVELS];
  109890. float max_curve_dB;
  109891. int normal_channel_p;
  109892. int normal_point_p;
  109893. int normal_start;
  109894. int normal_partition;
  109895. double normal_thresh;
  109896. } vorbis_info_psy;
  109897. typedef struct{
  109898. int eighth_octave_lines;
  109899. /* for block long/short tuning; encode only */
  109900. float preecho_thresh[VE_BANDS];
  109901. float postecho_thresh[VE_BANDS];
  109902. float stretch_penalty;
  109903. float preecho_minenergy;
  109904. float ampmax_att_per_sec;
  109905. /* channel coupling config */
  109906. int coupling_pkHz[PACKETBLOBS];
  109907. int coupling_pointlimit[2][PACKETBLOBS];
  109908. int coupling_prepointamp[PACKETBLOBS];
  109909. int coupling_postpointamp[PACKETBLOBS];
  109910. int sliding_lowpass[2][PACKETBLOBS];
  109911. } vorbis_info_psy_global;
  109912. typedef struct {
  109913. float ampmax;
  109914. int channels;
  109915. vorbis_info_psy_global *gi;
  109916. int coupling_pointlimit[2][P_NOISECURVES];
  109917. } vorbis_look_psy_global;
  109918. typedef struct {
  109919. int n;
  109920. struct vorbis_info_psy *vi;
  109921. float ***tonecurves;
  109922. float **noiseoffset;
  109923. float *ath;
  109924. long *octave; /* in n.ocshift format */
  109925. long *bark;
  109926. long firstoc;
  109927. long shiftoc;
  109928. int eighth_octave_lines; /* power of two, please */
  109929. int total_octave_lines;
  109930. long rate; /* cache it */
  109931. float m_val; /* Masking compensation value */
  109932. } vorbis_look_psy;
  109933. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109934. vorbis_info_psy_global *gi,int n,long rate);
  109935. extern void _vp_psy_clear(vorbis_look_psy *p);
  109936. extern void *_vi_psy_dup(void *source);
  109937. extern void _vi_psy_free(vorbis_info_psy *i);
  109938. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109939. extern void _vp_remove_floor(vorbis_look_psy *p,
  109940. float *mdct,
  109941. int *icodedflr,
  109942. float *residue,
  109943. int sliding_lowpass);
  109944. extern void _vp_noisemask(vorbis_look_psy *p,
  109945. float *logmdct,
  109946. float *logmask);
  109947. extern void _vp_tonemask(vorbis_look_psy *p,
  109948. float *logfft,
  109949. float *logmask,
  109950. float global_specmax,
  109951. float local_specmax);
  109952. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109953. float *noise,
  109954. float *tone,
  109955. int offset_select,
  109956. float *logmask,
  109957. float *mdct,
  109958. float *logmdct);
  109959. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109960. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109961. vorbis_info_psy_global *g,
  109962. vorbis_look_psy *p,
  109963. vorbis_info_mapping0 *vi,
  109964. float **mdct);
  109965. extern void _vp_couple(int blobno,
  109966. vorbis_info_psy_global *g,
  109967. vorbis_look_psy *p,
  109968. vorbis_info_mapping0 *vi,
  109969. float **res,
  109970. float **mag_memo,
  109971. int **mag_sort,
  109972. int **ifloor,
  109973. int *nonzero,
  109974. int sliding_lowpass);
  109975. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109976. float *in,float *out,int *sortedindex);
  109977. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109978. float *magnitudes,int *sortedindex);
  109979. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109980. vorbis_look_psy *p,
  109981. vorbis_info_mapping0 *vi,
  109982. float **mags);
  109983. extern void hf_reduction(vorbis_info_psy_global *g,
  109984. vorbis_look_psy *p,
  109985. vorbis_info_mapping0 *vi,
  109986. float **mdct);
  109987. #endif
  109988. /*** End of inlined file: psy.h ***/
  109989. /*** Start of inlined file: bitrate.h ***/
  109990. #ifndef _V_BITRATE_H_
  109991. #define _V_BITRATE_H_
  109992. /*** Start of inlined file: os.h ***/
  109993. #ifndef _OS_H
  109994. #define _OS_H
  109995. /********************************************************************
  109996. * *
  109997. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109998. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109999. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110000. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110001. * *
  110002. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110003. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110004. * *
  110005. ********************************************************************
  110006. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110007. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110008. ********************************************************************/
  110009. #ifdef HAVE_CONFIG_H
  110010. #include "config.h"
  110011. #endif
  110012. #include <math.h>
  110013. /*** Start of inlined file: misc.h ***/
  110014. #ifndef _V_RANDOM_H_
  110015. #define _V_RANDOM_H_
  110016. extern int analysis_noisy;
  110017. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110018. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110019. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110020. ogg_int64_t off);
  110021. #ifdef DEBUG_MALLOC
  110022. #define _VDBG_GRAPHFILE "malloc.m"
  110023. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110024. extern void _VDBG_free(void *ptr,char *file,long line);
  110025. #ifndef MISC_C
  110026. #undef _ogg_malloc
  110027. #undef _ogg_calloc
  110028. #undef _ogg_realloc
  110029. #undef _ogg_free
  110030. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110031. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110032. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110033. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110034. #endif
  110035. #endif
  110036. #endif
  110037. /*** End of inlined file: misc.h ***/
  110038. #ifndef _V_IFDEFJAIL_H_
  110039. # define _V_IFDEFJAIL_H_
  110040. # ifdef __GNUC__
  110041. # define STIN static __inline__
  110042. # elif _WIN32
  110043. # define STIN static __inline
  110044. # else
  110045. # define STIN static
  110046. # endif
  110047. #ifdef DJGPP
  110048. # define rint(x) (floor((x)+0.5f))
  110049. #endif
  110050. #ifndef M_PI
  110051. # define M_PI (3.1415926536f)
  110052. #endif
  110053. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110054. # include <malloc.h>
  110055. # define rint(x) (floor((x)+0.5f))
  110056. # define NO_FLOAT_MATH_LIB
  110057. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110058. #endif
  110059. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110060. void *_alloca(size_t size);
  110061. # define alloca _alloca
  110062. #endif
  110063. #ifndef FAST_HYPOT
  110064. # define FAST_HYPOT hypot
  110065. #endif
  110066. #endif
  110067. #ifdef HAVE_ALLOCA_H
  110068. # include <alloca.h>
  110069. #endif
  110070. #ifdef USE_MEMORY_H
  110071. # include <memory.h>
  110072. #endif
  110073. #ifndef min
  110074. # define min(x,y) ((x)>(y)?(y):(x))
  110075. #endif
  110076. #ifndef max
  110077. # define max(x,y) ((x)<(y)?(y):(x))
  110078. #endif
  110079. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110080. # define VORBIS_FPU_CONTROL
  110081. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110082. Because of encapsulation constraints (GCC can't see inside the asm
  110083. block and so we end up doing stupid things like a store/load that
  110084. is collectively a noop), we do it this way */
  110085. /* we must set up the fpu before this works!! */
  110086. typedef ogg_int16_t vorbis_fpu_control;
  110087. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110088. ogg_int16_t ret;
  110089. ogg_int16_t temp;
  110090. __asm__ __volatile__("fnstcw %0\n\t"
  110091. "movw %0,%%dx\n\t"
  110092. "orw $62463,%%dx\n\t"
  110093. "movw %%dx,%1\n\t"
  110094. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110095. *fpu=ret;
  110096. }
  110097. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110098. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110099. }
  110100. /* assumes the FPU is in round mode! */
  110101. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110102. we get extra fst/fld to
  110103. truncate precision */
  110104. int i;
  110105. __asm__("fistl %0": "=m"(i) : "t"(f));
  110106. return(i);
  110107. }
  110108. #endif
  110109. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110110. # define VORBIS_FPU_CONTROL
  110111. typedef ogg_int16_t vorbis_fpu_control;
  110112. static __inline int vorbis_ftoi(double f){
  110113. int i;
  110114. __asm{
  110115. fld f
  110116. fistp i
  110117. }
  110118. return i;
  110119. }
  110120. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110121. }
  110122. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110123. }
  110124. #endif
  110125. #ifndef VORBIS_FPU_CONTROL
  110126. typedef int vorbis_fpu_control;
  110127. static int vorbis_ftoi(double f){
  110128. return (int)(f+.5);
  110129. }
  110130. /* We don't have special code for this compiler/arch, so do it the slow way */
  110131. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110132. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110133. #endif
  110134. #endif /* _OS_H */
  110135. /*** End of inlined file: os.h ***/
  110136. /* encode side bitrate tracking */
  110137. typedef struct bitrate_manager_state {
  110138. int managed;
  110139. long avg_reservoir;
  110140. long minmax_reservoir;
  110141. long avg_bitsper;
  110142. long min_bitsper;
  110143. long max_bitsper;
  110144. long short_per_long;
  110145. double avgfloat;
  110146. vorbis_block *vb;
  110147. int choice;
  110148. } bitrate_manager_state;
  110149. typedef struct bitrate_manager_info{
  110150. long avg_rate;
  110151. long min_rate;
  110152. long max_rate;
  110153. long reservoir_bits;
  110154. double reservoir_bias;
  110155. double slew_damp;
  110156. } bitrate_manager_info;
  110157. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110158. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110159. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110160. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110161. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110162. #endif
  110163. /*** End of inlined file: bitrate.h ***/
  110164. static int ilog(unsigned int v){
  110165. int ret=0;
  110166. while(v){
  110167. ret++;
  110168. v>>=1;
  110169. }
  110170. return(ret);
  110171. }
  110172. static int ilog2(unsigned int v){
  110173. int ret=0;
  110174. if(v)--v;
  110175. while(v){
  110176. ret++;
  110177. v>>=1;
  110178. }
  110179. return(ret);
  110180. }
  110181. typedef struct private_state {
  110182. /* local lookup storage */
  110183. envelope_lookup *ve; /* envelope lookup */
  110184. int window[2];
  110185. vorbis_look_transform **transform[2]; /* block, type */
  110186. drft_lookup fft_look[2];
  110187. int modebits;
  110188. vorbis_look_floor **flr;
  110189. vorbis_look_residue **residue;
  110190. vorbis_look_psy *psy;
  110191. vorbis_look_psy_global *psy_g_look;
  110192. /* local storage, only used on the encoding side. This way the
  110193. application does not need to worry about freeing some packets'
  110194. memory and not others'; packet storage is always tracked.
  110195. Cleared next call to a _dsp_ function */
  110196. unsigned char *header;
  110197. unsigned char *header1;
  110198. unsigned char *header2;
  110199. bitrate_manager_state bms;
  110200. ogg_int64_t sample_count;
  110201. } private_state;
  110202. /* codec_setup_info contains all the setup information specific to the
  110203. specific compression/decompression mode in progress (eg,
  110204. psychoacoustic settings, channel setup, options, codebook
  110205. etc).
  110206. *********************************************************************/
  110207. /*** Start of inlined file: highlevel.h ***/
  110208. typedef struct highlevel_byblocktype {
  110209. double tone_mask_setting;
  110210. double tone_peaklimit_setting;
  110211. double noise_bias_setting;
  110212. double noise_compand_setting;
  110213. } highlevel_byblocktype;
  110214. typedef struct highlevel_encode_setup {
  110215. void *setup;
  110216. int set_in_stone;
  110217. double base_setting;
  110218. double long_setting;
  110219. double short_setting;
  110220. double impulse_noisetune;
  110221. int managed;
  110222. long bitrate_min;
  110223. long bitrate_av;
  110224. double bitrate_av_damp;
  110225. long bitrate_max;
  110226. long bitrate_reservoir;
  110227. double bitrate_reservoir_bias;
  110228. int impulse_block_p;
  110229. int noise_normalize_p;
  110230. double stereo_point_setting;
  110231. double lowpass_kHz;
  110232. double ath_floating_dB;
  110233. double ath_absolute_dB;
  110234. double amplitude_track_dBpersec;
  110235. double trigger_setting;
  110236. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110237. } highlevel_encode_setup;
  110238. /*** End of inlined file: highlevel.h ***/
  110239. typedef struct codec_setup_info {
  110240. /* Vorbis supports only short and long blocks, but allows the
  110241. encoder to choose the sizes */
  110242. long blocksizes[2];
  110243. /* modes are the primary means of supporting on-the-fly different
  110244. blocksizes, different channel mappings (LR or M/A),
  110245. different residue backends, etc. Each mode consists of a
  110246. blocksize flag and a mapping (along with the mapping setup */
  110247. int modes;
  110248. int maps;
  110249. int floors;
  110250. int residues;
  110251. int books;
  110252. int psys; /* encode only */
  110253. vorbis_info_mode *mode_param[64];
  110254. int map_type[64];
  110255. vorbis_info_mapping *map_param[64];
  110256. int floor_type[64];
  110257. vorbis_info_floor *floor_param[64];
  110258. int residue_type[64];
  110259. vorbis_info_residue *residue_param[64];
  110260. static_codebook *book_param[256];
  110261. codebook *fullbooks;
  110262. vorbis_info_psy *psy_param[4]; /* encode only */
  110263. vorbis_info_psy_global psy_g_param;
  110264. bitrate_manager_info bi;
  110265. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110266. highly redundant structure, but
  110267. improves clarity of program flow. */
  110268. int halfrate_flag; /* painless downsample for decode */
  110269. } codec_setup_info;
  110270. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110271. extern void _vp_global_free(vorbis_look_psy_global *look);
  110272. #endif
  110273. /*** End of inlined file: codec_internal.h ***/
  110274. /*** Start of inlined file: registry.h ***/
  110275. #ifndef _V_REG_H_
  110276. #define _V_REG_H_
  110277. #define VI_TRANSFORMB 1
  110278. #define VI_WINDOWB 1
  110279. #define VI_TIMEB 1
  110280. #define VI_FLOORB 2
  110281. #define VI_RESB 3
  110282. #define VI_MAPB 1
  110283. extern vorbis_func_floor *_floor_P[];
  110284. extern vorbis_func_residue *_residue_P[];
  110285. extern vorbis_func_mapping *_mapping_P[];
  110286. #endif
  110287. /*** End of inlined file: registry.h ***/
  110288. /*** Start of inlined file: scales.h ***/
  110289. #ifndef _V_SCALES_H_
  110290. #define _V_SCALES_H_
  110291. #include <math.h>
  110292. /* 20log10(x) */
  110293. #define VORBIS_IEEE_FLOAT32 1
  110294. #ifdef VORBIS_IEEE_FLOAT32
  110295. static float unitnorm(float x){
  110296. union {
  110297. ogg_uint32_t i;
  110298. float f;
  110299. } ix;
  110300. ix.f = x;
  110301. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110302. return ix.f;
  110303. }
  110304. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110305. static float todB(const float *x){
  110306. union {
  110307. ogg_uint32_t i;
  110308. float f;
  110309. } ix;
  110310. ix.f = *x;
  110311. ix.i = ix.i&0x7fffffff;
  110312. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110313. }
  110314. #define todB_nn(x) todB(x)
  110315. #else
  110316. static float unitnorm(float x){
  110317. if(x<0)return(-1.f);
  110318. return(1.f);
  110319. }
  110320. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110321. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110322. #endif
  110323. #define fromdB(x) (exp((x)*.11512925f))
  110324. /* The bark scale equations are approximations, since the original
  110325. table was somewhat hand rolled. The below are chosen to have the
  110326. best possible fit to the rolled tables, thus their somewhat odd
  110327. appearance (these are more accurate and over a longer range than
  110328. the oft-quoted bark equations found in the texts I have). The
  110329. approximations are valid from 0 - 30kHz (nyquist) or so.
  110330. all f in Hz, z in Bark */
  110331. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110332. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110333. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110334. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110335. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110336. 0.0 */
  110337. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110338. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110339. #endif
  110340. /*** End of inlined file: scales.h ***/
  110341. int analysis_noisy=1;
  110342. /* decides between modes, dispatches to the appropriate mapping. */
  110343. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110344. int ret,i;
  110345. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110346. vb->glue_bits=0;
  110347. vb->time_bits=0;
  110348. vb->floor_bits=0;
  110349. vb->res_bits=0;
  110350. /* first things first. Make sure encode is ready */
  110351. for(i=0;i<PACKETBLOBS;i++)
  110352. oggpack_reset(vbi->packetblob[i]);
  110353. /* we only have one mapping type (0), and we let the mapping code
  110354. itself figure out what soft mode to use. This allows easier
  110355. bitrate management */
  110356. if((ret=_mapping_P[0]->forward(vb)))
  110357. return(ret);
  110358. if(op){
  110359. if(vorbis_bitrate_managed(vb))
  110360. /* The app is using a bitmanaged mode... but not using the
  110361. bitrate management interface. */
  110362. return(OV_EINVAL);
  110363. op->packet=oggpack_get_buffer(&vb->opb);
  110364. op->bytes=oggpack_bytes(&vb->opb);
  110365. op->b_o_s=0;
  110366. op->e_o_s=vb->eofflag;
  110367. op->granulepos=vb->granulepos;
  110368. op->packetno=vb->sequence; /* for sake of completeness */
  110369. }
  110370. return(0);
  110371. }
  110372. /* there was no great place to put this.... */
  110373. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110374. int j;
  110375. FILE *of;
  110376. char buffer[80];
  110377. /* if(i==5870){*/
  110378. sprintf(buffer,"%s_%d.m",base,i);
  110379. of=fopen(buffer,"w");
  110380. if(!of)perror("failed to open data dump file");
  110381. for(j=0;j<n;j++){
  110382. if(bark){
  110383. float b=toBARK((4000.f*j/n)+.25);
  110384. fprintf(of,"%f ",b);
  110385. }else
  110386. if(off!=0)
  110387. fprintf(of,"%f ",(double)(j+off)/8000.);
  110388. else
  110389. fprintf(of,"%f ",(double)j);
  110390. if(dB){
  110391. float val;
  110392. if(v[j]==0.)
  110393. val=-140.;
  110394. else
  110395. val=todB(v+j);
  110396. fprintf(of,"%f\n",val);
  110397. }else{
  110398. fprintf(of,"%f\n",v[j]);
  110399. }
  110400. }
  110401. fclose(of);
  110402. /* } */
  110403. }
  110404. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110405. ogg_int64_t off){
  110406. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110407. }
  110408. #endif
  110409. /*** End of inlined file: analysis.c ***/
  110410. /*** Start of inlined file: bitrate.c ***/
  110411. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110412. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110413. // tasks..
  110414. #if JUCE_MSVC
  110415. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110416. #endif
  110417. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110418. #if JUCE_USE_OGGVORBIS
  110419. #include <stdlib.h>
  110420. #include <string.h>
  110421. #include <math.h>
  110422. /* compute bitrate tracking setup */
  110423. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110424. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110425. bitrate_manager_info *bi=&ci->bi;
  110426. memset(bm,0,sizeof(*bm));
  110427. if(bi && (bi->reservoir_bits>0)){
  110428. long ratesamples=vi->rate;
  110429. int halfsamples=ci->blocksizes[0]>>1;
  110430. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110431. bm->managed=1;
  110432. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110433. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110434. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110435. bm->avgfloat=PACKETBLOBS/2;
  110436. /* not a necessary fix, but one that leads to a more balanced
  110437. typical initialization */
  110438. {
  110439. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110440. bm->minmax_reservoir=desired_fill;
  110441. bm->avg_reservoir=desired_fill;
  110442. }
  110443. }
  110444. }
  110445. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110446. memset(bm,0,sizeof(*bm));
  110447. return;
  110448. }
  110449. int vorbis_bitrate_managed(vorbis_block *vb){
  110450. vorbis_dsp_state *vd=vb->vd;
  110451. private_state *b=(private_state*)vd->backend_state;
  110452. bitrate_manager_state *bm=&b->bms;
  110453. if(bm && bm->managed)return(1);
  110454. return(0);
  110455. }
  110456. /* finish taking in the block we just processed */
  110457. int vorbis_bitrate_addblock(vorbis_block *vb){
  110458. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110459. vorbis_dsp_state *vd=vb->vd;
  110460. private_state *b=(private_state*)vd->backend_state;
  110461. bitrate_manager_state *bm=&b->bms;
  110462. vorbis_info *vi=vd->vi;
  110463. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110464. bitrate_manager_info *bi=&ci->bi;
  110465. int choice=rint(bm->avgfloat);
  110466. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110467. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110468. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110469. int samples=ci->blocksizes[vb->W]>>1;
  110470. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110471. if(!bm->managed){
  110472. /* not a bitrate managed stream, but for API simplicity, we'll
  110473. buffer the packet to keep the code path clean */
  110474. if(bm->vb)return(-1); /* one has been submitted without
  110475. being claimed */
  110476. bm->vb=vb;
  110477. return(0);
  110478. }
  110479. bm->vb=vb;
  110480. /* look ahead for avg floater */
  110481. if(bm->avg_bitsper>0){
  110482. double slew=0.;
  110483. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110484. double slewlimit= 15./bi->slew_damp;
  110485. /* choosing a new floater:
  110486. if we're over target, we slew down
  110487. if we're under target, we slew up
  110488. choose slew as follows: look through packetblobs of this frame
  110489. and set slew as the first in the appropriate direction that
  110490. gives us the slew we want. This may mean no slew if delta is
  110491. already favorable.
  110492. Then limit slew to slew max */
  110493. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110494. while(choice>0 && this_bits>avg_target_bits &&
  110495. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110496. choice--;
  110497. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110498. }
  110499. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110500. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110501. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110502. choice++;
  110503. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110504. }
  110505. }
  110506. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110507. if(slew<-slewlimit)slew=-slewlimit;
  110508. if(slew>slewlimit)slew=slewlimit;
  110509. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110510. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110511. }
  110512. /* enforce min(if used) on the current floater (if used) */
  110513. if(bm->min_bitsper>0){
  110514. /* do we need to force the bitrate up? */
  110515. if(this_bits<min_target_bits){
  110516. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110517. choice++;
  110518. if(choice>=PACKETBLOBS)break;
  110519. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110520. }
  110521. }
  110522. }
  110523. /* enforce max (if used) on the current floater (if used) */
  110524. if(bm->max_bitsper>0){
  110525. /* do we need to force the bitrate down? */
  110526. if(this_bits>max_target_bits){
  110527. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110528. choice--;
  110529. if(choice<0)break;
  110530. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110531. }
  110532. }
  110533. }
  110534. /* Choice of packetblobs now made based on floater, and min/max
  110535. requirements. Now boundary check extreme choices */
  110536. if(choice<0){
  110537. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110538. frame will need to be truncated */
  110539. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110540. bm->choice=choice=0;
  110541. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110542. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110543. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110544. }
  110545. }else{
  110546. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110547. if(choice>=PACKETBLOBS)
  110548. choice=PACKETBLOBS-1;
  110549. bm->choice=choice;
  110550. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110551. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110552. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110553. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110554. }
  110555. /* now we have the final packet and the final packet size. Update statistics */
  110556. /* min and max reservoir */
  110557. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110558. if(max_target_bits>0 && this_bits>max_target_bits){
  110559. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110560. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110561. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110562. }else{
  110563. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110564. if(bm->minmax_reservoir>desired_fill){
  110565. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110566. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110567. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110568. }else{
  110569. bm->minmax_reservoir=desired_fill;
  110570. }
  110571. }else{
  110572. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110573. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110574. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110575. }else{
  110576. bm->minmax_reservoir=desired_fill;
  110577. }
  110578. }
  110579. }
  110580. }
  110581. /* avg reservoir */
  110582. if(bm->avg_bitsper>0){
  110583. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110584. bm->avg_reservoir+=this_bits-avg_target_bits;
  110585. }
  110586. return(0);
  110587. }
  110588. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110589. private_state *b=(private_state*)vd->backend_state;
  110590. bitrate_manager_state *bm=&b->bms;
  110591. vorbis_block *vb=bm->vb;
  110592. int choice=PACKETBLOBS/2;
  110593. if(!vb)return 0;
  110594. if(op){
  110595. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110596. if(vorbis_bitrate_managed(vb))
  110597. choice=bm->choice;
  110598. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110599. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110600. op->b_o_s=0;
  110601. op->e_o_s=vb->eofflag;
  110602. op->granulepos=vb->granulepos;
  110603. op->packetno=vb->sequence; /* for sake of completeness */
  110604. }
  110605. bm->vb=0;
  110606. return(1);
  110607. }
  110608. #endif
  110609. /*** End of inlined file: bitrate.c ***/
  110610. /*** Start of inlined file: block.c ***/
  110611. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110612. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110613. // tasks..
  110614. #if JUCE_MSVC
  110615. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110616. #endif
  110617. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110618. #if JUCE_USE_OGGVORBIS
  110619. #include <stdio.h>
  110620. #include <stdlib.h>
  110621. #include <string.h>
  110622. /*** Start of inlined file: window.h ***/
  110623. #ifndef _V_WINDOW_
  110624. #define _V_WINDOW_
  110625. extern float *_vorbis_window_get(int n);
  110626. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110627. int lW,int W,int nW);
  110628. #endif
  110629. /*** End of inlined file: window.h ***/
  110630. /*** Start of inlined file: lpc.h ***/
  110631. #ifndef _V_LPC_H_
  110632. #define _V_LPC_H_
  110633. /* simple linear scale LPC code */
  110634. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110635. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110636. float *data,long n);
  110637. #endif
  110638. /*** End of inlined file: lpc.h ***/
  110639. /* pcm accumulator examples (not exhaustive):
  110640. <-------------- lW ---------------->
  110641. <--------------- W ---------------->
  110642. : .....|..... _______________ |
  110643. : .''' | '''_--- | |\ |
  110644. :.....''' |_____--- '''......| | \_______|
  110645. :.................|__________________|_______|__|______|
  110646. |<------ Sl ------>| > Sr < |endW
  110647. |beginSl |endSl | |endSr
  110648. |beginW |endlW |beginSr
  110649. |< lW >|
  110650. <--------------- W ---------------->
  110651. | | .. ______________ |
  110652. | | ' `/ | ---_ |
  110653. |___.'___/`. | ---_____|
  110654. |_______|__|_______|_________________|
  110655. | >|Sl|< |<------ Sr ----->|endW
  110656. | | |endSl |beginSr |endSr
  110657. |beginW | |endlW
  110658. mult[0] |beginSl mult[n]
  110659. <-------------- lW ----------------->
  110660. |<--W-->|
  110661. : .............. ___ | |
  110662. : .''' |`/ \ | |
  110663. :.....''' |/`....\|...|
  110664. :.........................|___|___|___|
  110665. |Sl |Sr |endW
  110666. | | |endSr
  110667. | |beginSr
  110668. | |endSl
  110669. |beginSl
  110670. |beginW
  110671. */
  110672. /* block abstraction setup *********************************************/
  110673. #ifndef WORD_ALIGN
  110674. #define WORD_ALIGN 8
  110675. #endif
  110676. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110677. int i;
  110678. memset(vb,0,sizeof(*vb));
  110679. vb->vd=v;
  110680. vb->localalloc=0;
  110681. vb->localstore=NULL;
  110682. if(v->analysisp){
  110683. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110684. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110685. vbi->ampmax=-9999;
  110686. for(i=0;i<PACKETBLOBS;i++){
  110687. if(i==PACKETBLOBS/2){
  110688. vbi->packetblob[i]=&vb->opb;
  110689. }else{
  110690. vbi->packetblob[i]=
  110691. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110692. }
  110693. oggpack_writeinit(vbi->packetblob[i]);
  110694. }
  110695. }
  110696. return(0);
  110697. }
  110698. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110699. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110700. if(bytes+vb->localtop>vb->localalloc){
  110701. /* can't just _ogg_realloc... there are outstanding pointers */
  110702. if(vb->localstore){
  110703. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110704. vb->totaluse+=vb->localtop;
  110705. link->next=vb->reap;
  110706. link->ptr=vb->localstore;
  110707. vb->reap=link;
  110708. }
  110709. /* highly conservative */
  110710. vb->localalloc=bytes;
  110711. vb->localstore=_ogg_malloc(vb->localalloc);
  110712. vb->localtop=0;
  110713. }
  110714. {
  110715. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110716. vb->localtop+=bytes;
  110717. return ret;
  110718. }
  110719. }
  110720. /* reap the chain, pull the ripcord */
  110721. void _vorbis_block_ripcord(vorbis_block *vb){
  110722. /* reap the chain */
  110723. struct alloc_chain *reap=vb->reap;
  110724. while(reap){
  110725. struct alloc_chain *next=reap->next;
  110726. _ogg_free(reap->ptr);
  110727. memset(reap,0,sizeof(*reap));
  110728. _ogg_free(reap);
  110729. reap=next;
  110730. }
  110731. /* consolidate storage */
  110732. if(vb->totaluse){
  110733. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110734. vb->localalloc+=vb->totaluse;
  110735. vb->totaluse=0;
  110736. }
  110737. /* pull the ripcord */
  110738. vb->localtop=0;
  110739. vb->reap=NULL;
  110740. }
  110741. int vorbis_block_clear(vorbis_block *vb){
  110742. int i;
  110743. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110744. _vorbis_block_ripcord(vb);
  110745. if(vb->localstore)_ogg_free(vb->localstore);
  110746. if(vbi){
  110747. for(i=0;i<PACKETBLOBS;i++){
  110748. oggpack_writeclear(vbi->packetblob[i]);
  110749. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110750. }
  110751. _ogg_free(vbi);
  110752. }
  110753. memset(vb,0,sizeof(*vb));
  110754. return(0);
  110755. }
  110756. /* Analysis side code, but directly related to blocking. Thus it's
  110757. here and not in analysis.c (which is for analysis transforms only).
  110758. The init is here because some of it is shared */
  110759. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110760. int i;
  110761. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110762. private_state *b=NULL;
  110763. int hs;
  110764. if(ci==NULL) return 1;
  110765. hs=ci->halfrate_flag;
  110766. memset(v,0,sizeof(*v));
  110767. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110768. v->vi=vi;
  110769. b->modebits=ilog2(ci->modes);
  110770. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110771. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110772. /* MDCT is tranform 0 */
  110773. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110774. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110775. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110776. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110777. /* Vorbis I uses only window type 0 */
  110778. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110779. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110780. if(encp){ /* encode/decode differ here */
  110781. /* analysis always needs an fft */
  110782. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110783. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110784. /* finish the codebooks */
  110785. if(!ci->fullbooks){
  110786. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110787. for(i=0;i<ci->books;i++)
  110788. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110789. }
  110790. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110791. for(i=0;i<ci->psys;i++){
  110792. _vp_psy_init(b->psy+i,
  110793. ci->psy_param[i],
  110794. &ci->psy_g_param,
  110795. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110796. vi->rate);
  110797. }
  110798. v->analysisp=1;
  110799. }else{
  110800. /* finish the codebooks */
  110801. if(!ci->fullbooks){
  110802. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110803. for(i=0;i<ci->books;i++){
  110804. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110805. /* decode codebooks are now standalone after init */
  110806. vorbis_staticbook_destroy(ci->book_param[i]);
  110807. ci->book_param[i]=NULL;
  110808. }
  110809. }
  110810. }
  110811. /* initialize the storage vectors. blocksize[1] is small for encode,
  110812. but the correct size for decode */
  110813. v->pcm_storage=ci->blocksizes[1];
  110814. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110815. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110816. {
  110817. int i;
  110818. for(i=0;i<vi->channels;i++)
  110819. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110820. }
  110821. /* all 1 (large block) or 0 (small block) */
  110822. /* explicitly set for the sake of clarity */
  110823. v->lW=0; /* previous window size */
  110824. v->W=0; /* current window size */
  110825. /* all vector indexes */
  110826. v->centerW=ci->blocksizes[1]/2;
  110827. v->pcm_current=v->centerW;
  110828. /* initialize all the backend lookups */
  110829. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110830. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110831. for(i=0;i<ci->floors;i++)
  110832. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110833. look(v,ci->floor_param[i]);
  110834. for(i=0;i<ci->residues;i++)
  110835. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110836. look(v,ci->residue_param[i]);
  110837. return 0;
  110838. }
  110839. /* arbitrary settings and spec-mandated numbers get filled in here */
  110840. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110841. private_state *b=NULL;
  110842. if(_vds_shared_init(v,vi,1))return 1;
  110843. b=(private_state*)v->backend_state;
  110844. b->psy_g_look=_vp_global_look(vi);
  110845. /* Initialize the envelope state storage */
  110846. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110847. _ve_envelope_init(b->ve,vi);
  110848. vorbis_bitrate_init(vi,&b->bms);
  110849. /* compressed audio packets start after the headers
  110850. with sequence number 3 */
  110851. v->sequence=3;
  110852. return(0);
  110853. }
  110854. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110855. int i;
  110856. if(v){
  110857. vorbis_info *vi=v->vi;
  110858. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110859. private_state *b=(private_state*)v->backend_state;
  110860. if(b){
  110861. if(b->ve){
  110862. _ve_envelope_clear(b->ve);
  110863. _ogg_free(b->ve);
  110864. }
  110865. if(b->transform[0]){
  110866. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110867. _ogg_free(b->transform[0][0]);
  110868. _ogg_free(b->transform[0]);
  110869. }
  110870. if(b->transform[1]){
  110871. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110872. _ogg_free(b->transform[1][0]);
  110873. _ogg_free(b->transform[1]);
  110874. }
  110875. if(b->flr){
  110876. for(i=0;i<ci->floors;i++)
  110877. _floor_P[ci->floor_type[i]]->
  110878. free_look(b->flr[i]);
  110879. _ogg_free(b->flr);
  110880. }
  110881. if(b->residue){
  110882. for(i=0;i<ci->residues;i++)
  110883. _residue_P[ci->residue_type[i]]->
  110884. free_look(b->residue[i]);
  110885. _ogg_free(b->residue);
  110886. }
  110887. if(b->psy){
  110888. for(i=0;i<ci->psys;i++)
  110889. _vp_psy_clear(b->psy+i);
  110890. _ogg_free(b->psy);
  110891. }
  110892. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110893. vorbis_bitrate_clear(&b->bms);
  110894. drft_clear(&b->fft_look[0]);
  110895. drft_clear(&b->fft_look[1]);
  110896. }
  110897. if(v->pcm){
  110898. for(i=0;i<vi->channels;i++)
  110899. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110900. _ogg_free(v->pcm);
  110901. if(v->pcmret)_ogg_free(v->pcmret);
  110902. }
  110903. if(b){
  110904. /* free header, header1, header2 */
  110905. if(b->header)_ogg_free(b->header);
  110906. if(b->header1)_ogg_free(b->header1);
  110907. if(b->header2)_ogg_free(b->header2);
  110908. _ogg_free(b);
  110909. }
  110910. memset(v,0,sizeof(*v));
  110911. }
  110912. }
  110913. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110914. int i;
  110915. vorbis_info *vi=v->vi;
  110916. private_state *b=(private_state*)v->backend_state;
  110917. /* free header, header1, header2 */
  110918. if(b->header)_ogg_free(b->header);b->header=NULL;
  110919. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110920. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110921. /* Do we have enough storage space for the requested buffer? If not,
  110922. expand the PCM (and envelope) storage */
  110923. if(v->pcm_current+vals>=v->pcm_storage){
  110924. v->pcm_storage=v->pcm_current+vals*2;
  110925. for(i=0;i<vi->channels;i++){
  110926. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110927. }
  110928. }
  110929. for(i=0;i<vi->channels;i++)
  110930. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110931. return(v->pcmret);
  110932. }
  110933. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110934. int i;
  110935. int order=32;
  110936. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110937. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110938. long j;
  110939. v->preextrapolate=1;
  110940. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110941. for(i=0;i<v->vi->channels;i++){
  110942. /* need to run the extrapolation in reverse! */
  110943. for(j=0;j<v->pcm_current;j++)
  110944. work[j]=v->pcm[i][v->pcm_current-j-1];
  110945. /* prime as above */
  110946. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110947. /* run the predictor filter */
  110948. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110949. order,
  110950. work+v->pcm_current-v->centerW,
  110951. v->centerW);
  110952. for(j=0;j<v->pcm_current;j++)
  110953. v->pcm[i][v->pcm_current-j-1]=work[j];
  110954. }
  110955. }
  110956. }
  110957. /* call with val<=0 to set eof */
  110958. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110959. vorbis_info *vi=v->vi;
  110960. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110961. if(vals<=0){
  110962. int order=32;
  110963. int i;
  110964. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110965. /* if it wasn't done earlier (very short sample) */
  110966. if(!v->preextrapolate)
  110967. _preextrapolate_helper(v);
  110968. /* We're encoding the end of the stream. Just make sure we have
  110969. [at least] a few full blocks of zeroes at the end. */
  110970. /* actually, we don't want zeroes; that could drop a large
  110971. amplitude off a cliff, creating spread spectrum noise that will
  110972. suck to encode. Extrapolate for the sake of cleanliness. */
  110973. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110974. v->eofflag=v->pcm_current;
  110975. v->pcm_current+=ci->blocksizes[1]*3;
  110976. for(i=0;i<vi->channels;i++){
  110977. if(v->eofflag>order*2){
  110978. /* extrapolate with LPC to fill in */
  110979. long n;
  110980. /* make a predictor filter */
  110981. n=v->eofflag;
  110982. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110983. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110984. /* run the predictor filter */
  110985. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110986. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110987. }else{
  110988. /* not enough data to extrapolate (unlikely to happen due to
  110989. guarding the overlap, but bulletproof in case that
  110990. assumtion goes away). zeroes will do. */
  110991. memset(v->pcm[i]+v->eofflag,0,
  110992. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110993. }
  110994. }
  110995. }else{
  110996. if(v->pcm_current+vals>v->pcm_storage)
  110997. return(OV_EINVAL);
  110998. v->pcm_current+=vals;
  110999. /* we may want to reverse extrapolate the beginning of a stream
  111000. too... in case we're beginning on a cliff! */
  111001. /* clumsy, but simple. It only runs once, so simple is good. */
  111002. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111003. _preextrapolate_helper(v);
  111004. }
  111005. return(0);
  111006. }
  111007. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111008. the next block on which to continue analysis */
  111009. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111010. int i;
  111011. vorbis_info *vi=v->vi;
  111012. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111013. private_state *b=(private_state*)v->backend_state;
  111014. vorbis_look_psy_global *g=b->psy_g_look;
  111015. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111016. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111017. /* check to see if we're started... */
  111018. if(!v->preextrapolate)return(0);
  111019. /* check to see if we're done... */
  111020. if(v->eofflag==-1)return(0);
  111021. /* By our invariant, we have lW, W and centerW set. Search for
  111022. the next boundary so we can determine nW (the next window size)
  111023. which lets us compute the shape of the current block's window */
  111024. /* we do an envelope search even on a single blocksize; we may still
  111025. be throwing more bits at impulses, and envelope search handles
  111026. marking impulses too. */
  111027. {
  111028. long bp=_ve_envelope_search(v);
  111029. if(bp==-1){
  111030. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111031. full long block */
  111032. v->nW=0;
  111033. }else{
  111034. if(ci->blocksizes[0]==ci->blocksizes[1])
  111035. v->nW=0;
  111036. else
  111037. v->nW=bp;
  111038. }
  111039. }
  111040. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111041. {
  111042. /* center of next block + next block maximum right side. */
  111043. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111044. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111045. although this check is
  111046. less strict that the
  111047. _ve_envelope_search,
  111048. the search is not run
  111049. if we only use one
  111050. block size */
  111051. }
  111052. /* fill in the block. Note that for a short window, lW and nW are *short*
  111053. regardless of actual settings in the stream */
  111054. _vorbis_block_ripcord(vb);
  111055. vb->lW=v->lW;
  111056. vb->W=v->W;
  111057. vb->nW=v->nW;
  111058. if(v->W){
  111059. if(!v->lW || !v->nW){
  111060. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111061. /*fprintf(stderr,"-");*/
  111062. }else{
  111063. vbi->blocktype=BLOCKTYPE_LONG;
  111064. /*fprintf(stderr,"_");*/
  111065. }
  111066. }else{
  111067. if(_ve_envelope_mark(v)){
  111068. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111069. /*fprintf(stderr,"|");*/
  111070. }else{
  111071. vbi->blocktype=BLOCKTYPE_PADDING;
  111072. /*fprintf(stderr,".");*/
  111073. }
  111074. }
  111075. vb->vd=v;
  111076. vb->sequence=v->sequence++;
  111077. vb->granulepos=v->granulepos;
  111078. vb->pcmend=ci->blocksizes[v->W];
  111079. /* copy the vectors; this uses the local storage in vb */
  111080. /* this tracks 'strongest peak' for later psychoacoustics */
  111081. /* moved to the global psy state; clean this mess up */
  111082. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111083. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111084. vbi->ampmax=g->ampmax;
  111085. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111086. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111087. for(i=0;i<vi->channels;i++){
  111088. vbi->pcmdelay[i]=
  111089. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111090. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111091. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111092. /* before we added the delay
  111093. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111094. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111095. */
  111096. }
  111097. /* handle eof detection: eof==0 means that we've not yet received EOF
  111098. eof>0 marks the last 'real' sample in pcm[]
  111099. eof<0 'no more to do'; doesn't get here */
  111100. if(v->eofflag){
  111101. if(v->centerW>=v->eofflag){
  111102. v->eofflag=-1;
  111103. vb->eofflag=1;
  111104. return(1);
  111105. }
  111106. }
  111107. /* advance storage vectors and clean up */
  111108. {
  111109. int new_centerNext=ci->blocksizes[1]/2;
  111110. int movementW=centerNext-new_centerNext;
  111111. if(movementW>0){
  111112. _ve_envelope_shift(b->ve,movementW);
  111113. v->pcm_current-=movementW;
  111114. for(i=0;i<vi->channels;i++)
  111115. memmove(v->pcm[i],v->pcm[i]+movementW,
  111116. v->pcm_current*sizeof(*v->pcm[i]));
  111117. v->lW=v->W;
  111118. v->W=v->nW;
  111119. v->centerW=new_centerNext;
  111120. if(v->eofflag){
  111121. v->eofflag-=movementW;
  111122. if(v->eofflag<=0)v->eofflag=-1;
  111123. /* do not add padding to end of stream! */
  111124. if(v->centerW>=v->eofflag){
  111125. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111126. }else{
  111127. v->granulepos+=movementW;
  111128. }
  111129. }else{
  111130. v->granulepos+=movementW;
  111131. }
  111132. }
  111133. }
  111134. /* done */
  111135. return(1);
  111136. }
  111137. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111138. vorbis_info *vi=v->vi;
  111139. codec_setup_info *ci;
  111140. int hs;
  111141. if(!v->backend_state)return -1;
  111142. if(!vi)return -1;
  111143. ci=(codec_setup_info*) vi->codec_setup;
  111144. if(!ci)return -1;
  111145. hs=ci->halfrate_flag;
  111146. v->centerW=ci->blocksizes[1]>>(hs+1);
  111147. v->pcm_current=v->centerW>>hs;
  111148. v->pcm_returned=-1;
  111149. v->granulepos=-1;
  111150. v->sequence=-1;
  111151. v->eofflag=0;
  111152. ((private_state *)(v->backend_state))->sample_count=-1;
  111153. return(0);
  111154. }
  111155. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111156. if(_vds_shared_init(v,vi,0)) return 1;
  111157. vorbis_synthesis_restart(v);
  111158. return 0;
  111159. }
  111160. /* Unlike in analysis, the window is only partially applied for each
  111161. block. The time domain envelope is not yet handled at the point of
  111162. calling (as it relies on the previous block). */
  111163. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111164. vorbis_info *vi=v->vi;
  111165. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111166. private_state *b=(private_state*)v->backend_state;
  111167. int hs=ci->halfrate_flag;
  111168. int i,j;
  111169. if(!vb)return(OV_EINVAL);
  111170. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111171. v->lW=v->W;
  111172. v->W=vb->W;
  111173. v->nW=-1;
  111174. if((v->sequence==-1)||
  111175. (v->sequence+1 != vb->sequence)){
  111176. v->granulepos=-1; /* out of sequence; lose count */
  111177. b->sample_count=-1;
  111178. }
  111179. v->sequence=vb->sequence;
  111180. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111181. was called on block */
  111182. int n=ci->blocksizes[v->W]>>(hs+1);
  111183. int n0=ci->blocksizes[0]>>(hs+1);
  111184. int n1=ci->blocksizes[1]>>(hs+1);
  111185. int thisCenter;
  111186. int prevCenter;
  111187. v->glue_bits+=vb->glue_bits;
  111188. v->time_bits+=vb->time_bits;
  111189. v->floor_bits+=vb->floor_bits;
  111190. v->res_bits+=vb->res_bits;
  111191. if(v->centerW){
  111192. thisCenter=n1;
  111193. prevCenter=0;
  111194. }else{
  111195. thisCenter=0;
  111196. prevCenter=n1;
  111197. }
  111198. /* v->pcm is now used like a two-stage double buffer. We don't want
  111199. to have to constantly shift *or* adjust memory usage. Don't
  111200. accept a new block until the old is shifted out */
  111201. for(j=0;j<vi->channels;j++){
  111202. /* the overlap/add section */
  111203. if(v->lW){
  111204. if(v->W){
  111205. /* large/large */
  111206. float *w=_vorbis_window_get(b->window[1]-hs);
  111207. float *pcm=v->pcm[j]+prevCenter;
  111208. float *p=vb->pcm[j];
  111209. for(i=0;i<n1;i++)
  111210. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111211. }else{
  111212. /* large/small */
  111213. float *w=_vorbis_window_get(b->window[0]-hs);
  111214. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111215. float *p=vb->pcm[j];
  111216. for(i=0;i<n0;i++)
  111217. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111218. }
  111219. }else{
  111220. if(v->W){
  111221. /* small/large */
  111222. float *w=_vorbis_window_get(b->window[0]-hs);
  111223. float *pcm=v->pcm[j]+prevCenter;
  111224. float *p=vb->pcm[j]+n1/2-n0/2;
  111225. for(i=0;i<n0;i++)
  111226. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111227. for(;i<n1/2+n0/2;i++)
  111228. pcm[i]=p[i];
  111229. }else{
  111230. /* small/small */
  111231. float *w=_vorbis_window_get(b->window[0]-hs);
  111232. float *pcm=v->pcm[j]+prevCenter;
  111233. float *p=vb->pcm[j];
  111234. for(i=0;i<n0;i++)
  111235. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111236. }
  111237. }
  111238. /* the copy section */
  111239. {
  111240. float *pcm=v->pcm[j]+thisCenter;
  111241. float *p=vb->pcm[j]+n;
  111242. for(i=0;i<n;i++)
  111243. pcm[i]=p[i];
  111244. }
  111245. }
  111246. if(v->centerW)
  111247. v->centerW=0;
  111248. else
  111249. v->centerW=n1;
  111250. /* deal with initial packet state; we do this using the explicit
  111251. pcm_returned==-1 flag otherwise we're sensitive to first block
  111252. being short or long */
  111253. if(v->pcm_returned==-1){
  111254. v->pcm_returned=thisCenter;
  111255. v->pcm_current=thisCenter;
  111256. }else{
  111257. v->pcm_returned=prevCenter;
  111258. v->pcm_current=prevCenter+
  111259. ((ci->blocksizes[v->lW]/4+
  111260. ci->blocksizes[v->W]/4)>>hs);
  111261. }
  111262. }
  111263. /* track the frame number... This is for convenience, but also
  111264. making sure our last packet doesn't end with added padding. If
  111265. the last packet is partial, the number of samples we'll have to
  111266. return will be past the vb->granulepos.
  111267. This is not foolproof! It will be confused if we begin
  111268. decoding at the last page after a seek or hole. In that case,
  111269. we don't have a starting point to judge where the last frame
  111270. is. For this reason, vorbisfile will always try to make sure
  111271. it reads the last two marked pages in proper sequence */
  111272. if(b->sample_count==-1){
  111273. b->sample_count=0;
  111274. }else{
  111275. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111276. }
  111277. if(v->granulepos==-1){
  111278. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111279. v->granulepos=vb->granulepos;
  111280. /* is this a short page? */
  111281. if(b->sample_count>v->granulepos){
  111282. /* corner case; if this is both the first and last audio page,
  111283. then spec says the end is cut, not beginning */
  111284. if(vb->eofflag){
  111285. /* trim the end */
  111286. /* no preceeding granulepos; assume we started at zero (we'd
  111287. have to in a short single-page stream) */
  111288. /* granulepos could be -1 due to a seek, but that would result
  111289. in a long count, not short count */
  111290. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111291. }else{
  111292. /* trim the beginning */
  111293. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111294. if(v->pcm_returned>v->pcm_current)
  111295. v->pcm_returned=v->pcm_current;
  111296. }
  111297. }
  111298. }
  111299. }else{
  111300. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111301. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111302. if(v->granulepos>vb->granulepos){
  111303. long extra=v->granulepos-vb->granulepos;
  111304. if(extra)
  111305. if(vb->eofflag){
  111306. /* partial last frame. Strip the extra samples off */
  111307. v->pcm_current-=extra>>hs;
  111308. } /* else {Shouldn't happen *unless* the bitstream is out of
  111309. spec. Either way, believe the bitstream } */
  111310. } /* else {Shouldn't happen *unless* the bitstream is out of
  111311. spec. Either way, believe the bitstream } */
  111312. v->granulepos=vb->granulepos;
  111313. }
  111314. }
  111315. /* Update, cleanup */
  111316. if(vb->eofflag)v->eofflag=1;
  111317. return(0);
  111318. }
  111319. /* pcm==NULL indicates we just want the pending samples, no more */
  111320. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111321. vorbis_info *vi=v->vi;
  111322. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111323. if(pcm){
  111324. int i;
  111325. for(i=0;i<vi->channels;i++)
  111326. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111327. *pcm=v->pcmret;
  111328. }
  111329. return(v->pcm_current-v->pcm_returned);
  111330. }
  111331. return(0);
  111332. }
  111333. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111334. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111335. v->pcm_returned+=n;
  111336. return(0);
  111337. }
  111338. /* intended for use with a specific vorbisfile feature; we want access
  111339. to the [usually synthetic/postextrapolated] buffer and lapping at
  111340. the end of a decode cycle, specifically, a half-short-block worth.
  111341. This funtion works like pcmout above, except it will also expose
  111342. this implicit buffer data not normally decoded. */
  111343. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111344. vorbis_info *vi=v->vi;
  111345. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111346. int hs=ci->halfrate_flag;
  111347. int n=ci->blocksizes[v->W]>>(hs+1);
  111348. int n0=ci->blocksizes[0]>>(hs+1);
  111349. int n1=ci->blocksizes[1]>>(hs+1);
  111350. int i,j;
  111351. if(v->pcm_returned<0)return 0;
  111352. /* our returned data ends at pcm_returned; because the synthesis pcm
  111353. buffer is a two-fragment ring, that means our data block may be
  111354. fragmented by buffering, wrapping or a short block not filling
  111355. out a buffer. To simplify things, we unfragment if it's at all
  111356. possibly needed. Otherwise, we'd need to call lapout more than
  111357. once as well as hold additional dsp state. Opt for
  111358. simplicity. */
  111359. /* centerW was advanced by blockin; it would be the center of the
  111360. *next* block */
  111361. if(v->centerW==n1){
  111362. /* the data buffer wraps; swap the halves */
  111363. /* slow, sure, small */
  111364. for(j=0;j<vi->channels;j++){
  111365. float *p=v->pcm[j];
  111366. for(i=0;i<n1;i++){
  111367. float temp=p[i];
  111368. p[i]=p[i+n1];
  111369. p[i+n1]=temp;
  111370. }
  111371. }
  111372. v->pcm_current-=n1;
  111373. v->pcm_returned-=n1;
  111374. v->centerW=0;
  111375. }
  111376. /* solidify buffer into contiguous space */
  111377. if((v->lW^v->W)==1){
  111378. /* long/short or short/long */
  111379. for(j=0;j<vi->channels;j++){
  111380. float *s=v->pcm[j];
  111381. float *d=v->pcm[j]+(n1-n0)/2;
  111382. for(i=(n1+n0)/2-1;i>=0;--i)
  111383. d[i]=s[i];
  111384. }
  111385. v->pcm_returned+=(n1-n0)/2;
  111386. v->pcm_current+=(n1-n0)/2;
  111387. }else{
  111388. if(v->lW==0){
  111389. /* short/short */
  111390. for(j=0;j<vi->channels;j++){
  111391. float *s=v->pcm[j];
  111392. float *d=v->pcm[j]+n1-n0;
  111393. for(i=n0-1;i>=0;--i)
  111394. d[i]=s[i];
  111395. }
  111396. v->pcm_returned+=n1-n0;
  111397. v->pcm_current+=n1-n0;
  111398. }
  111399. }
  111400. if(pcm){
  111401. int i;
  111402. for(i=0;i<vi->channels;i++)
  111403. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111404. *pcm=v->pcmret;
  111405. }
  111406. return(n1+n-v->pcm_returned);
  111407. }
  111408. float *vorbis_window(vorbis_dsp_state *v,int W){
  111409. vorbis_info *vi=v->vi;
  111410. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111411. int hs=ci->halfrate_flag;
  111412. private_state *b=(private_state*)v->backend_state;
  111413. if(b->window[W]-1<0)return NULL;
  111414. return _vorbis_window_get(b->window[W]-hs);
  111415. }
  111416. #endif
  111417. /*** End of inlined file: block.c ***/
  111418. /*** Start of inlined file: codebook.c ***/
  111419. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111420. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111421. // tasks..
  111422. #if JUCE_MSVC
  111423. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111424. #endif
  111425. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111426. #if JUCE_USE_OGGVORBIS
  111427. #include <stdlib.h>
  111428. #include <string.h>
  111429. #include <math.h>
  111430. /* packs the given codebook into the bitstream **************************/
  111431. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111432. long i,j;
  111433. int ordered=0;
  111434. /* first the basic parameters */
  111435. oggpack_write(opb,0x564342,24);
  111436. oggpack_write(opb,c->dim,16);
  111437. oggpack_write(opb,c->entries,24);
  111438. /* pack the codewords. There are two packings; length ordered and
  111439. length random. Decide between the two now. */
  111440. for(i=1;i<c->entries;i++)
  111441. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111442. if(i==c->entries)ordered=1;
  111443. if(ordered){
  111444. /* length ordered. We only need to say how many codewords of
  111445. each length. The actual codewords are generated
  111446. deterministically */
  111447. long count=0;
  111448. oggpack_write(opb,1,1); /* ordered */
  111449. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111450. for(i=1;i<c->entries;i++){
  111451. long thisx=c->lengthlist[i];
  111452. long last=c->lengthlist[i-1];
  111453. if(thisx>last){
  111454. for(j=last;j<thisx;j++){
  111455. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111456. count=i;
  111457. }
  111458. }
  111459. }
  111460. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111461. }else{
  111462. /* length random. Again, we don't code the codeword itself, just
  111463. the length. This time, though, we have to encode each length */
  111464. oggpack_write(opb,0,1); /* unordered */
  111465. /* algortihmic mapping has use for 'unused entries', which we tag
  111466. here. The algorithmic mapping happens as usual, but the unused
  111467. entry has no codeword. */
  111468. for(i=0;i<c->entries;i++)
  111469. if(c->lengthlist[i]==0)break;
  111470. if(i==c->entries){
  111471. oggpack_write(opb,0,1); /* no unused entries */
  111472. for(i=0;i<c->entries;i++)
  111473. oggpack_write(opb,c->lengthlist[i]-1,5);
  111474. }else{
  111475. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111476. for(i=0;i<c->entries;i++){
  111477. if(c->lengthlist[i]==0){
  111478. oggpack_write(opb,0,1);
  111479. }else{
  111480. oggpack_write(opb,1,1);
  111481. oggpack_write(opb,c->lengthlist[i]-1,5);
  111482. }
  111483. }
  111484. }
  111485. }
  111486. /* is the entry number the desired return value, or do we have a
  111487. mapping? If we have a mapping, what type? */
  111488. oggpack_write(opb,c->maptype,4);
  111489. switch(c->maptype){
  111490. case 0:
  111491. /* no mapping */
  111492. break;
  111493. case 1:case 2:
  111494. /* implicitly populated value mapping */
  111495. /* explicitly populated value mapping */
  111496. if(!c->quantlist){
  111497. /* no quantlist? error */
  111498. return(-1);
  111499. }
  111500. /* values that define the dequantization */
  111501. oggpack_write(opb,c->q_min,32);
  111502. oggpack_write(opb,c->q_delta,32);
  111503. oggpack_write(opb,c->q_quant-1,4);
  111504. oggpack_write(opb,c->q_sequencep,1);
  111505. {
  111506. int quantvals;
  111507. switch(c->maptype){
  111508. case 1:
  111509. /* a single column of (c->entries/c->dim) quantized values for
  111510. building a full value list algorithmically (square lattice) */
  111511. quantvals=_book_maptype1_quantvals(c);
  111512. break;
  111513. case 2:
  111514. /* every value (c->entries*c->dim total) specified explicitly */
  111515. quantvals=c->entries*c->dim;
  111516. break;
  111517. default: /* NOT_REACHABLE */
  111518. quantvals=-1;
  111519. }
  111520. /* quantized values */
  111521. for(i=0;i<quantvals;i++)
  111522. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111523. }
  111524. break;
  111525. default:
  111526. /* error case; we don't have any other map types now */
  111527. return(-1);
  111528. }
  111529. return(0);
  111530. }
  111531. /* unpacks a codebook from the packet buffer into the codebook struct,
  111532. readies the codebook auxiliary structures for decode *************/
  111533. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111534. long i,j;
  111535. memset(s,0,sizeof(*s));
  111536. s->allocedp=1;
  111537. /* make sure alignment is correct */
  111538. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111539. /* first the basic parameters */
  111540. s->dim=oggpack_read(opb,16);
  111541. s->entries=oggpack_read(opb,24);
  111542. if(s->entries==-1)goto _eofout;
  111543. /* codeword ordering.... length ordered or unordered? */
  111544. switch((int)oggpack_read(opb,1)){
  111545. case 0:
  111546. /* unordered */
  111547. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111548. /* allocated but unused entries? */
  111549. if(oggpack_read(opb,1)){
  111550. /* yes, unused entries */
  111551. for(i=0;i<s->entries;i++){
  111552. if(oggpack_read(opb,1)){
  111553. long num=oggpack_read(opb,5);
  111554. if(num==-1)goto _eofout;
  111555. s->lengthlist[i]=num+1;
  111556. }else
  111557. s->lengthlist[i]=0;
  111558. }
  111559. }else{
  111560. /* all entries used; no tagging */
  111561. for(i=0;i<s->entries;i++){
  111562. long num=oggpack_read(opb,5);
  111563. if(num==-1)goto _eofout;
  111564. s->lengthlist[i]=num+1;
  111565. }
  111566. }
  111567. break;
  111568. case 1:
  111569. /* ordered */
  111570. {
  111571. long length=oggpack_read(opb,5)+1;
  111572. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111573. for(i=0;i<s->entries;){
  111574. long num=oggpack_read(opb,_ilog(s->entries-i));
  111575. if(num==-1)goto _eofout;
  111576. for(j=0;j<num && i<s->entries;j++,i++)
  111577. s->lengthlist[i]=length;
  111578. length++;
  111579. }
  111580. }
  111581. break;
  111582. default:
  111583. /* EOF */
  111584. return(-1);
  111585. }
  111586. /* Do we have a mapping to unpack? */
  111587. switch((s->maptype=oggpack_read(opb,4))){
  111588. case 0:
  111589. /* no mapping */
  111590. break;
  111591. case 1: case 2:
  111592. /* implicitly populated value mapping */
  111593. /* explicitly populated value mapping */
  111594. s->q_min=oggpack_read(opb,32);
  111595. s->q_delta=oggpack_read(opb,32);
  111596. s->q_quant=oggpack_read(opb,4)+1;
  111597. s->q_sequencep=oggpack_read(opb,1);
  111598. {
  111599. int quantvals=0;
  111600. switch(s->maptype){
  111601. case 1:
  111602. quantvals=_book_maptype1_quantvals(s);
  111603. break;
  111604. case 2:
  111605. quantvals=s->entries*s->dim;
  111606. break;
  111607. }
  111608. /* quantized values */
  111609. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111610. for(i=0;i<quantvals;i++)
  111611. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111612. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111613. }
  111614. break;
  111615. default:
  111616. goto _errout;
  111617. }
  111618. /* all set */
  111619. return(0);
  111620. _errout:
  111621. _eofout:
  111622. vorbis_staticbook_clear(s);
  111623. return(-1);
  111624. }
  111625. /* returns the number of bits ************************************************/
  111626. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111627. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111628. return(book->c->lengthlist[a]);
  111629. }
  111630. /* One the encode side, our vector writers are each designed for a
  111631. specific purpose, and the encoder is not flexible without modification:
  111632. The LSP vector coder uses a single stage nearest-match with no
  111633. interleave, so no step and no error return. This is specced by floor0
  111634. and doesn't change.
  111635. Residue0 encoding interleaves, uses multiple stages, and each stage
  111636. peels of a specific amount of resolution from a lattice (thus we want
  111637. to match by threshold, not nearest match). Residue doesn't *have* to
  111638. be encoded that way, but to change it, one will need to add more
  111639. infrastructure on the encode side (decode side is specced and simpler) */
  111640. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111641. /* returns entry number and *modifies a* to the quantization value *****/
  111642. int vorbis_book_errorv(codebook *book,float *a){
  111643. int dim=book->dim,k;
  111644. int best=_best(book,a,1);
  111645. for(k=0;k<dim;k++)
  111646. a[k]=(book->valuelist+best*dim)[k];
  111647. return(best);
  111648. }
  111649. /* returns the number of bits and *modifies a* to the quantization value *****/
  111650. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111651. int k,dim=book->dim;
  111652. for(k=0;k<dim;k++)
  111653. a[k]=(book->valuelist+best*dim)[k];
  111654. return(vorbis_book_encode(book,best,b));
  111655. }
  111656. /* the 'eliminate the decode tree' optimization actually requires the
  111657. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111658. (and one of the first places where carefully thought out design
  111659. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111660. to an MSb bitpacker), but not actually the huge hit it appears to
  111661. be. The first-stage decode table catches most words so that
  111662. bitreverse is not in the main execution path. */
  111663. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111664. int read=book->dec_maxlength;
  111665. long lo,hi;
  111666. long lok = oggpack_look(b,book->dec_firsttablen);
  111667. if (lok >= 0) {
  111668. long entry = book->dec_firsttable[lok];
  111669. if(entry&0x80000000UL){
  111670. lo=(entry>>15)&0x7fff;
  111671. hi=book->used_entries-(entry&0x7fff);
  111672. }else{
  111673. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111674. return(entry-1);
  111675. }
  111676. }else{
  111677. lo=0;
  111678. hi=book->used_entries;
  111679. }
  111680. lok = oggpack_look(b, read);
  111681. while(lok<0 && read>1)
  111682. lok = oggpack_look(b, --read);
  111683. if(lok<0)return -1;
  111684. /* bisect search for the codeword in the ordered list */
  111685. {
  111686. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111687. while(hi-lo>1){
  111688. long p=(hi-lo)>>1;
  111689. long test=book->codelist[lo+p]>testword;
  111690. lo+=p&(test-1);
  111691. hi-=p&(-test);
  111692. }
  111693. if(book->dec_codelengths[lo]<=read){
  111694. oggpack_adv(b, book->dec_codelengths[lo]);
  111695. return(lo);
  111696. }
  111697. }
  111698. oggpack_adv(b, read);
  111699. return(-1);
  111700. }
  111701. /* Decode side is specced and easier, because we don't need to find
  111702. matches using different criteria; we simply read and map. There are
  111703. two things we need to do 'depending':
  111704. We may need to support interleave. We don't really, but it's
  111705. convenient to do it here rather than rebuild the vector later.
  111706. Cascades may be additive or multiplicitive; this is not inherent in
  111707. the codebook, but set in the code using the codebook. Like
  111708. interleaving, it's easiest to do it here.
  111709. addmul==0 -> declarative (set the value)
  111710. addmul==1 -> additive
  111711. addmul==2 -> multiplicitive */
  111712. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111713. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111714. long packed_entry=decode_packed_entry_number(book,b);
  111715. if(packed_entry>=0)
  111716. return(book->dec_index[packed_entry]);
  111717. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111718. return(packed_entry);
  111719. }
  111720. /* returns 0 on OK or -1 on eof *************************************/
  111721. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111722. int step=n/book->dim;
  111723. long *entry = (long*)alloca(sizeof(*entry)*step);
  111724. float **t = (float**)alloca(sizeof(*t)*step);
  111725. int i,j,o;
  111726. for (i = 0; i < step; i++) {
  111727. entry[i]=decode_packed_entry_number(book,b);
  111728. if(entry[i]==-1)return(-1);
  111729. t[i] = book->valuelist+entry[i]*book->dim;
  111730. }
  111731. for(i=0,o=0;i<book->dim;i++,o+=step)
  111732. for (j=0;j<step;j++)
  111733. a[o+j]+=t[j][i];
  111734. return(0);
  111735. }
  111736. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111737. int i,j,entry;
  111738. float *t;
  111739. if(book->dim>8){
  111740. for(i=0;i<n;){
  111741. entry = decode_packed_entry_number(book,b);
  111742. if(entry==-1)return(-1);
  111743. t = book->valuelist+entry*book->dim;
  111744. for (j=0;j<book->dim;)
  111745. a[i++]+=t[j++];
  111746. }
  111747. }else{
  111748. for(i=0;i<n;){
  111749. entry = decode_packed_entry_number(book,b);
  111750. if(entry==-1)return(-1);
  111751. t = book->valuelist+entry*book->dim;
  111752. j=0;
  111753. switch((int)book->dim){
  111754. case 8:
  111755. a[i++]+=t[j++];
  111756. case 7:
  111757. a[i++]+=t[j++];
  111758. case 6:
  111759. a[i++]+=t[j++];
  111760. case 5:
  111761. a[i++]+=t[j++];
  111762. case 4:
  111763. a[i++]+=t[j++];
  111764. case 3:
  111765. a[i++]+=t[j++];
  111766. case 2:
  111767. a[i++]+=t[j++];
  111768. case 1:
  111769. a[i++]+=t[j++];
  111770. case 0:
  111771. break;
  111772. }
  111773. }
  111774. }
  111775. return(0);
  111776. }
  111777. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111778. int i,j,entry;
  111779. float *t;
  111780. for(i=0;i<n;){
  111781. entry = decode_packed_entry_number(book,b);
  111782. if(entry==-1)return(-1);
  111783. t = book->valuelist+entry*book->dim;
  111784. for (j=0;j<book->dim;)
  111785. a[i++]=t[j++];
  111786. }
  111787. return(0);
  111788. }
  111789. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111790. oggpack_buffer *b,int n){
  111791. long i,j,entry;
  111792. int chptr=0;
  111793. for(i=offset/ch;i<(offset+n)/ch;){
  111794. entry = decode_packed_entry_number(book,b);
  111795. if(entry==-1)return(-1);
  111796. {
  111797. const float *t = book->valuelist+entry*book->dim;
  111798. for (j=0;j<book->dim;j++){
  111799. a[chptr++][i]+=t[j];
  111800. if(chptr==ch){
  111801. chptr=0;
  111802. i++;
  111803. }
  111804. }
  111805. }
  111806. }
  111807. return(0);
  111808. }
  111809. #ifdef _V_SELFTEST
  111810. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111811. number of vectors through (keeping track of the quantized values),
  111812. and decode using the unpacked book. quantized version of in should
  111813. exactly equal out */
  111814. #include <stdio.h>
  111815. #include "vorbis/book/lsp20_0.vqh"
  111816. #include "vorbis/book/res0a_13.vqh"
  111817. #define TESTSIZE 40
  111818. float test1[TESTSIZE]={
  111819. 0.105939f,
  111820. 0.215373f,
  111821. 0.429117f,
  111822. 0.587974f,
  111823. 0.181173f,
  111824. 0.296583f,
  111825. 0.515707f,
  111826. 0.715261f,
  111827. 0.162327f,
  111828. 0.263834f,
  111829. 0.342876f,
  111830. 0.406025f,
  111831. 0.103571f,
  111832. 0.223561f,
  111833. 0.368513f,
  111834. 0.540313f,
  111835. 0.136672f,
  111836. 0.395882f,
  111837. 0.587183f,
  111838. 0.652476f,
  111839. 0.114338f,
  111840. 0.417300f,
  111841. 0.525486f,
  111842. 0.698679f,
  111843. 0.147492f,
  111844. 0.324481f,
  111845. 0.643089f,
  111846. 0.757582f,
  111847. 0.139556f,
  111848. 0.215795f,
  111849. 0.324559f,
  111850. 0.399387f,
  111851. 0.120236f,
  111852. 0.267420f,
  111853. 0.446940f,
  111854. 0.608760f,
  111855. 0.115587f,
  111856. 0.287234f,
  111857. 0.571081f,
  111858. 0.708603f,
  111859. };
  111860. float test3[TESTSIZE]={
  111861. 0,1,-2,3,4,-5,6,7,8,9,
  111862. 8,-2,7,-1,4,6,8,3,1,-9,
  111863. 10,11,12,13,14,15,26,17,18,19,
  111864. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111865. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111866. &_vq_book_res0a_13,NULL};
  111867. float *testvec[]={test1,test3};
  111868. int main(){
  111869. oggpack_buffer write;
  111870. oggpack_buffer read;
  111871. long ptr=0,i;
  111872. oggpack_writeinit(&write);
  111873. fprintf(stderr,"Testing codebook abstraction...:\n");
  111874. while(testlist[ptr]){
  111875. codebook c;
  111876. static_codebook s;
  111877. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111878. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111879. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111880. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111881. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111882. /* pack the codebook, write the testvector */
  111883. oggpack_reset(&write);
  111884. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111885. we can write */
  111886. vorbis_staticbook_pack(testlist[ptr],&write);
  111887. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111888. for(i=0;i<TESTSIZE;i+=c.dim){
  111889. int best=_best(&c,qv+i,1);
  111890. vorbis_book_encodev(&c,best,qv+i,&write);
  111891. }
  111892. vorbis_book_clear(&c);
  111893. fprintf(stderr,"OK.\n");
  111894. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111895. /* transfer the write data to a read buffer and unpack/read */
  111896. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111897. if(vorbis_staticbook_unpack(&read,&s)){
  111898. fprintf(stderr,"Error unpacking codebook.\n");
  111899. exit(1);
  111900. }
  111901. if(vorbis_book_init_decode(&c,&s)){
  111902. fprintf(stderr,"Error initializing codebook.\n");
  111903. exit(1);
  111904. }
  111905. for(i=0;i<TESTSIZE;i+=c.dim)
  111906. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111907. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111908. exit(1);
  111909. }
  111910. for(i=0;i<TESTSIZE;i++)
  111911. if(fabs(qv[i]-iv[i])>.000001){
  111912. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111913. iv[i],qv[i],i);
  111914. exit(1);
  111915. }
  111916. fprintf(stderr,"OK\n");
  111917. ptr++;
  111918. }
  111919. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111920. exit(0);
  111921. }
  111922. #endif
  111923. #endif
  111924. /*** End of inlined file: codebook.c ***/
  111925. /*** Start of inlined file: envelope.c ***/
  111926. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111927. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111928. // tasks..
  111929. #if JUCE_MSVC
  111930. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111931. #endif
  111932. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111933. #if JUCE_USE_OGGVORBIS
  111934. #include <stdlib.h>
  111935. #include <string.h>
  111936. #include <stdio.h>
  111937. #include <math.h>
  111938. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111939. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111940. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111941. int ch=vi->channels;
  111942. int i,j;
  111943. int n=e->winlength=128;
  111944. e->searchstep=64; /* not random */
  111945. e->minenergy=gi->preecho_minenergy;
  111946. e->ch=ch;
  111947. e->storage=128;
  111948. e->cursor=ci->blocksizes[1]/2;
  111949. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111950. mdct_init(&e->mdct,n);
  111951. for(i=0;i<n;i++){
  111952. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111953. e->mdct_win[i]*=e->mdct_win[i];
  111954. }
  111955. /* magic follows */
  111956. e->band[0].begin=2; e->band[0].end=4;
  111957. e->band[1].begin=4; e->band[1].end=5;
  111958. e->band[2].begin=6; e->band[2].end=6;
  111959. e->band[3].begin=9; e->band[3].end=8;
  111960. e->band[4].begin=13; e->band[4].end=8;
  111961. e->band[5].begin=17; e->band[5].end=8;
  111962. e->band[6].begin=22; e->band[6].end=8;
  111963. for(j=0;j<VE_BANDS;j++){
  111964. n=e->band[j].end;
  111965. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111966. for(i=0;i<n;i++){
  111967. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111968. e->band[j].total+=e->band[j].window[i];
  111969. }
  111970. e->band[j].total=1./e->band[j].total;
  111971. }
  111972. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111973. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111974. }
  111975. void _ve_envelope_clear(envelope_lookup *e){
  111976. int i;
  111977. mdct_clear(&e->mdct);
  111978. for(i=0;i<VE_BANDS;i++)
  111979. _ogg_free(e->band[i].window);
  111980. _ogg_free(e->mdct_win);
  111981. _ogg_free(e->filter);
  111982. _ogg_free(e->mark);
  111983. memset(e,0,sizeof(*e));
  111984. }
  111985. /* fairly straight threshhold-by-band based until we find something
  111986. that works better and isn't patented. */
  111987. static int _ve_amp(envelope_lookup *ve,
  111988. vorbis_info_psy_global *gi,
  111989. float *data,
  111990. envelope_band *bands,
  111991. envelope_filter_state *filters,
  111992. long pos){
  111993. long n=ve->winlength;
  111994. int ret=0;
  111995. long i,j;
  111996. float decay;
  111997. /* we want to have a 'minimum bar' for energy, else we're just
  111998. basing blocks on quantization noise that outweighs the signal
  111999. itself (for low power signals) */
  112000. float minV=ve->minenergy;
  112001. float *vec=(float*) alloca(n*sizeof(*vec));
  112002. /* stretch is used to gradually lengthen the number of windows
  112003. considered prevoius-to-potential-trigger */
  112004. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112005. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112006. if(penalty<0.f)penalty=0.f;
  112007. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112008. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112009. totalshift+pos*ve->searchstep);*/
  112010. /* window and transform */
  112011. for(i=0;i<n;i++)
  112012. vec[i]=data[i]*ve->mdct_win[i];
  112013. mdct_forward(&ve->mdct,vec,vec);
  112014. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112015. /* near-DC spreading function; this has nothing to do with
  112016. psychoacoustics, just sidelobe leakage and window size */
  112017. {
  112018. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112019. int ptr=filters->nearptr;
  112020. /* the accumulation is regularly refreshed from scratch to avoid
  112021. floating point creep */
  112022. if(ptr==0){
  112023. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112024. filters->nearDC_partialacc=temp;
  112025. }else{
  112026. decay=filters->nearDC_acc+=temp;
  112027. filters->nearDC_partialacc+=temp;
  112028. }
  112029. filters->nearDC_acc-=filters->nearDC[ptr];
  112030. filters->nearDC[ptr]=temp;
  112031. decay*=(1./(VE_NEARDC+1));
  112032. filters->nearptr++;
  112033. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112034. decay=todB(&decay)*.5-15.f;
  112035. }
  112036. /* perform spreading and limiting, also smooth the spectrum. yes,
  112037. the MDCT results in all real coefficients, but it still *behaves*
  112038. like real/imaginary pairs */
  112039. for(i=0;i<n/2;i+=2){
  112040. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112041. val=todB(&val)*.5f;
  112042. if(val<decay)val=decay;
  112043. if(val<minV)val=minV;
  112044. vec[i>>1]=val;
  112045. decay-=8.;
  112046. }
  112047. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112048. /* perform preecho/postecho triggering by band */
  112049. for(j=0;j<VE_BANDS;j++){
  112050. float acc=0.;
  112051. float valmax,valmin;
  112052. /* accumulate amplitude */
  112053. for(i=0;i<bands[j].end;i++)
  112054. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112055. acc*=bands[j].total;
  112056. /* convert amplitude to delta */
  112057. {
  112058. int p,thisx=filters[j].ampptr;
  112059. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112060. p=thisx;
  112061. p--;
  112062. if(p<0)p+=VE_AMP;
  112063. postmax=max(acc,filters[j].ampbuf[p]);
  112064. postmin=min(acc,filters[j].ampbuf[p]);
  112065. for(i=0;i<stretch;i++){
  112066. p--;
  112067. if(p<0)p+=VE_AMP;
  112068. premax=max(premax,filters[j].ampbuf[p]);
  112069. premin=min(premin,filters[j].ampbuf[p]);
  112070. }
  112071. valmin=postmin-premin;
  112072. valmax=postmax-premax;
  112073. /*filters[j].markers[pos]=valmax;*/
  112074. filters[j].ampbuf[thisx]=acc;
  112075. filters[j].ampptr++;
  112076. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112077. }
  112078. /* look at min/max, decide trigger */
  112079. if(valmax>gi->preecho_thresh[j]+penalty){
  112080. ret|=1;
  112081. ret|=4;
  112082. }
  112083. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112084. }
  112085. return(ret);
  112086. }
  112087. #if 0
  112088. static int seq=0;
  112089. static ogg_int64_t totalshift=-1024;
  112090. #endif
  112091. long _ve_envelope_search(vorbis_dsp_state *v){
  112092. vorbis_info *vi=v->vi;
  112093. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112094. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112095. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112096. long i,j;
  112097. int first=ve->current/ve->searchstep;
  112098. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112099. if(first<0)first=0;
  112100. /* make sure we have enough storage to match the PCM */
  112101. if(last+VE_WIN+VE_POST>ve->storage){
  112102. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112103. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112104. }
  112105. for(j=first;j<last;j++){
  112106. int ret=0;
  112107. ve->stretch++;
  112108. if(ve->stretch>VE_MAXSTRETCH*2)
  112109. ve->stretch=VE_MAXSTRETCH*2;
  112110. for(i=0;i<ve->ch;i++){
  112111. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112112. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112113. }
  112114. ve->mark[j+VE_POST]=0;
  112115. if(ret&1){
  112116. ve->mark[j]=1;
  112117. ve->mark[j+1]=1;
  112118. }
  112119. if(ret&2){
  112120. ve->mark[j]=1;
  112121. if(j>0)ve->mark[j-1]=1;
  112122. }
  112123. if(ret&4)ve->stretch=-1;
  112124. }
  112125. ve->current=last*ve->searchstep;
  112126. {
  112127. long centerW=v->centerW;
  112128. long testW=
  112129. centerW+
  112130. ci->blocksizes[v->W]/4+
  112131. ci->blocksizes[1]/2+
  112132. ci->blocksizes[0]/4;
  112133. j=ve->cursor;
  112134. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112135. working back one window */
  112136. if(j>=testW)return(1);
  112137. ve->cursor=j;
  112138. if(ve->mark[j/ve->searchstep]){
  112139. if(j>centerW){
  112140. #if 0
  112141. if(j>ve->curmark){
  112142. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112143. int l,m;
  112144. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112145. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112146. seq,
  112147. (totalshift+ve->cursor)/44100.,
  112148. (totalshift+j)/44100.);
  112149. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112150. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112151. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112152. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112153. for(m=0;m<VE_BANDS;m++){
  112154. char buf[80];
  112155. sprintf(buf,"delL%d",m);
  112156. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112157. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112158. }
  112159. for(m=0;m<VE_BANDS;m++){
  112160. char buf[80];
  112161. sprintf(buf,"delR%d",m);
  112162. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112163. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112164. }
  112165. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112166. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112167. seq++;
  112168. }
  112169. #endif
  112170. ve->curmark=j;
  112171. if(j>=testW)return(1);
  112172. return(0);
  112173. }
  112174. }
  112175. j+=ve->searchstep;
  112176. }
  112177. }
  112178. return(-1);
  112179. }
  112180. int _ve_envelope_mark(vorbis_dsp_state *v){
  112181. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112182. vorbis_info *vi=v->vi;
  112183. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112184. long centerW=v->centerW;
  112185. long beginW=centerW-ci->blocksizes[v->W]/4;
  112186. long endW=centerW+ci->blocksizes[v->W]/4;
  112187. if(v->W){
  112188. beginW-=ci->blocksizes[v->lW]/4;
  112189. endW+=ci->blocksizes[v->nW]/4;
  112190. }else{
  112191. beginW-=ci->blocksizes[0]/4;
  112192. endW+=ci->blocksizes[0]/4;
  112193. }
  112194. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112195. {
  112196. long first=beginW/ve->searchstep;
  112197. long last=endW/ve->searchstep;
  112198. long i;
  112199. for(i=first;i<last;i++)
  112200. if(ve->mark[i])return(1);
  112201. }
  112202. return(0);
  112203. }
  112204. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112205. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112206. ahead of ve->current */
  112207. int smallshift=shift/e->searchstep;
  112208. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112209. #if 0
  112210. for(i=0;i<VE_BANDS*e->ch;i++)
  112211. memmove(e->filter[i].markers,
  112212. e->filter[i].markers+smallshift,
  112213. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112214. totalshift+=shift;
  112215. #endif
  112216. e->current-=shift;
  112217. if(e->curmark>=0)
  112218. e->curmark-=shift;
  112219. e->cursor-=shift;
  112220. }
  112221. #endif
  112222. /*** End of inlined file: envelope.c ***/
  112223. /*** Start of inlined file: floor0.c ***/
  112224. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112225. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112226. // tasks..
  112227. #if JUCE_MSVC
  112228. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112229. #endif
  112230. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112231. #if JUCE_USE_OGGVORBIS
  112232. #include <stdlib.h>
  112233. #include <string.h>
  112234. #include <math.h>
  112235. /*** Start of inlined file: lsp.h ***/
  112236. #ifndef _V_LSP_H_
  112237. #define _V_LSP_H_
  112238. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112239. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112240. float *lsp,int m,
  112241. float amp,float ampoffset);
  112242. #endif
  112243. /*** End of inlined file: lsp.h ***/
  112244. #include <stdio.h>
  112245. typedef struct {
  112246. int ln;
  112247. int m;
  112248. int **linearmap;
  112249. int n[2];
  112250. vorbis_info_floor0 *vi;
  112251. long bits;
  112252. long frames;
  112253. } vorbis_look_floor0;
  112254. /***********************************************/
  112255. static void floor0_free_info(vorbis_info_floor *i){
  112256. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112257. if(info){
  112258. memset(info,0,sizeof(*info));
  112259. _ogg_free(info);
  112260. }
  112261. }
  112262. static void floor0_free_look(vorbis_look_floor *i){
  112263. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112264. if(look){
  112265. if(look->linearmap){
  112266. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112267. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112268. _ogg_free(look->linearmap);
  112269. }
  112270. memset(look,0,sizeof(*look));
  112271. _ogg_free(look);
  112272. }
  112273. }
  112274. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112275. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112276. int j;
  112277. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112278. info->order=oggpack_read(opb,8);
  112279. info->rate=oggpack_read(opb,16);
  112280. info->barkmap=oggpack_read(opb,16);
  112281. info->ampbits=oggpack_read(opb,6);
  112282. info->ampdB=oggpack_read(opb,8);
  112283. info->numbooks=oggpack_read(opb,4)+1;
  112284. if(info->order<1)goto err_out;
  112285. if(info->rate<1)goto err_out;
  112286. if(info->barkmap<1)goto err_out;
  112287. if(info->numbooks<1)goto err_out;
  112288. for(j=0;j<info->numbooks;j++){
  112289. info->books[j]=oggpack_read(opb,8);
  112290. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112291. }
  112292. return(info);
  112293. err_out:
  112294. floor0_free_info(info);
  112295. return(NULL);
  112296. }
  112297. /* initialize Bark scale and normalization lookups. We could do this
  112298. with static tables, but Vorbis allows a number of possible
  112299. combinations, so it's best to do it computationally.
  112300. The below is authoritative in terms of defining scale mapping.
  112301. Note that the scale depends on the sampling rate as well as the
  112302. linear block and mapping sizes */
  112303. static void floor0_map_lazy_init(vorbis_block *vb,
  112304. vorbis_info_floor *infoX,
  112305. vorbis_look_floor0 *look){
  112306. if(!look->linearmap[vb->W]){
  112307. vorbis_dsp_state *vd=vb->vd;
  112308. vorbis_info *vi=vd->vi;
  112309. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112310. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112311. int W=vb->W;
  112312. int n=ci->blocksizes[W]/2,j;
  112313. /* we choose a scaling constant so that:
  112314. floor(bark(rate/2-1)*C)=mapped-1
  112315. floor(bark(rate/2)*C)=mapped */
  112316. float scale=look->ln/toBARK(info->rate/2.f);
  112317. /* the mapping from a linear scale to a smaller bark scale is
  112318. straightforward. We do *not* make sure that the linear mapping
  112319. does not skip bark-scale bins; the decoder simply skips them and
  112320. the encoder may do what it wishes in filling them. They're
  112321. necessary in some mapping combinations to keep the scale spacing
  112322. accurate */
  112323. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112324. for(j=0;j<n;j++){
  112325. int val=floor( toBARK((info->rate/2.f)/n*j)
  112326. *scale); /* bark numbers represent band edges */
  112327. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112328. look->linearmap[W][j]=val;
  112329. }
  112330. look->linearmap[W][j]=-1;
  112331. look->n[W]=n;
  112332. }
  112333. }
  112334. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112335. vorbis_info_floor *i){
  112336. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112337. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112338. look->m=info->order;
  112339. look->ln=info->barkmap;
  112340. look->vi=info;
  112341. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112342. return look;
  112343. }
  112344. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112345. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112346. vorbis_info_floor0 *info=look->vi;
  112347. int j,k;
  112348. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112349. if(ampraw>0){ /* also handles the -1 out of data case */
  112350. long maxval=(1<<info->ampbits)-1;
  112351. float amp=(float)ampraw/maxval*info->ampdB;
  112352. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112353. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112354. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112355. codebook *b=ci->fullbooks+info->books[booknum];
  112356. float last=0.f;
  112357. /* the additional b->dim is a guard against any possible stack
  112358. smash; b->dim is provably more than we can overflow the
  112359. vector */
  112360. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112361. for(j=0;j<look->m;j+=b->dim)
  112362. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112363. for(j=0;j<look->m;){
  112364. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112365. last=lsp[j-1];
  112366. }
  112367. lsp[look->m]=amp;
  112368. return(lsp);
  112369. }
  112370. }
  112371. eop:
  112372. return(NULL);
  112373. }
  112374. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112375. void *memo,float *out){
  112376. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112377. vorbis_info_floor0 *info=look->vi;
  112378. floor0_map_lazy_init(vb,info,look);
  112379. if(memo){
  112380. float *lsp=(float *)memo;
  112381. float amp=lsp[look->m];
  112382. /* take the coefficients back to a spectral envelope curve */
  112383. vorbis_lsp_to_curve(out,
  112384. look->linearmap[vb->W],
  112385. look->n[vb->W],
  112386. look->ln,
  112387. lsp,look->m,amp,(float)info->ampdB);
  112388. return(1);
  112389. }
  112390. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112391. return(0);
  112392. }
  112393. /* export hooks */
  112394. vorbis_func_floor floor0_exportbundle={
  112395. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112396. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112397. };
  112398. #endif
  112399. /*** End of inlined file: floor0.c ***/
  112400. /*** Start of inlined file: floor1.c ***/
  112401. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112402. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112403. // tasks..
  112404. #if JUCE_MSVC
  112405. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112406. #endif
  112407. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112408. #if JUCE_USE_OGGVORBIS
  112409. #include <stdlib.h>
  112410. #include <string.h>
  112411. #include <math.h>
  112412. #include <stdio.h>
  112413. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112414. typedef struct {
  112415. int sorted_index[VIF_POSIT+2];
  112416. int forward_index[VIF_POSIT+2];
  112417. int reverse_index[VIF_POSIT+2];
  112418. int hineighbor[VIF_POSIT];
  112419. int loneighbor[VIF_POSIT];
  112420. int posts;
  112421. int n;
  112422. int quant_q;
  112423. vorbis_info_floor1 *vi;
  112424. long phrasebits;
  112425. long postbits;
  112426. long frames;
  112427. } vorbis_look_floor1;
  112428. typedef struct lsfit_acc{
  112429. long x0;
  112430. long x1;
  112431. long xa;
  112432. long ya;
  112433. long x2a;
  112434. long y2a;
  112435. long xya;
  112436. long an;
  112437. } lsfit_acc;
  112438. /***********************************************/
  112439. static void floor1_free_info(vorbis_info_floor *i){
  112440. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112441. if(info){
  112442. memset(info,0,sizeof(*info));
  112443. _ogg_free(info);
  112444. }
  112445. }
  112446. static void floor1_free_look(vorbis_look_floor *i){
  112447. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112448. if(look){
  112449. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112450. (float)look->phrasebits/look->frames,
  112451. (float)look->postbits/look->frames,
  112452. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112453. memset(look,0,sizeof(*look));
  112454. _ogg_free(look);
  112455. }
  112456. }
  112457. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112458. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112459. int j,k;
  112460. int count=0;
  112461. int rangebits;
  112462. int maxposit=info->postlist[1];
  112463. int maxclass=-1;
  112464. /* save out partitions */
  112465. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112466. for(j=0;j<info->partitions;j++){
  112467. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112468. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112469. }
  112470. /* save out partition classes */
  112471. for(j=0;j<maxclass+1;j++){
  112472. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112473. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112474. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112475. for(k=0;k<(1<<info->class_subs[j]);k++)
  112476. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112477. }
  112478. /* save out the post list */
  112479. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112480. oggpack_write(opb,ilog2(maxposit),4);
  112481. rangebits=ilog2(maxposit);
  112482. for(j=0,k=0;j<info->partitions;j++){
  112483. count+=info->class_dim[info->partitionclass[j]];
  112484. for(;k<count;k++)
  112485. oggpack_write(opb,info->postlist[k+2],rangebits);
  112486. }
  112487. }
  112488. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112489. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112490. int j,k,count=0,maxclass=-1,rangebits;
  112491. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112492. /* read partitions */
  112493. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112494. for(j=0;j<info->partitions;j++){
  112495. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112496. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112497. }
  112498. /* read partition classes */
  112499. for(j=0;j<maxclass+1;j++){
  112500. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112501. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112502. if(info->class_subs[j]<0)
  112503. goto err_out;
  112504. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112505. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112506. goto err_out;
  112507. for(k=0;k<(1<<info->class_subs[j]);k++){
  112508. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112509. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112510. goto err_out;
  112511. }
  112512. }
  112513. /* read the post list */
  112514. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112515. rangebits=oggpack_read(opb,4);
  112516. for(j=0,k=0;j<info->partitions;j++){
  112517. count+=info->class_dim[info->partitionclass[j]];
  112518. for(;k<count;k++){
  112519. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112520. if(t<0 || t>=(1<<rangebits))
  112521. goto err_out;
  112522. }
  112523. }
  112524. info->postlist[0]=0;
  112525. info->postlist[1]=1<<rangebits;
  112526. return(info);
  112527. err_out:
  112528. floor1_free_info(info);
  112529. return(NULL);
  112530. }
  112531. static int JUCE_CDECL icomp(const void *a,const void *b){
  112532. return(**(int **)a-**(int **)b);
  112533. }
  112534. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112535. vorbis_info_floor *in){
  112536. int *sortpointer[VIF_POSIT+2];
  112537. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112538. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112539. int i,j,n=0;
  112540. look->vi=info;
  112541. look->n=info->postlist[1];
  112542. /* we drop each position value in-between already decoded values,
  112543. and use linear interpolation to predict each new value past the
  112544. edges. The positions are read in the order of the position
  112545. list... we precompute the bounding positions in the lookup. Of
  112546. course, the neighbors can change (if a position is declined), but
  112547. this is an initial mapping */
  112548. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112549. n+=2;
  112550. look->posts=n;
  112551. /* also store a sorted position index */
  112552. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112553. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112554. /* points from sort order back to range number */
  112555. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112556. /* points from range order to sorted position */
  112557. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112558. /* we actually need the post values too */
  112559. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112560. /* quantize values to multiplier spec */
  112561. switch(info->mult){
  112562. case 1: /* 1024 -> 256 */
  112563. look->quant_q=256;
  112564. break;
  112565. case 2: /* 1024 -> 128 */
  112566. look->quant_q=128;
  112567. break;
  112568. case 3: /* 1024 -> 86 */
  112569. look->quant_q=86;
  112570. break;
  112571. case 4: /* 1024 -> 64 */
  112572. look->quant_q=64;
  112573. break;
  112574. }
  112575. /* discover our neighbors for decode where we don't use fit flags
  112576. (that would push the neighbors outward) */
  112577. for(i=0;i<n-2;i++){
  112578. int lo=0;
  112579. int hi=1;
  112580. int lx=0;
  112581. int hx=look->n;
  112582. int currentx=info->postlist[i+2];
  112583. for(j=0;j<i+2;j++){
  112584. int x=info->postlist[j];
  112585. if(x>lx && x<currentx){
  112586. lo=j;
  112587. lx=x;
  112588. }
  112589. if(x<hx && x>currentx){
  112590. hi=j;
  112591. hx=x;
  112592. }
  112593. }
  112594. look->loneighbor[i]=lo;
  112595. look->hineighbor[i]=hi;
  112596. }
  112597. return(look);
  112598. }
  112599. static int render_point(int x0,int x1,int y0,int y1,int x){
  112600. y0&=0x7fff; /* mask off flag */
  112601. y1&=0x7fff;
  112602. {
  112603. int dy=y1-y0;
  112604. int adx=x1-x0;
  112605. int ady=abs(dy);
  112606. int err=ady*(x-x0);
  112607. int off=err/adx;
  112608. if(dy<0)return(y0-off);
  112609. return(y0+off);
  112610. }
  112611. }
  112612. static int vorbis_dBquant(const float *x){
  112613. int i= *x*7.3142857f+1023.5f;
  112614. if(i>1023)return(1023);
  112615. if(i<0)return(0);
  112616. return i;
  112617. }
  112618. static float FLOOR1_fromdB_LOOKUP[256]={
  112619. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112620. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112621. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112622. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112623. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112624. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112625. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112626. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112627. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112628. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112629. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112630. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112631. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112632. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112633. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112634. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112635. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112636. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112637. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112638. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112639. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112640. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112641. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112642. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112643. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112644. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112645. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112646. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112647. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112648. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112649. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112650. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112651. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112652. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112653. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112654. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112655. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112656. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112657. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112658. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112659. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112660. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112661. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112662. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112663. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112664. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112665. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112666. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112667. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112668. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112669. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112670. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112671. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112672. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112673. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112674. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112675. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112676. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112677. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112678. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112679. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112680. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112681. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112682. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112683. };
  112684. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112685. int dy=y1-y0;
  112686. int adx=x1-x0;
  112687. int ady=abs(dy);
  112688. int base=dy/adx;
  112689. int sy=(dy<0?base-1:base+1);
  112690. int x=x0;
  112691. int y=y0;
  112692. int err=0;
  112693. ady-=abs(base*adx);
  112694. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112695. while(++x<x1){
  112696. err=err+ady;
  112697. if(err>=adx){
  112698. err-=adx;
  112699. y+=sy;
  112700. }else{
  112701. y+=base;
  112702. }
  112703. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112704. }
  112705. }
  112706. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112707. int dy=y1-y0;
  112708. int adx=x1-x0;
  112709. int ady=abs(dy);
  112710. int base=dy/adx;
  112711. int sy=(dy<0?base-1:base+1);
  112712. int x=x0;
  112713. int y=y0;
  112714. int err=0;
  112715. ady-=abs(base*adx);
  112716. d[x]=y;
  112717. while(++x<x1){
  112718. err=err+ady;
  112719. if(err>=adx){
  112720. err-=adx;
  112721. y+=sy;
  112722. }else{
  112723. y+=base;
  112724. }
  112725. d[x]=y;
  112726. }
  112727. }
  112728. /* the floor has already been filtered to only include relevant sections */
  112729. static int accumulate_fit(const float *flr,const float *mdct,
  112730. int x0, int x1,lsfit_acc *a,
  112731. int n,vorbis_info_floor1 *info){
  112732. long i;
  112733. 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;
  112734. memset(a,0,sizeof(*a));
  112735. a->x0=x0;
  112736. a->x1=x1;
  112737. if(x1>=n)x1=n-1;
  112738. for(i=x0;i<=x1;i++){
  112739. int quantized=vorbis_dBquant(flr+i);
  112740. if(quantized){
  112741. if(mdct[i]+info->twofitatten>=flr[i]){
  112742. xa += i;
  112743. ya += quantized;
  112744. x2a += i*i;
  112745. y2a += quantized*quantized;
  112746. xya += i*quantized;
  112747. na++;
  112748. }else{
  112749. xb += i;
  112750. yb += quantized;
  112751. x2b += i*i;
  112752. y2b += quantized*quantized;
  112753. xyb += i*quantized;
  112754. nb++;
  112755. }
  112756. }
  112757. }
  112758. xb+=xa;
  112759. yb+=ya;
  112760. x2b+=x2a;
  112761. y2b+=y2a;
  112762. xyb+=xya;
  112763. nb+=na;
  112764. /* weight toward the actually used frequencies if we meet the threshhold */
  112765. {
  112766. int weight=nb*info->twofitweight/(na+1);
  112767. a->xa=xa*weight+xb;
  112768. a->ya=ya*weight+yb;
  112769. a->x2a=x2a*weight+x2b;
  112770. a->y2a=y2a*weight+y2b;
  112771. a->xya=xya*weight+xyb;
  112772. a->an=na*weight+nb;
  112773. }
  112774. return(na);
  112775. }
  112776. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112777. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112778. long x0=a[0].x0;
  112779. long x1=a[fits-1].x1;
  112780. for(i=0;i<fits;i++){
  112781. x+=a[i].xa;
  112782. y+=a[i].ya;
  112783. x2+=a[i].x2a;
  112784. y2+=a[i].y2a;
  112785. xy+=a[i].xya;
  112786. an+=a[i].an;
  112787. }
  112788. if(*y0>=0){
  112789. x+= x0;
  112790. y+= *y0;
  112791. x2+= x0 * x0;
  112792. y2+= *y0 * *y0;
  112793. xy+= *y0 * x0;
  112794. an++;
  112795. }
  112796. if(*y1>=0){
  112797. x+= x1;
  112798. y+= *y1;
  112799. x2+= x1 * x1;
  112800. y2+= *y1 * *y1;
  112801. xy+= *y1 * x1;
  112802. an++;
  112803. }
  112804. if(an){
  112805. /* need 64 bit multiplies, which C doesn't give portably as int */
  112806. double fx=x;
  112807. double fy=y;
  112808. double fx2=x2;
  112809. double fxy=xy;
  112810. double denom=1./(an*fx2-fx*fx);
  112811. double a=(fy*fx2-fxy*fx)*denom;
  112812. double b=(an*fxy-fx*fy)*denom;
  112813. *y0=rint(a+b*x0);
  112814. *y1=rint(a+b*x1);
  112815. /* limit to our range! */
  112816. if(*y0>1023)*y0=1023;
  112817. if(*y1>1023)*y1=1023;
  112818. if(*y0<0)*y0=0;
  112819. if(*y1<0)*y1=0;
  112820. }else{
  112821. *y0=0;
  112822. *y1=0;
  112823. }
  112824. }
  112825. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112826. long y=0;
  112827. int i;
  112828. for(i=0;i<fits && y==0;i++)
  112829. y+=a[i].ya;
  112830. *y0=*y1=y;
  112831. }*/
  112832. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112833. const float *mdct,
  112834. vorbis_info_floor1 *info){
  112835. int dy=y1-y0;
  112836. int adx=x1-x0;
  112837. int ady=abs(dy);
  112838. int base=dy/adx;
  112839. int sy=(dy<0?base-1:base+1);
  112840. int x=x0;
  112841. int y=y0;
  112842. int err=0;
  112843. int val=vorbis_dBquant(mask+x);
  112844. int mse=0;
  112845. int n=0;
  112846. ady-=abs(base*adx);
  112847. mse=(y-val);
  112848. mse*=mse;
  112849. n++;
  112850. if(mdct[x]+info->twofitatten>=mask[x]){
  112851. if(y+info->maxover<val)return(1);
  112852. if(y-info->maxunder>val)return(1);
  112853. }
  112854. while(++x<x1){
  112855. err=err+ady;
  112856. if(err>=adx){
  112857. err-=adx;
  112858. y+=sy;
  112859. }else{
  112860. y+=base;
  112861. }
  112862. val=vorbis_dBquant(mask+x);
  112863. mse+=((y-val)*(y-val));
  112864. n++;
  112865. if(mdct[x]+info->twofitatten>=mask[x]){
  112866. if(val){
  112867. if(y+info->maxover<val)return(1);
  112868. if(y-info->maxunder>val)return(1);
  112869. }
  112870. }
  112871. }
  112872. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112873. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112874. if(mse/n>info->maxerr)return(1);
  112875. return(0);
  112876. }
  112877. static int post_Y(int *A,int *B,int pos){
  112878. if(A[pos]<0)
  112879. return B[pos];
  112880. if(B[pos]<0)
  112881. return A[pos];
  112882. return (A[pos]+B[pos])>>1;
  112883. }
  112884. int *floor1_fit(vorbis_block *vb,void *look_,
  112885. const float *logmdct, /* in */
  112886. const float *logmask){
  112887. long i,j;
  112888. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112889. vorbis_info_floor1 *info=look->vi;
  112890. long n=look->n;
  112891. long posts=look->posts;
  112892. long nonzero=0;
  112893. lsfit_acc fits[VIF_POSIT+1];
  112894. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112895. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112896. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112897. int hineighbor[VIF_POSIT+2];
  112898. int *output=NULL;
  112899. int memo[VIF_POSIT+2];
  112900. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112901. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112902. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112903. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112904. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112905. /* quantize the relevant floor points and collect them into line fit
  112906. structures (one per minimal division) at the same time */
  112907. if(posts==0){
  112908. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112909. }else{
  112910. for(i=0;i<posts-1;i++)
  112911. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112912. look->sorted_index[i+1],fits+i,
  112913. n,info);
  112914. }
  112915. if(nonzero){
  112916. /* start by fitting the implicit base case.... */
  112917. int y0=-200;
  112918. int y1=-200;
  112919. fit_line(fits,posts-1,&y0,&y1);
  112920. fit_valueA[0]=y0;
  112921. fit_valueB[0]=y0;
  112922. fit_valueB[1]=y1;
  112923. fit_valueA[1]=y1;
  112924. /* Non degenerate case */
  112925. /* start progressive splitting. This is a greedy, non-optimal
  112926. algorithm, but simple and close enough to the best
  112927. answer. */
  112928. for(i=2;i<posts;i++){
  112929. int sortpos=look->reverse_index[i];
  112930. int ln=loneighbor[sortpos];
  112931. int hn=hineighbor[sortpos];
  112932. /* eliminate repeat searches of a particular range with a memo */
  112933. if(memo[ln]!=hn){
  112934. /* haven't performed this error search yet */
  112935. int lsortpos=look->reverse_index[ln];
  112936. int hsortpos=look->reverse_index[hn];
  112937. memo[ln]=hn;
  112938. {
  112939. /* A note: we want to bound/minimize *local*, not global, error */
  112940. int lx=info->postlist[ln];
  112941. int hx=info->postlist[hn];
  112942. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112943. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112944. if(ly==-1 || hy==-1){
  112945. exit(1);
  112946. }
  112947. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112948. /* outside error bounds/begin search area. Split it. */
  112949. int ly0=-200;
  112950. int ly1=-200;
  112951. int hy0=-200;
  112952. int hy1=-200;
  112953. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112954. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112955. /* store new edge values */
  112956. fit_valueB[ln]=ly0;
  112957. if(ln==0)fit_valueA[ln]=ly0;
  112958. fit_valueA[i]=ly1;
  112959. fit_valueB[i]=hy0;
  112960. fit_valueA[hn]=hy1;
  112961. if(hn==1)fit_valueB[hn]=hy1;
  112962. if(ly1>=0 || hy0>=0){
  112963. /* store new neighbor values */
  112964. for(j=sortpos-1;j>=0;j--)
  112965. if(hineighbor[j]==hn)
  112966. hineighbor[j]=i;
  112967. else
  112968. break;
  112969. for(j=sortpos+1;j<posts;j++)
  112970. if(loneighbor[j]==ln)
  112971. loneighbor[j]=i;
  112972. else
  112973. break;
  112974. }
  112975. }else{
  112976. fit_valueA[i]=-200;
  112977. fit_valueB[i]=-200;
  112978. }
  112979. }
  112980. }
  112981. }
  112982. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112983. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112984. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112985. /* fill in posts marked as not using a fit; we will zero
  112986. back out to 'unused' when encoding them so long as curve
  112987. interpolation doesn't force them into use */
  112988. for(i=2;i<posts;i++){
  112989. int ln=look->loneighbor[i-2];
  112990. int hn=look->hineighbor[i-2];
  112991. int x0=info->postlist[ln];
  112992. int x1=info->postlist[hn];
  112993. int y0=output[ln];
  112994. int y1=output[hn];
  112995. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112996. int vx=post_Y(fit_valueA,fit_valueB,i);
  112997. if(vx>=0 && predicted!=vx){
  112998. output[i]=vx;
  112999. }else{
  113000. output[i]= predicted|0x8000;
  113001. }
  113002. }
  113003. }
  113004. return(output);
  113005. }
  113006. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113007. int *A,int *B,
  113008. int del){
  113009. long i;
  113010. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113011. long posts=look->posts;
  113012. int *output=NULL;
  113013. if(A && B){
  113014. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113015. for(i=0;i<posts;i++){
  113016. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113017. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113018. }
  113019. }
  113020. return(output);
  113021. }
  113022. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113023. void*look_,
  113024. int *post,int *ilogmask){
  113025. long i,j;
  113026. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113027. vorbis_info_floor1 *info=look->vi;
  113028. long posts=look->posts;
  113029. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113030. int out[VIF_POSIT+2];
  113031. static_codebook **sbooks=ci->book_param;
  113032. codebook *books=ci->fullbooks;
  113033. static long seq=0;
  113034. /* quantize values to multiplier spec */
  113035. if(post){
  113036. for(i=0;i<posts;i++){
  113037. int val=post[i]&0x7fff;
  113038. switch(info->mult){
  113039. case 1: /* 1024 -> 256 */
  113040. val>>=2;
  113041. break;
  113042. case 2: /* 1024 -> 128 */
  113043. val>>=3;
  113044. break;
  113045. case 3: /* 1024 -> 86 */
  113046. val/=12;
  113047. break;
  113048. case 4: /* 1024 -> 64 */
  113049. val>>=4;
  113050. break;
  113051. }
  113052. post[i]=val | (post[i]&0x8000);
  113053. }
  113054. out[0]=post[0];
  113055. out[1]=post[1];
  113056. /* find prediction values for each post and subtract them */
  113057. for(i=2;i<posts;i++){
  113058. int ln=look->loneighbor[i-2];
  113059. int hn=look->hineighbor[i-2];
  113060. int x0=info->postlist[ln];
  113061. int x1=info->postlist[hn];
  113062. int y0=post[ln];
  113063. int y1=post[hn];
  113064. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113065. if((post[i]&0x8000) || (predicted==post[i])){
  113066. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113067. in interpolation */
  113068. out[i]=0;
  113069. }else{
  113070. int headroom=(look->quant_q-predicted<predicted?
  113071. look->quant_q-predicted:predicted);
  113072. int val=post[i]-predicted;
  113073. /* at this point the 'deviation' value is in the range +/- max
  113074. range, but the real, unique range can always be mapped to
  113075. only [0-maxrange). So we want to wrap the deviation into
  113076. this limited range, but do it in the way that least screws
  113077. an essentially gaussian probability distribution. */
  113078. if(val<0)
  113079. if(val<-headroom)
  113080. val=headroom-val-1;
  113081. else
  113082. val=-1-(val<<1);
  113083. else
  113084. if(val>=headroom)
  113085. val= val+headroom;
  113086. else
  113087. val<<=1;
  113088. out[i]=val;
  113089. post[ln]&=0x7fff;
  113090. post[hn]&=0x7fff;
  113091. }
  113092. }
  113093. /* we have everything we need. pack it out */
  113094. /* mark nontrivial floor */
  113095. oggpack_write(opb,1,1);
  113096. /* beginning/end post */
  113097. look->frames++;
  113098. look->postbits+=ilog(look->quant_q-1)*2;
  113099. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113100. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113101. /* partition by partition */
  113102. for(i=0,j=2;i<info->partitions;i++){
  113103. int classx=info->partitionclass[i];
  113104. int cdim=info->class_dim[classx];
  113105. int csubbits=info->class_subs[classx];
  113106. int csub=1<<csubbits;
  113107. int bookas[8]={0,0,0,0,0,0,0,0};
  113108. int cval=0;
  113109. int cshift=0;
  113110. int k,l;
  113111. /* generate the partition's first stage cascade value */
  113112. if(csubbits){
  113113. int maxval[8];
  113114. for(k=0;k<csub;k++){
  113115. int booknum=info->class_subbook[classx][k];
  113116. if(booknum<0){
  113117. maxval[k]=1;
  113118. }else{
  113119. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113120. }
  113121. }
  113122. for(k=0;k<cdim;k++){
  113123. for(l=0;l<csub;l++){
  113124. int val=out[j+k];
  113125. if(val<maxval[l]){
  113126. bookas[k]=l;
  113127. break;
  113128. }
  113129. }
  113130. cval|= bookas[k]<<cshift;
  113131. cshift+=csubbits;
  113132. }
  113133. /* write it */
  113134. look->phrasebits+=
  113135. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113136. #ifdef TRAIN_FLOOR1
  113137. {
  113138. FILE *of;
  113139. char buffer[80];
  113140. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113141. vb->pcmend/2,posts-2,class);
  113142. of=fopen(buffer,"a");
  113143. fprintf(of,"%d\n",cval);
  113144. fclose(of);
  113145. }
  113146. #endif
  113147. }
  113148. /* write post values */
  113149. for(k=0;k<cdim;k++){
  113150. int book=info->class_subbook[classx][bookas[k]];
  113151. if(book>=0){
  113152. /* hack to allow training with 'bad' books */
  113153. if(out[j+k]<(books+book)->entries)
  113154. look->postbits+=vorbis_book_encode(books+book,
  113155. out[j+k],opb);
  113156. /*else
  113157. fprintf(stderr,"+!");*/
  113158. #ifdef TRAIN_FLOOR1
  113159. {
  113160. FILE *of;
  113161. char buffer[80];
  113162. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113163. vb->pcmend/2,posts-2,class,bookas[k]);
  113164. of=fopen(buffer,"a");
  113165. fprintf(of,"%d\n",out[j+k]);
  113166. fclose(of);
  113167. }
  113168. #endif
  113169. }
  113170. }
  113171. j+=cdim;
  113172. }
  113173. {
  113174. /* generate quantized floor equivalent to what we'd unpack in decode */
  113175. /* render the lines */
  113176. int hx=0;
  113177. int lx=0;
  113178. int ly=post[0]*info->mult;
  113179. for(j=1;j<look->posts;j++){
  113180. int current=look->forward_index[j];
  113181. int hy=post[current]&0x7fff;
  113182. if(hy==post[current]){
  113183. hy*=info->mult;
  113184. hx=info->postlist[current];
  113185. render_line0(lx,hx,ly,hy,ilogmask);
  113186. lx=hx;
  113187. ly=hy;
  113188. }
  113189. }
  113190. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113191. seq++;
  113192. return(1);
  113193. }
  113194. }else{
  113195. oggpack_write(opb,0,1);
  113196. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113197. seq++;
  113198. return(0);
  113199. }
  113200. }
  113201. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113202. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113203. vorbis_info_floor1 *info=look->vi;
  113204. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113205. int i,j,k;
  113206. codebook *books=ci->fullbooks;
  113207. /* unpack wrapped/predicted values from stream */
  113208. if(oggpack_read(&vb->opb,1)==1){
  113209. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113210. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113211. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113212. /* partition by partition */
  113213. for(i=0,j=2;i<info->partitions;i++){
  113214. int classx=info->partitionclass[i];
  113215. int cdim=info->class_dim[classx];
  113216. int csubbits=info->class_subs[classx];
  113217. int csub=1<<csubbits;
  113218. int cval=0;
  113219. /* decode the partition's first stage cascade value */
  113220. if(csubbits){
  113221. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113222. if(cval==-1)goto eop;
  113223. }
  113224. for(k=0;k<cdim;k++){
  113225. int book=info->class_subbook[classx][cval&(csub-1)];
  113226. cval>>=csubbits;
  113227. if(book>=0){
  113228. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113229. goto eop;
  113230. }else{
  113231. fit_value[j+k]=0;
  113232. }
  113233. }
  113234. j+=cdim;
  113235. }
  113236. /* unwrap positive values and reconsitute via linear interpolation */
  113237. for(i=2;i<look->posts;i++){
  113238. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113239. info->postlist[look->hineighbor[i-2]],
  113240. fit_value[look->loneighbor[i-2]],
  113241. fit_value[look->hineighbor[i-2]],
  113242. info->postlist[i]);
  113243. int hiroom=look->quant_q-predicted;
  113244. int loroom=predicted;
  113245. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113246. int val=fit_value[i];
  113247. if(val){
  113248. if(val>=room){
  113249. if(hiroom>loroom){
  113250. val = val-loroom;
  113251. }else{
  113252. val = -1-(val-hiroom);
  113253. }
  113254. }else{
  113255. if(val&1){
  113256. val= -((val+1)>>1);
  113257. }else{
  113258. val>>=1;
  113259. }
  113260. }
  113261. fit_value[i]=val+predicted;
  113262. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113263. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113264. }else{
  113265. fit_value[i]=predicted|0x8000;
  113266. }
  113267. }
  113268. return(fit_value);
  113269. }
  113270. eop:
  113271. return(NULL);
  113272. }
  113273. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113274. float *out){
  113275. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113276. vorbis_info_floor1 *info=look->vi;
  113277. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113278. int n=ci->blocksizes[vb->W]/2;
  113279. int j;
  113280. if(memo){
  113281. /* render the lines */
  113282. int *fit_value=(int *)memo;
  113283. int hx=0;
  113284. int lx=0;
  113285. int ly=fit_value[0]*info->mult;
  113286. for(j=1;j<look->posts;j++){
  113287. int current=look->forward_index[j];
  113288. int hy=fit_value[current]&0x7fff;
  113289. if(hy==fit_value[current]){
  113290. hy*=info->mult;
  113291. hx=info->postlist[current];
  113292. render_line(lx,hx,ly,hy,out);
  113293. lx=hx;
  113294. ly=hy;
  113295. }
  113296. }
  113297. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113298. return(1);
  113299. }
  113300. memset(out,0,sizeof(*out)*n);
  113301. return(0);
  113302. }
  113303. /* export hooks */
  113304. vorbis_func_floor floor1_exportbundle={
  113305. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113306. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113307. };
  113308. #endif
  113309. /*** End of inlined file: floor1.c ***/
  113310. /*** Start of inlined file: info.c ***/
  113311. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113312. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113313. // tasks..
  113314. #if JUCE_MSVC
  113315. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113316. #endif
  113317. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113318. #if JUCE_USE_OGGVORBIS
  113319. /* general handling of the header and the vorbis_info structure (and
  113320. substructures) */
  113321. #include <stdlib.h>
  113322. #include <string.h>
  113323. #include <ctype.h>
  113324. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113325. while(bytes--){
  113326. oggpack_write(o,*s++,8);
  113327. }
  113328. }
  113329. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113330. while(bytes--){
  113331. *buf++=oggpack_read(o,8);
  113332. }
  113333. }
  113334. void vorbis_comment_init(vorbis_comment *vc){
  113335. memset(vc,0,sizeof(*vc));
  113336. }
  113337. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113338. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113339. (vc->comments+2)*sizeof(*vc->user_comments));
  113340. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113341. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113342. vc->comment_lengths[vc->comments]=strlen(comment);
  113343. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113344. strcpy(vc->user_comments[vc->comments], comment);
  113345. vc->comments++;
  113346. vc->user_comments[vc->comments]=NULL;
  113347. }
  113348. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113349. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113350. strcpy(comment, tag);
  113351. strcat(comment, "=");
  113352. strcat(comment, contents);
  113353. vorbis_comment_add(vc, comment);
  113354. }
  113355. /* This is more or less the same as strncasecmp - but that doesn't exist
  113356. * everywhere, and this is a fairly trivial function, so we include it */
  113357. static int tagcompare(const char *s1, const char *s2, int n){
  113358. int c=0;
  113359. while(c < n){
  113360. if(toupper(s1[c]) != toupper(s2[c]))
  113361. return !0;
  113362. c++;
  113363. }
  113364. return 0;
  113365. }
  113366. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113367. long i;
  113368. int found = 0;
  113369. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113370. char *fulltag = (char*)alloca(taglen+ 1);
  113371. strcpy(fulltag, tag);
  113372. strcat(fulltag, "=");
  113373. for(i=0;i<vc->comments;i++){
  113374. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113375. if(count == found)
  113376. /* We return a pointer to the data, not a copy */
  113377. return vc->user_comments[i] + taglen;
  113378. else
  113379. found++;
  113380. }
  113381. }
  113382. return NULL; /* didn't find anything */
  113383. }
  113384. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113385. int i,count=0;
  113386. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113387. char *fulltag = (char*)alloca(taglen+1);
  113388. strcpy(fulltag,tag);
  113389. strcat(fulltag, "=");
  113390. for(i=0;i<vc->comments;i++){
  113391. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113392. count++;
  113393. }
  113394. return count;
  113395. }
  113396. void vorbis_comment_clear(vorbis_comment *vc){
  113397. if(vc){
  113398. long i;
  113399. for(i=0;i<vc->comments;i++)
  113400. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113401. if(vc->user_comments)_ogg_free(vc->user_comments);
  113402. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113403. if(vc->vendor)_ogg_free(vc->vendor);
  113404. }
  113405. memset(vc,0,sizeof(*vc));
  113406. }
  113407. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113408. They may be equal, but short will never ge greater than long */
  113409. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113410. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113411. return ci ? ci->blocksizes[zo] : -1;
  113412. }
  113413. /* used by synthesis, which has a full, alloced vi */
  113414. void vorbis_info_init(vorbis_info *vi){
  113415. memset(vi,0,sizeof(*vi));
  113416. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113417. }
  113418. void vorbis_info_clear(vorbis_info *vi){
  113419. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113420. int i;
  113421. if(ci){
  113422. for(i=0;i<ci->modes;i++)
  113423. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113424. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113425. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113426. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113427. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113428. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113429. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113430. for(i=0;i<ci->books;i++){
  113431. if(ci->book_param[i]){
  113432. /* knows if the book was not alloced */
  113433. vorbis_staticbook_destroy(ci->book_param[i]);
  113434. }
  113435. if(ci->fullbooks)
  113436. vorbis_book_clear(ci->fullbooks+i);
  113437. }
  113438. if(ci->fullbooks)
  113439. _ogg_free(ci->fullbooks);
  113440. for(i=0;i<ci->psys;i++)
  113441. _vi_psy_free(ci->psy_param[i]);
  113442. _ogg_free(ci);
  113443. }
  113444. memset(vi,0,sizeof(*vi));
  113445. }
  113446. /* Header packing/unpacking ********************************************/
  113447. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113448. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113449. if(!ci)return(OV_EFAULT);
  113450. vi->version=oggpack_read(opb,32);
  113451. if(vi->version!=0)return(OV_EVERSION);
  113452. vi->channels=oggpack_read(opb,8);
  113453. vi->rate=oggpack_read(opb,32);
  113454. vi->bitrate_upper=oggpack_read(opb,32);
  113455. vi->bitrate_nominal=oggpack_read(opb,32);
  113456. vi->bitrate_lower=oggpack_read(opb,32);
  113457. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113458. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113459. if(vi->rate<1)goto err_out;
  113460. if(vi->channels<1)goto err_out;
  113461. if(ci->blocksizes[0]<8)goto err_out;
  113462. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113463. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113464. return(0);
  113465. err_out:
  113466. vorbis_info_clear(vi);
  113467. return(OV_EBADHEADER);
  113468. }
  113469. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113470. int i;
  113471. int vendorlen=oggpack_read(opb,32);
  113472. if(vendorlen<0)goto err_out;
  113473. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113474. _v_readstring(opb,vc->vendor,vendorlen);
  113475. vc->comments=oggpack_read(opb,32);
  113476. if(vc->comments<0)goto err_out;
  113477. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113478. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113479. for(i=0;i<vc->comments;i++){
  113480. int len=oggpack_read(opb,32);
  113481. if(len<0)goto err_out;
  113482. vc->comment_lengths[i]=len;
  113483. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113484. _v_readstring(opb,vc->user_comments[i],len);
  113485. }
  113486. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113487. return(0);
  113488. err_out:
  113489. vorbis_comment_clear(vc);
  113490. return(OV_EBADHEADER);
  113491. }
  113492. /* all of the real encoding details are here. The modes, books,
  113493. everything */
  113494. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113495. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113496. int i;
  113497. if(!ci)return(OV_EFAULT);
  113498. /* codebooks */
  113499. ci->books=oggpack_read(opb,8)+1;
  113500. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113501. for(i=0;i<ci->books;i++){
  113502. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113503. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113504. }
  113505. /* time backend settings; hooks are unused */
  113506. {
  113507. int times=oggpack_read(opb,6)+1;
  113508. for(i=0;i<times;i++){
  113509. int test=oggpack_read(opb,16);
  113510. if(test<0 || test>=VI_TIMEB)goto err_out;
  113511. }
  113512. }
  113513. /* floor backend settings */
  113514. ci->floors=oggpack_read(opb,6)+1;
  113515. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113516. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113517. for(i=0;i<ci->floors;i++){
  113518. ci->floor_type[i]=oggpack_read(opb,16);
  113519. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113520. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113521. if(!ci->floor_param[i])goto err_out;
  113522. }
  113523. /* residue backend settings */
  113524. ci->residues=oggpack_read(opb,6)+1;
  113525. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113526. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113527. for(i=0;i<ci->residues;i++){
  113528. ci->residue_type[i]=oggpack_read(opb,16);
  113529. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113530. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113531. if(!ci->residue_param[i])goto err_out;
  113532. }
  113533. /* map backend settings */
  113534. ci->maps=oggpack_read(opb,6)+1;
  113535. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113536. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113537. for(i=0;i<ci->maps;i++){
  113538. ci->map_type[i]=oggpack_read(opb,16);
  113539. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113540. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113541. if(!ci->map_param[i])goto err_out;
  113542. }
  113543. /* mode settings */
  113544. ci->modes=oggpack_read(opb,6)+1;
  113545. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113546. for(i=0;i<ci->modes;i++){
  113547. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113548. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113549. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113550. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113551. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113552. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113553. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113554. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113555. }
  113556. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113557. return(0);
  113558. err_out:
  113559. vorbis_info_clear(vi);
  113560. return(OV_EBADHEADER);
  113561. }
  113562. /* The Vorbis header is in three packets; the initial small packet in
  113563. the first page that identifies basic parameters, a second packet
  113564. with bitstream comments and a third packet that holds the
  113565. codebook. */
  113566. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113567. oggpack_buffer opb;
  113568. if(op){
  113569. oggpack_readinit(&opb,op->packet,op->bytes);
  113570. /* Which of the three types of header is this? */
  113571. /* Also verify header-ness, vorbis */
  113572. {
  113573. char buffer[6];
  113574. int packtype=oggpack_read(&opb,8);
  113575. memset(buffer,0,6);
  113576. _v_readstring(&opb,buffer,6);
  113577. if(memcmp(buffer,"vorbis",6)){
  113578. /* not a vorbis header */
  113579. return(OV_ENOTVORBIS);
  113580. }
  113581. switch(packtype){
  113582. case 0x01: /* least significant *bit* is read first */
  113583. if(!op->b_o_s){
  113584. /* Not the initial packet */
  113585. return(OV_EBADHEADER);
  113586. }
  113587. if(vi->rate!=0){
  113588. /* previously initialized info header */
  113589. return(OV_EBADHEADER);
  113590. }
  113591. return(_vorbis_unpack_info(vi,&opb));
  113592. case 0x03: /* least significant *bit* is read first */
  113593. if(vi->rate==0){
  113594. /* um... we didn't get the initial header */
  113595. return(OV_EBADHEADER);
  113596. }
  113597. return(_vorbis_unpack_comment(vc,&opb));
  113598. case 0x05: /* least significant *bit* is read first */
  113599. if(vi->rate==0 || vc->vendor==NULL){
  113600. /* um... we didn;t get the initial header or comments yet */
  113601. return(OV_EBADHEADER);
  113602. }
  113603. return(_vorbis_unpack_books(vi,&opb));
  113604. default:
  113605. /* Not a valid vorbis header type */
  113606. return(OV_EBADHEADER);
  113607. break;
  113608. }
  113609. }
  113610. }
  113611. return(OV_EBADHEADER);
  113612. }
  113613. /* pack side **********************************************************/
  113614. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113615. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113616. if(!ci)return(OV_EFAULT);
  113617. /* preamble */
  113618. oggpack_write(opb,0x01,8);
  113619. _v_writestring(opb,"vorbis", 6);
  113620. /* basic information about the stream */
  113621. oggpack_write(opb,0x00,32);
  113622. oggpack_write(opb,vi->channels,8);
  113623. oggpack_write(opb,vi->rate,32);
  113624. oggpack_write(opb,vi->bitrate_upper,32);
  113625. oggpack_write(opb,vi->bitrate_nominal,32);
  113626. oggpack_write(opb,vi->bitrate_lower,32);
  113627. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113628. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113629. oggpack_write(opb,1,1);
  113630. return(0);
  113631. }
  113632. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113633. char temp[]="Xiph.Org libVorbis I 20050304";
  113634. int bytes = strlen(temp);
  113635. /* preamble */
  113636. oggpack_write(opb,0x03,8);
  113637. _v_writestring(opb,"vorbis", 6);
  113638. /* vendor */
  113639. oggpack_write(opb,bytes,32);
  113640. _v_writestring(opb,temp, bytes);
  113641. /* comments */
  113642. oggpack_write(opb,vc->comments,32);
  113643. if(vc->comments){
  113644. int i;
  113645. for(i=0;i<vc->comments;i++){
  113646. if(vc->user_comments[i]){
  113647. oggpack_write(opb,vc->comment_lengths[i],32);
  113648. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113649. }else{
  113650. oggpack_write(opb,0,32);
  113651. }
  113652. }
  113653. }
  113654. oggpack_write(opb,1,1);
  113655. return(0);
  113656. }
  113657. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113658. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113659. int i;
  113660. if(!ci)return(OV_EFAULT);
  113661. oggpack_write(opb,0x05,8);
  113662. _v_writestring(opb,"vorbis", 6);
  113663. /* books */
  113664. oggpack_write(opb,ci->books-1,8);
  113665. for(i=0;i<ci->books;i++)
  113666. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113667. /* times; hook placeholders */
  113668. oggpack_write(opb,0,6);
  113669. oggpack_write(opb,0,16);
  113670. /* floors */
  113671. oggpack_write(opb,ci->floors-1,6);
  113672. for(i=0;i<ci->floors;i++){
  113673. oggpack_write(opb,ci->floor_type[i],16);
  113674. if(_floor_P[ci->floor_type[i]]->pack)
  113675. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113676. else
  113677. goto err_out;
  113678. }
  113679. /* residues */
  113680. oggpack_write(opb,ci->residues-1,6);
  113681. for(i=0;i<ci->residues;i++){
  113682. oggpack_write(opb,ci->residue_type[i],16);
  113683. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113684. }
  113685. /* maps */
  113686. oggpack_write(opb,ci->maps-1,6);
  113687. for(i=0;i<ci->maps;i++){
  113688. oggpack_write(opb,ci->map_type[i],16);
  113689. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113690. }
  113691. /* modes */
  113692. oggpack_write(opb,ci->modes-1,6);
  113693. for(i=0;i<ci->modes;i++){
  113694. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113695. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113696. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113697. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113698. }
  113699. oggpack_write(opb,1,1);
  113700. return(0);
  113701. err_out:
  113702. return(-1);
  113703. }
  113704. int vorbis_commentheader_out(vorbis_comment *vc,
  113705. ogg_packet *op){
  113706. oggpack_buffer opb;
  113707. oggpack_writeinit(&opb);
  113708. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113709. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113710. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113711. op->bytes=oggpack_bytes(&opb);
  113712. op->b_o_s=0;
  113713. op->e_o_s=0;
  113714. op->granulepos=0;
  113715. op->packetno=1;
  113716. return 0;
  113717. }
  113718. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113719. vorbis_comment *vc,
  113720. ogg_packet *op,
  113721. ogg_packet *op_comm,
  113722. ogg_packet *op_code){
  113723. int ret=OV_EIMPL;
  113724. vorbis_info *vi=v->vi;
  113725. oggpack_buffer opb;
  113726. private_state *b=(private_state*)v->backend_state;
  113727. if(!b){
  113728. ret=OV_EFAULT;
  113729. goto err_out;
  113730. }
  113731. /* first header packet **********************************************/
  113732. oggpack_writeinit(&opb);
  113733. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113734. /* build the packet */
  113735. if(b->header)_ogg_free(b->header);
  113736. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113737. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113738. op->packet=b->header;
  113739. op->bytes=oggpack_bytes(&opb);
  113740. op->b_o_s=1;
  113741. op->e_o_s=0;
  113742. op->granulepos=0;
  113743. op->packetno=0;
  113744. /* second header packet (comments) **********************************/
  113745. oggpack_reset(&opb);
  113746. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113747. if(b->header1)_ogg_free(b->header1);
  113748. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113749. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113750. op_comm->packet=b->header1;
  113751. op_comm->bytes=oggpack_bytes(&opb);
  113752. op_comm->b_o_s=0;
  113753. op_comm->e_o_s=0;
  113754. op_comm->granulepos=0;
  113755. op_comm->packetno=1;
  113756. /* third header packet (modes/codebooks) ****************************/
  113757. oggpack_reset(&opb);
  113758. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113759. if(b->header2)_ogg_free(b->header2);
  113760. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113761. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113762. op_code->packet=b->header2;
  113763. op_code->bytes=oggpack_bytes(&opb);
  113764. op_code->b_o_s=0;
  113765. op_code->e_o_s=0;
  113766. op_code->granulepos=0;
  113767. op_code->packetno=2;
  113768. oggpack_writeclear(&opb);
  113769. return(0);
  113770. err_out:
  113771. oggpack_writeclear(&opb);
  113772. memset(op,0,sizeof(*op));
  113773. memset(op_comm,0,sizeof(*op_comm));
  113774. memset(op_code,0,sizeof(*op_code));
  113775. if(b->header)_ogg_free(b->header);
  113776. if(b->header1)_ogg_free(b->header1);
  113777. if(b->header2)_ogg_free(b->header2);
  113778. b->header=NULL;
  113779. b->header1=NULL;
  113780. b->header2=NULL;
  113781. return(ret);
  113782. }
  113783. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113784. if(granulepos>=0)
  113785. return((double)granulepos/v->vi->rate);
  113786. return(-1);
  113787. }
  113788. #endif
  113789. /*** End of inlined file: info.c ***/
  113790. /*** Start of inlined file: lpc.c ***/
  113791. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113792. are derived from code written by Jutta Degener and Carsten Bormann;
  113793. thus we include their copyright below. The entirety of this file
  113794. is freely redistributable on the condition that both of these
  113795. copyright notices are preserved without modification. */
  113796. /* Preserved Copyright: *********************************************/
  113797. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113798. Technische Universita"t Berlin
  113799. Any use of this software is permitted provided that this notice is not
  113800. removed and that neither the authors nor the Technische Universita"t
  113801. Berlin are deemed to have made any representations as to the
  113802. suitability of this software for any purpose nor are held responsible
  113803. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113804. THIS SOFTWARE.
  113805. As a matter of courtesy, the authors request to be informed about uses
  113806. this software has found, about bugs in this software, and about any
  113807. improvements that may be of general interest.
  113808. Berlin, 28.11.1994
  113809. Jutta Degener
  113810. Carsten Bormann
  113811. *********************************************************************/
  113812. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113813. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113814. // tasks..
  113815. #if JUCE_MSVC
  113816. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113817. #endif
  113818. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113819. #if JUCE_USE_OGGVORBIS
  113820. #include <stdlib.h>
  113821. #include <string.h>
  113822. #include <math.h>
  113823. /* Autocorrelation LPC coeff generation algorithm invented by
  113824. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113825. /* Input : n elements of time doamin data
  113826. Output: m lpc coefficients, excitation energy */
  113827. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113828. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113829. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113830. double error;
  113831. int i,j;
  113832. /* autocorrelation, p+1 lag coefficients */
  113833. j=m+1;
  113834. while(j--){
  113835. double d=0; /* double needed for accumulator depth */
  113836. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113837. aut[j]=d;
  113838. }
  113839. /* Generate lpc coefficients from autocorr values */
  113840. error=aut[0];
  113841. for(i=0;i<m;i++){
  113842. double r= -aut[i+1];
  113843. if(error==0){
  113844. memset(lpci,0,m*sizeof(*lpci));
  113845. return 0;
  113846. }
  113847. /* Sum up this iteration's reflection coefficient; note that in
  113848. Vorbis we don't save it. If anyone wants to recycle this code
  113849. and needs reflection coefficients, save the results of 'r' from
  113850. each iteration. */
  113851. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113852. r/=error;
  113853. /* Update LPC coefficients and total error */
  113854. lpc[i]=r;
  113855. for(j=0;j<i/2;j++){
  113856. double tmp=lpc[j];
  113857. lpc[j]+=r*lpc[i-1-j];
  113858. lpc[i-1-j]+=r*tmp;
  113859. }
  113860. if(i%2)lpc[j]+=lpc[j]*r;
  113861. error*=1.f-r*r;
  113862. }
  113863. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113864. /* we need the error value to know how big an impulse to hit the
  113865. filter with later */
  113866. return error;
  113867. }
  113868. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113869. float *data,long n){
  113870. /* in: coeff[0...m-1] LPC coefficients
  113871. prime[0...m-1] initial values (allocated size of n+m-1)
  113872. out: data[0...n-1] data samples */
  113873. long i,j,o,p;
  113874. float y;
  113875. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113876. if(!prime)
  113877. for(i=0;i<m;i++)
  113878. work[i]=0.f;
  113879. else
  113880. for(i=0;i<m;i++)
  113881. work[i]=prime[i];
  113882. for(i=0;i<n;i++){
  113883. y=0;
  113884. o=i;
  113885. p=m;
  113886. for(j=0;j<m;j++)
  113887. y-=work[o++]*coeff[--p];
  113888. data[i]=work[o]=y;
  113889. }
  113890. }
  113891. #endif
  113892. /*** End of inlined file: lpc.c ***/
  113893. /*** Start of inlined file: lsp.c ***/
  113894. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113895. an iterative root polisher (CACM algorithm 283). It *is* possible
  113896. to confuse this algorithm into not converging; that should only
  113897. happen with absurdly closely spaced roots (very sharp peaks in the
  113898. LPC f response) which in turn should be impossible in our use of
  113899. the code. If this *does* happen anyway, it's a bug in the floor
  113900. finder; find the cause of the confusion (probably a single bin
  113901. spike or accidental near-float-limit resolution problems) and
  113902. correct it. */
  113903. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113904. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113905. // tasks..
  113906. #if JUCE_MSVC
  113907. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113908. #endif
  113909. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113910. #if JUCE_USE_OGGVORBIS
  113911. #include <math.h>
  113912. #include <string.h>
  113913. #include <stdlib.h>
  113914. /*** Start of inlined file: lookup.h ***/
  113915. #ifndef _V_LOOKUP_H_
  113916. #ifdef FLOAT_LOOKUP
  113917. extern float vorbis_coslook(float a);
  113918. extern float vorbis_invsqlook(float a);
  113919. extern float vorbis_invsq2explook(int a);
  113920. extern float vorbis_fromdBlook(float a);
  113921. #endif
  113922. #ifdef INT_LOOKUP
  113923. extern long vorbis_invsqlook_i(long a,long e);
  113924. extern long vorbis_coslook_i(long a);
  113925. extern float vorbis_fromdBlook_i(long a);
  113926. #endif
  113927. #endif
  113928. /*** End of inlined file: lookup.h ***/
  113929. /* three possible LSP to f curve functions; the exact computation
  113930. (float), a lookup based float implementation, and an integer
  113931. implementation. The float lookup is likely the optimal choice on
  113932. any machine with an FPU. The integer implementation is *not* fixed
  113933. point (due to the need for a large dynamic range and thus a
  113934. seperately tracked exponent) and thus much more complex than the
  113935. relatively simple float implementations. It's mostly for future
  113936. work on a fully fixed point implementation for processors like the
  113937. ARM family. */
  113938. /* undefine both for the 'old' but more precise implementation */
  113939. #define FLOAT_LOOKUP
  113940. #undef INT_LOOKUP
  113941. #ifdef FLOAT_LOOKUP
  113942. /*** Start of inlined file: lookup.c ***/
  113943. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113944. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113945. // tasks..
  113946. #if JUCE_MSVC
  113947. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113948. #endif
  113949. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113950. #if JUCE_USE_OGGVORBIS
  113951. #include <math.h>
  113952. /*** Start of inlined file: lookup.h ***/
  113953. #ifndef _V_LOOKUP_H_
  113954. #ifdef FLOAT_LOOKUP
  113955. extern float vorbis_coslook(float a);
  113956. extern float vorbis_invsqlook(float a);
  113957. extern float vorbis_invsq2explook(int a);
  113958. extern float vorbis_fromdBlook(float a);
  113959. #endif
  113960. #ifdef INT_LOOKUP
  113961. extern long vorbis_invsqlook_i(long a,long e);
  113962. extern long vorbis_coslook_i(long a);
  113963. extern float vorbis_fromdBlook_i(long a);
  113964. #endif
  113965. #endif
  113966. /*** End of inlined file: lookup.h ***/
  113967. /*** Start of inlined file: lookup_data.h ***/
  113968. #ifndef _V_LOOKUP_DATA_H_
  113969. #ifdef FLOAT_LOOKUP
  113970. #define COS_LOOKUP_SZ 128
  113971. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113972. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113973. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113974. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113975. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113976. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113977. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113978. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113979. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113980. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113981. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113982. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113983. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113984. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113985. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113986. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113987. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113988. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113989. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113990. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113991. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113992. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113993. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113994. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113995. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113996. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113997. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113998. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113999. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114000. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114001. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114002. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114003. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114004. -1.0000000000000f,
  114005. };
  114006. #define INVSQ_LOOKUP_SZ 32
  114007. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114008. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114009. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114010. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114011. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114012. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114013. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114014. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114015. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114016. 1.000000000000f,
  114017. };
  114018. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114019. #define INVSQ2EXP_LOOKUP_MAX 32
  114020. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114021. INVSQ2EXP_LOOKUP_MIN+1]={
  114022. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114023. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114024. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114025. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114026. 256.f, 181.019336f, 128.f, 90.50966799f,
  114027. 64.f, 45.254834f, 32.f, 22.627417f,
  114028. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114029. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114030. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114031. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114032. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114033. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114034. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114035. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114036. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114037. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114038. 1.525878906e-05f,
  114039. };
  114040. #endif
  114041. #define FROMdB_LOOKUP_SZ 35
  114042. #define FROMdB2_LOOKUP_SZ 32
  114043. #define FROMdB_SHIFT 5
  114044. #define FROMdB2_SHIFT 3
  114045. #define FROMdB2_MASK 31
  114046. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114047. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114048. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114049. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114050. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114051. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114052. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114053. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114054. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114055. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114056. };
  114057. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114058. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114059. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114060. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114061. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114062. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114063. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114064. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114065. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114066. };
  114067. #ifdef INT_LOOKUP
  114068. #define INVSQ_LOOKUP_I_SHIFT 10
  114069. #define INVSQ_LOOKUP_I_MASK 1023
  114070. static long INVSQ_LOOKUP_I[64+1]={
  114071. 92682l, 91966l, 91267l, 90583l,
  114072. 89915l, 89261l, 88621l, 87995l,
  114073. 87381l, 86781l, 86192l, 85616l,
  114074. 85051l, 84497l, 83953l, 83420l,
  114075. 82897l, 82384l, 81880l, 81385l,
  114076. 80899l, 80422l, 79953l, 79492l,
  114077. 79039l, 78594l, 78156l, 77726l,
  114078. 77302l, 76885l, 76475l, 76072l,
  114079. 75674l, 75283l, 74898l, 74519l,
  114080. 74146l, 73778l, 73415l, 73058l,
  114081. 72706l, 72359l, 72016l, 71679l,
  114082. 71347l, 71019l, 70695l, 70376l,
  114083. 70061l, 69750l, 69444l, 69141l,
  114084. 68842l, 68548l, 68256l, 67969l,
  114085. 67685l, 67405l, 67128l, 66855l,
  114086. 66585l, 66318l, 66054l, 65794l,
  114087. 65536l,
  114088. };
  114089. #define COS_LOOKUP_I_SHIFT 9
  114090. #define COS_LOOKUP_I_MASK 511
  114091. #define COS_LOOKUP_I_SZ 128
  114092. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114093. 16384l, 16379l, 16364l, 16340l,
  114094. 16305l, 16261l, 16207l, 16143l,
  114095. 16069l, 15986l, 15893l, 15791l,
  114096. 15679l, 15557l, 15426l, 15286l,
  114097. 15137l, 14978l, 14811l, 14635l,
  114098. 14449l, 14256l, 14053l, 13842l,
  114099. 13623l, 13395l, 13160l, 12916l,
  114100. 12665l, 12406l, 12140l, 11866l,
  114101. 11585l, 11297l, 11003l, 10702l,
  114102. 10394l, 10080l, 9760l, 9434l,
  114103. 9102l, 8765l, 8423l, 8076l,
  114104. 7723l, 7366l, 7005l, 6639l,
  114105. 6270l, 5897l, 5520l, 5139l,
  114106. 4756l, 4370l, 3981l, 3590l,
  114107. 3196l, 2801l, 2404l, 2006l,
  114108. 1606l, 1205l, 804l, 402l,
  114109. 0l, -401l, -803l, -1204l,
  114110. -1605l, -2005l, -2403l, -2800l,
  114111. -3195l, -3589l, -3980l, -4369l,
  114112. -4755l, -5138l, -5519l, -5896l,
  114113. -6269l, -6638l, -7004l, -7365l,
  114114. -7722l, -8075l, -8422l, -8764l,
  114115. -9101l, -9433l, -9759l, -10079l,
  114116. -10393l, -10701l, -11002l, -11296l,
  114117. -11584l, -11865l, -12139l, -12405l,
  114118. -12664l, -12915l, -13159l, -13394l,
  114119. -13622l, -13841l, -14052l, -14255l,
  114120. -14448l, -14634l, -14810l, -14977l,
  114121. -15136l, -15285l, -15425l, -15556l,
  114122. -15678l, -15790l, -15892l, -15985l,
  114123. -16068l, -16142l, -16206l, -16260l,
  114124. -16304l, -16339l, -16363l, -16378l,
  114125. -16383l,
  114126. };
  114127. #endif
  114128. #endif
  114129. /*** End of inlined file: lookup_data.h ***/
  114130. #ifdef FLOAT_LOOKUP
  114131. /* interpolated lookup based cos function, domain 0 to PI only */
  114132. float vorbis_coslook(float a){
  114133. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114134. int i=vorbis_ftoi(d-.5);
  114135. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114136. }
  114137. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114138. float vorbis_invsqlook(float a){
  114139. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114140. int i=vorbis_ftoi(d-.5f);
  114141. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114142. }
  114143. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114144. float vorbis_invsq2explook(int a){
  114145. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114146. }
  114147. #include <stdio.h>
  114148. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114149. float vorbis_fromdBlook(float a){
  114150. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114151. return (i<0)?1.f:
  114152. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114153. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114154. }
  114155. #endif
  114156. #ifdef INT_LOOKUP
  114157. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114158. 16.16 format
  114159. returns in m.8 format */
  114160. long vorbis_invsqlook_i(long a,long e){
  114161. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114162. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114163. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114164. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114165. d)>>16); /* result 1.16 */
  114166. e+=32;
  114167. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114168. e=(e>>1)-8;
  114169. return(val>>e);
  114170. }
  114171. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114172. /* a is in n.12 format */
  114173. float vorbis_fromdBlook_i(long a){
  114174. int i=(-a)>>(12-FROMdB2_SHIFT);
  114175. return (i<0)?1.f:
  114176. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114177. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114178. }
  114179. /* interpolated lookup based cos function, domain 0 to PI only */
  114180. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114181. long vorbis_coslook_i(long a){
  114182. int i=a>>COS_LOOKUP_I_SHIFT;
  114183. int d=a&COS_LOOKUP_I_MASK;
  114184. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114185. COS_LOOKUP_I_SHIFT);
  114186. }
  114187. #endif
  114188. #endif
  114189. /*** End of inlined file: lookup.c ***/
  114190. /* catch this in the build system; we #include for
  114191. compilers (like gcc) that can't inline across
  114192. modules */
  114193. /* side effect: changes *lsp to cosines of lsp */
  114194. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114195. float amp,float ampoffset){
  114196. int i;
  114197. float wdel=M_PI/ln;
  114198. vorbis_fpu_control fpu;
  114199. (void) fpu; // to avoid an unused variable warning
  114200. vorbis_fpu_setround(&fpu);
  114201. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114202. i=0;
  114203. while(i<n){
  114204. int k=map[i];
  114205. int qexp;
  114206. float p=.7071067812f;
  114207. float q=.7071067812f;
  114208. float w=vorbis_coslook(wdel*k);
  114209. float *ftmp=lsp;
  114210. int c=m>>1;
  114211. do{
  114212. q*=ftmp[0]-w;
  114213. p*=ftmp[1]-w;
  114214. ftmp+=2;
  114215. }while(--c);
  114216. if(m&1){
  114217. /* odd order filter; slightly assymetric */
  114218. /* the last coefficient */
  114219. q*=ftmp[0]-w;
  114220. q*=q;
  114221. p*=p*(1.f-w*w);
  114222. }else{
  114223. /* even order filter; still symmetric */
  114224. q*=q*(1.f+w);
  114225. p*=p*(1.f-w);
  114226. }
  114227. q=frexp(p+q,&qexp);
  114228. q=vorbis_fromdBlook(amp*
  114229. vorbis_invsqlook(q)*
  114230. vorbis_invsq2explook(qexp+m)-
  114231. ampoffset);
  114232. do{
  114233. curve[i++]*=q;
  114234. }while(map[i]==k);
  114235. }
  114236. vorbis_fpu_restore(fpu);
  114237. }
  114238. #else
  114239. #ifdef INT_LOOKUP
  114240. /*** Start of inlined file: lookup.c ***/
  114241. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114242. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114243. // tasks..
  114244. #if JUCE_MSVC
  114245. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114246. #endif
  114247. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114248. #if JUCE_USE_OGGVORBIS
  114249. #include <math.h>
  114250. /*** Start of inlined file: lookup.h ***/
  114251. #ifndef _V_LOOKUP_H_
  114252. #ifdef FLOAT_LOOKUP
  114253. extern float vorbis_coslook(float a);
  114254. extern float vorbis_invsqlook(float a);
  114255. extern float vorbis_invsq2explook(int a);
  114256. extern float vorbis_fromdBlook(float a);
  114257. #endif
  114258. #ifdef INT_LOOKUP
  114259. extern long vorbis_invsqlook_i(long a,long e);
  114260. extern long vorbis_coslook_i(long a);
  114261. extern float vorbis_fromdBlook_i(long a);
  114262. #endif
  114263. #endif
  114264. /*** End of inlined file: lookup.h ***/
  114265. /*** Start of inlined file: lookup_data.h ***/
  114266. #ifndef _V_LOOKUP_DATA_H_
  114267. #ifdef FLOAT_LOOKUP
  114268. #define COS_LOOKUP_SZ 128
  114269. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114270. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114271. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114272. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114273. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114274. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114275. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114276. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114277. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114278. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114279. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114280. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114281. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114282. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114283. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114284. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114285. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114286. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114287. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114288. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114289. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114290. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114291. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114292. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114293. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114294. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114295. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114296. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114297. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114298. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114299. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114300. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114301. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114302. -1.0000000000000f,
  114303. };
  114304. #define INVSQ_LOOKUP_SZ 32
  114305. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114306. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114307. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114308. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114309. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114310. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114311. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114312. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114313. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114314. 1.000000000000f,
  114315. };
  114316. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114317. #define INVSQ2EXP_LOOKUP_MAX 32
  114318. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114319. INVSQ2EXP_LOOKUP_MIN+1]={
  114320. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114321. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114322. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114323. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114324. 256.f, 181.019336f, 128.f, 90.50966799f,
  114325. 64.f, 45.254834f, 32.f, 22.627417f,
  114326. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114327. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114328. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114329. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114330. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114331. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114332. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114333. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114334. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114335. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114336. 1.525878906e-05f,
  114337. };
  114338. #endif
  114339. #define FROMdB_LOOKUP_SZ 35
  114340. #define FROMdB2_LOOKUP_SZ 32
  114341. #define FROMdB_SHIFT 5
  114342. #define FROMdB2_SHIFT 3
  114343. #define FROMdB2_MASK 31
  114344. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114345. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114346. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114347. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114348. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114349. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114350. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114351. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114352. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114353. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114354. };
  114355. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114356. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114357. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114358. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114359. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114360. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114361. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114362. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114363. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114364. };
  114365. #ifdef INT_LOOKUP
  114366. #define INVSQ_LOOKUP_I_SHIFT 10
  114367. #define INVSQ_LOOKUP_I_MASK 1023
  114368. static long INVSQ_LOOKUP_I[64+1]={
  114369. 92682l, 91966l, 91267l, 90583l,
  114370. 89915l, 89261l, 88621l, 87995l,
  114371. 87381l, 86781l, 86192l, 85616l,
  114372. 85051l, 84497l, 83953l, 83420l,
  114373. 82897l, 82384l, 81880l, 81385l,
  114374. 80899l, 80422l, 79953l, 79492l,
  114375. 79039l, 78594l, 78156l, 77726l,
  114376. 77302l, 76885l, 76475l, 76072l,
  114377. 75674l, 75283l, 74898l, 74519l,
  114378. 74146l, 73778l, 73415l, 73058l,
  114379. 72706l, 72359l, 72016l, 71679l,
  114380. 71347l, 71019l, 70695l, 70376l,
  114381. 70061l, 69750l, 69444l, 69141l,
  114382. 68842l, 68548l, 68256l, 67969l,
  114383. 67685l, 67405l, 67128l, 66855l,
  114384. 66585l, 66318l, 66054l, 65794l,
  114385. 65536l,
  114386. };
  114387. #define COS_LOOKUP_I_SHIFT 9
  114388. #define COS_LOOKUP_I_MASK 511
  114389. #define COS_LOOKUP_I_SZ 128
  114390. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114391. 16384l, 16379l, 16364l, 16340l,
  114392. 16305l, 16261l, 16207l, 16143l,
  114393. 16069l, 15986l, 15893l, 15791l,
  114394. 15679l, 15557l, 15426l, 15286l,
  114395. 15137l, 14978l, 14811l, 14635l,
  114396. 14449l, 14256l, 14053l, 13842l,
  114397. 13623l, 13395l, 13160l, 12916l,
  114398. 12665l, 12406l, 12140l, 11866l,
  114399. 11585l, 11297l, 11003l, 10702l,
  114400. 10394l, 10080l, 9760l, 9434l,
  114401. 9102l, 8765l, 8423l, 8076l,
  114402. 7723l, 7366l, 7005l, 6639l,
  114403. 6270l, 5897l, 5520l, 5139l,
  114404. 4756l, 4370l, 3981l, 3590l,
  114405. 3196l, 2801l, 2404l, 2006l,
  114406. 1606l, 1205l, 804l, 402l,
  114407. 0l, -401l, -803l, -1204l,
  114408. -1605l, -2005l, -2403l, -2800l,
  114409. -3195l, -3589l, -3980l, -4369l,
  114410. -4755l, -5138l, -5519l, -5896l,
  114411. -6269l, -6638l, -7004l, -7365l,
  114412. -7722l, -8075l, -8422l, -8764l,
  114413. -9101l, -9433l, -9759l, -10079l,
  114414. -10393l, -10701l, -11002l, -11296l,
  114415. -11584l, -11865l, -12139l, -12405l,
  114416. -12664l, -12915l, -13159l, -13394l,
  114417. -13622l, -13841l, -14052l, -14255l,
  114418. -14448l, -14634l, -14810l, -14977l,
  114419. -15136l, -15285l, -15425l, -15556l,
  114420. -15678l, -15790l, -15892l, -15985l,
  114421. -16068l, -16142l, -16206l, -16260l,
  114422. -16304l, -16339l, -16363l, -16378l,
  114423. -16383l,
  114424. };
  114425. #endif
  114426. #endif
  114427. /*** End of inlined file: lookup_data.h ***/
  114428. #ifdef FLOAT_LOOKUP
  114429. /* interpolated lookup based cos function, domain 0 to PI only */
  114430. float vorbis_coslook(float a){
  114431. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114432. int i=vorbis_ftoi(d-.5);
  114433. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114434. }
  114435. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114436. float vorbis_invsqlook(float a){
  114437. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114438. int i=vorbis_ftoi(d-.5f);
  114439. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114440. }
  114441. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114442. float vorbis_invsq2explook(int a){
  114443. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114444. }
  114445. #include <stdio.h>
  114446. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114447. float vorbis_fromdBlook(float a){
  114448. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114449. return (i<0)?1.f:
  114450. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114451. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114452. }
  114453. #endif
  114454. #ifdef INT_LOOKUP
  114455. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114456. 16.16 format
  114457. returns in m.8 format */
  114458. long vorbis_invsqlook_i(long a,long e){
  114459. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114460. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114461. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114462. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114463. d)>>16); /* result 1.16 */
  114464. e+=32;
  114465. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114466. e=(e>>1)-8;
  114467. return(val>>e);
  114468. }
  114469. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114470. /* a is in n.12 format */
  114471. float vorbis_fromdBlook_i(long a){
  114472. int i=(-a)>>(12-FROMdB2_SHIFT);
  114473. return (i<0)?1.f:
  114474. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114475. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114476. }
  114477. /* interpolated lookup based cos function, domain 0 to PI only */
  114478. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114479. long vorbis_coslook_i(long a){
  114480. int i=a>>COS_LOOKUP_I_SHIFT;
  114481. int d=a&COS_LOOKUP_I_MASK;
  114482. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114483. COS_LOOKUP_I_SHIFT);
  114484. }
  114485. #endif
  114486. #endif
  114487. /*** End of inlined file: lookup.c ***/
  114488. /* catch this in the build system; we #include for
  114489. compilers (like gcc) that can't inline across
  114490. modules */
  114491. static int MLOOP_1[64]={
  114492. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114493. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114494. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114495. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114496. };
  114497. static int MLOOP_2[64]={
  114498. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114499. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114500. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114501. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114502. };
  114503. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114504. /* side effect: changes *lsp to cosines of lsp */
  114505. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114506. float amp,float ampoffset){
  114507. /* 0 <= m < 256 */
  114508. /* set up for using all int later */
  114509. int i;
  114510. int ampoffseti=rint(ampoffset*4096.f);
  114511. int ampi=rint(amp*16.f);
  114512. long *ilsp=alloca(m*sizeof(*ilsp));
  114513. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114514. i=0;
  114515. while(i<n){
  114516. int j,k=map[i];
  114517. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114518. unsigned long qi=46341;
  114519. int qexp=0,shift;
  114520. long wi=vorbis_coslook_i(k*65536/ln);
  114521. qi*=labs(ilsp[0]-wi);
  114522. pi*=labs(ilsp[1]-wi);
  114523. for(j=3;j<m;j+=2){
  114524. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114525. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114526. shift=MLOOP_3[(pi|qi)>>16];
  114527. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114528. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114529. qexp+=shift;
  114530. }
  114531. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114532. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114533. shift=MLOOP_3[(pi|qi)>>16];
  114534. /* pi,qi normalized collectively, both tracked using qexp */
  114535. if(m&1){
  114536. /* odd order filter; slightly assymetric */
  114537. /* the last coefficient */
  114538. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114539. pi=(pi>>shift)<<14;
  114540. qexp+=shift;
  114541. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114542. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114543. shift=MLOOP_3[(pi|qi)>>16];
  114544. pi>>=shift;
  114545. qi>>=shift;
  114546. qexp+=shift-14*((m+1)>>1);
  114547. pi=((pi*pi)>>16);
  114548. qi=((qi*qi)>>16);
  114549. qexp=qexp*2+m;
  114550. pi*=(1<<14)-((wi*wi)>>14);
  114551. qi+=pi>>14;
  114552. }else{
  114553. /* even order filter; still symmetric */
  114554. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114555. worth tracking step by step */
  114556. pi>>=shift;
  114557. qi>>=shift;
  114558. qexp+=shift-7*m;
  114559. pi=((pi*pi)>>16);
  114560. qi=((qi*qi)>>16);
  114561. qexp=qexp*2+m;
  114562. pi*=(1<<14)-wi;
  114563. qi*=(1<<14)+wi;
  114564. qi=(qi+pi)>>14;
  114565. }
  114566. /* we've let the normalization drift because it wasn't important;
  114567. however, for the lookup, things must be normalized again. We
  114568. need at most one right shift or a number of left shifts */
  114569. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114570. qi>>=1; qexp++;
  114571. }else
  114572. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114573. qi<<=1; qexp--;
  114574. }
  114575. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114576. vorbis_invsqlook_i(qi,qexp)-
  114577. /* m.8, m+n<=8 */
  114578. ampoffseti); /* 8.12[0] */
  114579. curve[i]*=amp;
  114580. while(map[++i]==k)curve[i]*=amp;
  114581. }
  114582. }
  114583. #else
  114584. /* old, nonoptimized but simple version for any poor sap who needs to
  114585. figure out what the hell this code does, or wants the other
  114586. fraction of a dB precision */
  114587. /* side effect: changes *lsp to cosines of lsp */
  114588. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114589. float amp,float ampoffset){
  114590. int i;
  114591. float wdel=M_PI/ln;
  114592. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114593. i=0;
  114594. while(i<n){
  114595. int j,k=map[i];
  114596. float p=.5f;
  114597. float q=.5f;
  114598. float w=2.f*cos(wdel*k);
  114599. for(j=1;j<m;j+=2){
  114600. q *= w-lsp[j-1];
  114601. p *= w-lsp[j];
  114602. }
  114603. if(j==m){
  114604. /* odd order filter; slightly assymetric */
  114605. /* the last coefficient */
  114606. q*=w-lsp[j-1];
  114607. p*=p*(4.f-w*w);
  114608. q*=q;
  114609. }else{
  114610. /* even order filter; still symmetric */
  114611. p*=p*(2.f-w);
  114612. q*=q*(2.f+w);
  114613. }
  114614. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114615. curve[i]*=q;
  114616. while(map[++i]==k)curve[i]*=q;
  114617. }
  114618. }
  114619. #endif
  114620. #endif
  114621. static void cheby(float *g, int ord) {
  114622. int i, j;
  114623. g[0] *= .5f;
  114624. for(i=2; i<= ord; i++) {
  114625. for(j=ord; j >= i; j--) {
  114626. g[j-2] -= g[j];
  114627. g[j] += g[j];
  114628. }
  114629. }
  114630. }
  114631. static int JUCE_CDECL comp(const void *a,const void *b){
  114632. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114633. }
  114634. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114635. but there are root sets for which it gets into limit cycles
  114636. (exacerbated by zero suppression) and fails. We can't afford to
  114637. fail, even if the failure is 1 in 100,000,000, so we now use
  114638. Laguerre and later polish with Newton-Raphson (which can then
  114639. afford to fail) */
  114640. #define EPSILON 10e-7
  114641. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114642. int i,m;
  114643. double lastdelta=0.f;
  114644. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114645. for(i=0;i<=ord;i++)defl[i]=a[i];
  114646. for(m=ord;m>0;m--){
  114647. double newx=0.f,delta;
  114648. /* iterate a root */
  114649. while(1){
  114650. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114651. /* eval the polynomial and its first two derivatives */
  114652. for(i=m;i>0;i--){
  114653. ppp = newx*ppp + pp;
  114654. pp = newx*pp + p;
  114655. p = newx*p + defl[i-1];
  114656. }
  114657. /* Laguerre's method */
  114658. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114659. if(denom<0)
  114660. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114661. if(pp>0){
  114662. denom = pp + sqrt(denom);
  114663. if(denom<EPSILON)denom=EPSILON;
  114664. }else{
  114665. denom = pp - sqrt(denom);
  114666. if(denom>-(EPSILON))denom=-(EPSILON);
  114667. }
  114668. delta = m*p/denom;
  114669. newx -= delta;
  114670. if(delta<0.f)delta*=-1;
  114671. if(fabs(delta/newx)<10e-12)break;
  114672. lastdelta=delta;
  114673. }
  114674. r[m-1]=newx;
  114675. /* forward deflation */
  114676. for(i=m;i>0;i--)
  114677. defl[i-1]+=newx*defl[i];
  114678. defl++;
  114679. }
  114680. return(0);
  114681. }
  114682. /* for spit-and-polish only */
  114683. static int Newton_Raphson(float *a,int ord,float *r){
  114684. int i, k, count=0;
  114685. double error=1.f;
  114686. double *root=(double*)alloca(ord*sizeof(*root));
  114687. for(i=0; i<ord;i++) root[i] = r[i];
  114688. while(error>1e-20){
  114689. error=0;
  114690. for(i=0; i<ord; i++) { /* Update each point. */
  114691. double pp=0.,delta;
  114692. double rooti=root[i];
  114693. double p=a[ord];
  114694. for(k=ord-1; k>= 0; k--) {
  114695. pp= pp* rooti + p;
  114696. p = p * rooti + a[k];
  114697. }
  114698. delta = p/pp;
  114699. root[i] -= delta;
  114700. error+= delta*delta;
  114701. }
  114702. if(count>40)return(-1);
  114703. count++;
  114704. }
  114705. /* Replaced the original bubble sort with a real sort. With your
  114706. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114707. for(i=0; i<ord;i++) r[i] = root[i];
  114708. return(0);
  114709. }
  114710. /* Convert lpc coefficients to lsp coefficients */
  114711. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114712. int order2=(m+1)>>1;
  114713. int g1_order,g2_order;
  114714. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114715. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114716. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114717. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114718. int i;
  114719. /* even and odd are slightly different base cases */
  114720. g1_order=(m+1)>>1;
  114721. g2_order=(m) >>1;
  114722. /* Compute the lengths of the x polynomials. */
  114723. /* Compute the first half of K & R F1 & F2 polynomials. */
  114724. /* Compute half of the symmetric and antisymmetric polynomials. */
  114725. /* Remove the roots at +1 and -1. */
  114726. g1[g1_order] = 1.f;
  114727. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114728. g2[g2_order] = 1.f;
  114729. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114730. if(g1_order>g2_order){
  114731. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114732. }else{
  114733. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114734. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114735. }
  114736. /* Convert into polynomials in cos(alpha) */
  114737. cheby(g1,g1_order);
  114738. cheby(g2,g2_order);
  114739. /* Find the roots of the 2 even polynomials.*/
  114740. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114741. Laguerre_With_Deflation(g2,g2_order,g2r))
  114742. return(-1);
  114743. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114744. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114745. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114746. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114747. for(i=0;i<g1_order;i++)
  114748. lsp[i*2] = acos(g1r[i]);
  114749. for(i=0;i<g2_order;i++)
  114750. lsp[i*2+1] = acos(g2r[i]);
  114751. return(0);
  114752. }
  114753. #endif
  114754. /*** End of inlined file: lsp.c ***/
  114755. /*** Start of inlined file: mapping0.c ***/
  114756. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114757. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114758. // tasks..
  114759. #if JUCE_MSVC
  114760. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114761. #endif
  114762. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114763. #if JUCE_USE_OGGVORBIS
  114764. #include <stdlib.h>
  114765. #include <stdio.h>
  114766. #include <string.h>
  114767. #include <math.h>
  114768. /* simplistic, wasteful way of doing this (unique lookup for each
  114769. mode/submapping); there should be a central repository for
  114770. identical lookups. That will require minor work, so I'm putting it
  114771. off as low priority.
  114772. Why a lookup for each backend in a given mode? Because the
  114773. blocksize is set by the mode, and low backend lookups may require
  114774. parameters from other areas of the mode/mapping */
  114775. static void mapping0_free_info(vorbis_info_mapping *i){
  114776. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114777. if(info){
  114778. memset(info,0,sizeof(*info));
  114779. _ogg_free(info);
  114780. }
  114781. }
  114782. static int ilog3(unsigned int v){
  114783. int ret=0;
  114784. if(v)--v;
  114785. while(v){
  114786. ret++;
  114787. v>>=1;
  114788. }
  114789. return(ret);
  114790. }
  114791. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114792. oggpack_buffer *opb){
  114793. int i;
  114794. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114795. /* another 'we meant to do it this way' hack... up to beta 4, we
  114796. packed 4 binary zeros here to signify one submapping in use. We
  114797. now redefine that to mean four bitflags that indicate use of
  114798. deeper features; bit0:submappings, bit1:coupling,
  114799. bit2,3:reserved. This is backward compatable with all actual uses
  114800. of the beta code. */
  114801. if(info->submaps>1){
  114802. oggpack_write(opb,1,1);
  114803. oggpack_write(opb,info->submaps-1,4);
  114804. }else
  114805. oggpack_write(opb,0,1);
  114806. if(info->coupling_steps>0){
  114807. oggpack_write(opb,1,1);
  114808. oggpack_write(opb,info->coupling_steps-1,8);
  114809. for(i=0;i<info->coupling_steps;i++){
  114810. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114811. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114812. }
  114813. }else
  114814. oggpack_write(opb,0,1);
  114815. oggpack_write(opb,0,2); /* 2,3:reserved */
  114816. /* we don't write the channel submappings if we only have one... */
  114817. if(info->submaps>1){
  114818. for(i=0;i<vi->channels;i++)
  114819. oggpack_write(opb,info->chmuxlist[i],4);
  114820. }
  114821. for(i=0;i<info->submaps;i++){
  114822. oggpack_write(opb,0,8); /* time submap unused */
  114823. oggpack_write(opb,info->floorsubmap[i],8);
  114824. oggpack_write(opb,info->residuesubmap[i],8);
  114825. }
  114826. }
  114827. /* also responsible for range checking */
  114828. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114829. int i;
  114830. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114831. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114832. memset(info,0,sizeof(*info));
  114833. if(oggpack_read(opb,1))
  114834. info->submaps=oggpack_read(opb,4)+1;
  114835. else
  114836. info->submaps=1;
  114837. if(oggpack_read(opb,1)){
  114838. info->coupling_steps=oggpack_read(opb,8)+1;
  114839. for(i=0;i<info->coupling_steps;i++){
  114840. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114841. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114842. if(testM<0 ||
  114843. testA<0 ||
  114844. testM==testA ||
  114845. testM>=vi->channels ||
  114846. testA>=vi->channels) goto err_out;
  114847. }
  114848. }
  114849. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114850. if(info->submaps>1){
  114851. for(i=0;i<vi->channels;i++){
  114852. info->chmuxlist[i]=oggpack_read(opb,4);
  114853. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114854. }
  114855. }
  114856. for(i=0;i<info->submaps;i++){
  114857. oggpack_read(opb,8); /* time submap unused */
  114858. info->floorsubmap[i]=oggpack_read(opb,8);
  114859. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114860. info->residuesubmap[i]=oggpack_read(opb,8);
  114861. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114862. }
  114863. return info;
  114864. err_out:
  114865. mapping0_free_info(info);
  114866. return(NULL);
  114867. }
  114868. #if 0
  114869. static long seq=0;
  114870. static ogg_int64_t total=0;
  114871. static float FLOOR1_fromdB_LOOKUP[256]={
  114872. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114873. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114874. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114875. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114876. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114877. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114878. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114879. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114880. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114881. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114882. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114883. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114884. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114885. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114886. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114887. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114888. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114889. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114890. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114891. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114892. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114893. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114894. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114895. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114896. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114897. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114898. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114899. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114900. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114901. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114902. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114903. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114904. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114905. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114906. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114907. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114908. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114909. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114910. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114911. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114912. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114913. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114914. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114915. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114916. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114917. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114918. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114919. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114920. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114921. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114922. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114923. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114924. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114925. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114926. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114927. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114928. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114929. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114930. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114931. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114932. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114933. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114934. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114935. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114936. };
  114937. #endif
  114938. extern int *floor1_fit(vorbis_block *vb,void *look,
  114939. const float *logmdct, /* in */
  114940. const float *logmask);
  114941. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114942. int *A,int *B,
  114943. int del);
  114944. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114945. void*look,
  114946. int *post,int *ilogmask);
  114947. static int mapping0_forward(vorbis_block *vb){
  114948. vorbis_dsp_state *vd=vb->vd;
  114949. vorbis_info *vi=vd->vi;
  114950. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114951. private_state *b=(private_state*)vb->vd->backend_state;
  114952. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114953. int n=vb->pcmend;
  114954. int i,j,k;
  114955. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114956. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114957. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114958. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114959. float global_ampmax=vbi->ampmax;
  114960. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114961. int blocktype=vbi->blocktype;
  114962. int modenumber=vb->W;
  114963. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114964. vorbis_look_psy *psy_look=
  114965. b->psy+blocktype+(vb->W?2:0);
  114966. vb->mode=modenumber;
  114967. for(i=0;i<vi->channels;i++){
  114968. float scale=4.f/n;
  114969. float scale_dB;
  114970. float *pcm =vb->pcm[i];
  114971. float *logfft =pcm;
  114972. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114973. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114974. todB estimation used on IEEE 754
  114975. compliant machines had a bug that
  114976. returned dB values about a third
  114977. of a decibel too high. The bug
  114978. was harmless because tunings
  114979. implicitly took that into
  114980. account. However, fixing the bug
  114981. in the estimator requires
  114982. changing all the tunings as well.
  114983. For now, it's easier to sync
  114984. things back up here, and
  114985. recalibrate the tunings in the
  114986. next major model upgrade. */
  114987. #if 0
  114988. if(vi->channels==2)
  114989. if(i==0)
  114990. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114991. else
  114992. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114993. #endif
  114994. /* window the PCM data */
  114995. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114996. #if 0
  114997. if(vi->channels==2)
  114998. if(i==0)
  114999. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115000. else
  115001. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115002. #endif
  115003. /* transform the PCM data */
  115004. /* only MDCT right now.... */
  115005. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115006. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115007. drft_forward(&b->fft_look[vb->W],pcm);
  115008. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115009. original todB estimation used on
  115010. IEEE 754 compliant machines had a
  115011. bug that returned dB values about
  115012. a third of a decibel too high.
  115013. The bug was harmless because
  115014. tunings implicitly took that into
  115015. account. However, fixing the bug
  115016. in the estimator requires
  115017. changing all the tunings as well.
  115018. For now, it's easier to sync
  115019. things back up here, and
  115020. recalibrate the tunings in the
  115021. next major model upgrade. */
  115022. local_ampmax[i]=logfft[0];
  115023. for(j=1;j<n-1;j+=2){
  115024. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115025. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115026. .345 is a hack; the original todB
  115027. estimation used on IEEE 754
  115028. compliant machines had a bug that
  115029. returned dB values about a third
  115030. of a decibel too high. The bug
  115031. was harmless because tunings
  115032. implicitly took that into
  115033. account. However, fixing the bug
  115034. in the estimator requires
  115035. changing all the tunings as well.
  115036. For now, it's easier to sync
  115037. things back up here, and
  115038. recalibrate the tunings in the
  115039. next major model upgrade. */
  115040. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115041. }
  115042. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115043. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115044. #if 0
  115045. if(vi->channels==2){
  115046. if(i==0){
  115047. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115048. }else{
  115049. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115050. }
  115051. }
  115052. #endif
  115053. }
  115054. {
  115055. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115056. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115057. for(i=0;i<vi->channels;i++){
  115058. /* the encoder setup assumes that all the modes used by any
  115059. specific bitrate tweaking use the same floor */
  115060. int submap=info->chmuxlist[i];
  115061. /* the following makes things clearer to *me* anyway */
  115062. float *mdct =gmdct[i];
  115063. float *logfft =vb->pcm[i];
  115064. float *logmdct =logfft+n/2;
  115065. float *logmask =logfft;
  115066. vb->mode=modenumber;
  115067. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115068. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115069. for(j=0;j<n/2;j++)
  115070. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115071. todB estimation used on IEEE 754
  115072. compliant machines had a bug that
  115073. returned dB values about a third
  115074. of a decibel too high. The bug
  115075. was harmless because tunings
  115076. implicitly took that into
  115077. account. However, fixing the bug
  115078. in the estimator requires
  115079. changing all the tunings as well.
  115080. For now, it's easier to sync
  115081. things back up here, and
  115082. recalibrate the tunings in the
  115083. next major model upgrade. */
  115084. #if 0
  115085. if(vi->channels==2){
  115086. if(i==0)
  115087. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115088. else
  115089. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115090. }else{
  115091. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115092. }
  115093. #endif
  115094. /* first step; noise masking. Not only does 'noise masking'
  115095. give us curves from which we can decide how much resolution
  115096. to give noise parts of the spectrum, it also implicitly hands
  115097. us a tonality estimate (the larger the value in the
  115098. 'noise_depth' vector, the more tonal that area is) */
  115099. _vp_noisemask(psy_look,
  115100. logmdct,
  115101. noise); /* noise does not have by-frequency offset
  115102. bias applied yet */
  115103. #if 0
  115104. if(vi->channels==2){
  115105. if(i==0)
  115106. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115107. else
  115108. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115109. }
  115110. #endif
  115111. /* second step: 'all the other crap'; all the stuff that isn't
  115112. computed/fit for bitrate management goes in the second psy
  115113. vector. This includes tone masking, peak limiting and ATH */
  115114. _vp_tonemask(psy_look,
  115115. logfft,
  115116. tone,
  115117. global_ampmax,
  115118. local_ampmax[i]);
  115119. #if 0
  115120. if(vi->channels==2){
  115121. if(i==0)
  115122. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115123. else
  115124. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115125. }
  115126. #endif
  115127. /* third step; we offset the noise vectors, overlay tone
  115128. masking. We then do a floor1-specific line fit. If we're
  115129. performing bitrate management, the line fit is performed
  115130. multiple times for up/down tweakage on demand. */
  115131. #if 0
  115132. {
  115133. float aotuv[psy_look->n];
  115134. #endif
  115135. _vp_offset_and_mix(psy_look,
  115136. noise,
  115137. tone,
  115138. 1,
  115139. logmask,
  115140. mdct,
  115141. logmdct);
  115142. #if 0
  115143. if(vi->channels==2){
  115144. if(i==0)
  115145. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115146. else
  115147. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115148. }
  115149. }
  115150. #endif
  115151. #if 0
  115152. if(vi->channels==2){
  115153. if(i==0)
  115154. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115155. else
  115156. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115157. }
  115158. #endif
  115159. /* this algorithm is hardwired to floor 1 for now; abort out if
  115160. we're *not* floor1. This won't happen unless someone has
  115161. broken the encode setup lib. Guard it anyway. */
  115162. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115163. floor_posts[i][PACKETBLOBS/2]=
  115164. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115165. logmdct,
  115166. logmask);
  115167. /* are we managing bitrate? If so, perform two more fits for
  115168. later rate tweaking (fits represent hi/lo) */
  115169. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115170. /* higher rate by way of lower noise curve */
  115171. _vp_offset_and_mix(psy_look,
  115172. noise,
  115173. tone,
  115174. 2,
  115175. logmask,
  115176. mdct,
  115177. logmdct);
  115178. #if 0
  115179. if(vi->channels==2){
  115180. if(i==0)
  115181. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115182. else
  115183. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115184. }
  115185. #endif
  115186. floor_posts[i][PACKETBLOBS-1]=
  115187. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115188. logmdct,
  115189. logmask);
  115190. /* lower rate by way of higher noise curve */
  115191. _vp_offset_and_mix(psy_look,
  115192. noise,
  115193. tone,
  115194. 0,
  115195. logmask,
  115196. mdct,
  115197. logmdct);
  115198. #if 0
  115199. if(vi->channels==2)
  115200. if(i==0)
  115201. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115202. else
  115203. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115204. #endif
  115205. floor_posts[i][0]=
  115206. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115207. logmdct,
  115208. logmask);
  115209. /* we also interpolate a range of intermediate curves for
  115210. intermediate rates */
  115211. for(k=1;k<PACKETBLOBS/2;k++)
  115212. floor_posts[i][k]=
  115213. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115214. floor_posts[i][0],
  115215. floor_posts[i][PACKETBLOBS/2],
  115216. k*65536/(PACKETBLOBS/2));
  115217. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115218. floor_posts[i][k]=
  115219. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115220. floor_posts[i][PACKETBLOBS/2],
  115221. floor_posts[i][PACKETBLOBS-1],
  115222. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115223. }
  115224. }
  115225. }
  115226. vbi->ampmax=global_ampmax;
  115227. /*
  115228. the next phases are performed once for vbr-only and PACKETBLOB
  115229. times for bitrate managed modes.
  115230. 1) encode actual mode being used
  115231. 2) encode the floor for each channel, compute coded mask curve/res
  115232. 3) normalize and couple.
  115233. 4) encode residue
  115234. 5) save packet bytes to the packetblob vector
  115235. */
  115236. /* iterate over the many masking curve fits we've created */
  115237. {
  115238. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115239. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115240. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115241. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115242. float **mag_memo;
  115243. int **mag_sort;
  115244. if(info->coupling_steps){
  115245. mag_memo=_vp_quantize_couple_memo(vb,
  115246. &ci->psy_g_param,
  115247. psy_look,
  115248. info,
  115249. gmdct);
  115250. mag_sort=_vp_quantize_couple_sort(vb,
  115251. psy_look,
  115252. info,
  115253. mag_memo);
  115254. hf_reduction(&ci->psy_g_param,
  115255. psy_look,
  115256. info,
  115257. mag_memo);
  115258. }
  115259. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115260. if(psy_look->vi->normal_channel_p){
  115261. for(i=0;i<vi->channels;i++){
  115262. float *mdct =gmdct[i];
  115263. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115264. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115265. }
  115266. }
  115267. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115268. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115269. k++){
  115270. oggpack_buffer *opb=vbi->packetblob[k];
  115271. /* start out our new packet blob with packet type and mode */
  115272. /* Encode the packet type */
  115273. oggpack_write(opb,0,1);
  115274. /* Encode the modenumber */
  115275. /* Encode frame mode, pre,post windowsize, then dispatch */
  115276. oggpack_write(opb,modenumber,b->modebits);
  115277. if(vb->W){
  115278. oggpack_write(opb,vb->lW,1);
  115279. oggpack_write(opb,vb->nW,1);
  115280. }
  115281. /* encode floor, compute masking curve, sep out residue */
  115282. for(i=0;i<vi->channels;i++){
  115283. int submap=info->chmuxlist[i];
  115284. float *mdct =gmdct[i];
  115285. float *res =vb->pcm[i];
  115286. int *ilogmask=ilogmaskch[i]=
  115287. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115288. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115289. floor_posts[i][k],
  115290. ilogmask);
  115291. #if 0
  115292. {
  115293. char buf[80];
  115294. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115295. float work[n/2];
  115296. for(j=0;j<n/2;j++)
  115297. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115298. _analysis_output(buf,seq,work,n/2,1,1,0);
  115299. }
  115300. #endif
  115301. _vp_remove_floor(psy_look,
  115302. mdct,
  115303. ilogmask,
  115304. res,
  115305. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115306. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115307. #if 0
  115308. {
  115309. char buf[80];
  115310. float work[n/2];
  115311. for(j=0;j<n/2;j++)
  115312. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115313. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115314. _analysis_output(buf,seq,work,n/2,1,1,0);
  115315. }
  115316. #endif
  115317. }
  115318. /* our iteration is now based on masking curve, not prequant and
  115319. coupling. Only one prequant/coupling step */
  115320. /* quantize/couple */
  115321. /* incomplete implementation that assumes the tree is all depth
  115322. one, or no tree at all */
  115323. if(info->coupling_steps){
  115324. _vp_couple(k,
  115325. &ci->psy_g_param,
  115326. psy_look,
  115327. info,
  115328. vb->pcm,
  115329. mag_memo,
  115330. mag_sort,
  115331. ilogmaskch,
  115332. nonzero,
  115333. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115334. }
  115335. /* classify and encode by submap */
  115336. for(i=0;i<info->submaps;i++){
  115337. int ch_in_bundle=0;
  115338. long **classifications;
  115339. int resnum=info->residuesubmap[i];
  115340. for(j=0;j<vi->channels;j++){
  115341. if(info->chmuxlist[j]==i){
  115342. zerobundle[ch_in_bundle]=0;
  115343. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115344. res_bundle[ch_in_bundle]=vb->pcm[j];
  115345. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115346. }
  115347. }
  115348. classifications=_residue_P[ci->residue_type[resnum]]->
  115349. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115350. _residue_P[ci->residue_type[resnum]]->
  115351. forward(opb,vb,b->residue[resnum],
  115352. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115353. }
  115354. /* ok, done encoding. Next protopacket. */
  115355. }
  115356. }
  115357. #if 0
  115358. seq++;
  115359. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115360. #endif
  115361. return(0);
  115362. }
  115363. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115364. vorbis_dsp_state *vd=vb->vd;
  115365. vorbis_info *vi=vd->vi;
  115366. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115367. private_state *b=(private_state*)vd->backend_state;
  115368. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115369. int i,j;
  115370. long n=vb->pcmend=ci->blocksizes[vb->W];
  115371. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115372. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115373. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115374. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115375. /* recover the spectral envelope; store it in the PCM vector for now */
  115376. for(i=0;i<vi->channels;i++){
  115377. int submap=info->chmuxlist[i];
  115378. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115379. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115380. if(floormemo[i])
  115381. nonzero[i]=1;
  115382. else
  115383. nonzero[i]=0;
  115384. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115385. }
  115386. /* channel coupling can 'dirty' the nonzero listing */
  115387. for(i=0;i<info->coupling_steps;i++){
  115388. if(nonzero[info->coupling_mag[i]] ||
  115389. nonzero[info->coupling_ang[i]]){
  115390. nonzero[info->coupling_mag[i]]=1;
  115391. nonzero[info->coupling_ang[i]]=1;
  115392. }
  115393. }
  115394. /* recover the residue into our working vectors */
  115395. for(i=0;i<info->submaps;i++){
  115396. int ch_in_bundle=0;
  115397. for(j=0;j<vi->channels;j++){
  115398. if(info->chmuxlist[j]==i){
  115399. if(nonzero[j])
  115400. zerobundle[ch_in_bundle]=1;
  115401. else
  115402. zerobundle[ch_in_bundle]=0;
  115403. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115404. }
  115405. }
  115406. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115407. inverse(vb,b->residue[info->residuesubmap[i]],
  115408. pcmbundle,zerobundle,ch_in_bundle);
  115409. }
  115410. /* channel coupling */
  115411. for(i=info->coupling_steps-1;i>=0;i--){
  115412. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115413. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115414. for(j=0;j<n/2;j++){
  115415. float mag=pcmM[j];
  115416. float ang=pcmA[j];
  115417. if(mag>0)
  115418. if(ang>0){
  115419. pcmM[j]=mag;
  115420. pcmA[j]=mag-ang;
  115421. }else{
  115422. pcmA[j]=mag;
  115423. pcmM[j]=mag+ang;
  115424. }
  115425. else
  115426. if(ang>0){
  115427. pcmM[j]=mag;
  115428. pcmA[j]=mag+ang;
  115429. }else{
  115430. pcmA[j]=mag;
  115431. pcmM[j]=mag-ang;
  115432. }
  115433. }
  115434. }
  115435. /* compute and apply spectral envelope */
  115436. for(i=0;i<vi->channels;i++){
  115437. float *pcm=vb->pcm[i];
  115438. int submap=info->chmuxlist[i];
  115439. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115440. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115441. floormemo[i],pcm);
  115442. }
  115443. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115444. /* only MDCT right now.... */
  115445. for(i=0;i<vi->channels;i++){
  115446. float *pcm=vb->pcm[i];
  115447. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115448. }
  115449. /* all done! */
  115450. return(0);
  115451. }
  115452. /* export hooks */
  115453. vorbis_func_mapping mapping0_exportbundle={
  115454. &mapping0_pack,
  115455. &mapping0_unpack,
  115456. &mapping0_free_info,
  115457. &mapping0_forward,
  115458. &mapping0_inverse
  115459. };
  115460. #endif
  115461. /*** End of inlined file: mapping0.c ***/
  115462. /*** Start of inlined file: mdct.c ***/
  115463. /* this can also be run as an integer transform by uncommenting a
  115464. define in mdct.h; the integerization is a first pass and although
  115465. it's likely stable for Vorbis, the dynamic range is constrained and
  115466. roundoff isn't done (so it's noisy). Consider it functional, but
  115467. only a starting point. There's no point on a machine with an FPU */
  115468. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115469. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115470. // tasks..
  115471. #if JUCE_MSVC
  115472. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115473. #endif
  115474. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115475. #if JUCE_USE_OGGVORBIS
  115476. #include <stdio.h>
  115477. #include <stdlib.h>
  115478. #include <string.h>
  115479. #include <math.h>
  115480. /* build lookups for trig functions; also pre-figure scaling and
  115481. some window function algebra. */
  115482. void mdct_init(mdct_lookup *lookup,int n){
  115483. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115484. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115485. int i;
  115486. int n2=n>>1;
  115487. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115488. lookup->n=n;
  115489. lookup->trig=T;
  115490. lookup->bitrev=bitrev;
  115491. /* trig lookups... */
  115492. for(i=0;i<n/4;i++){
  115493. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115494. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115495. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115496. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115497. }
  115498. for(i=0;i<n/8;i++){
  115499. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115500. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115501. }
  115502. /* bitreverse lookup... */
  115503. {
  115504. int mask=(1<<(log2n-1))-1,i,j;
  115505. int msb=1<<(log2n-2);
  115506. for(i=0;i<n/8;i++){
  115507. int acc=0;
  115508. for(j=0;msb>>j;j++)
  115509. if((msb>>j)&i)acc|=1<<j;
  115510. bitrev[i*2]=((~acc)&mask)-1;
  115511. bitrev[i*2+1]=acc;
  115512. }
  115513. }
  115514. lookup->scale=FLOAT_CONV(4.f/n);
  115515. }
  115516. /* 8 point butterfly (in place, 4 register) */
  115517. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115518. REG_TYPE r0 = x[6] + x[2];
  115519. REG_TYPE r1 = x[6] - x[2];
  115520. REG_TYPE r2 = x[4] + x[0];
  115521. REG_TYPE r3 = x[4] - x[0];
  115522. x[6] = r0 + r2;
  115523. x[4] = r0 - r2;
  115524. r0 = x[5] - x[1];
  115525. r2 = x[7] - x[3];
  115526. x[0] = r1 + r0;
  115527. x[2] = r1 - r0;
  115528. r0 = x[5] + x[1];
  115529. r1 = x[7] + x[3];
  115530. x[3] = r2 + r3;
  115531. x[1] = r2 - r3;
  115532. x[7] = r1 + r0;
  115533. x[5] = r1 - r0;
  115534. }
  115535. /* 16 point butterfly (in place, 4 register) */
  115536. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115537. REG_TYPE r0 = x[1] - x[9];
  115538. REG_TYPE r1 = x[0] - x[8];
  115539. x[8] += x[0];
  115540. x[9] += x[1];
  115541. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115542. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115543. r0 = x[3] - x[11];
  115544. r1 = x[10] - x[2];
  115545. x[10] += x[2];
  115546. x[11] += x[3];
  115547. x[2] = r0;
  115548. x[3] = r1;
  115549. r0 = x[12] - x[4];
  115550. r1 = x[13] - x[5];
  115551. x[12] += x[4];
  115552. x[13] += x[5];
  115553. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115554. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115555. r0 = x[14] - x[6];
  115556. r1 = x[15] - x[7];
  115557. x[14] += x[6];
  115558. x[15] += x[7];
  115559. x[6] = r0;
  115560. x[7] = r1;
  115561. mdct_butterfly_8(x);
  115562. mdct_butterfly_8(x+8);
  115563. }
  115564. /* 32 point butterfly (in place, 4 register) */
  115565. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115566. REG_TYPE r0 = x[30] - x[14];
  115567. REG_TYPE r1 = x[31] - x[15];
  115568. x[30] += x[14];
  115569. x[31] += x[15];
  115570. x[14] = r0;
  115571. x[15] = r1;
  115572. r0 = x[28] - x[12];
  115573. r1 = x[29] - x[13];
  115574. x[28] += x[12];
  115575. x[29] += x[13];
  115576. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115577. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115578. r0 = x[26] - x[10];
  115579. r1 = x[27] - x[11];
  115580. x[26] += x[10];
  115581. x[27] += x[11];
  115582. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115583. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115584. r0 = x[24] - x[8];
  115585. r1 = x[25] - x[9];
  115586. x[24] += x[8];
  115587. x[25] += x[9];
  115588. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115589. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115590. r0 = x[22] - x[6];
  115591. r1 = x[7] - x[23];
  115592. x[22] += x[6];
  115593. x[23] += x[7];
  115594. x[6] = r1;
  115595. x[7] = r0;
  115596. r0 = x[4] - x[20];
  115597. r1 = x[5] - x[21];
  115598. x[20] += x[4];
  115599. x[21] += x[5];
  115600. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115601. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115602. r0 = x[2] - x[18];
  115603. r1 = x[3] - x[19];
  115604. x[18] += x[2];
  115605. x[19] += x[3];
  115606. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115607. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115608. r0 = x[0] - x[16];
  115609. r1 = x[1] - x[17];
  115610. x[16] += x[0];
  115611. x[17] += x[1];
  115612. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115613. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115614. mdct_butterfly_16(x);
  115615. mdct_butterfly_16(x+16);
  115616. }
  115617. /* N point first stage butterfly (in place, 2 register) */
  115618. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115619. DATA_TYPE *x,
  115620. int points){
  115621. DATA_TYPE *x1 = x + points - 8;
  115622. DATA_TYPE *x2 = x + (points>>1) - 8;
  115623. REG_TYPE r0;
  115624. REG_TYPE r1;
  115625. do{
  115626. r0 = x1[6] - x2[6];
  115627. r1 = x1[7] - x2[7];
  115628. x1[6] += x2[6];
  115629. x1[7] += x2[7];
  115630. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115631. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115632. r0 = x1[4] - x2[4];
  115633. r1 = x1[5] - x2[5];
  115634. x1[4] += x2[4];
  115635. x1[5] += x2[5];
  115636. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115637. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115638. r0 = x1[2] - x2[2];
  115639. r1 = x1[3] - x2[3];
  115640. x1[2] += x2[2];
  115641. x1[3] += x2[3];
  115642. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115643. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115644. r0 = x1[0] - x2[0];
  115645. r1 = x1[1] - x2[1];
  115646. x1[0] += x2[0];
  115647. x1[1] += x2[1];
  115648. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115649. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115650. x1-=8;
  115651. x2-=8;
  115652. T+=16;
  115653. }while(x2>=x);
  115654. }
  115655. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115656. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115657. DATA_TYPE *x,
  115658. int points,
  115659. int trigint){
  115660. DATA_TYPE *x1 = x + points - 8;
  115661. DATA_TYPE *x2 = x + (points>>1) - 8;
  115662. REG_TYPE r0;
  115663. REG_TYPE r1;
  115664. do{
  115665. r0 = x1[6] - x2[6];
  115666. r1 = x1[7] - x2[7];
  115667. x1[6] += x2[6];
  115668. x1[7] += x2[7];
  115669. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115670. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115671. T+=trigint;
  115672. r0 = x1[4] - x2[4];
  115673. r1 = x1[5] - x2[5];
  115674. x1[4] += x2[4];
  115675. x1[5] += x2[5];
  115676. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115677. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115678. T+=trigint;
  115679. r0 = x1[2] - x2[2];
  115680. r1 = x1[3] - x2[3];
  115681. x1[2] += x2[2];
  115682. x1[3] += x2[3];
  115683. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115684. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115685. T+=trigint;
  115686. r0 = x1[0] - x2[0];
  115687. r1 = x1[1] - x2[1];
  115688. x1[0] += x2[0];
  115689. x1[1] += x2[1];
  115690. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115691. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115692. T+=trigint;
  115693. x1-=8;
  115694. x2-=8;
  115695. }while(x2>=x);
  115696. }
  115697. STIN void mdct_butterflies(mdct_lookup *init,
  115698. DATA_TYPE *x,
  115699. int points){
  115700. DATA_TYPE *T=init->trig;
  115701. int stages=init->log2n-5;
  115702. int i,j;
  115703. if(--stages>0){
  115704. mdct_butterfly_first(T,x,points);
  115705. }
  115706. for(i=1;--stages>0;i++){
  115707. for(j=0;j<(1<<i);j++)
  115708. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115709. }
  115710. for(j=0;j<points;j+=32)
  115711. mdct_butterfly_32(x+j);
  115712. }
  115713. void mdct_clear(mdct_lookup *l){
  115714. if(l){
  115715. if(l->trig)_ogg_free(l->trig);
  115716. if(l->bitrev)_ogg_free(l->bitrev);
  115717. memset(l,0,sizeof(*l));
  115718. }
  115719. }
  115720. STIN void mdct_bitreverse(mdct_lookup *init,
  115721. DATA_TYPE *x){
  115722. int n = init->n;
  115723. int *bit = init->bitrev;
  115724. DATA_TYPE *w0 = x;
  115725. DATA_TYPE *w1 = x = w0+(n>>1);
  115726. DATA_TYPE *T = init->trig+n;
  115727. do{
  115728. DATA_TYPE *x0 = x+bit[0];
  115729. DATA_TYPE *x1 = x+bit[1];
  115730. REG_TYPE r0 = x0[1] - x1[1];
  115731. REG_TYPE r1 = x0[0] + x1[0];
  115732. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115733. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115734. w1 -= 4;
  115735. r0 = HALVE(x0[1] + x1[1]);
  115736. r1 = HALVE(x0[0] - x1[0]);
  115737. w0[0] = r0 + r2;
  115738. w1[2] = r0 - r2;
  115739. w0[1] = r1 + r3;
  115740. w1[3] = r3 - r1;
  115741. x0 = x+bit[2];
  115742. x1 = x+bit[3];
  115743. r0 = x0[1] - x1[1];
  115744. r1 = x0[0] + x1[0];
  115745. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115746. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115747. r0 = HALVE(x0[1] + x1[1]);
  115748. r1 = HALVE(x0[0] - x1[0]);
  115749. w0[2] = r0 + r2;
  115750. w1[0] = r0 - r2;
  115751. w0[3] = r1 + r3;
  115752. w1[1] = r3 - r1;
  115753. T += 4;
  115754. bit += 4;
  115755. w0 += 4;
  115756. }while(w0<w1);
  115757. }
  115758. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115759. int n=init->n;
  115760. int n2=n>>1;
  115761. int n4=n>>2;
  115762. /* rotate */
  115763. DATA_TYPE *iX = in+n2-7;
  115764. DATA_TYPE *oX = out+n2+n4;
  115765. DATA_TYPE *T = init->trig+n4;
  115766. do{
  115767. oX -= 4;
  115768. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115769. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115770. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115771. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115772. iX -= 8;
  115773. T += 4;
  115774. }while(iX>=in);
  115775. iX = in+n2-8;
  115776. oX = out+n2+n4;
  115777. T = init->trig+n4;
  115778. do{
  115779. T -= 4;
  115780. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115781. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115782. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115783. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115784. iX -= 8;
  115785. oX += 4;
  115786. }while(iX>=in);
  115787. mdct_butterflies(init,out+n2,n2);
  115788. mdct_bitreverse(init,out);
  115789. /* roatate + window */
  115790. {
  115791. DATA_TYPE *oX1=out+n2+n4;
  115792. DATA_TYPE *oX2=out+n2+n4;
  115793. DATA_TYPE *iX =out;
  115794. T =init->trig+n2;
  115795. do{
  115796. oX1-=4;
  115797. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115798. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115799. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115800. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115801. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115802. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115803. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115804. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115805. oX2+=4;
  115806. iX += 8;
  115807. T += 8;
  115808. }while(iX<oX1);
  115809. iX=out+n2+n4;
  115810. oX1=out+n4;
  115811. oX2=oX1;
  115812. do{
  115813. oX1-=4;
  115814. iX-=4;
  115815. oX2[0] = -(oX1[3] = iX[3]);
  115816. oX2[1] = -(oX1[2] = iX[2]);
  115817. oX2[2] = -(oX1[1] = iX[1]);
  115818. oX2[3] = -(oX1[0] = iX[0]);
  115819. oX2+=4;
  115820. }while(oX2<iX);
  115821. iX=out+n2+n4;
  115822. oX1=out+n2+n4;
  115823. oX2=out+n2;
  115824. do{
  115825. oX1-=4;
  115826. oX1[0]= iX[3];
  115827. oX1[1]= iX[2];
  115828. oX1[2]= iX[1];
  115829. oX1[3]= iX[0];
  115830. iX+=4;
  115831. }while(oX1>oX2);
  115832. }
  115833. }
  115834. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115835. int n=init->n;
  115836. int n2=n>>1;
  115837. int n4=n>>2;
  115838. int n8=n>>3;
  115839. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115840. DATA_TYPE *w2=w+n2;
  115841. /* rotate */
  115842. /* window + rotate + step 1 */
  115843. REG_TYPE r0;
  115844. REG_TYPE r1;
  115845. DATA_TYPE *x0=in+n2+n4;
  115846. DATA_TYPE *x1=x0+1;
  115847. DATA_TYPE *T=init->trig+n2;
  115848. int i=0;
  115849. for(i=0;i<n8;i+=2){
  115850. x0 -=4;
  115851. T-=2;
  115852. r0= x0[2] + x1[0];
  115853. r1= x0[0] + x1[2];
  115854. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115855. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115856. x1 +=4;
  115857. }
  115858. x1=in+1;
  115859. for(;i<n2-n8;i+=2){
  115860. T-=2;
  115861. x0 -=4;
  115862. r0= x0[2] - x1[0];
  115863. r1= x0[0] - x1[2];
  115864. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115865. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115866. x1 +=4;
  115867. }
  115868. x0=in+n;
  115869. for(;i<n2;i+=2){
  115870. T-=2;
  115871. x0 -=4;
  115872. r0= -x0[2] - x1[0];
  115873. r1= -x0[0] - x1[2];
  115874. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115875. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115876. x1 +=4;
  115877. }
  115878. mdct_butterflies(init,w+n2,n2);
  115879. mdct_bitreverse(init,w);
  115880. /* roatate + window */
  115881. T=init->trig+n2;
  115882. x0=out+n2;
  115883. for(i=0;i<n4;i++){
  115884. x0--;
  115885. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115886. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115887. w+=2;
  115888. T+=2;
  115889. }
  115890. }
  115891. #endif
  115892. /*** End of inlined file: mdct.c ***/
  115893. /*** Start of inlined file: psy.c ***/
  115894. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115895. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115896. // tasks..
  115897. #if JUCE_MSVC
  115898. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115899. #endif
  115900. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115901. #if JUCE_USE_OGGVORBIS
  115902. #include <stdlib.h>
  115903. #include <math.h>
  115904. #include <string.h>
  115905. /*** Start of inlined file: masking.h ***/
  115906. #ifndef _V_MASKING_H_
  115907. #define _V_MASKING_H_
  115908. /* more detailed ATH; the bass if flat to save stressing the floor
  115909. overly for only a bin or two of savings. */
  115910. #define MAX_ATH 88
  115911. static float ATH[]={
  115912. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115913. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115914. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115915. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115916. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115917. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115918. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115919. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115920. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115921. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115922. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115923. };
  115924. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115925. replaced by an empirically collected data set. The previously
  115926. published values were, far too often, simply on crack. */
  115927. #define EHMER_OFFSET 16
  115928. #define EHMER_MAX 56
  115929. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115930. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115931. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115932. for collection of these curves) */
  115933. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115934. /* 62.5 Hz */
  115935. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115936. -60, -60, -60, -60, -62, -62, -65, -73,
  115937. -69, -68, -68, -67, -70, -70, -72, -74,
  115938. -75, -79, -79, -80, -83, -88, -93, -100,
  115939. -110, -999, -999, -999, -999, -999, -999, -999,
  115940. -999, -999, -999, -999, -999, -999, -999, -999,
  115941. -999, -999, -999, -999, -999, -999, -999, -999},
  115942. { -48, -48, -48, -48, -48, -48, -48, -48,
  115943. -48, -48, -48, -48, -48, -53, -61, -66,
  115944. -66, -68, -67, -70, -76, -76, -72, -73,
  115945. -75, -76, -78, -79, -83, -88, -93, -100,
  115946. -110, -999, -999, -999, -999, -999, -999, -999,
  115947. -999, -999, -999, -999, -999, -999, -999, -999,
  115948. -999, -999, -999, -999, -999, -999, -999, -999},
  115949. { -37, -37, -37, -37, -37, -37, -37, -37,
  115950. -38, -40, -42, -46, -48, -53, -55, -62,
  115951. -65, -58, -56, -56, -61, -60, -65, -67,
  115952. -69, -71, -77, -77, -78, -80, -82, -84,
  115953. -88, -93, -98, -106, -112, -999, -999, -999,
  115954. -999, -999, -999, -999, -999, -999, -999, -999,
  115955. -999, -999, -999, -999, -999, -999, -999, -999},
  115956. { -25, -25, -25, -25, -25, -25, -25, -25,
  115957. -25, -26, -27, -29, -32, -38, -48, -52,
  115958. -52, -50, -48, -48, -51, -52, -54, -60,
  115959. -67, -67, -66, -68, -69, -73, -73, -76,
  115960. -80, -81, -81, -85, -85, -86, -88, -93,
  115961. -100, -110, -999, -999, -999, -999, -999, -999,
  115962. -999, -999, -999, -999, -999, -999, -999, -999},
  115963. { -16, -16, -16, -16, -16, -16, -16, -16,
  115964. -17, -19, -20, -22, -26, -28, -31, -40,
  115965. -47, -39, -39, -40, -42, -43, -47, -51,
  115966. -57, -52, -55, -55, -60, -58, -62, -63,
  115967. -70, -67, -69, -72, -73, -77, -80, -82,
  115968. -83, -87, -90, -94, -98, -104, -115, -999,
  115969. -999, -999, -999, -999, -999, -999, -999, -999},
  115970. { -8, -8, -8, -8, -8, -8, -8, -8,
  115971. -8, -8, -10, -11, -15, -19, -25, -30,
  115972. -34, -31, -30, -31, -29, -32, -35, -42,
  115973. -48, -42, -44, -46, -50, -50, -51, -52,
  115974. -59, -54, -55, -55, -58, -62, -63, -66,
  115975. -72, -73, -76, -75, -78, -80, -80, -81,
  115976. -84, -88, -90, -94, -98, -101, -106, -110}},
  115977. /* 88Hz */
  115978. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115979. -66, -66, -66, -66, -66, -67, -67, -67,
  115980. -76, -72, -71, -74, -76, -76, -75, -78,
  115981. -79, -79, -81, -83, -86, -89, -93, -97,
  115982. -100, -105, -110, -999, -999, -999, -999, -999,
  115983. -999, -999, -999, -999, -999, -999, -999, -999,
  115984. -999, -999, -999, -999, -999, -999, -999, -999},
  115985. { -47, -47, -47, -47, -47, -47, -47, -47,
  115986. -47, -47, -47, -48, -51, -55, -59, -66,
  115987. -66, -66, -67, -66, -68, -69, -70, -74,
  115988. -79, -77, -77, -78, -80, -81, -82, -84,
  115989. -86, -88, -91, -95, -100, -108, -116, -999,
  115990. -999, -999, -999, -999, -999, -999, -999, -999,
  115991. -999, -999, -999, -999, -999, -999, -999, -999},
  115992. { -36, -36, -36, -36, -36, -36, -36, -36,
  115993. -36, -37, -37, -41, -44, -48, -51, -58,
  115994. -62, -60, -57, -59, -59, -60, -63, -65,
  115995. -72, -71, -70, -72, -74, -77, -76, -78,
  115996. -81, -81, -80, -83, -86, -91, -96, -100,
  115997. -105, -110, -999, -999, -999, -999, -999, -999,
  115998. -999, -999, -999, -999, -999, -999, -999, -999},
  115999. { -28, -28, -28, -28, -28, -28, -28, -28,
  116000. -28, -30, -32, -32, -33, -35, -41, -49,
  116001. -50, -49, -47, -48, -48, -52, -51, -57,
  116002. -65, -61, -59, -61, -64, -69, -70, -74,
  116003. -77, -77, -78, -81, -84, -85, -87, -90,
  116004. -92, -96, -100, -107, -112, -999, -999, -999,
  116005. -999, -999, -999, -999, -999, -999, -999, -999},
  116006. { -19, -19, -19, -19, -19, -19, -19, -19,
  116007. -20, -21, -23, -27, -30, -35, -36, -41,
  116008. -46, -44, -42, -40, -41, -41, -43, -48,
  116009. -55, -53, -52, -53, -56, -59, -58, -60,
  116010. -67, -66, -69, -71, -72, -75, -79, -81,
  116011. -84, -87, -90, -93, -97, -101, -107, -114,
  116012. -999, -999, -999, -999, -999, -999, -999, -999},
  116013. { -9, -9, -9, -9, -9, -9, -9, -9,
  116014. -11, -12, -12, -15, -16, -20, -23, -30,
  116015. -37, -34, -33, -34, -31, -32, -32, -38,
  116016. -47, -44, -41, -40, -47, -49, -46, -46,
  116017. -58, -50, -50, -54, -58, -62, -64, -67,
  116018. -67, -70, -72, -76, -79, -83, -87, -91,
  116019. -96, -100, -104, -110, -999, -999, -999, -999}},
  116020. /* 125 Hz */
  116021. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116022. -62, -62, -63, -64, -66, -67, -66, -68,
  116023. -75, -72, -76, -75, -76, -78, -79, -82,
  116024. -84, -85, -90, -94, -101, -110, -999, -999,
  116025. -999, -999, -999, -999, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999,
  116027. -999, -999, -999, -999, -999, -999, -999, -999},
  116028. { -59, -59, -59, -59, -59, -59, -59, -59,
  116029. -59, -59, -59, -60, -60, -61, -63, -66,
  116030. -71, -68, -70, -70, -71, -72, -72, -75,
  116031. -81, -78, -79, -82, -83, -86, -90, -97,
  116032. -103, -113, -999, -999, -999, -999, -999, -999,
  116033. -999, -999, -999, -999, -999, -999, -999, -999,
  116034. -999, -999, -999, -999, -999, -999, -999, -999},
  116035. { -53, -53, -53, -53, -53, -53, -53, -53,
  116036. -53, -54, -55, -57, -56, -57, -55, -61,
  116037. -65, -60, -60, -62, -63, -63, -66, -68,
  116038. -74, -73, -75, -75, -78, -80, -80, -82,
  116039. -85, -90, -96, -101, -108, -999, -999, -999,
  116040. -999, -999, -999, -999, -999, -999, -999, -999,
  116041. -999, -999, -999, -999, -999, -999, -999, -999},
  116042. { -46, -46, -46, -46, -46, -46, -46, -46,
  116043. -46, -46, -47, -47, -47, -47, -48, -51,
  116044. -57, -51, -49, -50, -51, -53, -54, -59,
  116045. -66, -60, -62, -67, -67, -70, -72, -75,
  116046. -76, -78, -81, -85, -88, -94, -97, -104,
  116047. -112, -999, -999, -999, -999, -999, -999, -999,
  116048. -999, -999, -999, -999, -999, -999, -999, -999},
  116049. { -36, -36, -36, -36, -36, -36, -36, -36,
  116050. -39, -41, -42, -42, -39, -38, -41, -43,
  116051. -52, -44, -40, -39, -37, -37, -40, -47,
  116052. -54, -50, -48, -50, -55, -61, -59, -62,
  116053. -66, -66, -66, -69, -69, -73, -74, -74,
  116054. -75, -77, -79, -82, -87, -91, -95, -100,
  116055. -108, -115, -999, -999, -999, -999, -999, -999},
  116056. { -28, -26, -24, -22, -20, -20, -23, -29,
  116057. -30, -31, -28, -27, -28, -28, -28, -35,
  116058. -40, -33, -32, -29, -30, -30, -30, -37,
  116059. -45, -41, -37, -38, -45, -47, -47, -48,
  116060. -53, -49, -48, -50, -49, -49, -51, -52,
  116061. -58, -56, -57, -56, -60, -61, -62, -70,
  116062. -72, -74, -78, -83, -88, -93, -100, -106}},
  116063. /* 177 Hz */
  116064. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116065. -999, -110, -105, -100, -95, -91, -87, -83,
  116066. -80, -78, -76, -78, -78, -81, -83, -85,
  116067. -86, -85, -86, -87, -90, -97, -107, -999,
  116068. -999, -999, -999, -999, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999,
  116070. -999, -999, -999, -999, -999, -999, -999, -999},
  116071. {-999, -999, -999, -110, -105, -100, -95, -90,
  116072. -85, -81, -77, -73, -70, -67, -67, -68,
  116073. -75, -73, -70, -69, -70, -72, -75, -79,
  116074. -84, -83, -84, -86, -88, -89, -89, -93,
  116075. -98, -105, -112, -999, -999, -999, -999, -999,
  116076. -999, -999, -999, -999, -999, -999, -999, -999,
  116077. -999, -999, -999, -999, -999, -999, -999, -999},
  116078. {-105, -100, -95, -90, -85, -80, -76, -71,
  116079. -68, -68, -65, -63, -63, -62, -62, -64,
  116080. -65, -64, -61, -62, -63, -64, -66, -68,
  116081. -73, -73, -74, -75, -76, -81, -83, -85,
  116082. -88, -89, -92, -95, -100, -108, -999, -999,
  116083. -999, -999, -999, -999, -999, -999, -999, -999,
  116084. -999, -999, -999, -999, -999, -999, -999, -999},
  116085. { -80, -75, -71, -68, -65, -63, -62, -61,
  116086. -61, -61, -61, -59, -56, -57, -53, -50,
  116087. -58, -52, -50, -50, -52, -53, -54, -58,
  116088. -67, -63, -67, -68, -72, -75, -78, -80,
  116089. -81, -81, -82, -85, -89, -90, -93, -97,
  116090. -101, -107, -114, -999, -999, -999, -999, -999,
  116091. -999, -999, -999, -999, -999, -999, -999, -999},
  116092. { -65, -61, -59, -57, -56, -55, -55, -56,
  116093. -56, -57, -55, -53, -52, -47, -44, -44,
  116094. -50, -44, -41, -39, -39, -42, -40, -46,
  116095. -51, -49, -50, -53, -54, -63, -60, -61,
  116096. -62, -66, -66, -66, -70, -73, -74, -75,
  116097. -76, -75, -79, -85, -89, -91, -96, -102,
  116098. -110, -999, -999, -999, -999, -999, -999, -999},
  116099. { -52, -50, -49, -49, -48, -48, -48, -49,
  116100. -50, -50, -49, -46, -43, -39, -35, -33,
  116101. -38, -36, -32, -29, -32, -32, -32, -35,
  116102. -44, -39, -38, -38, -46, -50, -45, -46,
  116103. -53, -50, -50, -50, -54, -54, -53, -53,
  116104. -56, -57, -59, -66, -70, -72, -74, -79,
  116105. -83, -85, -90, -97, -114, -999, -999, -999}},
  116106. /* 250 Hz */
  116107. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116108. -100, -95, -90, -86, -80, -75, -75, -79,
  116109. -80, -79, -80, -81, -82, -88, -95, -103,
  116110. -110, -999, -999, -999, -999, -999, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999,
  116113. -999, -999, -999, -999, -999, -999, -999, -999},
  116114. {-999, -999, -999, -999, -108, -103, -98, -93,
  116115. -88, -83, -79, -78, -75, -71, -67, -68,
  116116. -73, -73, -72, -73, -75, -77, -80, -82,
  116117. -88, -93, -100, -107, -114, -999, -999, -999,
  116118. -999, -999, -999, -999, -999, -999, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999,
  116120. -999, -999, -999, -999, -999, -999, -999, -999},
  116121. {-999, -999, -999, -110, -105, -101, -96, -90,
  116122. -86, -81, -77, -73, -69, -66, -61, -62,
  116123. -66, -64, -62, -65, -66, -70, -72, -76,
  116124. -81, -80, -84, -90, -95, -102, -110, -999,
  116125. -999, -999, -999, -999, -999, -999, -999, -999,
  116126. -999, -999, -999, -999, -999, -999, -999, -999,
  116127. -999, -999, -999, -999, -999, -999, -999, -999},
  116128. {-999, -999, -999, -107, -103, -97, -92, -88,
  116129. -83, -79, -74, -70, -66, -59, -53, -58,
  116130. -62, -55, -54, -54, -54, -58, -61, -62,
  116131. -72, -70, -72, -75, -78, -80, -81, -80,
  116132. -83, -83, -88, -93, -100, -107, -115, -999,
  116133. -999, -999, -999, -999, -999, -999, -999, -999,
  116134. -999, -999, -999, -999, -999, -999, -999, -999},
  116135. {-999, -999, -999, -105, -100, -95, -90, -85,
  116136. -80, -75, -70, -66, -62, -56, -48, -44,
  116137. -48, -46, -46, -43, -46, -48, -48, -51,
  116138. -58, -58, -59, -60, -62, -62, -61, -61,
  116139. -65, -64, -65, -68, -70, -74, -75, -78,
  116140. -81, -86, -95, -110, -999, -999, -999, -999,
  116141. -999, -999, -999, -999, -999, -999, -999, -999},
  116142. {-999, -999, -105, -100, -95, -90, -85, -80,
  116143. -75, -70, -65, -61, -55, -49, -39, -33,
  116144. -40, -35, -32, -38, -40, -33, -35, -37,
  116145. -46, -41, -45, -44, -46, -42, -45, -46,
  116146. -52, -50, -50, -50, -54, -54, -55, -57,
  116147. -62, -64, -66, -68, -70, -76, -81, -90,
  116148. -100, -110, -999, -999, -999, -999, -999, -999}},
  116149. /* 354 hz */
  116150. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116151. -105, -98, -90, -85, -82, -83, -80, -78,
  116152. -84, -79, -80, -83, -87, -89, -91, -93,
  116153. -99, -106, -117, -999, -999, -999, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999,
  116156. -999, -999, -999, -999, -999, -999, -999, -999},
  116157. {-999, -999, -999, -999, -999, -999, -999, -999,
  116158. -105, -98, -90, -85, -80, -75, -70, -68,
  116159. -74, -72, -74, -77, -80, -82, -85, -87,
  116160. -92, -89, -91, -95, -100, -106, -112, -999,
  116161. -999, -999, -999, -999, -999, -999, -999, -999,
  116162. -999, -999, -999, -999, -999, -999, -999, -999,
  116163. -999, -999, -999, -999, -999, -999, -999, -999},
  116164. {-999, -999, -999, -999, -999, -999, -999, -999,
  116165. -105, -98, -90, -83, -75, -71, -63, -64,
  116166. -67, -62, -64, -67, -70, -73, -77, -81,
  116167. -84, -83, -85, -89, -90, -93, -98, -104,
  116168. -109, -114, -999, -999, -999, -999, -999, -999,
  116169. -999, -999, -999, -999, -999, -999, -999, -999,
  116170. -999, -999, -999, -999, -999, -999, -999, -999},
  116171. {-999, -999, -999, -999, -999, -999, -999, -999,
  116172. -103, -96, -88, -81, -75, -68, -58, -54,
  116173. -56, -54, -56, -56, -58, -60, -63, -66,
  116174. -74, -69, -72, -72, -75, -74, -77, -81,
  116175. -81, -82, -84, -87, -93, -96, -99, -104,
  116176. -110, -999, -999, -999, -999, -999, -999, -999,
  116177. -999, -999, -999, -999, -999, -999, -999, -999},
  116178. {-999, -999, -999, -999, -999, -108, -102, -96,
  116179. -91, -85, -80, -74, -68, -60, -51, -46,
  116180. -48, -46, -43, -45, -47, -47, -49, -48,
  116181. -56, -53, -55, -58, -57, -63, -58, -60,
  116182. -66, -64, -67, -70, -70, -74, -77, -84,
  116183. -86, -89, -91, -93, -94, -101, -109, -118,
  116184. -999, -999, -999, -999, -999, -999, -999, -999},
  116185. {-999, -999, -999, -108, -103, -98, -93, -88,
  116186. -83, -78, -73, -68, -60, -53, -44, -35,
  116187. -38, -38, -34, -34, -36, -40, -41, -44,
  116188. -51, -45, -46, -47, -46, -54, -50, -49,
  116189. -50, -50, -50, -51, -54, -57, -58, -60,
  116190. -66, -66, -66, -64, -65, -68, -77, -82,
  116191. -87, -95, -110, -999, -999, -999, -999, -999}},
  116192. /* 500 Hz */
  116193. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116194. -107, -102, -97, -92, -87, -83, -78, -75,
  116195. -82, -79, -83, -85, -89, -92, -95, -98,
  116196. -101, -105, -109, -113, -999, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999,
  116199. -999, -999, -999, -999, -999, -999, -999, -999},
  116200. {-999, -999, -999, -999, -999, -999, -999, -106,
  116201. -100, -95, -90, -86, -81, -78, -74, -69,
  116202. -74, -74, -76, -79, -83, -84, -86, -89,
  116203. -92, -97, -93, -100, -103, -107, -110, -999,
  116204. -999, -999, -999, -999, -999, -999, -999, -999,
  116205. -999, -999, -999, -999, -999, -999, -999, -999,
  116206. -999, -999, -999, -999, -999, -999, -999, -999},
  116207. {-999, -999, -999, -999, -999, -999, -106, -100,
  116208. -95, -90, -87, -83, -80, -75, -69, -60,
  116209. -66, -66, -68, -70, -74, -78, -79, -81,
  116210. -81, -83, -84, -87, -93, -96, -99, -103,
  116211. -107, -110, -999, -999, -999, -999, -999, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999,
  116213. -999, -999, -999, -999, -999, -999, -999, -999},
  116214. {-999, -999, -999, -999, -999, -108, -103, -98,
  116215. -93, -89, -85, -82, -78, -71, -62, -55,
  116216. -58, -58, -54, -54, -55, -59, -61, -62,
  116217. -70, -66, -66, -67, -70, -72, -75, -78,
  116218. -84, -84, -84, -88, -91, -90, -95, -98,
  116219. -102, -103, -106, -110, -999, -999, -999, -999,
  116220. -999, -999, -999, -999, -999, -999, -999, -999},
  116221. {-999, -999, -999, -999, -108, -103, -98, -94,
  116222. -90, -87, -82, -79, -73, -67, -58, -47,
  116223. -50, -45, -41, -45, -48, -44, -44, -49,
  116224. -54, -51, -48, -47, -49, -50, -51, -57,
  116225. -58, -60, -63, -69, -70, -69, -71, -74,
  116226. -78, -82, -90, -95, -101, -105, -110, -999,
  116227. -999, -999, -999, -999, -999, -999, -999, -999},
  116228. {-999, -999, -999, -105, -101, -97, -93, -90,
  116229. -85, -80, -77, -72, -65, -56, -48, -37,
  116230. -40, -36, -34, -40, -50, -47, -38, -41,
  116231. -47, -38, -35, -39, -38, -43, -40, -45,
  116232. -50, -45, -44, -47, -50, -55, -48, -48,
  116233. -52, -66, -70, -76, -82, -90, -97, -105,
  116234. -110, -999, -999, -999, -999, -999, -999, -999}},
  116235. /* 707 Hz */
  116236. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116237. -999, -108, -103, -98, -93, -86, -79, -76,
  116238. -83, -81, -85, -87, -89, -93, -98, -102,
  116239. -107, -112, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999,
  116242. -999, -999, -999, -999, -999, -999, -999, -999},
  116243. {-999, -999, -999, -999, -999, -999, -999, -999,
  116244. -999, -108, -103, -98, -93, -86, -79, -71,
  116245. -77, -74, -77, -79, -81, -84, -85, -90,
  116246. -92, -93, -92, -98, -101, -108, -112, -999,
  116247. -999, -999, -999, -999, -999, -999, -999, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999,
  116249. -999, -999, -999, -999, -999, -999, -999, -999},
  116250. {-999, -999, -999, -999, -999, -999, -999, -999,
  116251. -108, -103, -98, -93, -87, -78, -68, -65,
  116252. -66, -62, -65, -67, -70, -73, -75, -78,
  116253. -82, -82, -83, -84, -91, -93, -98, -102,
  116254. -106, -110, -999, -999, -999, -999, -999, -999,
  116255. -999, -999, -999, -999, -999, -999, -999, -999,
  116256. -999, -999, -999, -999, -999, -999, -999, -999},
  116257. {-999, -999, -999, -999, -999, -999, -999, -999,
  116258. -105, -100, -95, -90, -82, -74, -62, -57,
  116259. -58, -56, -51, -52, -52, -54, -54, -58,
  116260. -66, -59, -60, -63, -66, -69, -73, -79,
  116261. -83, -84, -80, -81, -81, -82, -88, -92,
  116262. -98, -105, -113, -999, -999, -999, -999, -999,
  116263. -999, -999, -999, -999, -999, -999, -999, -999},
  116264. {-999, -999, -999, -999, -999, -999, -999, -107,
  116265. -102, -97, -92, -84, -79, -69, -57, -47,
  116266. -52, -47, -44, -45, -50, -52, -42, -42,
  116267. -53, -43, -43, -48, -51, -56, -55, -52,
  116268. -57, -59, -61, -62, -67, -71, -78, -83,
  116269. -86, -94, -98, -103, -110, -999, -999, -999,
  116270. -999, -999, -999, -999, -999, -999, -999, -999},
  116271. {-999, -999, -999, -999, -999, -999, -105, -100,
  116272. -95, -90, -84, -78, -70, -61, -51, -41,
  116273. -40, -38, -40, -46, -52, -51, -41, -40,
  116274. -46, -40, -38, -38, -41, -46, -41, -46,
  116275. -47, -43, -43, -45, -41, -45, -56, -67,
  116276. -68, -83, -87, -90, -95, -102, -107, -113,
  116277. -999, -999, -999, -999, -999, -999, -999, -999}},
  116278. /* 1000 Hz */
  116279. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116280. -999, -109, -105, -101, -96, -91, -84, -77,
  116281. -82, -82, -85, -89, -94, -100, -106, -110,
  116282. -999, -999, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999,
  116285. -999, -999, -999, -999, -999, -999, -999, -999},
  116286. {-999, -999, -999, -999, -999, -999, -999, -999,
  116287. -999, -106, -103, -98, -92, -85, -80, -71,
  116288. -75, -72, -76, -80, -84, -86, -89, -93,
  116289. -100, -107, -113, -999, -999, -999, -999, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999,
  116291. -999, -999, -999, -999, -999, -999, -999, -999,
  116292. -999, -999, -999, -999, -999, -999, -999, -999},
  116293. {-999, -999, -999, -999, -999, -999, -999, -107,
  116294. -104, -101, -97, -92, -88, -84, -80, -64,
  116295. -66, -63, -64, -66, -69, -73, -77, -83,
  116296. -83, -86, -91, -98, -104, -111, -999, -999,
  116297. -999, -999, -999, -999, -999, -999, -999, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999,
  116299. -999, -999, -999, -999, -999, -999, -999, -999},
  116300. {-999, -999, -999, -999, -999, -999, -999, -107,
  116301. -104, -101, -97, -92, -90, -84, -74, -57,
  116302. -58, -52, -55, -54, -50, -52, -50, -52,
  116303. -63, -62, -69, -76, -77, -78, -78, -79,
  116304. -82, -88, -94, -100, -106, -111, -999, -999,
  116305. -999, -999, -999, -999, -999, -999, -999, -999,
  116306. -999, -999, -999, -999, -999, -999, -999, -999},
  116307. {-999, -999, -999, -999, -999, -999, -106, -102,
  116308. -98, -95, -90, -85, -83, -78, -70, -50,
  116309. -50, -41, -44, -49, -47, -50, -50, -44,
  116310. -55, -46, -47, -48, -48, -54, -49, -49,
  116311. -58, -62, -71, -81, -87, -92, -97, -102,
  116312. -108, -114, -999, -999, -999, -999, -999, -999,
  116313. -999, -999, -999, -999, -999, -999, -999, -999},
  116314. {-999, -999, -999, -999, -999, -999, -106, -102,
  116315. -98, -95, -90, -85, -83, -78, -70, -45,
  116316. -43, -41, -47, -50, -51, -50, -49, -45,
  116317. -47, -41, -44, -41, -39, -43, -38, -37,
  116318. -40, -41, -44, -50, -58, -65, -73, -79,
  116319. -85, -92, -97, -101, -105, -109, -113, -999,
  116320. -999, -999, -999, -999, -999, -999, -999, -999}},
  116321. /* 1414 Hz */
  116322. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116323. -999, -999, -999, -107, -100, -95, -87, -81,
  116324. -85, -83, -88, -93, -100, -107, -114, -999,
  116325. -999, -999, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999,
  116327. -999, -999, -999, -999, -999, -999, -999, -999,
  116328. -999, -999, -999, -999, -999, -999, -999, -999},
  116329. {-999, -999, -999, -999, -999, -999, -999, -999,
  116330. -999, -999, -107, -101, -95, -88, -83, -76,
  116331. -73, -72, -79, -84, -90, -95, -100, -105,
  116332. -110, -115, -999, -999, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999,
  116334. -999, -999, -999, -999, -999, -999, -999, -999,
  116335. -999, -999, -999, -999, -999, -999, -999, -999},
  116336. {-999, -999, -999, -999, -999, -999, -999, -999,
  116337. -999, -999, -104, -98, -92, -87, -81, -70,
  116338. -65, -62, -67, -71, -74, -80, -85, -91,
  116339. -95, -99, -103, -108, -111, -114, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999,
  116342. -999, -999, -999, -999, -999, -999, -999, -999},
  116343. {-999, -999, -999, -999, -999, -999, -999, -999,
  116344. -999, -999, -103, -97, -90, -85, -76, -60,
  116345. -56, -54, -60, -62, -61, -56, -63, -65,
  116346. -73, -74, -77, -75, -78, -81, -86, -87,
  116347. -88, -91, -94, -98, -103, -110, -999, -999,
  116348. -999, -999, -999, -999, -999, -999, -999, -999,
  116349. -999, -999, -999, -999, -999, -999, -999, -999},
  116350. {-999, -999, -999, -999, -999, -999, -999, -105,
  116351. -100, -97, -92, -86, -81, -79, -70, -57,
  116352. -51, -47, -51, -58, -60, -56, -53, -50,
  116353. -58, -52, -50, -50, -53, -55, -64, -69,
  116354. -71, -85, -82, -78, -81, -85, -95, -102,
  116355. -112, -999, -999, -999, -999, -999, -999, -999,
  116356. -999, -999, -999, -999, -999, -999, -999, -999},
  116357. {-999, -999, -999, -999, -999, -999, -999, -105,
  116358. -100, -97, -92, -85, -83, -79, -72, -49,
  116359. -40, -43, -43, -54, -56, -51, -50, -40,
  116360. -43, -38, -36, -35, -37, -38, -37, -44,
  116361. -54, -60, -57, -60, -70, -75, -84, -92,
  116362. -103, -112, -999, -999, -999, -999, -999, -999,
  116363. -999, -999, -999, -999, -999, -999, -999, -999}},
  116364. /* 2000 Hz */
  116365. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116366. -999, -999, -999, -110, -102, -95, -89, -82,
  116367. -83, -84, -90, -92, -99, -107, -113, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999,
  116370. -999, -999, -999, -999, -999, -999, -999, -999,
  116371. -999, -999, -999, -999, -999, -999, -999, -999},
  116372. {-999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -107, -101, -95, -89, -83, -72,
  116374. -74, -78, -85, -88, -88, -90, -92, -98,
  116375. -105, -111, -999, -999, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999,
  116377. -999, -999, -999, -999, -999, -999, -999, -999,
  116378. -999, -999, -999, -999, -999, -999, -999, -999},
  116379. {-999, -999, -999, -999, -999, -999, -999, -999,
  116380. -999, -109, -103, -97, -93, -87, -81, -70,
  116381. -70, -67, -75, -73, -76, -79, -81, -83,
  116382. -88, -89, -97, -103, -110, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999,
  116385. -999, -999, -999, -999, -999, -999, -999, -999},
  116386. {-999, -999, -999, -999, -999, -999, -999, -999,
  116387. -999, -107, -100, -94, -88, -83, -75, -63,
  116388. -59, -59, -63, -66, -60, -62, -67, -67,
  116389. -77, -76, -81, -88, -86, -92, -96, -102,
  116390. -109, -116, -999, -999, -999, -999, -999, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999,
  116392. -999, -999, -999, -999, -999, -999, -999, -999},
  116393. {-999, -999, -999, -999, -999, -999, -999, -999,
  116394. -999, -105, -98, -92, -86, -81, -73, -56,
  116395. -52, -47, -55, -60, -58, -52, -51, -45,
  116396. -49, -50, -53, -54, -61, -71, -70, -69,
  116397. -78, -79, -87, -90, -96, -104, -112, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999},
  116400. {-999, -999, -999, -999, -999, -999, -999, -999,
  116401. -999, -103, -96, -90, -86, -78, -70, -51,
  116402. -42, -47, -48, -55, -54, -54, -53, -42,
  116403. -35, -28, -33, -38, -37, -44, -47, -49,
  116404. -54, -63, -68, -78, -82, -89, -94, -99,
  116405. -104, -109, -114, -999, -999, -999, -999, -999,
  116406. -999, -999, -999, -999, -999, -999, -999, -999}},
  116407. /* 2828 Hz */
  116408. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -110, -100, -90, -79,
  116410. -85, -81, -82, -82, -89, -94, -99, -103,
  116411. -109, -115, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999,
  116413. -999, -999, -999, -999, -999, -999, -999, -999,
  116414. -999, -999, -999, -999, -999, -999, -999, -999},
  116415. {-999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -105, -97, -85, -72,
  116417. -74, -70, -70, -70, -76, -85, -91, -93,
  116418. -97, -103, -109, -115, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999,
  116421. -999, -999, -999, -999, -999, -999, -999, -999},
  116422. {-999, -999, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -112, -93, -81, -68,
  116424. -62, -60, -60, -57, -63, -70, -77, -82,
  116425. -90, -93, -98, -104, -109, -113, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999,
  116428. -999, -999, -999, -999, -999, -999, -999, -999},
  116429. {-999, -999, -999, -999, -999, -999, -999, -999,
  116430. -999, -999, -999, -113, -100, -93, -84, -63,
  116431. -58, -48, -53, -54, -52, -52, -57, -64,
  116432. -66, -76, -83, -81, -85, -85, -90, -95,
  116433. -98, -101, -103, -106, -108, -111, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999,
  116435. -999, -999, -999, -999, -999, -999, -999, -999},
  116436. {-999, -999, -999, -999, -999, -999, -999, -999,
  116437. -999, -999, -999, -105, -95, -86, -74, -53,
  116438. -50, -38, -43, -49, -43, -42, -39, -39,
  116439. -46, -52, -57, -56, -72, -69, -74, -81,
  116440. -87, -92, -94, -97, -99, -102, -105, -108,
  116441. -999, -999, -999, -999, -999, -999, -999, -999,
  116442. -999, -999, -999, -999, -999, -999, -999, -999},
  116443. {-999, -999, -999, -999, -999, -999, -999, -999,
  116444. -999, -999, -108, -99, -90, -76, -66, -45,
  116445. -43, -41, -44, -47, -43, -47, -40, -30,
  116446. -31, -31, -39, -33, -40, -41, -43, -53,
  116447. -59, -70, -73, -77, -79, -82, -84, -87,
  116448. -999, -999, -999, -999, -999, -999, -999, -999,
  116449. -999, -999, -999, -999, -999, -999, -999, -999}},
  116450. /* 4000 Hz */
  116451. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -110, -91, -76,
  116453. -75, -85, -93, -98, -104, -110, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999,
  116456. -999, -999, -999, -999, -999, -999, -999, -999,
  116457. -999, -999, -999, -999, -999, -999, -999, -999},
  116458. {-999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -110, -91, -70,
  116460. -70, -75, -86, -89, -94, -98, -101, -106,
  116461. -110, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -999, -999, -999, -999, -999, -999, -999},
  116465. {-999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -110, -95, -80, -60,
  116467. -65, -64, -74, -83, -88, -91, -95, -99,
  116468. -103, -107, -110, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999,
  116471. -999, -999, -999, -999, -999, -999, -999, -999},
  116472. {-999, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -110, -95, -80, -58,
  116474. -55, -49, -66, -68, -71, -78, -78, -80,
  116475. -88, -85, -89, -97, -100, -105, -110, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999,
  116478. -999, -999, -999, -999, -999, -999, -999, -999},
  116479. {-999, -999, -999, -999, -999, -999, -999, -999,
  116480. -999, -999, -999, -999, -110, -95, -80, -53,
  116481. -52, -41, -59, -59, -49, -58, -56, -63,
  116482. -86, -79, -90, -93, -98, -103, -107, -112,
  116483. -999, -999, -999, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999,
  116485. -999, -999, -999, -999, -999, -999, -999, -999},
  116486. {-999, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -110, -97, -91, -73, -45,
  116488. -40, -33, -53, -61, -49, -54, -50, -50,
  116489. -60, -52, -67, -74, -81, -92, -96, -100,
  116490. -105, -110, -999, -999, -999, -999, -999, -999,
  116491. -999, -999, -999, -999, -999, -999, -999, -999,
  116492. -999, -999, -999, -999, -999, -999, -999, -999}},
  116493. /* 5657 Hz */
  116494. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116495. -999, -999, -999, -113, -106, -99, -92, -77,
  116496. -80, -88, -97, -106, -115, -999, -999, -999,
  116497. -999, -999, -999, -999, -999, -999, -999, -999,
  116498. -999, -999, -999, -999, -999, -999, -999, -999,
  116499. -999, -999, -999, -999, -999, -999, -999, -999,
  116500. -999, -999, -999, -999, -999, -999, -999, -999},
  116501. {-999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -116, -109, -102, -95, -89, -74,
  116503. -72, -88, -87, -95, -102, -109, -116, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999,
  116507. -999, -999, -999, -999, -999, -999, -999, -999},
  116508. {-999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -116, -109, -102, -95, -89, -75,
  116510. -66, -74, -77, -78, -86, -87, -90, -96,
  116511. -105, -115, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999,
  116514. -999, -999, -999, -999, -999, -999, -999, -999},
  116515. {-999, -999, -999, -999, -999, -999, -999, -999,
  116516. -999, -999, -115, -108, -101, -94, -88, -66,
  116517. -56, -61, -70, -65, -78, -72, -83, -84,
  116518. -93, -98, -105, -110, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999,
  116520. -999, -999, -999, -999, -999, -999, -999, -999,
  116521. -999, -999, -999, -999, -999, -999, -999, -999},
  116522. {-999, -999, -999, -999, -999, -999, -999, -999,
  116523. -999, -999, -110, -105, -95, -89, -82, -57,
  116524. -52, -52, -59, -56, -59, -58, -69, -67,
  116525. -88, -82, -82, -89, -94, -100, -108, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999,
  116528. -999, -999, -999, -999, -999, -999, -999, -999},
  116529. {-999, -999, -999, -999, -999, -999, -999, -999,
  116530. -999, -110, -101, -96, -90, -83, -77, -54,
  116531. -43, -38, -50, -48, -52, -48, -42, -42,
  116532. -51, -52, -53, -59, -65, -71, -78, -85,
  116533. -95, -999, -999, -999, -999, -999, -999, -999,
  116534. -999, -999, -999, -999, -999, -999, -999, -999,
  116535. -999, -999, -999, -999, -999, -999, -999, -999}},
  116536. /* 8000 Hz */
  116537. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116538. -999, -999, -999, -999, -120, -105, -86, -68,
  116539. -78, -79, -90, -100, -110, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -999, -999, -999, -999, -999, -999, -999,
  116542. -999, -999, -999, -999, -999, -999, -999, -999,
  116543. -999, -999, -999, -999, -999, -999, -999, -999},
  116544. {-999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -120, -105, -86, -66,
  116546. -73, -77, -88, -96, -105, -115, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999,
  116549. -999, -999, -999, -999, -999, -999, -999, -999,
  116550. -999, -999, -999, -999, -999, -999, -999, -999},
  116551. {-999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -120, -105, -92, -80, -61,
  116553. -64, -68, -80, -87, -92, -100, -110, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999,
  116556. -999, -999, -999, -999, -999, -999, -999, -999,
  116557. -999, -999, -999, -999, -999, -999, -999, -999},
  116558. {-999, -999, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -120, -104, -91, -79, -52,
  116560. -60, -54, -64, -69, -77, -80, -82, -84,
  116561. -85, -87, -88, -90, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999,
  116564. -999, -999, -999, -999, -999, -999, -999, -999},
  116565. {-999, -999, -999, -999, -999, -999, -999, -999,
  116566. -999, -999, -999, -118, -100, -87, -77, -49,
  116567. -50, -44, -58, -61, -61, -67, -65, -62,
  116568. -62, -62, -65, -68, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999,
  116571. -999, -999, -999, -999, -999, -999, -999, -999},
  116572. {-999, -999, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -115, -98, -84, -62, -49,
  116574. -44, -38, -46, -49, -49, -46, -39, -37,
  116575. -39, -40, -42, -43, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999,
  116577. -999, -999, -999, -999, -999, -999, -999, -999,
  116578. -999, -999, -999, -999, -999, -999, -999, -999}},
  116579. /* 11314 Hz */
  116580. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -999, -110, -88, -74,
  116582. -77, -82, -82, -85, -90, -94, -99, -104,
  116583. -999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -999, -999, -999, -999, -999, -999, -999,
  116585. -999, -999, -999, -999, -999, -999, -999, -999,
  116586. -999, -999, -999, -999, -999, -999, -999, -999},
  116587. {-999, -999, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -110, -88, -66,
  116589. -70, -81, -80, -81, -84, -88, -91, -93,
  116590. -999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999,
  116592. -999, -999, -999, -999, -999, -999, -999, -999,
  116593. -999, -999, -999, -999, -999, -999, -999, -999},
  116594. {-999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -110, -88, -61,
  116596. -63, -70, -71, -74, -77, -80, -83, -85,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999,
  116600. -999, -999, -999, -999, -999, -999, -999, -999},
  116601. {-999, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -110, -86, -62,
  116603. -63, -62, -62, -58, -52, -50, -50, -52,
  116604. -54, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999,
  116607. -999, -999, -999, -999, -999, -999, -999, -999},
  116608. {-999, -999, -999, -999, -999, -999, -999, -999,
  116609. -999, -999, -999, -999, -118, -108, -84, -53,
  116610. -50, -50, -50, -55, -47, -45, -40, -40,
  116611. -40, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999,
  116614. -999, -999, -999, -999, -999, -999, -999, -999},
  116615. {-999, -999, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -118, -100, -73, -43,
  116617. -37, -42, -43, -53, -38, -37, -35, -35,
  116618. -38, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999,
  116621. -999, -999, -999, -999, -999, -999, -999, -999}},
  116622. /* 16000 Hz */
  116623. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -999, -110, -100, -91, -84, -74,
  116625. -80, -80, -80, -80, -80, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -999, -999, -999, -999, -999, -999,
  116628. -999, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999},
  116630. {-999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -110, -100, -91, -84, -74,
  116632. -68, -68, -68, -68, -68, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999,
  116636. -999, -999, -999, -999, -999, -999, -999, -999},
  116637. {-999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -110, -100, -86, -78, -70,
  116639. -60, -45, -30, -21, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999,
  116642. -999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -999, -999, -999, -999, -999, -999, -999},
  116644. {-999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -999, -999, -110, -100, -87, -78, -67,
  116646. -48, -38, -29, -21, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -999, -999, -999, -999, -999, -999, -999},
  116651. {-999, -999, -999, -999, -999, -999, -999, -999,
  116652. -999, -999, -999, -110, -100, -86, -69, -56,
  116653. -45, -35, -33, -29, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -999, -999, -999, -999, -999, -999, -999},
  116658. {-999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -110, -100, -83, -71, -48,
  116660. -27, -38, -37, -34, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -999, -999, -999, -999, -999, -999, -999,
  116664. -999, -999, -999, -999, -999, -999, -999, -999}}
  116665. };
  116666. #endif
  116667. /*** End of inlined file: masking.h ***/
  116668. #define NEGINF -9999.f
  116669. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116670. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116671. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116672. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116673. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116674. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116675. look->channels=vi->channels;
  116676. look->ampmax=-9999.;
  116677. look->gi=gi;
  116678. return(look);
  116679. }
  116680. void _vp_global_free(vorbis_look_psy_global *look){
  116681. if(look){
  116682. memset(look,0,sizeof(*look));
  116683. _ogg_free(look);
  116684. }
  116685. }
  116686. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116687. if(i){
  116688. memset(i,0,sizeof(*i));
  116689. _ogg_free(i);
  116690. }
  116691. }
  116692. void _vi_psy_free(vorbis_info_psy *i){
  116693. if(i){
  116694. memset(i,0,sizeof(*i));
  116695. _ogg_free(i);
  116696. }
  116697. }
  116698. static void min_curve(float *c,
  116699. float *c2){
  116700. int i;
  116701. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116702. }
  116703. static void max_curve(float *c,
  116704. float *c2){
  116705. int i;
  116706. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116707. }
  116708. static void attenuate_curve(float *c,float att){
  116709. int i;
  116710. for(i=0;i<EHMER_MAX;i++)
  116711. c[i]+=att;
  116712. }
  116713. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116714. float center_boost, float center_decay_rate){
  116715. int i,j,k,m;
  116716. float ath[EHMER_MAX];
  116717. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116718. float athc[P_LEVELS][EHMER_MAX];
  116719. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116720. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116721. memset(workc,0,sizeof(workc));
  116722. for(i=0;i<P_BANDS;i++){
  116723. /* we add back in the ATH to avoid low level curves falling off to
  116724. -infinity and unnecessarily cutting off high level curves in the
  116725. curve limiting (last step). */
  116726. /* A half-band's settings must be valid over the whole band, and
  116727. it's better to mask too little than too much */
  116728. int ath_offset=i*4;
  116729. for(j=0;j<EHMER_MAX;j++){
  116730. float min=999.;
  116731. for(k=0;k<4;k++)
  116732. if(j+k+ath_offset<MAX_ATH){
  116733. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116734. }else{
  116735. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116736. }
  116737. ath[j]=min;
  116738. }
  116739. /* copy curves into working space, replicate the 50dB curve to 30
  116740. and 40, replicate the 100dB curve to 110 */
  116741. for(j=0;j<6;j++)
  116742. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116743. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116744. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116745. /* apply centered curve boost/decay */
  116746. for(j=0;j<P_LEVELS;j++){
  116747. for(k=0;k<EHMER_MAX;k++){
  116748. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116749. if(adj<0. && center_boost>0)adj=0.;
  116750. if(adj>0. && center_boost<0)adj=0.;
  116751. workc[i][j][k]+=adj;
  116752. }
  116753. }
  116754. /* normalize curves so the driving amplitude is 0dB */
  116755. /* make temp curves with the ATH overlayed */
  116756. for(j=0;j<P_LEVELS;j++){
  116757. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116758. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116759. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116760. max_curve(athc[j],workc[i][j]);
  116761. }
  116762. /* Now limit the louder curves.
  116763. the idea is this: We don't know what the playback attenuation
  116764. will be; 0dB SL moves every time the user twiddles the volume
  116765. knob. So that means we have to use a single 'most pessimal' curve
  116766. for all masking amplitudes, right? Wrong. The *loudest* sound
  116767. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116768. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116769. etc... */
  116770. for(j=1;j<P_LEVELS;j++){
  116771. min_curve(athc[j],athc[j-1]);
  116772. min_curve(workc[i][j],athc[j]);
  116773. }
  116774. }
  116775. for(i=0;i<P_BANDS;i++){
  116776. int hi_curve,lo_curve,bin;
  116777. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116778. /* low frequency curves are measured with greater resolution than
  116779. the MDCT/FFT will actually give us; we want the curve applied
  116780. to the tone data to be pessimistic and thus apply the minimum
  116781. masking possible for a given bin. That means that a single bin
  116782. could span more than one octave and that the curve will be a
  116783. composite of multiple octaves. It also may mean that a single
  116784. bin may span > an eighth of an octave and that the eighth
  116785. octave values may also be composited. */
  116786. /* which octave curves will we be compositing? */
  116787. bin=floor(fromOC(i*.5)/binHz);
  116788. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116789. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116790. if(lo_curve>i)lo_curve=i;
  116791. if(lo_curve<0)lo_curve=0;
  116792. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116793. for(m=0;m<P_LEVELS;m++){
  116794. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116795. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116796. /* render the curve into bins, then pull values back into curve.
  116797. The point is that any inherent subsampling aliasing results in
  116798. a safe minimum */
  116799. for(k=lo_curve;k<=hi_curve;k++){
  116800. int l=0;
  116801. for(j=0;j<EHMER_MAX;j++){
  116802. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116803. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116804. if(lo_bin<0)lo_bin=0;
  116805. if(lo_bin>n)lo_bin=n;
  116806. if(lo_bin<l)l=lo_bin;
  116807. if(hi_bin<0)hi_bin=0;
  116808. if(hi_bin>n)hi_bin=n;
  116809. for(;l<hi_bin && l<n;l++)
  116810. if(brute_buffer[l]>workc[k][m][j])
  116811. brute_buffer[l]=workc[k][m][j];
  116812. }
  116813. for(;l<n;l++)
  116814. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116815. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116816. }
  116817. /* be equally paranoid about being valid up to next half ocatve */
  116818. if(i+1<P_BANDS){
  116819. int l=0;
  116820. k=i+1;
  116821. for(j=0;j<EHMER_MAX;j++){
  116822. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116823. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116824. if(lo_bin<0)lo_bin=0;
  116825. if(lo_bin>n)lo_bin=n;
  116826. if(lo_bin<l)l=lo_bin;
  116827. if(hi_bin<0)hi_bin=0;
  116828. if(hi_bin>n)hi_bin=n;
  116829. for(;l<hi_bin && l<n;l++)
  116830. if(brute_buffer[l]>workc[k][m][j])
  116831. brute_buffer[l]=workc[k][m][j];
  116832. }
  116833. for(;l<n;l++)
  116834. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116835. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116836. }
  116837. for(j=0;j<EHMER_MAX;j++){
  116838. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116839. if(bin<0){
  116840. ret[i][m][j+2]=-999.;
  116841. }else{
  116842. if(bin>=n){
  116843. ret[i][m][j+2]=-999.;
  116844. }else{
  116845. ret[i][m][j+2]=brute_buffer[bin];
  116846. }
  116847. }
  116848. }
  116849. /* add fenceposts */
  116850. for(j=0;j<EHMER_OFFSET;j++)
  116851. if(ret[i][m][j+2]>-200.f)break;
  116852. ret[i][m][0]=j;
  116853. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116854. if(ret[i][m][j+2]>-200.f)
  116855. break;
  116856. ret[i][m][1]=j;
  116857. }
  116858. }
  116859. return(ret);
  116860. }
  116861. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116862. vorbis_info_psy_global *gi,int n,long rate){
  116863. long i,j,lo=-99,hi=1;
  116864. long maxoc;
  116865. memset(p,0,sizeof(*p));
  116866. p->eighth_octave_lines=gi->eighth_octave_lines;
  116867. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116868. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116869. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116870. p->total_octave_lines=maxoc-p->firstoc+1;
  116871. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116872. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116873. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116874. p->vi=vi;
  116875. p->n=n;
  116876. p->rate=rate;
  116877. /* AoTuV HF weighting */
  116878. p->m_val = 1.;
  116879. if(rate < 26000) p->m_val = 0;
  116880. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116881. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116882. /* set up the lookups for a given blocksize and sample rate */
  116883. for(i=0,j=0;i<MAX_ATH-1;i++){
  116884. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116885. float base=ATH[i];
  116886. if(j<endpos){
  116887. float delta=(ATH[i+1]-base)/(endpos-j);
  116888. for(;j<endpos && j<n;j++){
  116889. p->ath[j]=base+100.;
  116890. base+=delta;
  116891. }
  116892. }
  116893. }
  116894. for(i=0;i<n;i++){
  116895. float bark=toBARK(rate/(2*n)*i);
  116896. for(;lo+vi->noisewindowlomin<i &&
  116897. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116898. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116899. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116900. p->bark[i]=((lo-1)<<16)+(hi-1);
  116901. }
  116902. for(i=0;i<n;i++)
  116903. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116904. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116905. vi->tone_centerboost,vi->tone_decay);
  116906. /* set up rolling noise median */
  116907. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116908. for(i=0;i<P_NOISECURVES;i++)
  116909. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116910. for(i=0;i<n;i++){
  116911. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116912. int inthalfoc;
  116913. float del;
  116914. if(halfoc<0)halfoc=0;
  116915. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116916. inthalfoc=(int)halfoc;
  116917. del=halfoc-inthalfoc;
  116918. for(j=0;j<P_NOISECURVES;j++)
  116919. p->noiseoffset[j][i]=
  116920. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116921. p->vi->noiseoff[j][inthalfoc+1]*del;
  116922. }
  116923. #if 0
  116924. {
  116925. static int ls=0;
  116926. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116927. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116928. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116929. }
  116930. #endif
  116931. }
  116932. void _vp_psy_clear(vorbis_look_psy *p){
  116933. int i,j;
  116934. if(p){
  116935. if(p->ath)_ogg_free(p->ath);
  116936. if(p->octave)_ogg_free(p->octave);
  116937. if(p->bark)_ogg_free(p->bark);
  116938. if(p->tonecurves){
  116939. for(i=0;i<P_BANDS;i++){
  116940. for(j=0;j<P_LEVELS;j++){
  116941. _ogg_free(p->tonecurves[i][j]);
  116942. }
  116943. _ogg_free(p->tonecurves[i]);
  116944. }
  116945. _ogg_free(p->tonecurves);
  116946. }
  116947. if(p->noiseoffset){
  116948. for(i=0;i<P_NOISECURVES;i++){
  116949. _ogg_free(p->noiseoffset[i]);
  116950. }
  116951. _ogg_free(p->noiseoffset);
  116952. }
  116953. memset(p,0,sizeof(*p));
  116954. }
  116955. }
  116956. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116957. static void seed_curve(float *seed,
  116958. const float **curves,
  116959. float amp,
  116960. int oc, int n,
  116961. int linesper,float dBoffset){
  116962. int i,post1;
  116963. int seedptr;
  116964. const float *posts,*curve;
  116965. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116966. choice=max(choice,0);
  116967. choice=min(choice,P_LEVELS-1);
  116968. posts=curves[choice];
  116969. curve=posts+2;
  116970. post1=(int)posts[1];
  116971. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116972. for(i=posts[0];i<post1;i++){
  116973. if(seedptr>0){
  116974. float lin=amp+curve[i];
  116975. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116976. }
  116977. seedptr+=linesper;
  116978. if(seedptr>=n)break;
  116979. }
  116980. }
  116981. static void seed_loop(vorbis_look_psy *p,
  116982. const float ***curves,
  116983. const float *f,
  116984. const float *flr,
  116985. float *seed,
  116986. float specmax){
  116987. vorbis_info_psy *vi=p->vi;
  116988. long n=p->n,i;
  116989. float dBoffset=vi->max_curve_dB-specmax;
  116990. /* prime the working vector with peak values */
  116991. for(i=0;i<n;i++){
  116992. float max=f[i];
  116993. long oc=p->octave[i];
  116994. while(i+1<n && p->octave[i+1]==oc){
  116995. i++;
  116996. if(f[i]>max)max=f[i];
  116997. }
  116998. if(max+6.f>flr[i]){
  116999. oc=oc>>p->shiftoc;
  117000. if(oc>=P_BANDS)oc=P_BANDS-1;
  117001. if(oc<0)oc=0;
  117002. seed_curve(seed,
  117003. curves[oc],
  117004. max,
  117005. p->octave[i]-p->firstoc,
  117006. p->total_octave_lines,
  117007. p->eighth_octave_lines,
  117008. dBoffset);
  117009. }
  117010. }
  117011. }
  117012. static void seed_chase(float *seeds, int linesper, long n){
  117013. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117014. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117015. long stack=0;
  117016. long pos=0;
  117017. long i;
  117018. for(i=0;i<n;i++){
  117019. if(stack<2){
  117020. posstack[stack]=i;
  117021. ampstack[stack++]=seeds[i];
  117022. }else{
  117023. while(1){
  117024. if(seeds[i]<ampstack[stack-1]){
  117025. posstack[stack]=i;
  117026. ampstack[stack++]=seeds[i];
  117027. break;
  117028. }else{
  117029. if(i<posstack[stack-1]+linesper){
  117030. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117031. i<posstack[stack-2]+linesper){
  117032. /* we completely overlap, making stack-1 irrelevant. pop it */
  117033. stack--;
  117034. continue;
  117035. }
  117036. }
  117037. posstack[stack]=i;
  117038. ampstack[stack++]=seeds[i];
  117039. break;
  117040. }
  117041. }
  117042. }
  117043. }
  117044. /* the stack now contains only the positions that are relevant. Scan
  117045. 'em straight through */
  117046. for(i=0;i<stack;i++){
  117047. long endpos;
  117048. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117049. endpos=posstack[i+1];
  117050. }else{
  117051. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117052. discarded in short frames */
  117053. }
  117054. if(endpos>n)endpos=n;
  117055. for(;pos<endpos;pos++)
  117056. seeds[pos]=ampstack[i];
  117057. }
  117058. /* there. Linear time. I now remember this was on a problem set I
  117059. had in Grad Skool... I didn't solve it at the time ;-) */
  117060. }
  117061. /* bleaugh, this is more complicated than it needs to be */
  117062. #include<stdio.h>
  117063. static void max_seeds(vorbis_look_psy *p,
  117064. float *seed,
  117065. float *flr){
  117066. long n=p->total_octave_lines;
  117067. int linesper=p->eighth_octave_lines;
  117068. long linpos=0;
  117069. long pos;
  117070. seed_chase(seed,linesper,n); /* for masking */
  117071. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117072. while(linpos+1<p->n){
  117073. float minV=seed[pos];
  117074. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117075. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117076. while(pos+1<=end){
  117077. pos++;
  117078. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117079. minV=seed[pos];
  117080. }
  117081. end=pos+p->firstoc;
  117082. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117083. if(flr[linpos]<minV)flr[linpos]=minV;
  117084. }
  117085. {
  117086. float minV=seed[p->total_octave_lines-1];
  117087. for(;linpos<p->n;linpos++)
  117088. if(flr[linpos]<minV)flr[linpos]=minV;
  117089. }
  117090. }
  117091. static void bark_noise_hybridmp(int n,const long *b,
  117092. const float *f,
  117093. float *noise,
  117094. const float offset,
  117095. const int fixed){
  117096. float *N=(float*) alloca(n*sizeof(*N));
  117097. float *X=(float*) alloca(n*sizeof(*N));
  117098. float *XX=(float*) alloca(n*sizeof(*N));
  117099. float *Y=(float*) alloca(n*sizeof(*N));
  117100. float *XY=(float*) alloca(n*sizeof(*N));
  117101. float tN, tX, tXX, tY, tXY;
  117102. int i;
  117103. int lo, hi;
  117104. float R, A, B, D;
  117105. float w, x, y;
  117106. tN = tX = tXX = tY = tXY = 0.f;
  117107. y = f[0] + offset;
  117108. if (y < 1.f) y = 1.f;
  117109. w = y * y * .5;
  117110. tN += w;
  117111. tX += w;
  117112. tY += w * y;
  117113. N[0] = tN;
  117114. X[0] = tX;
  117115. XX[0] = tXX;
  117116. Y[0] = tY;
  117117. XY[0] = tXY;
  117118. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117119. y = f[i] + offset;
  117120. if (y < 1.f) y = 1.f;
  117121. w = y * y;
  117122. tN += w;
  117123. tX += w * x;
  117124. tXX += w * x * x;
  117125. tY += w * y;
  117126. tXY += w * x * y;
  117127. N[i] = tN;
  117128. X[i] = tX;
  117129. XX[i] = tXX;
  117130. Y[i] = tY;
  117131. XY[i] = tXY;
  117132. }
  117133. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117134. lo = b[i] >> 16;
  117135. if( lo>=0 ) break;
  117136. hi = b[i] & 0xffff;
  117137. tN = N[hi] + N[-lo];
  117138. tX = X[hi] - X[-lo];
  117139. tXX = XX[hi] + XX[-lo];
  117140. tY = Y[hi] + Y[-lo];
  117141. tXY = XY[hi] - XY[-lo];
  117142. A = tY * tXX - tX * tXY;
  117143. B = tN * tXY - tX * tY;
  117144. D = tN * tXX - tX * tX;
  117145. R = (A + x * B) / D;
  117146. if (R < 0.f)
  117147. R = 0.f;
  117148. noise[i] = R - offset;
  117149. }
  117150. for ( ;; i++, x += 1.f) {
  117151. lo = b[i] >> 16;
  117152. hi = b[i] & 0xffff;
  117153. if(hi>=n)break;
  117154. tN = N[hi] - N[lo];
  117155. tX = X[hi] - X[lo];
  117156. tXX = XX[hi] - XX[lo];
  117157. tY = Y[hi] - Y[lo];
  117158. tXY = XY[hi] - XY[lo];
  117159. A = tY * tXX - tX * tXY;
  117160. B = tN * tXY - tX * tY;
  117161. D = tN * tXX - tX * tX;
  117162. R = (A + x * B) / D;
  117163. if (R < 0.f) R = 0.f;
  117164. noise[i] = R - offset;
  117165. }
  117166. for ( ; i < n; i++, x += 1.f) {
  117167. R = (A + x * B) / D;
  117168. if (R < 0.f) R = 0.f;
  117169. noise[i] = R - offset;
  117170. }
  117171. if (fixed <= 0) return;
  117172. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117173. hi = i + fixed / 2;
  117174. lo = hi - fixed;
  117175. if(lo>=0)break;
  117176. tN = N[hi] + N[-lo];
  117177. tX = X[hi] - X[-lo];
  117178. tXX = XX[hi] + XX[-lo];
  117179. tY = Y[hi] + Y[-lo];
  117180. tXY = XY[hi] - XY[-lo];
  117181. A = tY * tXX - tX * tXY;
  117182. B = tN * tXY - tX * tY;
  117183. D = tN * tXX - tX * tX;
  117184. R = (A + x * B) / D;
  117185. if (R - offset < noise[i]) noise[i] = R - offset;
  117186. }
  117187. for ( ;; i++, x += 1.f) {
  117188. hi = i + fixed / 2;
  117189. lo = hi - fixed;
  117190. if(hi>=n)break;
  117191. tN = N[hi] - N[lo];
  117192. tX = X[hi] - X[lo];
  117193. tXX = XX[hi] - XX[lo];
  117194. tY = Y[hi] - Y[lo];
  117195. tXY = XY[hi] - XY[lo];
  117196. A = tY * tXX - tX * tXY;
  117197. B = tN * tXY - tX * tY;
  117198. D = tN * tXX - tX * tX;
  117199. R = (A + x * B) / D;
  117200. if (R - offset < noise[i]) noise[i] = R - offset;
  117201. }
  117202. for ( ; i < n; i++, x += 1.f) {
  117203. R = (A + x * B) / D;
  117204. if (R - offset < noise[i]) noise[i] = R - offset;
  117205. }
  117206. }
  117207. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117208. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117209. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117210. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117211. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117212. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117213. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117214. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117215. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117216. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117217. 973377.F, 913981.F, 858210.F, 805842.F,
  117218. 756669.F, 710497.F, 667142.F, 626433.F,
  117219. 588208.F, 552316.F, 518613.F, 486967.F,
  117220. 457252.F, 429351.F, 403152.F, 378551.F,
  117221. 355452.F, 333762.F, 313396.F, 294273.F,
  117222. 276316.F, 259455.F, 243623.F, 228757.F,
  117223. 214798.F, 201691.F, 189384.F, 177828.F,
  117224. 166977.F, 156788.F, 147221.F, 138237.F,
  117225. 129802.F, 121881.F, 114444.F, 107461.F,
  117226. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117227. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117228. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117229. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117230. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117231. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117232. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117233. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117234. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117235. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117236. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117237. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117238. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117239. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117240. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117241. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117242. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117243. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117244. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117245. 842.910F, 791.475F, 743.179F, 697.830F,
  117246. 655.249F, 615.265F, 577.722F, 542.469F,
  117247. 509.367F, 478.286F, 449.101F, 421.696F,
  117248. 395.964F, 371.803F, 349.115F, 327.812F,
  117249. 307.809F, 289.026F, 271.390F, 254.830F,
  117250. 239.280F, 224.679F, 210.969F, 198.096F,
  117251. 186.008F, 174.658F, 164.000F, 153.993F,
  117252. 144.596F, 135.773F, 127.488F, 119.708F,
  117253. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117254. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117255. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117256. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117257. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117258. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117259. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117260. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117261. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117262. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117263. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117264. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117265. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117266. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117267. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117268. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117269. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117270. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117271. 1.20790F, 1.13419F, 1.06499F, 1.F
  117272. };
  117273. void _vp_remove_floor(vorbis_look_psy *p,
  117274. float *mdct,
  117275. int *codedflr,
  117276. float *residue,
  117277. int sliding_lowpass){
  117278. int i,n=p->n;
  117279. if(sliding_lowpass>n)sliding_lowpass=n;
  117280. for(i=0;i<sliding_lowpass;i++){
  117281. residue[i]=
  117282. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117283. }
  117284. for(;i<n;i++)
  117285. residue[i]=0.;
  117286. }
  117287. void _vp_noisemask(vorbis_look_psy *p,
  117288. float *logmdct,
  117289. float *logmask){
  117290. int i,n=p->n;
  117291. float *work=(float*) alloca(n*sizeof(*work));
  117292. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117293. 140.,-1);
  117294. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117295. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117296. p->vi->noisewindowfixed);
  117297. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117298. #if 0
  117299. {
  117300. static int seq=0;
  117301. float work2[n];
  117302. for(i=0;i<n;i++){
  117303. work2[i]=logmask[i]+work[i];
  117304. }
  117305. if(seq&1)
  117306. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117307. else
  117308. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117309. if(seq&1)
  117310. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117311. else
  117312. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117313. seq++;
  117314. }
  117315. #endif
  117316. for(i=0;i<n;i++){
  117317. int dB=logmask[i]+.5;
  117318. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117319. if(dB<0)dB=0;
  117320. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117321. }
  117322. }
  117323. void _vp_tonemask(vorbis_look_psy *p,
  117324. float *logfft,
  117325. float *logmask,
  117326. float global_specmax,
  117327. float local_specmax){
  117328. int i,n=p->n;
  117329. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117330. float att=local_specmax+p->vi->ath_adjatt;
  117331. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117332. /* set the ATH (floating below localmax, not global max by a
  117333. specified att) */
  117334. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117335. for(i=0;i<n;i++)
  117336. logmask[i]=p->ath[i]+att;
  117337. /* tone masking */
  117338. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117339. max_seeds(p,seed,logmask);
  117340. }
  117341. void _vp_offset_and_mix(vorbis_look_psy *p,
  117342. float *noise,
  117343. float *tone,
  117344. int offset_select,
  117345. float *logmask,
  117346. float *mdct,
  117347. float *logmdct){
  117348. int i,n=p->n;
  117349. float de, coeffi, cx;/* AoTuV */
  117350. float toneatt=p->vi->tone_masteratt[offset_select];
  117351. cx = p->m_val;
  117352. for(i=0;i<n;i++){
  117353. float val= noise[i]+p->noiseoffset[offset_select][i];
  117354. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117355. logmask[i]=max(val,tone[i]+toneatt);
  117356. /* AoTuV */
  117357. /** @ M1 **
  117358. The following codes improve a noise problem.
  117359. A fundamental idea uses the value of masking and carries out
  117360. the relative compensation of the MDCT.
  117361. However, this code is not perfect and all noise problems cannot be solved.
  117362. by Aoyumi @ 2004/04/18
  117363. */
  117364. if(offset_select == 1) {
  117365. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117366. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117367. if(val > coeffi){
  117368. /* mdct value is > -17.2 dB below floor */
  117369. de = 1.0-((val-coeffi)*0.005*cx);
  117370. /* pro-rated attenuation:
  117371. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117372. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117373. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117374. etc... */
  117375. if(de < 0) de = 0.0001;
  117376. }else
  117377. /* mdct value is <= -17.2 dB below floor */
  117378. de = 1.0-((val-coeffi)*0.0003*cx);
  117379. /* pro-rated attenuation:
  117380. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117381. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117382. etc... */
  117383. mdct[i] *= de;
  117384. }
  117385. }
  117386. }
  117387. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117388. vorbis_info *vi=vd->vi;
  117389. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117390. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117391. int n=ci->blocksizes[vd->W]/2;
  117392. float secs=(float)n/vi->rate;
  117393. amp+=secs*gi->ampmax_att_per_sec;
  117394. if(amp<-9999)amp=-9999;
  117395. return(amp);
  117396. }
  117397. static void couple_lossless(float A, float B,
  117398. float *qA, float *qB){
  117399. int test1=fabs(*qA)>fabs(*qB);
  117400. test1-= fabs(*qA)<fabs(*qB);
  117401. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117402. if(test1==1){
  117403. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117404. }else{
  117405. float temp=*qB;
  117406. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117407. *qA=temp;
  117408. }
  117409. if(*qB>fabs(*qA)*1.9999f){
  117410. *qB= -fabs(*qA)*2.f;
  117411. *qA= -*qA;
  117412. }
  117413. }
  117414. static float hypot_lookup[32]={
  117415. -0.009935, -0.011245, -0.012726, -0.014397,
  117416. -0.016282, -0.018407, -0.020800, -0.023494,
  117417. -0.026522, -0.029923, -0.033737, -0.038010,
  117418. -0.042787, -0.048121, -0.054064, -0.060671,
  117419. -0.068000, -0.076109, -0.085054, -0.094892,
  117420. -0.105675, -0.117451, -0.130260, -0.144134,
  117421. -0.159093, -0.175146, -0.192286, -0.210490,
  117422. -0.229718, -0.249913, -0.271001, -0.292893};
  117423. static void precomputed_couple_point(float premag,
  117424. int floorA,int floorB,
  117425. float *mag, float *ang){
  117426. int test=(floorA>floorB)-1;
  117427. int offset=31-abs(floorA-floorB);
  117428. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117429. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117430. *mag=premag*floormag;
  117431. *ang=0.f;
  117432. }
  117433. /* just like below, this is currently set up to only do
  117434. single-step-depth coupling. Otherwise, we'd have to do more
  117435. copying (which will be inevitable later) */
  117436. /* doing the real circular magnitude calculation is audibly superior
  117437. to (A+B)/sqrt(2) */
  117438. static float dipole_hypot(float a, float b){
  117439. if(a>0.){
  117440. if(b>0.)return sqrt(a*a+b*b);
  117441. if(a>-b)return sqrt(a*a-b*b);
  117442. return -sqrt(b*b-a*a);
  117443. }
  117444. if(b<0.)return -sqrt(a*a+b*b);
  117445. if(-a>b)return -sqrt(a*a-b*b);
  117446. return sqrt(b*b-a*a);
  117447. }
  117448. static float round_hypot(float a, float b){
  117449. if(a>0.){
  117450. if(b>0.)return sqrt(a*a+b*b);
  117451. if(a>-b)return sqrt(a*a+b*b);
  117452. return -sqrt(b*b+a*a);
  117453. }
  117454. if(b<0.)return -sqrt(a*a+b*b);
  117455. if(-a>b)return -sqrt(a*a+b*b);
  117456. return sqrt(b*b+a*a);
  117457. }
  117458. /* revert to round hypot for now */
  117459. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117460. vorbis_info_psy_global *g,
  117461. vorbis_look_psy *p,
  117462. vorbis_info_mapping0 *vi,
  117463. float **mdct){
  117464. int i,j,n=p->n;
  117465. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117466. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117467. for(i=0;i<vi->coupling_steps;i++){
  117468. float *mdctM=mdct[vi->coupling_mag[i]];
  117469. float *mdctA=mdct[vi->coupling_ang[i]];
  117470. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117471. for(j=0;j<limit;j++)
  117472. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117473. for(;j<n;j++)
  117474. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117475. }
  117476. return(ret);
  117477. }
  117478. /* this is for per-channel noise normalization */
  117479. static int JUCE_CDECL apsort(const void *a, const void *b){
  117480. float f1=fabs(**(float**)a);
  117481. float f2=fabs(**(float**)b);
  117482. return (f1<f2)-(f1>f2);
  117483. }
  117484. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117485. vorbis_look_psy *p,
  117486. vorbis_info_mapping0 *vi,
  117487. float **mags){
  117488. if(p->vi->normal_point_p){
  117489. int i,j,k,n=p->n;
  117490. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117491. int partition=p->vi->normal_partition;
  117492. float **work=(float**) alloca(sizeof(*work)*partition);
  117493. for(i=0;i<vi->coupling_steps;i++){
  117494. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117495. for(j=0;j<n;j+=partition){
  117496. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117497. qsort(work,partition,sizeof(*work),apsort);
  117498. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117499. }
  117500. }
  117501. return(ret);
  117502. }
  117503. return(NULL);
  117504. }
  117505. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117506. float *magnitudes,int *sortedindex){
  117507. int i,j,n=p->n;
  117508. vorbis_info_psy *vi=p->vi;
  117509. int partition=vi->normal_partition;
  117510. float **work=(float**) alloca(sizeof(*work)*partition);
  117511. int start=vi->normal_start;
  117512. for(j=start;j<n;j+=partition){
  117513. if(j+partition>n)partition=n-j;
  117514. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117515. qsort(work,partition,sizeof(*work),apsort);
  117516. for(i=0;i<partition;i++){
  117517. sortedindex[i+j-start]=work[i]-magnitudes;
  117518. }
  117519. }
  117520. }
  117521. void _vp_noise_normalize(vorbis_look_psy *p,
  117522. float *in,float *out,int *sortedindex){
  117523. int flag=0,i,j=0,n=p->n;
  117524. vorbis_info_psy *vi=p->vi;
  117525. int partition=vi->normal_partition;
  117526. int start=vi->normal_start;
  117527. if(start>n)start=n;
  117528. if(vi->normal_channel_p){
  117529. for(;j<start;j++)
  117530. out[j]=rint(in[j]);
  117531. for(;j+partition<=n;j+=partition){
  117532. float acc=0.;
  117533. int k;
  117534. for(i=j;i<j+partition;i++)
  117535. acc+=in[i]*in[i];
  117536. for(i=0;i<partition;i++){
  117537. k=sortedindex[i+j-start];
  117538. if(in[k]*in[k]>=.25f){
  117539. out[k]=rint(in[k]);
  117540. acc-=in[k]*in[k];
  117541. flag=1;
  117542. }else{
  117543. if(acc<vi->normal_thresh)break;
  117544. out[k]=unitnorm(in[k]);
  117545. acc-=1.;
  117546. }
  117547. }
  117548. for(;i<partition;i++){
  117549. k=sortedindex[i+j-start];
  117550. out[k]=0.;
  117551. }
  117552. }
  117553. }
  117554. for(;j<n;j++)
  117555. out[j]=rint(in[j]);
  117556. }
  117557. void _vp_couple(int blobno,
  117558. vorbis_info_psy_global *g,
  117559. vorbis_look_psy *p,
  117560. vorbis_info_mapping0 *vi,
  117561. float **res,
  117562. float **mag_memo,
  117563. int **mag_sort,
  117564. int **ifloor,
  117565. int *nonzero,
  117566. int sliding_lowpass){
  117567. int i,j,k,n=p->n;
  117568. /* perform any requested channel coupling */
  117569. /* point stereo can only be used in a first stage (in this encoder)
  117570. because of the dependency on floor lookups */
  117571. for(i=0;i<vi->coupling_steps;i++){
  117572. /* once we're doing multistage coupling in which a channel goes
  117573. through more than one coupling step, the floor vector
  117574. magnitudes will also have to be recalculated an propogated
  117575. along with PCM. Right now, we're not (that will wait until 5.1
  117576. most likely), so the code isn't here yet. The memory management
  117577. here is all assuming single depth couplings anyway. */
  117578. /* make sure coupling a zero and a nonzero channel results in two
  117579. nonzero channels. */
  117580. if(nonzero[vi->coupling_mag[i]] ||
  117581. nonzero[vi->coupling_ang[i]]){
  117582. float *rM=res[vi->coupling_mag[i]];
  117583. float *rA=res[vi->coupling_ang[i]];
  117584. float *qM=rM+n;
  117585. float *qA=rA+n;
  117586. int *floorM=ifloor[vi->coupling_mag[i]];
  117587. int *floorA=ifloor[vi->coupling_ang[i]];
  117588. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117589. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117590. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117591. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117592. int pointlimit=limit;
  117593. nonzero[vi->coupling_mag[i]]=1;
  117594. nonzero[vi->coupling_ang[i]]=1;
  117595. /* The threshold of a stereo is changed with the size of n */
  117596. if(n > 1000)
  117597. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117598. for(j=0;j<p->n;j+=partition){
  117599. float acc=0.f;
  117600. for(k=0;k<partition;k++){
  117601. int l=k+j;
  117602. if(l<sliding_lowpass){
  117603. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117604. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117605. precomputed_couple_point(mag_memo[i][l],
  117606. floorM[l],floorA[l],
  117607. qM+l,qA+l);
  117608. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117609. }else{
  117610. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117611. }
  117612. }else{
  117613. qM[l]=0.;
  117614. qA[l]=0.;
  117615. }
  117616. }
  117617. if(p->vi->normal_point_p){
  117618. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117619. int l=mag_sort[i][j+k];
  117620. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117621. qM[l]=unitnorm(qM[l]);
  117622. acc-=1.f;
  117623. }
  117624. }
  117625. }
  117626. }
  117627. }
  117628. }
  117629. }
  117630. /* AoTuV */
  117631. /** @ M2 **
  117632. The boost problem by the combination of noise normalization and point stereo is eased.
  117633. However, this is a temporary patch.
  117634. by Aoyumi @ 2004/04/18
  117635. */
  117636. void hf_reduction(vorbis_info_psy_global *g,
  117637. vorbis_look_psy *p,
  117638. vorbis_info_mapping0 *vi,
  117639. float **mdct){
  117640. int i,j,n=p->n, de=0.3*p->m_val;
  117641. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117642. for(i=0; i<vi->coupling_steps; i++){
  117643. /* for(j=start; j<limit; j++){} // ???*/
  117644. for(j=limit; j<n; j++)
  117645. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117646. }
  117647. }
  117648. #endif
  117649. /*** End of inlined file: psy.c ***/
  117650. /*** Start of inlined file: registry.c ***/
  117651. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117652. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117653. // tasks..
  117654. #if JUCE_MSVC
  117655. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117656. #endif
  117657. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117658. #if JUCE_USE_OGGVORBIS
  117659. /* seems like major overkill now; the backend numbers will grow into
  117660. the infrastructure soon enough */
  117661. extern vorbis_func_floor floor0_exportbundle;
  117662. extern vorbis_func_floor floor1_exportbundle;
  117663. extern vorbis_func_residue residue0_exportbundle;
  117664. extern vorbis_func_residue residue1_exportbundle;
  117665. extern vorbis_func_residue residue2_exportbundle;
  117666. extern vorbis_func_mapping mapping0_exportbundle;
  117667. vorbis_func_floor *_floor_P[]={
  117668. &floor0_exportbundle,
  117669. &floor1_exportbundle,
  117670. };
  117671. vorbis_func_residue *_residue_P[]={
  117672. &residue0_exportbundle,
  117673. &residue1_exportbundle,
  117674. &residue2_exportbundle,
  117675. };
  117676. vorbis_func_mapping *_mapping_P[]={
  117677. &mapping0_exportbundle,
  117678. };
  117679. #endif
  117680. /*** End of inlined file: registry.c ***/
  117681. /*** Start of inlined file: res0.c ***/
  117682. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117683. encode/decode loops are coded for clarity and performance is not
  117684. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117685. it's slow. */
  117686. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117687. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117688. // tasks..
  117689. #if JUCE_MSVC
  117690. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117691. #endif
  117692. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117693. #if JUCE_USE_OGGVORBIS
  117694. #include <stdlib.h>
  117695. #include <string.h>
  117696. #include <math.h>
  117697. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117698. #include <stdio.h>
  117699. #endif
  117700. typedef struct {
  117701. vorbis_info_residue0 *info;
  117702. int parts;
  117703. int stages;
  117704. codebook *fullbooks;
  117705. codebook *phrasebook;
  117706. codebook ***partbooks;
  117707. int partvals;
  117708. int **decodemap;
  117709. long postbits;
  117710. long phrasebits;
  117711. long frames;
  117712. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117713. int train_seq;
  117714. long *training_data[8][64];
  117715. float training_max[8][64];
  117716. float training_min[8][64];
  117717. float tmin;
  117718. float tmax;
  117719. #endif
  117720. } vorbis_look_residue0;
  117721. void res0_free_info(vorbis_info_residue *i){
  117722. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117723. if(info){
  117724. memset(info,0,sizeof(*info));
  117725. _ogg_free(info);
  117726. }
  117727. }
  117728. void res0_free_look(vorbis_look_residue *i){
  117729. int j;
  117730. if(i){
  117731. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117732. #ifdef TRAIN_RES
  117733. {
  117734. int j,k,l;
  117735. for(j=0;j<look->parts;j++){
  117736. /*fprintf(stderr,"partition %d: ",j);*/
  117737. for(k=0;k<8;k++)
  117738. if(look->training_data[k][j]){
  117739. char buffer[80];
  117740. FILE *of;
  117741. codebook *statebook=look->partbooks[j][k];
  117742. /* long and short into the same bucket by current convention */
  117743. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117744. of=fopen(buffer,"a");
  117745. for(l=0;l<statebook->entries;l++)
  117746. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117747. fclose(of);
  117748. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117749. look->training_min[k][j],look->training_max[k][j]);*/
  117750. _ogg_free(look->training_data[k][j]);
  117751. look->training_data[k][j]=NULL;
  117752. }
  117753. /*fprintf(stderr,"\n");*/
  117754. }
  117755. }
  117756. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117757. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117758. (float)look->phrasebits/look->frames,
  117759. (float)look->postbits/look->frames,
  117760. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117761. #endif
  117762. /*vorbis_info_residue0 *info=look->info;
  117763. fprintf(stderr,
  117764. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117765. "(%g/frame) \n",look->frames,look->phrasebits,
  117766. look->resbitsflat,
  117767. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117768. for(j=0;j<look->parts;j++){
  117769. long acc=0;
  117770. fprintf(stderr,"\t[%d] == ",j);
  117771. for(k=0;k<look->stages;k++)
  117772. if((info->secondstages[j]>>k)&1){
  117773. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117774. acc+=look->resbits[j][k];
  117775. }
  117776. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117777. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117778. }
  117779. fprintf(stderr,"\n");*/
  117780. for(j=0;j<look->parts;j++)
  117781. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117782. _ogg_free(look->partbooks);
  117783. for(j=0;j<look->partvals;j++)
  117784. _ogg_free(look->decodemap[j]);
  117785. _ogg_free(look->decodemap);
  117786. memset(look,0,sizeof(*look));
  117787. _ogg_free(look);
  117788. }
  117789. }
  117790. static int icount(unsigned int v){
  117791. int ret=0;
  117792. while(v){
  117793. ret+=v&1;
  117794. v>>=1;
  117795. }
  117796. return(ret);
  117797. }
  117798. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117799. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117800. int j,acc=0;
  117801. oggpack_write(opb,info->begin,24);
  117802. oggpack_write(opb,info->end,24);
  117803. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117804. code with a partitioned book */
  117805. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117806. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117807. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117808. bitmask of one indicates this partition class has bits to write
  117809. this pass */
  117810. for(j=0;j<info->partitions;j++){
  117811. if(ilog(info->secondstages[j])>3){
  117812. /* yes, this is a minor hack due to not thinking ahead */
  117813. oggpack_write(opb,info->secondstages[j],3);
  117814. oggpack_write(opb,1,1);
  117815. oggpack_write(opb,info->secondstages[j]>>3,5);
  117816. }else
  117817. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117818. acc+=icount(info->secondstages[j]);
  117819. }
  117820. for(j=0;j<acc;j++)
  117821. oggpack_write(opb,info->booklist[j],8);
  117822. }
  117823. /* vorbis_info is for range checking */
  117824. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117825. int j,acc=0;
  117826. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117827. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117828. info->begin=oggpack_read(opb,24);
  117829. info->end=oggpack_read(opb,24);
  117830. info->grouping=oggpack_read(opb,24)+1;
  117831. info->partitions=oggpack_read(opb,6)+1;
  117832. info->groupbook=oggpack_read(opb,8);
  117833. for(j=0;j<info->partitions;j++){
  117834. int cascade=oggpack_read(opb,3);
  117835. if(oggpack_read(opb,1))
  117836. cascade|=(oggpack_read(opb,5)<<3);
  117837. info->secondstages[j]=cascade;
  117838. acc+=icount(cascade);
  117839. }
  117840. for(j=0;j<acc;j++)
  117841. info->booklist[j]=oggpack_read(opb,8);
  117842. if(info->groupbook>=ci->books)goto errout;
  117843. for(j=0;j<acc;j++)
  117844. if(info->booklist[j]>=ci->books)goto errout;
  117845. return(info);
  117846. errout:
  117847. res0_free_info(info);
  117848. return(NULL);
  117849. }
  117850. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117851. vorbis_info_residue *vr){
  117852. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117853. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117854. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117855. int j,k,acc=0;
  117856. int dim;
  117857. int maxstage=0;
  117858. look->info=info;
  117859. look->parts=info->partitions;
  117860. look->fullbooks=ci->fullbooks;
  117861. look->phrasebook=ci->fullbooks+info->groupbook;
  117862. dim=look->phrasebook->dim;
  117863. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117864. for(j=0;j<look->parts;j++){
  117865. int stages=ilog(info->secondstages[j]);
  117866. if(stages){
  117867. if(stages>maxstage)maxstage=stages;
  117868. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117869. for(k=0;k<stages;k++)
  117870. if(info->secondstages[j]&(1<<k)){
  117871. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117872. #ifdef TRAIN_RES
  117873. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117874. sizeof(***look->training_data));
  117875. #endif
  117876. }
  117877. }
  117878. }
  117879. look->partvals=rint(pow((float)look->parts,(float)dim));
  117880. look->stages=maxstage;
  117881. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117882. for(j=0;j<look->partvals;j++){
  117883. long val=j;
  117884. long mult=look->partvals/look->parts;
  117885. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117886. for(k=0;k<dim;k++){
  117887. long deco=val/mult;
  117888. val-=deco*mult;
  117889. mult/=look->parts;
  117890. look->decodemap[j][k]=deco;
  117891. }
  117892. }
  117893. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117894. {
  117895. static int train_seq=0;
  117896. look->train_seq=train_seq++;
  117897. }
  117898. #endif
  117899. return(look);
  117900. }
  117901. /* break an abstraction and copy some code for performance purposes */
  117902. static int local_book_besterror(codebook *book,float *a){
  117903. int dim=book->dim,i,k,o;
  117904. int best=0;
  117905. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117906. /* find the quant val of each scalar */
  117907. for(k=0,o=dim;k<dim;++k){
  117908. float val=a[--o];
  117909. i=tt->threshvals>>1;
  117910. if(val<tt->quantthresh[i]){
  117911. if(val<tt->quantthresh[i-1]){
  117912. for(--i;i>0;--i)
  117913. if(val>=tt->quantthresh[i-1])
  117914. break;
  117915. }
  117916. }else{
  117917. for(++i;i<tt->threshvals-1;++i)
  117918. if(val<tt->quantthresh[i])break;
  117919. }
  117920. best=(best*tt->quantvals)+tt->quantmap[i];
  117921. }
  117922. /* regular lattices are easy :-) */
  117923. if(book->c->lengthlist[best]<=0){
  117924. const static_codebook *c=book->c;
  117925. int i,j;
  117926. float bestf=0.f;
  117927. float *e=book->valuelist;
  117928. best=-1;
  117929. for(i=0;i<book->entries;i++){
  117930. if(c->lengthlist[i]>0){
  117931. float thisx=0.f;
  117932. for(j=0;j<dim;j++){
  117933. float val=(e[j]-a[j]);
  117934. thisx+=val*val;
  117935. }
  117936. if(best==-1 || thisx<bestf){
  117937. bestf=thisx;
  117938. best=i;
  117939. }
  117940. }
  117941. e+=dim;
  117942. }
  117943. }
  117944. {
  117945. float *ptr=book->valuelist+best*dim;
  117946. for(i=0;i<dim;i++)
  117947. *a++ -= *ptr++;
  117948. }
  117949. return(best);
  117950. }
  117951. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117952. codebook *book,long *acc){
  117953. int i,bits=0;
  117954. int dim=book->dim;
  117955. int step=n/dim;
  117956. for(i=0;i<step;i++){
  117957. int entry=local_book_besterror(book,vec+i*dim);
  117958. #ifdef TRAIN_RES
  117959. acc[entry]++;
  117960. #endif
  117961. bits+=vorbis_book_encode(book,entry,opb);
  117962. }
  117963. return(bits);
  117964. }
  117965. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117966. float **in,int ch){
  117967. long i,j,k;
  117968. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117969. vorbis_info_residue0 *info=look->info;
  117970. /* move all this setup out later */
  117971. int samples_per_partition=info->grouping;
  117972. int possible_partitions=info->partitions;
  117973. int n=info->end-info->begin;
  117974. int partvals=n/samples_per_partition;
  117975. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117976. float scale=100./samples_per_partition;
  117977. /* we find the partition type for each partition of each
  117978. channel. We'll go back and do the interleaved encoding in a
  117979. bit. For now, clarity */
  117980. for(i=0;i<ch;i++){
  117981. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117982. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117983. }
  117984. for(i=0;i<partvals;i++){
  117985. int offset=i*samples_per_partition+info->begin;
  117986. for(j=0;j<ch;j++){
  117987. float max=0.;
  117988. float ent=0.;
  117989. for(k=0;k<samples_per_partition;k++){
  117990. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117991. ent+=fabs(rint(in[j][offset+k]));
  117992. }
  117993. ent*=scale;
  117994. for(k=0;k<possible_partitions-1;k++)
  117995. if(max<=info->classmetric1[k] &&
  117996. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117997. break;
  117998. partword[j][i]=k;
  117999. }
  118000. }
  118001. #ifdef TRAIN_RESAUX
  118002. {
  118003. FILE *of;
  118004. char buffer[80];
  118005. for(i=0;i<ch;i++){
  118006. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118007. of=fopen(buffer,"a");
  118008. for(j=0;j<partvals;j++)
  118009. fprintf(of,"%ld, ",partword[i][j]);
  118010. fprintf(of,"\n");
  118011. fclose(of);
  118012. }
  118013. }
  118014. #endif
  118015. look->frames++;
  118016. return(partword);
  118017. }
  118018. /* designed for stereo or other modes where the partition size is an
  118019. integer multiple of the number of channels encoded in the current
  118020. submap */
  118021. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118022. int ch){
  118023. long i,j,k,l;
  118024. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118025. vorbis_info_residue0 *info=look->info;
  118026. /* move all this setup out later */
  118027. int samples_per_partition=info->grouping;
  118028. int possible_partitions=info->partitions;
  118029. int n=info->end-info->begin;
  118030. int partvals=n/samples_per_partition;
  118031. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118032. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118033. FILE *of;
  118034. char buffer[80];
  118035. #endif
  118036. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118037. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118038. for(i=0,l=info->begin/ch;i<partvals;i++){
  118039. float magmax=0.f;
  118040. float angmax=0.f;
  118041. for(j=0;j<samples_per_partition;j+=ch){
  118042. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118043. for(k=1;k<ch;k++)
  118044. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118045. l++;
  118046. }
  118047. for(j=0;j<possible_partitions-1;j++)
  118048. if(magmax<=info->classmetric1[j] &&
  118049. angmax<=info->classmetric2[j])
  118050. break;
  118051. partword[0][i]=j;
  118052. }
  118053. #ifdef TRAIN_RESAUX
  118054. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118055. of=fopen(buffer,"a");
  118056. for(i=0;i<partvals;i++)
  118057. fprintf(of,"%ld, ",partword[0][i]);
  118058. fprintf(of,"\n");
  118059. fclose(of);
  118060. #endif
  118061. look->frames++;
  118062. return(partword);
  118063. }
  118064. static int _01forward(oggpack_buffer *opb,
  118065. vorbis_block *vb,vorbis_look_residue *vl,
  118066. float **in,int ch,
  118067. long **partword,
  118068. int (*encode)(oggpack_buffer *,float *,int,
  118069. codebook *,long *)){
  118070. long i,j,k,s;
  118071. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118072. vorbis_info_residue0 *info=look->info;
  118073. /* move all this setup out later */
  118074. int samples_per_partition=info->grouping;
  118075. int possible_partitions=info->partitions;
  118076. int partitions_per_word=look->phrasebook->dim;
  118077. int n=info->end-info->begin;
  118078. int partvals=n/samples_per_partition;
  118079. long resbits[128];
  118080. long resvals[128];
  118081. #ifdef TRAIN_RES
  118082. for(i=0;i<ch;i++)
  118083. for(j=info->begin;j<info->end;j++){
  118084. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118085. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118086. }
  118087. #endif
  118088. memset(resbits,0,sizeof(resbits));
  118089. memset(resvals,0,sizeof(resvals));
  118090. /* we code the partition words for each channel, then the residual
  118091. words for a partition per channel until we've written all the
  118092. residual words for that partition word. Then write the next
  118093. partition channel words... */
  118094. for(s=0;s<look->stages;s++){
  118095. for(i=0;i<partvals;){
  118096. /* first we encode a partition codeword for each channel */
  118097. if(s==0){
  118098. for(j=0;j<ch;j++){
  118099. long val=partword[j][i];
  118100. for(k=1;k<partitions_per_word;k++){
  118101. val*=possible_partitions;
  118102. if(i+k<partvals)
  118103. val+=partword[j][i+k];
  118104. }
  118105. /* training hack */
  118106. if(val<look->phrasebook->entries)
  118107. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118108. #if 0 /*def TRAIN_RES*/
  118109. else
  118110. fprintf(stderr,"!");
  118111. #endif
  118112. }
  118113. }
  118114. /* now we encode interleaved residual values for the partitions */
  118115. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118116. long offset=i*samples_per_partition+info->begin;
  118117. for(j=0;j<ch;j++){
  118118. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118119. if(info->secondstages[partword[j][i]]&(1<<s)){
  118120. codebook *statebook=look->partbooks[partword[j][i]][s];
  118121. if(statebook){
  118122. int ret;
  118123. long *accumulator=NULL;
  118124. #ifdef TRAIN_RES
  118125. accumulator=look->training_data[s][partword[j][i]];
  118126. {
  118127. int l;
  118128. float *samples=in[j]+offset;
  118129. for(l=0;l<samples_per_partition;l++){
  118130. if(samples[l]<look->training_min[s][partword[j][i]])
  118131. look->training_min[s][partword[j][i]]=samples[l];
  118132. if(samples[l]>look->training_max[s][partword[j][i]])
  118133. look->training_max[s][partword[j][i]]=samples[l];
  118134. }
  118135. }
  118136. #endif
  118137. ret=encode(opb,in[j]+offset,samples_per_partition,
  118138. statebook,accumulator);
  118139. look->postbits+=ret;
  118140. resbits[partword[j][i]]+=ret;
  118141. }
  118142. }
  118143. }
  118144. }
  118145. }
  118146. }
  118147. /*{
  118148. long total=0;
  118149. long totalbits=0;
  118150. fprintf(stderr,"%d :: ",vb->mode);
  118151. for(k=0;k<possible_partitions;k++){
  118152. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118153. total+=resvals[k];
  118154. totalbits+=resbits[k];
  118155. }
  118156. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118157. }*/
  118158. return(0);
  118159. }
  118160. /* a truncated packet here just means 'stop working'; it's not an error */
  118161. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118162. float **in,int ch,
  118163. long (*decodepart)(codebook *, float *,
  118164. oggpack_buffer *,int)){
  118165. long i,j,k,l,s;
  118166. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118167. vorbis_info_residue0 *info=look->info;
  118168. /* move all this setup out later */
  118169. int samples_per_partition=info->grouping;
  118170. int partitions_per_word=look->phrasebook->dim;
  118171. int n=info->end-info->begin;
  118172. int partvals=n/samples_per_partition;
  118173. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118174. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118175. for(j=0;j<ch;j++)
  118176. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118177. for(s=0;s<look->stages;s++){
  118178. /* each loop decodes on partition codeword containing
  118179. partitions_pre_word partitions */
  118180. for(i=0,l=0;i<partvals;l++){
  118181. if(s==0){
  118182. /* fetch the partition word for each channel */
  118183. for(j=0;j<ch;j++){
  118184. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118185. if(temp==-1)goto eopbreak;
  118186. partword[j][l]=look->decodemap[temp];
  118187. if(partword[j][l]==NULL)goto errout;
  118188. }
  118189. }
  118190. /* now we decode residual values for the partitions */
  118191. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118192. for(j=0;j<ch;j++){
  118193. long offset=info->begin+i*samples_per_partition;
  118194. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118195. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118196. if(stagebook){
  118197. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118198. samples_per_partition)==-1)goto eopbreak;
  118199. }
  118200. }
  118201. }
  118202. }
  118203. }
  118204. errout:
  118205. eopbreak:
  118206. return(0);
  118207. }
  118208. #if 0
  118209. /* residue 0 and 1 are just slight variants of one another. 0 is
  118210. interleaved, 1 is not */
  118211. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118212. float **in,int *nonzero,int ch){
  118213. /* we encode only the nonzero parts of a bundle */
  118214. int i,used=0;
  118215. for(i=0;i<ch;i++)
  118216. if(nonzero[i])
  118217. in[used++]=in[i];
  118218. if(used)
  118219. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118220. return(_01class(vb,vl,in,used));
  118221. else
  118222. return(0);
  118223. }
  118224. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118225. float **in,float **out,int *nonzero,int ch,
  118226. long **partword){
  118227. /* we encode only the nonzero parts of a bundle */
  118228. int i,j,used=0,n=vb->pcmend/2;
  118229. for(i=0;i<ch;i++)
  118230. if(nonzero[i]){
  118231. if(out)
  118232. for(j=0;j<n;j++)
  118233. out[i][j]+=in[i][j];
  118234. in[used++]=in[i];
  118235. }
  118236. if(used){
  118237. int ret=_01forward(vb,vl,in,used,partword,
  118238. _interleaved_encodepart);
  118239. if(out){
  118240. used=0;
  118241. for(i=0;i<ch;i++)
  118242. if(nonzero[i]){
  118243. for(j=0;j<n;j++)
  118244. out[i][j]-=in[used][j];
  118245. used++;
  118246. }
  118247. }
  118248. return(ret);
  118249. }else{
  118250. return(0);
  118251. }
  118252. }
  118253. #endif
  118254. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118255. float **in,int *nonzero,int ch){
  118256. int i,used=0;
  118257. for(i=0;i<ch;i++)
  118258. if(nonzero[i])
  118259. in[used++]=in[i];
  118260. if(used)
  118261. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118262. else
  118263. return(0);
  118264. }
  118265. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118266. float **in,float **out,int *nonzero,int ch,
  118267. long **partword){
  118268. int i,j,used=0,n=vb->pcmend/2;
  118269. for(i=0;i<ch;i++)
  118270. if(nonzero[i]){
  118271. if(out)
  118272. for(j=0;j<n;j++)
  118273. out[i][j]+=in[i][j];
  118274. in[used++]=in[i];
  118275. }
  118276. if(used){
  118277. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118278. if(out){
  118279. used=0;
  118280. for(i=0;i<ch;i++)
  118281. if(nonzero[i]){
  118282. for(j=0;j<n;j++)
  118283. out[i][j]-=in[used][j];
  118284. used++;
  118285. }
  118286. }
  118287. return(ret);
  118288. }else{
  118289. return(0);
  118290. }
  118291. }
  118292. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118293. float **in,int *nonzero,int ch){
  118294. int i,used=0;
  118295. for(i=0;i<ch;i++)
  118296. if(nonzero[i])
  118297. in[used++]=in[i];
  118298. if(used)
  118299. return(_01class(vb,vl,in,used));
  118300. else
  118301. return(0);
  118302. }
  118303. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118304. float **in,int *nonzero,int ch){
  118305. int i,used=0;
  118306. for(i=0;i<ch;i++)
  118307. if(nonzero[i])
  118308. in[used++]=in[i];
  118309. if(used)
  118310. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118311. else
  118312. return(0);
  118313. }
  118314. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118315. float **in,int *nonzero,int ch){
  118316. int i,used=0;
  118317. for(i=0;i<ch;i++)
  118318. if(nonzero[i])used++;
  118319. if(used)
  118320. return(_2class(vb,vl,in,ch));
  118321. else
  118322. return(0);
  118323. }
  118324. /* res2 is slightly more different; all the channels are interleaved
  118325. into a single vector and encoded. */
  118326. int res2_forward(oggpack_buffer *opb,
  118327. vorbis_block *vb,vorbis_look_residue *vl,
  118328. float **in,float **out,int *nonzero,int ch,
  118329. long **partword){
  118330. long i,j,k,n=vb->pcmend/2,used=0;
  118331. /* don't duplicate the code; use a working vector hack for now and
  118332. reshape ourselves into a single channel res1 */
  118333. /* ugly; reallocs for each coupling pass :-( */
  118334. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118335. for(i=0;i<ch;i++){
  118336. float *pcm=in[i];
  118337. if(nonzero[i])used++;
  118338. for(j=0,k=i;j<n;j++,k+=ch)
  118339. work[k]=pcm[j];
  118340. }
  118341. if(used){
  118342. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118343. /* update the sofar vector */
  118344. if(out){
  118345. for(i=0;i<ch;i++){
  118346. float *pcm=in[i];
  118347. float *sofar=out[i];
  118348. for(j=0,k=i;j<n;j++,k+=ch)
  118349. sofar[j]+=pcm[j]-work[k];
  118350. }
  118351. }
  118352. return(ret);
  118353. }else{
  118354. return(0);
  118355. }
  118356. }
  118357. /* duplicate code here as speed is somewhat more important */
  118358. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118359. float **in,int *nonzero,int ch){
  118360. long i,k,l,s;
  118361. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118362. vorbis_info_residue0 *info=look->info;
  118363. /* move all this setup out later */
  118364. int samples_per_partition=info->grouping;
  118365. int partitions_per_word=look->phrasebook->dim;
  118366. int n=info->end-info->begin;
  118367. int partvals=n/samples_per_partition;
  118368. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118369. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118370. for(i=0;i<ch;i++)if(nonzero[i])break;
  118371. if(i==ch)return(0); /* no nonzero vectors */
  118372. for(s=0;s<look->stages;s++){
  118373. for(i=0,l=0;i<partvals;l++){
  118374. if(s==0){
  118375. /* fetch the partition word */
  118376. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118377. if(temp==-1)goto eopbreak;
  118378. partword[l]=look->decodemap[temp];
  118379. if(partword[l]==NULL)goto errout;
  118380. }
  118381. /* now we decode residual values for the partitions */
  118382. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118383. if(info->secondstages[partword[l][k]]&(1<<s)){
  118384. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118385. if(stagebook){
  118386. if(vorbis_book_decodevv_add(stagebook,in,
  118387. i*samples_per_partition+info->begin,ch,
  118388. &vb->opb,samples_per_partition)==-1)
  118389. goto eopbreak;
  118390. }
  118391. }
  118392. }
  118393. }
  118394. errout:
  118395. eopbreak:
  118396. return(0);
  118397. }
  118398. vorbis_func_residue residue0_exportbundle={
  118399. NULL,
  118400. &res0_unpack,
  118401. &res0_look,
  118402. &res0_free_info,
  118403. &res0_free_look,
  118404. NULL,
  118405. NULL,
  118406. &res0_inverse
  118407. };
  118408. vorbis_func_residue residue1_exportbundle={
  118409. &res0_pack,
  118410. &res0_unpack,
  118411. &res0_look,
  118412. &res0_free_info,
  118413. &res0_free_look,
  118414. &res1_class,
  118415. &res1_forward,
  118416. &res1_inverse
  118417. };
  118418. vorbis_func_residue residue2_exportbundle={
  118419. &res0_pack,
  118420. &res0_unpack,
  118421. &res0_look,
  118422. &res0_free_info,
  118423. &res0_free_look,
  118424. &res2_class,
  118425. &res2_forward,
  118426. &res2_inverse
  118427. };
  118428. #endif
  118429. /*** End of inlined file: res0.c ***/
  118430. /*** Start of inlined file: sharedbook.c ***/
  118431. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118432. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118433. // tasks..
  118434. #if JUCE_MSVC
  118435. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118436. #endif
  118437. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118438. #if JUCE_USE_OGGVORBIS
  118439. #include <stdlib.h>
  118440. #include <math.h>
  118441. #include <string.h>
  118442. /**** pack/unpack helpers ******************************************/
  118443. int _ilog(unsigned int v){
  118444. int ret=0;
  118445. while(v){
  118446. ret++;
  118447. v>>=1;
  118448. }
  118449. return(ret);
  118450. }
  118451. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118452. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118453. Why not IEEE? It's just not that important here. */
  118454. #define VQ_FEXP 10
  118455. #define VQ_FMAN 21
  118456. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118457. /* doesn't currently guard under/overflow */
  118458. long _float32_pack(float val){
  118459. int sign=0;
  118460. long exp;
  118461. long mant;
  118462. if(val<0){
  118463. sign=0x80000000;
  118464. val= -val;
  118465. }
  118466. exp= floor(log(val)/log(2.f));
  118467. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118468. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118469. return(sign|exp|mant);
  118470. }
  118471. float _float32_unpack(long val){
  118472. double mant=val&0x1fffff;
  118473. int sign=val&0x80000000;
  118474. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118475. if(sign)mant= -mant;
  118476. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118477. }
  118478. /* given a list of word lengths, generate a list of codewords. Works
  118479. for length ordered or unordered, always assigns the lowest valued
  118480. codewords first. Extended to handle unused entries (length 0) */
  118481. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118482. long i,j,count=0;
  118483. ogg_uint32_t marker[33];
  118484. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118485. memset(marker,0,sizeof(marker));
  118486. for(i=0;i<n;i++){
  118487. long length=l[i];
  118488. if(length>0){
  118489. ogg_uint32_t entry=marker[length];
  118490. /* when we claim a node for an entry, we also claim the nodes
  118491. below it (pruning off the imagined tree that may have dangled
  118492. from it) as well as blocking the use of any nodes directly
  118493. above for leaves */
  118494. /* update ourself */
  118495. if(length<32 && (entry>>length)){
  118496. /* error condition; the lengths must specify an overpopulated tree */
  118497. _ogg_free(r);
  118498. return(NULL);
  118499. }
  118500. r[count++]=entry;
  118501. /* Look to see if the next shorter marker points to the node
  118502. above. if so, update it and repeat. */
  118503. {
  118504. for(j=length;j>0;j--){
  118505. if(marker[j]&1){
  118506. /* have to jump branches */
  118507. if(j==1)
  118508. marker[1]++;
  118509. else
  118510. marker[j]=marker[j-1]<<1;
  118511. break; /* invariant says next upper marker would already
  118512. have been moved if it was on the same path */
  118513. }
  118514. marker[j]++;
  118515. }
  118516. }
  118517. /* prune the tree; the implicit invariant says all the longer
  118518. markers were dangling from our just-taken node. Dangle them
  118519. from our *new* node. */
  118520. for(j=length+1;j<33;j++)
  118521. if((marker[j]>>1) == entry){
  118522. entry=marker[j];
  118523. marker[j]=marker[j-1]<<1;
  118524. }else
  118525. break;
  118526. }else
  118527. if(sparsecount==0)count++;
  118528. }
  118529. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118530. endian */
  118531. for(i=0,count=0;i<n;i++){
  118532. ogg_uint32_t temp=0;
  118533. for(j=0;j<l[i];j++){
  118534. temp<<=1;
  118535. temp|=(r[count]>>j)&1;
  118536. }
  118537. if(sparsecount){
  118538. if(l[i])
  118539. r[count++]=temp;
  118540. }else
  118541. r[count++]=temp;
  118542. }
  118543. return(r);
  118544. }
  118545. /* there might be a straightforward one-line way to do the below
  118546. that's portable and totally safe against roundoff, but I haven't
  118547. thought of it. Therefore, we opt on the side of caution */
  118548. long _book_maptype1_quantvals(const static_codebook *b){
  118549. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118550. /* the above *should* be reliable, but we'll not assume that FP is
  118551. ever reliable when bitstream sync is at stake; verify via integer
  118552. means that vals really is the greatest value of dim for which
  118553. vals^b->bim <= b->entries */
  118554. /* treat the above as an initial guess */
  118555. while(1){
  118556. long acc=1;
  118557. long acc1=1;
  118558. int i;
  118559. for(i=0;i<b->dim;i++){
  118560. acc*=vals;
  118561. acc1*=vals+1;
  118562. }
  118563. if(acc<=b->entries && acc1>b->entries){
  118564. return(vals);
  118565. }else{
  118566. if(acc>b->entries){
  118567. vals--;
  118568. }else{
  118569. vals++;
  118570. }
  118571. }
  118572. }
  118573. }
  118574. /* unpack the quantized list of values for encode/decode ***********/
  118575. /* we need to deal with two map types: in map type 1, the values are
  118576. generated algorithmically (each column of the vector counts through
  118577. the values in the quant vector). in map type 2, all the values came
  118578. in in an explicit list. Both value lists must be unpacked */
  118579. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118580. long j,k,count=0;
  118581. if(b->maptype==1 || b->maptype==2){
  118582. int quantvals;
  118583. float mindel=_float32_unpack(b->q_min);
  118584. float delta=_float32_unpack(b->q_delta);
  118585. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118586. /* maptype 1 and 2 both use a quantized value vector, but
  118587. different sizes */
  118588. switch(b->maptype){
  118589. case 1:
  118590. /* most of the time, entries%dimensions == 0, but we need to be
  118591. well defined. We define that the possible vales at each
  118592. scalar is values == entries/dim. If entries%dim != 0, we'll
  118593. have 'too few' values (values*dim<entries), which means that
  118594. we'll have 'left over' entries; left over entries use zeroed
  118595. values (and are wasted). So don't generate codebooks like
  118596. that */
  118597. quantvals=_book_maptype1_quantvals(b);
  118598. for(j=0;j<b->entries;j++){
  118599. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118600. float last=0.f;
  118601. int indexdiv=1;
  118602. for(k=0;k<b->dim;k++){
  118603. int index= (j/indexdiv)%quantvals;
  118604. float val=b->quantlist[index];
  118605. val=fabs(val)*delta+mindel+last;
  118606. if(b->q_sequencep)last=val;
  118607. if(sparsemap)
  118608. r[sparsemap[count]*b->dim+k]=val;
  118609. else
  118610. r[count*b->dim+k]=val;
  118611. indexdiv*=quantvals;
  118612. }
  118613. count++;
  118614. }
  118615. }
  118616. break;
  118617. case 2:
  118618. for(j=0;j<b->entries;j++){
  118619. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118620. float last=0.f;
  118621. for(k=0;k<b->dim;k++){
  118622. float val=b->quantlist[j*b->dim+k];
  118623. val=fabs(val)*delta+mindel+last;
  118624. if(b->q_sequencep)last=val;
  118625. if(sparsemap)
  118626. r[sparsemap[count]*b->dim+k]=val;
  118627. else
  118628. r[count*b->dim+k]=val;
  118629. }
  118630. count++;
  118631. }
  118632. }
  118633. break;
  118634. }
  118635. return(r);
  118636. }
  118637. return(NULL);
  118638. }
  118639. void vorbis_staticbook_clear(static_codebook *b){
  118640. if(b->allocedp){
  118641. if(b->quantlist)_ogg_free(b->quantlist);
  118642. if(b->lengthlist)_ogg_free(b->lengthlist);
  118643. if(b->nearest_tree){
  118644. _ogg_free(b->nearest_tree->ptr0);
  118645. _ogg_free(b->nearest_tree->ptr1);
  118646. _ogg_free(b->nearest_tree->p);
  118647. _ogg_free(b->nearest_tree->q);
  118648. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118649. _ogg_free(b->nearest_tree);
  118650. }
  118651. if(b->thresh_tree){
  118652. _ogg_free(b->thresh_tree->quantthresh);
  118653. _ogg_free(b->thresh_tree->quantmap);
  118654. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118655. _ogg_free(b->thresh_tree);
  118656. }
  118657. memset(b,0,sizeof(*b));
  118658. }
  118659. }
  118660. void vorbis_staticbook_destroy(static_codebook *b){
  118661. if(b->allocedp){
  118662. vorbis_staticbook_clear(b);
  118663. _ogg_free(b);
  118664. }
  118665. }
  118666. void vorbis_book_clear(codebook *b){
  118667. /* static book is not cleared; we're likely called on the lookup and
  118668. the static codebook belongs to the info struct */
  118669. if(b->valuelist)_ogg_free(b->valuelist);
  118670. if(b->codelist)_ogg_free(b->codelist);
  118671. if(b->dec_index)_ogg_free(b->dec_index);
  118672. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118673. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118674. memset(b,0,sizeof(*b));
  118675. }
  118676. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118677. memset(c,0,sizeof(*c));
  118678. c->c=s;
  118679. c->entries=s->entries;
  118680. c->used_entries=s->entries;
  118681. c->dim=s->dim;
  118682. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118683. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118684. return(0);
  118685. }
  118686. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118687. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118688. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118689. }
  118690. /* decode codebook arrangement is more heavily optimized than encode */
  118691. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118692. int i,j,n=0,tabn;
  118693. int *sortindex;
  118694. memset(c,0,sizeof(*c));
  118695. /* count actually used entries */
  118696. for(i=0;i<s->entries;i++)
  118697. if(s->lengthlist[i]>0)
  118698. n++;
  118699. c->entries=s->entries;
  118700. c->used_entries=n;
  118701. c->dim=s->dim;
  118702. /* two different remappings go on here.
  118703. First, we collapse the likely sparse codebook down only to
  118704. actually represented values/words. This collapsing needs to be
  118705. indexed as map-valueless books are used to encode original entry
  118706. positions as integers.
  118707. Second, we reorder all vectors, including the entry index above,
  118708. by sorted bitreversed codeword to allow treeless decode. */
  118709. {
  118710. /* perform sort */
  118711. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118712. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118713. if(codes==NULL)goto err_out;
  118714. for(i=0;i<n;i++){
  118715. codes[i]=ogg_bitreverse(codes[i]);
  118716. codep[i]=codes+i;
  118717. }
  118718. qsort(codep,n,sizeof(*codep),sort32a);
  118719. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118720. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118721. /* the index is a reverse index */
  118722. for(i=0;i<n;i++){
  118723. int position=codep[i]-codes;
  118724. sortindex[position]=i;
  118725. }
  118726. for(i=0;i<n;i++)
  118727. c->codelist[sortindex[i]]=codes[i];
  118728. _ogg_free(codes);
  118729. }
  118730. c->valuelist=_book_unquantize(s,n,sortindex);
  118731. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118732. for(n=0,i=0;i<s->entries;i++)
  118733. if(s->lengthlist[i]>0)
  118734. c->dec_index[sortindex[n++]]=i;
  118735. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118736. for(n=0,i=0;i<s->entries;i++)
  118737. if(s->lengthlist[i]>0)
  118738. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118739. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118740. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118741. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118742. tabn=1<<c->dec_firsttablen;
  118743. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118744. c->dec_maxlength=0;
  118745. for(i=0;i<n;i++){
  118746. if(c->dec_maxlength<c->dec_codelengths[i])
  118747. c->dec_maxlength=c->dec_codelengths[i];
  118748. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118749. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118750. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118751. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118752. }
  118753. }
  118754. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118755. hints for the non-direct-hits */
  118756. {
  118757. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118758. long lo=0,hi=0;
  118759. for(i=0;i<tabn;i++){
  118760. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118761. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118762. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118763. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118764. /* we only actually have 15 bits per hint to play with here.
  118765. In order to overflow gracefully (nothing breaks, efficiency
  118766. just drops), encode as the difference from the extremes. */
  118767. {
  118768. unsigned long loval=lo;
  118769. unsigned long hival=n-hi;
  118770. if(loval>0x7fff)loval=0x7fff;
  118771. if(hival>0x7fff)hival=0x7fff;
  118772. c->dec_firsttable[ogg_bitreverse(word)]=
  118773. 0x80000000UL | (loval<<15) | hival;
  118774. }
  118775. }
  118776. }
  118777. }
  118778. return(0);
  118779. err_out:
  118780. vorbis_book_clear(c);
  118781. return(-1);
  118782. }
  118783. static float _dist(int el,float *ref, float *b,int step){
  118784. int i;
  118785. float acc=0.f;
  118786. for(i=0;i<el;i++){
  118787. float val=(ref[i]-b[i*step]);
  118788. acc+=val*val;
  118789. }
  118790. return(acc);
  118791. }
  118792. int _best(codebook *book, float *a, int step){
  118793. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118794. #if 0
  118795. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118796. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118797. #endif
  118798. int dim=book->dim;
  118799. int k,o;
  118800. /*int savebest=-1;
  118801. float saverr;*/
  118802. /* do we have a threshhold encode hint? */
  118803. if(tt){
  118804. int index=0,i;
  118805. /* find the quant val of each scalar */
  118806. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118807. i=tt->threshvals>>1;
  118808. if(a[o]<tt->quantthresh[i]){
  118809. for(;i>0;i--)
  118810. if(a[o]>=tt->quantthresh[i-1])
  118811. break;
  118812. }else{
  118813. for(i++;i<tt->threshvals-1;i++)
  118814. if(a[o]<tt->quantthresh[i])break;
  118815. }
  118816. index=(index*tt->quantvals)+tt->quantmap[i];
  118817. }
  118818. /* regular lattices are easy :-) */
  118819. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118820. use a decision tree after all
  118821. and fall through*/
  118822. return(index);
  118823. }
  118824. #if 0
  118825. /* do we have a pigeonhole encode hint? */
  118826. if(pt){
  118827. const static_codebook *c=book->c;
  118828. int i,besti=-1;
  118829. float best=0.f;
  118830. int entry=0;
  118831. /* dealing with sequentialness is a pain in the ass */
  118832. if(c->q_sequencep){
  118833. int pv;
  118834. long mul=1;
  118835. float qlast=0;
  118836. for(k=0,o=0;k<dim;k++,o+=step){
  118837. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118838. if(pv<0 || pv>=pt->mapentries)break;
  118839. entry+=pt->pigeonmap[pv]*mul;
  118840. mul*=pt->quantvals;
  118841. qlast+=pv*pt->del+pt->min;
  118842. }
  118843. }else{
  118844. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118845. int pv=(int)((a[o]-pt->min)/pt->del);
  118846. if(pv<0 || pv>=pt->mapentries)break;
  118847. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118848. }
  118849. }
  118850. /* must be within the pigeonholable range; if we quant outside (or
  118851. in an entry that we define no list for), brute force it */
  118852. if(k==dim && pt->fitlength[entry]){
  118853. /* search the abbreviated list */
  118854. long *list=pt->fitlist+pt->fitmap[entry];
  118855. for(i=0;i<pt->fitlength[entry];i++){
  118856. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118857. if(besti==-1 || this<best){
  118858. best=this;
  118859. besti=list[i];
  118860. }
  118861. }
  118862. return(besti);
  118863. }
  118864. }
  118865. if(nt){
  118866. /* optimized using the decision tree */
  118867. while(1){
  118868. float c=0.f;
  118869. float *p=book->valuelist+nt->p[ptr];
  118870. float *q=book->valuelist+nt->q[ptr];
  118871. for(k=0,o=0;k<dim;k++,o+=step)
  118872. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118873. if(c>0.f) /* in A */
  118874. ptr= -nt->ptr0[ptr];
  118875. else /* in B */
  118876. ptr= -nt->ptr1[ptr];
  118877. if(ptr<=0)break;
  118878. }
  118879. return(-ptr);
  118880. }
  118881. #endif
  118882. /* brute force it! */
  118883. {
  118884. const static_codebook *c=book->c;
  118885. int i,besti=-1;
  118886. float best=0.f;
  118887. float *e=book->valuelist;
  118888. for(i=0;i<book->entries;i++){
  118889. if(c->lengthlist[i]>0){
  118890. float thisx=_dist(dim,e,a,step);
  118891. if(besti==-1 || thisx<best){
  118892. best=thisx;
  118893. besti=i;
  118894. }
  118895. }
  118896. e+=dim;
  118897. }
  118898. /*if(savebest!=-1 && savebest!=besti){
  118899. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118900. "original:");
  118901. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118902. fprintf(stderr,"\n"
  118903. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118904. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118905. (book->valuelist+savebest*dim)[i]);
  118906. fprintf(stderr,"\n"
  118907. "bruteforce (entry %d, err %g):",besti,best);
  118908. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118909. (book->valuelist+besti*dim)[i]);
  118910. fprintf(stderr,"\n");
  118911. }*/
  118912. return(besti);
  118913. }
  118914. }
  118915. long vorbis_book_codeword(codebook *book,int entry){
  118916. if(book->c) /* only use with encode; decode optimizations are
  118917. allowed to break this */
  118918. return book->codelist[entry];
  118919. return -1;
  118920. }
  118921. long vorbis_book_codelen(codebook *book,int entry){
  118922. if(book->c) /* only use with encode; decode optimizations are
  118923. allowed to break this */
  118924. return book->c->lengthlist[entry];
  118925. return -1;
  118926. }
  118927. #ifdef _V_SELFTEST
  118928. /* Unit tests of the dequantizer; this stuff will be OK
  118929. cross-platform, I simply want to be sure that special mapping cases
  118930. actually work properly; a bug could go unnoticed for a while */
  118931. #include <stdio.h>
  118932. /* cases:
  118933. no mapping
  118934. full, explicit mapping
  118935. algorithmic mapping
  118936. nonsequential
  118937. sequential
  118938. */
  118939. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118940. static long partial_quantlist1[]={0,7,2};
  118941. /* no mapping */
  118942. static_codebook test1={
  118943. 4,16,
  118944. NULL,
  118945. 0,
  118946. 0,0,0,0,
  118947. NULL,
  118948. NULL,NULL
  118949. };
  118950. static float *test1_result=NULL;
  118951. /* linear, full mapping, nonsequential */
  118952. static_codebook test2={
  118953. 4,3,
  118954. NULL,
  118955. 2,
  118956. -533200896,1611661312,4,0,
  118957. full_quantlist1,
  118958. NULL,NULL
  118959. };
  118960. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118961. /* linear, full mapping, sequential */
  118962. static_codebook test3={
  118963. 4,3,
  118964. NULL,
  118965. 2,
  118966. -533200896,1611661312,4,1,
  118967. full_quantlist1,
  118968. NULL,NULL
  118969. };
  118970. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118971. /* linear, algorithmic mapping, nonsequential */
  118972. static_codebook test4={
  118973. 3,27,
  118974. NULL,
  118975. 1,
  118976. -533200896,1611661312,4,0,
  118977. partial_quantlist1,
  118978. NULL,NULL
  118979. };
  118980. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118981. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118982. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118983. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118984. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118985. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118986. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118987. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118988. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118989. /* linear, algorithmic mapping, sequential */
  118990. static_codebook test5={
  118991. 3,27,
  118992. NULL,
  118993. 1,
  118994. -533200896,1611661312,4,1,
  118995. partial_quantlist1,
  118996. NULL,NULL
  118997. };
  118998. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118999. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119000. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119001. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119002. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119003. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119004. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119005. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119006. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119007. void run_test(static_codebook *b,float *comp){
  119008. float *out=_book_unquantize(b,b->entries,NULL);
  119009. int i;
  119010. if(comp){
  119011. if(!out){
  119012. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119013. exit(1);
  119014. }
  119015. for(i=0;i<b->entries*b->dim;i++)
  119016. if(fabs(out[i]-comp[i])>.0001){
  119017. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119018. "position %d, %g != %g\n",i,out[i],comp[i]);
  119019. exit(1);
  119020. }
  119021. }else{
  119022. if(out){
  119023. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119024. " correct result should have been NULL\n");
  119025. exit(1);
  119026. }
  119027. }
  119028. }
  119029. int main(){
  119030. /* run the nine dequant tests, and compare to the hand-rolled results */
  119031. fprintf(stderr,"Dequant test 1... ");
  119032. run_test(&test1,test1_result);
  119033. fprintf(stderr,"OK\nDequant test 2... ");
  119034. run_test(&test2,test2_result);
  119035. fprintf(stderr,"OK\nDequant test 3... ");
  119036. run_test(&test3,test3_result);
  119037. fprintf(stderr,"OK\nDequant test 4... ");
  119038. run_test(&test4,test4_result);
  119039. fprintf(stderr,"OK\nDequant test 5... ");
  119040. run_test(&test5,test5_result);
  119041. fprintf(stderr,"OK\n\n");
  119042. return(0);
  119043. }
  119044. #endif
  119045. #endif
  119046. /*** End of inlined file: sharedbook.c ***/
  119047. /*** Start of inlined file: smallft.c ***/
  119048. /* FFT implementation from OggSquish, minus cosine transforms,
  119049. * minus all but radix 2/4 case. In Vorbis we only need this
  119050. * cut-down version.
  119051. *
  119052. * To do more than just power-of-two sized vectors, see the full
  119053. * version I wrote for NetLib.
  119054. *
  119055. * Note that the packing is a little strange; rather than the FFT r/i
  119056. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119057. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119058. * FORTRAN version
  119059. */
  119060. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119061. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119062. // tasks..
  119063. #if JUCE_MSVC
  119064. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119065. #endif
  119066. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119067. #if JUCE_USE_OGGVORBIS
  119068. #include <stdlib.h>
  119069. #include <string.h>
  119070. #include <math.h>
  119071. static void drfti1(int n, float *wa, int *ifac){
  119072. static int ntryh[4] = { 4,2,3,5 };
  119073. static float tpi = 6.28318530717958648f;
  119074. float arg,argh,argld,fi;
  119075. int ntry=0,i,j=-1;
  119076. int k1, l1, l2, ib;
  119077. int ld, ii, ip, is, nq, nr;
  119078. int ido, ipm, nfm1;
  119079. int nl=n;
  119080. int nf=0;
  119081. L101:
  119082. j++;
  119083. if (j < 4)
  119084. ntry=ntryh[j];
  119085. else
  119086. ntry+=2;
  119087. L104:
  119088. nq=nl/ntry;
  119089. nr=nl-ntry*nq;
  119090. if (nr!=0) goto L101;
  119091. nf++;
  119092. ifac[nf+1]=ntry;
  119093. nl=nq;
  119094. if(ntry!=2)goto L107;
  119095. if(nf==1)goto L107;
  119096. for (i=1;i<nf;i++){
  119097. ib=nf-i+1;
  119098. ifac[ib+1]=ifac[ib];
  119099. }
  119100. ifac[2] = 2;
  119101. L107:
  119102. if(nl!=1)goto L104;
  119103. ifac[0]=n;
  119104. ifac[1]=nf;
  119105. argh=tpi/n;
  119106. is=0;
  119107. nfm1=nf-1;
  119108. l1=1;
  119109. if(nfm1==0)return;
  119110. for (k1=0;k1<nfm1;k1++){
  119111. ip=ifac[k1+2];
  119112. ld=0;
  119113. l2=l1*ip;
  119114. ido=n/l2;
  119115. ipm=ip-1;
  119116. for (j=0;j<ipm;j++){
  119117. ld+=l1;
  119118. i=is;
  119119. argld=(float)ld*argh;
  119120. fi=0.f;
  119121. for (ii=2;ii<ido;ii+=2){
  119122. fi+=1.f;
  119123. arg=fi*argld;
  119124. wa[i++]=cos(arg);
  119125. wa[i++]=sin(arg);
  119126. }
  119127. is+=ido;
  119128. }
  119129. l1=l2;
  119130. }
  119131. }
  119132. static void fdrffti(int n, float *wsave, int *ifac){
  119133. if (n == 1) return;
  119134. drfti1(n, wsave+n, ifac);
  119135. }
  119136. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119137. int i,k;
  119138. float ti2,tr2;
  119139. int t0,t1,t2,t3,t4,t5,t6;
  119140. t1=0;
  119141. t0=(t2=l1*ido);
  119142. t3=ido<<1;
  119143. for(k=0;k<l1;k++){
  119144. ch[t1<<1]=cc[t1]+cc[t2];
  119145. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119146. t1+=ido;
  119147. t2+=ido;
  119148. }
  119149. if(ido<2)return;
  119150. if(ido==2)goto L105;
  119151. t1=0;
  119152. t2=t0;
  119153. for(k=0;k<l1;k++){
  119154. t3=t2;
  119155. t4=(t1<<1)+(ido<<1);
  119156. t5=t1;
  119157. t6=t1+t1;
  119158. for(i=2;i<ido;i+=2){
  119159. t3+=2;
  119160. t4-=2;
  119161. t5+=2;
  119162. t6+=2;
  119163. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119164. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119165. ch[t6]=cc[t5]+ti2;
  119166. ch[t4]=ti2-cc[t5];
  119167. ch[t6-1]=cc[t5-1]+tr2;
  119168. ch[t4-1]=cc[t5-1]-tr2;
  119169. }
  119170. t1+=ido;
  119171. t2+=ido;
  119172. }
  119173. if(ido%2==1)return;
  119174. L105:
  119175. t3=(t2=(t1=ido)-1);
  119176. t2+=t0;
  119177. for(k=0;k<l1;k++){
  119178. ch[t1]=-cc[t2];
  119179. ch[t1-1]=cc[t3];
  119180. t1+=ido<<1;
  119181. t2+=ido;
  119182. t3+=ido;
  119183. }
  119184. }
  119185. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119186. float *wa2,float *wa3){
  119187. static float hsqt2 = .70710678118654752f;
  119188. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119189. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119190. t0=l1*ido;
  119191. t1=t0;
  119192. t4=t1<<1;
  119193. t2=t1+(t1<<1);
  119194. t3=0;
  119195. for(k=0;k<l1;k++){
  119196. tr1=cc[t1]+cc[t2];
  119197. tr2=cc[t3]+cc[t4];
  119198. ch[t5=t3<<2]=tr1+tr2;
  119199. ch[(ido<<2)+t5-1]=tr2-tr1;
  119200. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119201. ch[t5]=cc[t2]-cc[t1];
  119202. t1+=ido;
  119203. t2+=ido;
  119204. t3+=ido;
  119205. t4+=ido;
  119206. }
  119207. if(ido<2)return;
  119208. if(ido==2)goto L105;
  119209. t1=0;
  119210. for(k=0;k<l1;k++){
  119211. t2=t1;
  119212. t4=t1<<2;
  119213. t5=(t6=ido<<1)+t4;
  119214. for(i=2;i<ido;i+=2){
  119215. t3=(t2+=2);
  119216. t4+=2;
  119217. t5-=2;
  119218. t3+=t0;
  119219. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119220. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119221. t3+=t0;
  119222. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119223. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119224. t3+=t0;
  119225. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119226. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119227. tr1=cr2+cr4;
  119228. tr4=cr4-cr2;
  119229. ti1=ci2+ci4;
  119230. ti4=ci2-ci4;
  119231. ti2=cc[t2]+ci3;
  119232. ti3=cc[t2]-ci3;
  119233. tr2=cc[t2-1]+cr3;
  119234. tr3=cc[t2-1]-cr3;
  119235. ch[t4-1]=tr1+tr2;
  119236. ch[t4]=ti1+ti2;
  119237. ch[t5-1]=tr3-ti4;
  119238. ch[t5]=tr4-ti3;
  119239. ch[t4+t6-1]=ti4+tr3;
  119240. ch[t4+t6]=tr4+ti3;
  119241. ch[t5+t6-1]=tr2-tr1;
  119242. ch[t5+t6]=ti1-ti2;
  119243. }
  119244. t1+=ido;
  119245. }
  119246. if(ido&1)return;
  119247. L105:
  119248. t2=(t1=t0+ido-1)+(t0<<1);
  119249. t3=ido<<2;
  119250. t4=ido;
  119251. t5=ido<<1;
  119252. t6=ido;
  119253. for(k=0;k<l1;k++){
  119254. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119255. tr1=hsqt2*(cc[t1]-cc[t2]);
  119256. ch[t4-1]=tr1+cc[t6-1];
  119257. ch[t4+t5-1]=cc[t6-1]-tr1;
  119258. ch[t4]=ti1-cc[t1+t0];
  119259. ch[t4+t5]=ti1+cc[t1+t0];
  119260. t1+=ido;
  119261. t2+=ido;
  119262. t4+=t3;
  119263. t6+=ido;
  119264. }
  119265. }
  119266. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119267. float *c2,float *ch,float *ch2,float *wa){
  119268. static float tpi=6.283185307179586f;
  119269. int idij,ipph,i,j,k,l,ic,ik,is;
  119270. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119271. float dc2,ai1,ai2,ar1,ar2,ds2;
  119272. int nbd;
  119273. float dcp,arg,dsp,ar1h,ar2h;
  119274. int idp2,ipp2;
  119275. arg=tpi/(float)ip;
  119276. dcp=cos(arg);
  119277. dsp=sin(arg);
  119278. ipph=(ip+1)>>1;
  119279. ipp2=ip;
  119280. idp2=ido;
  119281. nbd=(ido-1)>>1;
  119282. t0=l1*ido;
  119283. t10=ip*ido;
  119284. if(ido==1)goto L119;
  119285. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119286. t1=0;
  119287. for(j=1;j<ip;j++){
  119288. t1+=t0;
  119289. t2=t1;
  119290. for(k=0;k<l1;k++){
  119291. ch[t2]=c1[t2];
  119292. t2+=ido;
  119293. }
  119294. }
  119295. is=-ido;
  119296. t1=0;
  119297. if(nbd>l1){
  119298. for(j=1;j<ip;j++){
  119299. t1+=t0;
  119300. is+=ido;
  119301. t2= -ido+t1;
  119302. for(k=0;k<l1;k++){
  119303. idij=is-1;
  119304. t2+=ido;
  119305. t3=t2;
  119306. for(i=2;i<ido;i+=2){
  119307. idij+=2;
  119308. t3+=2;
  119309. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119310. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119311. }
  119312. }
  119313. }
  119314. }else{
  119315. for(j=1;j<ip;j++){
  119316. is+=ido;
  119317. idij=is-1;
  119318. t1+=t0;
  119319. t2=t1;
  119320. for(i=2;i<ido;i+=2){
  119321. idij+=2;
  119322. t2+=2;
  119323. t3=t2;
  119324. for(k=0;k<l1;k++){
  119325. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119326. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119327. t3+=ido;
  119328. }
  119329. }
  119330. }
  119331. }
  119332. t1=0;
  119333. t2=ipp2*t0;
  119334. if(nbd<l1){
  119335. for(j=1;j<ipph;j++){
  119336. t1+=t0;
  119337. t2-=t0;
  119338. t3=t1;
  119339. t4=t2;
  119340. for(i=2;i<ido;i+=2){
  119341. t3+=2;
  119342. t4+=2;
  119343. t5=t3-ido;
  119344. t6=t4-ido;
  119345. for(k=0;k<l1;k++){
  119346. t5+=ido;
  119347. t6+=ido;
  119348. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119349. c1[t6-1]=ch[t5]-ch[t6];
  119350. c1[t5]=ch[t5]+ch[t6];
  119351. c1[t6]=ch[t6-1]-ch[t5-1];
  119352. }
  119353. }
  119354. }
  119355. }else{
  119356. for(j=1;j<ipph;j++){
  119357. t1+=t0;
  119358. t2-=t0;
  119359. t3=t1;
  119360. t4=t2;
  119361. for(k=0;k<l1;k++){
  119362. t5=t3;
  119363. t6=t4;
  119364. for(i=2;i<ido;i+=2){
  119365. t5+=2;
  119366. t6+=2;
  119367. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119368. c1[t6-1]=ch[t5]-ch[t6];
  119369. c1[t5]=ch[t5]+ch[t6];
  119370. c1[t6]=ch[t6-1]-ch[t5-1];
  119371. }
  119372. t3+=ido;
  119373. t4+=ido;
  119374. }
  119375. }
  119376. }
  119377. L119:
  119378. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119379. t1=0;
  119380. t2=ipp2*idl1;
  119381. for(j=1;j<ipph;j++){
  119382. t1+=t0;
  119383. t2-=t0;
  119384. t3=t1-ido;
  119385. t4=t2-ido;
  119386. for(k=0;k<l1;k++){
  119387. t3+=ido;
  119388. t4+=ido;
  119389. c1[t3]=ch[t3]+ch[t4];
  119390. c1[t4]=ch[t4]-ch[t3];
  119391. }
  119392. }
  119393. ar1=1.f;
  119394. ai1=0.f;
  119395. t1=0;
  119396. t2=ipp2*idl1;
  119397. t3=(ip-1)*idl1;
  119398. for(l=1;l<ipph;l++){
  119399. t1+=idl1;
  119400. t2-=idl1;
  119401. ar1h=dcp*ar1-dsp*ai1;
  119402. ai1=dcp*ai1+dsp*ar1;
  119403. ar1=ar1h;
  119404. t4=t1;
  119405. t5=t2;
  119406. t6=t3;
  119407. t7=idl1;
  119408. for(ik=0;ik<idl1;ik++){
  119409. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119410. ch2[t5++]=ai1*c2[t6++];
  119411. }
  119412. dc2=ar1;
  119413. ds2=ai1;
  119414. ar2=ar1;
  119415. ai2=ai1;
  119416. t4=idl1;
  119417. t5=(ipp2-1)*idl1;
  119418. for(j=2;j<ipph;j++){
  119419. t4+=idl1;
  119420. t5-=idl1;
  119421. ar2h=dc2*ar2-ds2*ai2;
  119422. ai2=dc2*ai2+ds2*ar2;
  119423. ar2=ar2h;
  119424. t6=t1;
  119425. t7=t2;
  119426. t8=t4;
  119427. t9=t5;
  119428. for(ik=0;ik<idl1;ik++){
  119429. ch2[t6++]+=ar2*c2[t8++];
  119430. ch2[t7++]+=ai2*c2[t9++];
  119431. }
  119432. }
  119433. }
  119434. t1=0;
  119435. for(j=1;j<ipph;j++){
  119436. t1+=idl1;
  119437. t2=t1;
  119438. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119439. }
  119440. if(ido<l1)goto L132;
  119441. t1=0;
  119442. t2=0;
  119443. for(k=0;k<l1;k++){
  119444. t3=t1;
  119445. t4=t2;
  119446. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119447. t1+=ido;
  119448. t2+=t10;
  119449. }
  119450. goto L135;
  119451. L132:
  119452. for(i=0;i<ido;i++){
  119453. t1=i;
  119454. t2=i;
  119455. for(k=0;k<l1;k++){
  119456. cc[t2]=ch[t1];
  119457. t1+=ido;
  119458. t2+=t10;
  119459. }
  119460. }
  119461. L135:
  119462. t1=0;
  119463. t2=ido<<1;
  119464. t3=0;
  119465. t4=ipp2*t0;
  119466. for(j=1;j<ipph;j++){
  119467. t1+=t2;
  119468. t3+=t0;
  119469. t4-=t0;
  119470. t5=t1;
  119471. t6=t3;
  119472. t7=t4;
  119473. for(k=0;k<l1;k++){
  119474. cc[t5-1]=ch[t6];
  119475. cc[t5]=ch[t7];
  119476. t5+=t10;
  119477. t6+=ido;
  119478. t7+=ido;
  119479. }
  119480. }
  119481. if(ido==1)return;
  119482. if(nbd<l1)goto L141;
  119483. t1=-ido;
  119484. t3=0;
  119485. t4=0;
  119486. t5=ipp2*t0;
  119487. for(j=1;j<ipph;j++){
  119488. t1+=t2;
  119489. t3+=t2;
  119490. t4+=t0;
  119491. t5-=t0;
  119492. t6=t1;
  119493. t7=t3;
  119494. t8=t4;
  119495. t9=t5;
  119496. for(k=0;k<l1;k++){
  119497. for(i=2;i<ido;i+=2){
  119498. ic=idp2-i;
  119499. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119500. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119501. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119502. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119503. }
  119504. t6+=t10;
  119505. t7+=t10;
  119506. t8+=ido;
  119507. t9+=ido;
  119508. }
  119509. }
  119510. return;
  119511. L141:
  119512. t1=-ido;
  119513. t3=0;
  119514. t4=0;
  119515. t5=ipp2*t0;
  119516. for(j=1;j<ipph;j++){
  119517. t1+=t2;
  119518. t3+=t2;
  119519. t4+=t0;
  119520. t5-=t0;
  119521. for(i=2;i<ido;i+=2){
  119522. t6=idp2+t1-i;
  119523. t7=i+t3;
  119524. t8=i+t4;
  119525. t9=i+t5;
  119526. for(k=0;k<l1;k++){
  119527. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119528. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119529. cc[t7]=ch[t8]+ch[t9];
  119530. cc[t6]=ch[t9]-ch[t8];
  119531. t6+=t10;
  119532. t7+=t10;
  119533. t8+=ido;
  119534. t9+=ido;
  119535. }
  119536. }
  119537. }
  119538. }
  119539. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119540. int i,k1,l1,l2;
  119541. int na,kh,nf;
  119542. int ip,iw,ido,idl1,ix2,ix3;
  119543. nf=ifac[1];
  119544. na=1;
  119545. l2=n;
  119546. iw=n;
  119547. for(k1=0;k1<nf;k1++){
  119548. kh=nf-k1;
  119549. ip=ifac[kh+1];
  119550. l1=l2/ip;
  119551. ido=n/l2;
  119552. idl1=ido*l1;
  119553. iw-=(ip-1)*ido;
  119554. na=1-na;
  119555. if(ip!=4)goto L102;
  119556. ix2=iw+ido;
  119557. ix3=ix2+ido;
  119558. if(na!=0)
  119559. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119560. else
  119561. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119562. goto L110;
  119563. L102:
  119564. if(ip!=2)goto L104;
  119565. if(na!=0)goto L103;
  119566. dradf2(ido,l1,c,ch,wa+iw-1);
  119567. goto L110;
  119568. L103:
  119569. dradf2(ido,l1,ch,c,wa+iw-1);
  119570. goto L110;
  119571. L104:
  119572. if(ido==1)na=1-na;
  119573. if(na!=0)goto L109;
  119574. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119575. na=1;
  119576. goto L110;
  119577. L109:
  119578. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119579. na=0;
  119580. L110:
  119581. l2=l1;
  119582. }
  119583. if(na==1)return;
  119584. for(i=0;i<n;i++)c[i]=ch[i];
  119585. }
  119586. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119587. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119588. float ti2,tr2;
  119589. t0=l1*ido;
  119590. t1=0;
  119591. t2=0;
  119592. t3=(ido<<1)-1;
  119593. for(k=0;k<l1;k++){
  119594. ch[t1]=cc[t2]+cc[t3+t2];
  119595. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119596. t2=(t1+=ido)<<1;
  119597. }
  119598. if(ido<2)return;
  119599. if(ido==2)goto L105;
  119600. t1=0;
  119601. t2=0;
  119602. for(k=0;k<l1;k++){
  119603. t3=t1;
  119604. t5=(t4=t2)+(ido<<1);
  119605. t6=t0+t1;
  119606. for(i=2;i<ido;i+=2){
  119607. t3+=2;
  119608. t4+=2;
  119609. t5-=2;
  119610. t6+=2;
  119611. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119612. tr2=cc[t4-1]-cc[t5-1];
  119613. ch[t3]=cc[t4]-cc[t5];
  119614. ti2=cc[t4]+cc[t5];
  119615. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119616. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119617. }
  119618. t2=(t1+=ido)<<1;
  119619. }
  119620. if(ido%2==1)return;
  119621. L105:
  119622. t1=ido-1;
  119623. t2=ido-1;
  119624. for(k=0;k<l1;k++){
  119625. ch[t1]=cc[t2]+cc[t2];
  119626. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119627. t1+=ido;
  119628. t2+=ido<<1;
  119629. }
  119630. }
  119631. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119632. float *wa2){
  119633. static float taur = -.5f;
  119634. static float taui = .8660254037844386f;
  119635. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119636. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119637. t0=l1*ido;
  119638. t1=0;
  119639. t2=t0<<1;
  119640. t3=ido<<1;
  119641. t4=ido+(ido<<1);
  119642. t5=0;
  119643. for(k=0;k<l1;k++){
  119644. tr2=cc[t3-1]+cc[t3-1];
  119645. cr2=cc[t5]+(taur*tr2);
  119646. ch[t1]=cc[t5]+tr2;
  119647. ci3=taui*(cc[t3]+cc[t3]);
  119648. ch[t1+t0]=cr2-ci3;
  119649. ch[t1+t2]=cr2+ci3;
  119650. t1+=ido;
  119651. t3+=t4;
  119652. t5+=t4;
  119653. }
  119654. if(ido==1)return;
  119655. t1=0;
  119656. t3=ido<<1;
  119657. for(k=0;k<l1;k++){
  119658. t7=t1+(t1<<1);
  119659. t6=(t5=t7+t3);
  119660. t8=t1;
  119661. t10=(t9=t1+t0)+t0;
  119662. for(i=2;i<ido;i+=2){
  119663. t5+=2;
  119664. t6-=2;
  119665. t7+=2;
  119666. t8+=2;
  119667. t9+=2;
  119668. t10+=2;
  119669. tr2=cc[t5-1]+cc[t6-1];
  119670. cr2=cc[t7-1]+(taur*tr2);
  119671. ch[t8-1]=cc[t7-1]+tr2;
  119672. ti2=cc[t5]-cc[t6];
  119673. ci2=cc[t7]+(taur*ti2);
  119674. ch[t8]=cc[t7]+ti2;
  119675. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119676. ci3=taui*(cc[t5]+cc[t6]);
  119677. dr2=cr2-ci3;
  119678. dr3=cr2+ci3;
  119679. di2=ci2+cr3;
  119680. di3=ci2-cr3;
  119681. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119682. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119683. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119684. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119685. }
  119686. t1+=ido;
  119687. }
  119688. }
  119689. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119690. float *wa2,float *wa3){
  119691. static float sqrt2=1.414213562373095f;
  119692. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119693. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119694. t0=l1*ido;
  119695. t1=0;
  119696. t2=ido<<2;
  119697. t3=0;
  119698. t6=ido<<1;
  119699. for(k=0;k<l1;k++){
  119700. t4=t3+t6;
  119701. t5=t1;
  119702. tr3=cc[t4-1]+cc[t4-1];
  119703. tr4=cc[t4]+cc[t4];
  119704. tr1=cc[t3]-cc[(t4+=t6)-1];
  119705. tr2=cc[t3]+cc[t4-1];
  119706. ch[t5]=tr2+tr3;
  119707. ch[t5+=t0]=tr1-tr4;
  119708. ch[t5+=t0]=tr2-tr3;
  119709. ch[t5+=t0]=tr1+tr4;
  119710. t1+=ido;
  119711. t3+=t2;
  119712. }
  119713. if(ido<2)return;
  119714. if(ido==2)goto L105;
  119715. t1=0;
  119716. for(k=0;k<l1;k++){
  119717. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119718. t7=t1;
  119719. for(i=2;i<ido;i+=2){
  119720. t2+=2;
  119721. t3+=2;
  119722. t4-=2;
  119723. t5-=2;
  119724. t7+=2;
  119725. ti1=cc[t2]+cc[t5];
  119726. ti2=cc[t2]-cc[t5];
  119727. ti3=cc[t3]-cc[t4];
  119728. tr4=cc[t3]+cc[t4];
  119729. tr1=cc[t2-1]-cc[t5-1];
  119730. tr2=cc[t2-1]+cc[t5-1];
  119731. ti4=cc[t3-1]-cc[t4-1];
  119732. tr3=cc[t3-1]+cc[t4-1];
  119733. ch[t7-1]=tr2+tr3;
  119734. cr3=tr2-tr3;
  119735. ch[t7]=ti2+ti3;
  119736. ci3=ti2-ti3;
  119737. cr2=tr1-tr4;
  119738. cr4=tr1+tr4;
  119739. ci2=ti1+ti4;
  119740. ci4=ti1-ti4;
  119741. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119742. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119743. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119744. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119745. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119746. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119747. }
  119748. t1+=ido;
  119749. }
  119750. if(ido%2 == 1)return;
  119751. L105:
  119752. t1=ido;
  119753. t2=ido<<2;
  119754. t3=ido-1;
  119755. t4=ido+(ido<<1);
  119756. for(k=0;k<l1;k++){
  119757. t5=t3;
  119758. ti1=cc[t1]+cc[t4];
  119759. ti2=cc[t4]-cc[t1];
  119760. tr1=cc[t1-1]-cc[t4-1];
  119761. tr2=cc[t1-1]+cc[t4-1];
  119762. ch[t5]=tr2+tr2;
  119763. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119764. ch[t5+=t0]=ti2+ti2;
  119765. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119766. t3+=ido;
  119767. t1+=t2;
  119768. t4+=t2;
  119769. }
  119770. }
  119771. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119772. float *c2,float *ch,float *ch2,float *wa){
  119773. static float tpi=6.283185307179586f;
  119774. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119775. t11,t12;
  119776. float dc2,ai1,ai2,ar1,ar2,ds2;
  119777. int nbd;
  119778. float dcp,arg,dsp,ar1h,ar2h;
  119779. int ipp2;
  119780. t10=ip*ido;
  119781. t0=l1*ido;
  119782. arg=tpi/(float)ip;
  119783. dcp=cos(arg);
  119784. dsp=sin(arg);
  119785. nbd=(ido-1)>>1;
  119786. ipp2=ip;
  119787. ipph=(ip+1)>>1;
  119788. if(ido<l1)goto L103;
  119789. t1=0;
  119790. t2=0;
  119791. for(k=0;k<l1;k++){
  119792. t3=t1;
  119793. t4=t2;
  119794. for(i=0;i<ido;i++){
  119795. ch[t3]=cc[t4];
  119796. t3++;
  119797. t4++;
  119798. }
  119799. t1+=ido;
  119800. t2+=t10;
  119801. }
  119802. goto L106;
  119803. L103:
  119804. t1=0;
  119805. for(i=0;i<ido;i++){
  119806. t2=t1;
  119807. t3=t1;
  119808. for(k=0;k<l1;k++){
  119809. ch[t2]=cc[t3];
  119810. t2+=ido;
  119811. t3+=t10;
  119812. }
  119813. t1++;
  119814. }
  119815. L106:
  119816. t1=0;
  119817. t2=ipp2*t0;
  119818. t7=(t5=ido<<1);
  119819. for(j=1;j<ipph;j++){
  119820. t1+=t0;
  119821. t2-=t0;
  119822. t3=t1;
  119823. t4=t2;
  119824. t6=t5;
  119825. for(k=0;k<l1;k++){
  119826. ch[t3]=cc[t6-1]+cc[t6-1];
  119827. ch[t4]=cc[t6]+cc[t6];
  119828. t3+=ido;
  119829. t4+=ido;
  119830. t6+=t10;
  119831. }
  119832. t5+=t7;
  119833. }
  119834. if (ido == 1)goto L116;
  119835. if(nbd<l1)goto L112;
  119836. t1=0;
  119837. t2=ipp2*t0;
  119838. t7=0;
  119839. for(j=1;j<ipph;j++){
  119840. t1+=t0;
  119841. t2-=t0;
  119842. t3=t1;
  119843. t4=t2;
  119844. t7+=(ido<<1);
  119845. t8=t7;
  119846. for(k=0;k<l1;k++){
  119847. t5=t3;
  119848. t6=t4;
  119849. t9=t8;
  119850. t11=t8;
  119851. for(i=2;i<ido;i+=2){
  119852. t5+=2;
  119853. t6+=2;
  119854. t9+=2;
  119855. t11-=2;
  119856. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119857. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119858. ch[t5]=cc[t9]-cc[t11];
  119859. ch[t6]=cc[t9]+cc[t11];
  119860. }
  119861. t3+=ido;
  119862. t4+=ido;
  119863. t8+=t10;
  119864. }
  119865. }
  119866. goto L116;
  119867. L112:
  119868. t1=0;
  119869. t2=ipp2*t0;
  119870. t7=0;
  119871. for(j=1;j<ipph;j++){
  119872. t1+=t0;
  119873. t2-=t0;
  119874. t3=t1;
  119875. t4=t2;
  119876. t7+=(ido<<1);
  119877. t8=t7;
  119878. t9=t7;
  119879. for(i=2;i<ido;i+=2){
  119880. t3+=2;
  119881. t4+=2;
  119882. t8+=2;
  119883. t9-=2;
  119884. t5=t3;
  119885. t6=t4;
  119886. t11=t8;
  119887. t12=t9;
  119888. for(k=0;k<l1;k++){
  119889. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119890. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119891. ch[t5]=cc[t11]-cc[t12];
  119892. ch[t6]=cc[t11]+cc[t12];
  119893. t5+=ido;
  119894. t6+=ido;
  119895. t11+=t10;
  119896. t12+=t10;
  119897. }
  119898. }
  119899. }
  119900. L116:
  119901. ar1=1.f;
  119902. ai1=0.f;
  119903. t1=0;
  119904. t9=(t2=ipp2*idl1);
  119905. t3=(ip-1)*idl1;
  119906. for(l=1;l<ipph;l++){
  119907. t1+=idl1;
  119908. t2-=idl1;
  119909. ar1h=dcp*ar1-dsp*ai1;
  119910. ai1=dcp*ai1+dsp*ar1;
  119911. ar1=ar1h;
  119912. t4=t1;
  119913. t5=t2;
  119914. t6=0;
  119915. t7=idl1;
  119916. t8=t3;
  119917. for(ik=0;ik<idl1;ik++){
  119918. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119919. c2[t5++]=ai1*ch2[t8++];
  119920. }
  119921. dc2=ar1;
  119922. ds2=ai1;
  119923. ar2=ar1;
  119924. ai2=ai1;
  119925. t6=idl1;
  119926. t7=t9-idl1;
  119927. for(j=2;j<ipph;j++){
  119928. t6+=idl1;
  119929. t7-=idl1;
  119930. ar2h=dc2*ar2-ds2*ai2;
  119931. ai2=dc2*ai2+ds2*ar2;
  119932. ar2=ar2h;
  119933. t4=t1;
  119934. t5=t2;
  119935. t11=t6;
  119936. t12=t7;
  119937. for(ik=0;ik<idl1;ik++){
  119938. c2[t4++]+=ar2*ch2[t11++];
  119939. c2[t5++]+=ai2*ch2[t12++];
  119940. }
  119941. }
  119942. }
  119943. t1=0;
  119944. for(j=1;j<ipph;j++){
  119945. t1+=idl1;
  119946. t2=t1;
  119947. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119948. }
  119949. t1=0;
  119950. t2=ipp2*t0;
  119951. for(j=1;j<ipph;j++){
  119952. t1+=t0;
  119953. t2-=t0;
  119954. t3=t1;
  119955. t4=t2;
  119956. for(k=0;k<l1;k++){
  119957. ch[t3]=c1[t3]-c1[t4];
  119958. ch[t4]=c1[t3]+c1[t4];
  119959. t3+=ido;
  119960. t4+=ido;
  119961. }
  119962. }
  119963. if(ido==1)goto L132;
  119964. if(nbd<l1)goto L128;
  119965. t1=0;
  119966. t2=ipp2*t0;
  119967. for(j=1;j<ipph;j++){
  119968. t1+=t0;
  119969. t2-=t0;
  119970. t3=t1;
  119971. t4=t2;
  119972. for(k=0;k<l1;k++){
  119973. t5=t3;
  119974. t6=t4;
  119975. for(i=2;i<ido;i+=2){
  119976. t5+=2;
  119977. t6+=2;
  119978. ch[t5-1]=c1[t5-1]-c1[t6];
  119979. ch[t6-1]=c1[t5-1]+c1[t6];
  119980. ch[t5]=c1[t5]+c1[t6-1];
  119981. ch[t6]=c1[t5]-c1[t6-1];
  119982. }
  119983. t3+=ido;
  119984. t4+=ido;
  119985. }
  119986. }
  119987. goto L132;
  119988. L128:
  119989. t1=0;
  119990. t2=ipp2*t0;
  119991. for(j=1;j<ipph;j++){
  119992. t1+=t0;
  119993. t2-=t0;
  119994. t3=t1;
  119995. t4=t2;
  119996. for(i=2;i<ido;i+=2){
  119997. t3+=2;
  119998. t4+=2;
  119999. t5=t3;
  120000. t6=t4;
  120001. for(k=0;k<l1;k++){
  120002. ch[t5-1]=c1[t5-1]-c1[t6];
  120003. ch[t6-1]=c1[t5-1]+c1[t6];
  120004. ch[t5]=c1[t5]+c1[t6-1];
  120005. ch[t6]=c1[t5]-c1[t6-1];
  120006. t5+=ido;
  120007. t6+=ido;
  120008. }
  120009. }
  120010. }
  120011. L132:
  120012. if(ido==1)return;
  120013. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120014. t1=0;
  120015. for(j=1;j<ip;j++){
  120016. t2=(t1+=t0);
  120017. for(k=0;k<l1;k++){
  120018. c1[t2]=ch[t2];
  120019. t2+=ido;
  120020. }
  120021. }
  120022. if(nbd>l1)goto L139;
  120023. is= -ido-1;
  120024. t1=0;
  120025. for(j=1;j<ip;j++){
  120026. is+=ido;
  120027. t1+=t0;
  120028. idij=is;
  120029. t2=t1;
  120030. for(i=2;i<ido;i+=2){
  120031. t2+=2;
  120032. idij+=2;
  120033. t3=t2;
  120034. for(k=0;k<l1;k++){
  120035. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120036. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120037. t3+=ido;
  120038. }
  120039. }
  120040. }
  120041. return;
  120042. L139:
  120043. is= -ido-1;
  120044. t1=0;
  120045. for(j=1;j<ip;j++){
  120046. is+=ido;
  120047. t1+=t0;
  120048. t2=t1;
  120049. for(k=0;k<l1;k++){
  120050. idij=is;
  120051. t3=t2;
  120052. for(i=2;i<ido;i+=2){
  120053. idij+=2;
  120054. t3+=2;
  120055. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120056. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120057. }
  120058. t2+=ido;
  120059. }
  120060. }
  120061. }
  120062. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120063. int i,k1,l1,l2;
  120064. int na;
  120065. int nf,ip,iw,ix2,ix3,ido,idl1;
  120066. nf=ifac[1];
  120067. na=0;
  120068. l1=1;
  120069. iw=1;
  120070. for(k1=0;k1<nf;k1++){
  120071. ip=ifac[k1 + 2];
  120072. l2=ip*l1;
  120073. ido=n/l2;
  120074. idl1=ido*l1;
  120075. if(ip!=4)goto L103;
  120076. ix2=iw+ido;
  120077. ix3=ix2+ido;
  120078. if(na!=0)
  120079. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120080. else
  120081. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120082. na=1-na;
  120083. goto L115;
  120084. L103:
  120085. if(ip!=2)goto L106;
  120086. if(na!=0)
  120087. dradb2(ido,l1,ch,c,wa+iw-1);
  120088. else
  120089. dradb2(ido,l1,c,ch,wa+iw-1);
  120090. na=1-na;
  120091. goto L115;
  120092. L106:
  120093. if(ip!=3)goto L109;
  120094. ix2=iw+ido;
  120095. if(na!=0)
  120096. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120097. else
  120098. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120099. na=1-na;
  120100. goto L115;
  120101. L109:
  120102. /* The radix five case can be translated later..... */
  120103. /* if(ip!=5)goto L112;
  120104. ix2=iw+ido;
  120105. ix3=ix2+ido;
  120106. ix4=ix3+ido;
  120107. if(na!=0)
  120108. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120109. else
  120110. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120111. na=1-na;
  120112. goto L115;
  120113. L112:*/
  120114. if(na!=0)
  120115. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120116. else
  120117. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120118. if(ido==1)na=1-na;
  120119. L115:
  120120. l1=l2;
  120121. iw+=(ip-1)*ido;
  120122. }
  120123. if(na==0)return;
  120124. for(i=0;i<n;i++)c[i]=ch[i];
  120125. }
  120126. void drft_forward(drft_lookup *l,float *data){
  120127. if(l->n==1)return;
  120128. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120129. }
  120130. void drft_backward(drft_lookup *l,float *data){
  120131. if (l->n==1)return;
  120132. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120133. }
  120134. void drft_init(drft_lookup *l,int n){
  120135. l->n=n;
  120136. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120137. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120138. fdrffti(n, l->trigcache, l->splitcache);
  120139. }
  120140. void drft_clear(drft_lookup *l){
  120141. if(l){
  120142. if(l->trigcache)_ogg_free(l->trigcache);
  120143. if(l->splitcache)_ogg_free(l->splitcache);
  120144. memset(l,0,sizeof(*l));
  120145. }
  120146. }
  120147. #endif
  120148. /*** End of inlined file: smallft.c ***/
  120149. /*** Start of inlined file: synthesis.c ***/
  120150. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120151. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120152. // tasks..
  120153. #if JUCE_MSVC
  120154. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120155. #endif
  120156. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120157. #if JUCE_USE_OGGVORBIS
  120158. #include <stdio.h>
  120159. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120160. vorbis_dsp_state *vd=vb->vd;
  120161. private_state *b=(private_state*)vd->backend_state;
  120162. vorbis_info *vi=vd->vi;
  120163. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120164. oggpack_buffer *opb=&vb->opb;
  120165. int type,mode,i;
  120166. /* first things first. Make sure decode is ready */
  120167. _vorbis_block_ripcord(vb);
  120168. oggpack_readinit(opb,op->packet,op->bytes);
  120169. /* Check the packet type */
  120170. if(oggpack_read(opb,1)!=0){
  120171. /* Oops. This is not an audio data packet */
  120172. return(OV_ENOTAUDIO);
  120173. }
  120174. /* read our mode and pre/post windowsize */
  120175. mode=oggpack_read(opb,b->modebits);
  120176. if(mode==-1)return(OV_EBADPACKET);
  120177. vb->mode=mode;
  120178. vb->W=ci->mode_param[mode]->blockflag;
  120179. if(vb->W){
  120180. /* this doesn;t get mapped through mode selection as it's used
  120181. only for window selection */
  120182. vb->lW=oggpack_read(opb,1);
  120183. vb->nW=oggpack_read(opb,1);
  120184. if(vb->nW==-1) return(OV_EBADPACKET);
  120185. }else{
  120186. vb->lW=0;
  120187. vb->nW=0;
  120188. }
  120189. /* more setup */
  120190. vb->granulepos=op->granulepos;
  120191. vb->sequence=op->packetno;
  120192. vb->eofflag=op->e_o_s;
  120193. /* alloc pcm passback storage */
  120194. vb->pcmend=ci->blocksizes[vb->W];
  120195. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120196. for(i=0;i<vi->channels;i++)
  120197. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120198. /* unpack_header enforces range checking */
  120199. type=ci->map_type[ci->mode_param[mode]->mapping];
  120200. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120201. mapping]));
  120202. }
  120203. /* used to track pcm position without actually performing decode.
  120204. Useful for sequential 'fast forward' */
  120205. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120206. vorbis_dsp_state *vd=vb->vd;
  120207. private_state *b=(private_state*)vd->backend_state;
  120208. vorbis_info *vi=vd->vi;
  120209. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120210. oggpack_buffer *opb=&vb->opb;
  120211. int mode;
  120212. /* first things first. Make sure decode is ready */
  120213. _vorbis_block_ripcord(vb);
  120214. oggpack_readinit(opb,op->packet,op->bytes);
  120215. /* Check the packet type */
  120216. if(oggpack_read(opb,1)!=0){
  120217. /* Oops. This is not an audio data packet */
  120218. return(OV_ENOTAUDIO);
  120219. }
  120220. /* read our mode and pre/post windowsize */
  120221. mode=oggpack_read(opb,b->modebits);
  120222. if(mode==-1)return(OV_EBADPACKET);
  120223. vb->mode=mode;
  120224. vb->W=ci->mode_param[mode]->blockflag;
  120225. if(vb->W){
  120226. vb->lW=oggpack_read(opb,1);
  120227. vb->nW=oggpack_read(opb,1);
  120228. if(vb->nW==-1) return(OV_EBADPACKET);
  120229. }else{
  120230. vb->lW=0;
  120231. vb->nW=0;
  120232. }
  120233. /* more setup */
  120234. vb->granulepos=op->granulepos;
  120235. vb->sequence=op->packetno;
  120236. vb->eofflag=op->e_o_s;
  120237. /* no pcm */
  120238. vb->pcmend=0;
  120239. vb->pcm=NULL;
  120240. return(0);
  120241. }
  120242. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120243. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120244. oggpack_buffer opb;
  120245. int mode;
  120246. oggpack_readinit(&opb,op->packet,op->bytes);
  120247. /* Check the packet type */
  120248. if(oggpack_read(&opb,1)!=0){
  120249. /* Oops. This is not an audio data packet */
  120250. return(OV_ENOTAUDIO);
  120251. }
  120252. {
  120253. int modebits=0;
  120254. int v=ci->modes;
  120255. while(v>1){
  120256. modebits++;
  120257. v>>=1;
  120258. }
  120259. /* read our mode and pre/post windowsize */
  120260. mode=oggpack_read(&opb,modebits);
  120261. }
  120262. if(mode==-1)return(OV_EBADPACKET);
  120263. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120264. }
  120265. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120266. /* set / clear half-sample-rate mode */
  120267. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120268. /* right now, our MDCT can't handle < 64 sample windows. */
  120269. if(ci->blocksizes[0]<=64 && flag)return -1;
  120270. ci->halfrate_flag=(flag?1:0);
  120271. return 0;
  120272. }
  120273. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120274. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120275. return ci->halfrate_flag;
  120276. }
  120277. #endif
  120278. /*** End of inlined file: synthesis.c ***/
  120279. /*** Start of inlined file: vorbisenc.c ***/
  120280. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120281. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120282. // tasks..
  120283. #if JUCE_MSVC
  120284. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120285. #endif
  120286. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120287. #if JUCE_USE_OGGVORBIS
  120288. #include <stdlib.h>
  120289. #include <string.h>
  120290. #include <math.h>
  120291. /* careful with this; it's using static array sizing to make managing
  120292. all the modes a little less annoying. If we use a residue backend
  120293. with > 12 partition types, or a different division of iteration,
  120294. this needs to be updated. */
  120295. typedef struct {
  120296. static_codebook *books[12][3];
  120297. } static_bookblock;
  120298. typedef struct {
  120299. int res_type;
  120300. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120301. vorbis_info_residue0 *res;
  120302. static_codebook *book_aux;
  120303. static_codebook *book_aux_managed;
  120304. static_bookblock *books_base;
  120305. static_bookblock *books_base_managed;
  120306. } vorbis_residue_template;
  120307. typedef struct {
  120308. vorbis_info_mapping0 *map;
  120309. vorbis_residue_template *res;
  120310. } vorbis_mapping_template;
  120311. typedef struct vp_adjblock{
  120312. int block[P_BANDS];
  120313. } vp_adjblock;
  120314. typedef struct {
  120315. int data[NOISE_COMPAND_LEVELS];
  120316. } compandblock;
  120317. /* high level configuration information for setting things up
  120318. step-by-step with the detailed vorbis_encode_ctl interface.
  120319. There's a fair amount of redundancy such that interactive setup
  120320. does not directly deal with any vorbis_info or codec_setup_info
  120321. initialization; it's all stored (until full init) in this highlevel
  120322. setup, then flushed out to the real codec setup structs later. */
  120323. typedef struct {
  120324. int att[P_NOISECURVES];
  120325. float boost;
  120326. float decay;
  120327. } att3;
  120328. typedef struct { int data[P_NOISECURVES]; } adj3;
  120329. typedef struct {
  120330. int pre[PACKETBLOBS];
  120331. int post[PACKETBLOBS];
  120332. float kHz[PACKETBLOBS];
  120333. float lowpasskHz[PACKETBLOBS];
  120334. } adj_stereo;
  120335. typedef struct {
  120336. int lo;
  120337. int hi;
  120338. int fixed;
  120339. } noiseguard;
  120340. typedef struct {
  120341. int data[P_NOISECURVES][17];
  120342. } noise3;
  120343. typedef struct {
  120344. int mappings;
  120345. double *rate_mapping;
  120346. double *quality_mapping;
  120347. int coupling_restriction;
  120348. long samplerate_min_restriction;
  120349. long samplerate_max_restriction;
  120350. int *blocksize_short;
  120351. int *blocksize_long;
  120352. att3 *psy_tone_masteratt;
  120353. int *psy_tone_0dB;
  120354. int *psy_tone_dBsuppress;
  120355. vp_adjblock *psy_tone_adj_impulse;
  120356. vp_adjblock *psy_tone_adj_long;
  120357. vp_adjblock *psy_tone_adj_other;
  120358. noiseguard *psy_noiseguards;
  120359. noise3 *psy_noise_bias_impulse;
  120360. noise3 *psy_noise_bias_padding;
  120361. noise3 *psy_noise_bias_trans;
  120362. noise3 *psy_noise_bias_long;
  120363. int *psy_noise_dBsuppress;
  120364. compandblock *psy_noise_compand;
  120365. double *psy_noise_compand_short_mapping;
  120366. double *psy_noise_compand_long_mapping;
  120367. int *psy_noise_normal_start[2];
  120368. int *psy_noise_normal_partition[2];
  120369. double *psy_noise_normal_thresh;
  120370. int *psy_ath_float;
  120371. int *psy_ath_abs;
  120372. double *psy_lowpass;
  120373. vorbis_info_psy_global *global_params;
  120374. double *global_mapping;
  120375. adj_stereo *stereo_modes;
  120376. static_codebook ***floor_books;
  120377. vorbis_info_floor1 *floor_params;
  120378. int *floor_short_mapping;
  120379. int *floor_long_mapping;
  120380. vorbis_mapping_template *maps;
  120381. } ve_setup_data_template;
  120382. /* a few static coder conventions */
  120383. static vorbis_info_mode _mode_template[2]={
  120384. {0,0,0,0},
  120385. {1,0,0,1}
  120386. };
  120387. static vorbis_info_mapping0 _map_nominal[2]={
  120388. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120389. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120390. };
  120391. /*** Start of inlined file: setup_44.h ***/
  120392. /*** Start of inlined file: floor_all.h ***/
  120393. /*** Start of inlined file: floor_books.h ***/
  120394. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120395. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120396. };
  120397. static static_codebook _huff_book_line_256x7_0sub1 = {
  120398. 1, 9,
  120399. _huff_lengthlist_line_256x7_0sub1,
  120400. 0, 0, 0, 0, 0,
  120401. NULL,
  120402. NULL,
  120403. NULL,
  120404. NULL,
  120405. 0
  120406. };
  120407. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120409. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120410. };
  120411. static static_codebook _huff_book_line_256x7_0sub2 = {
  120412. 1, 25,
  120413. _huff_lengthlist_line_256x7_0sub2,
  120414. 0, 0, 0, 0, 0,
  120415. NULL,
  120416. NULL,
  120417. NULL,
  120418. NULL,
  120419. 0
  120420. };
  120421. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120424. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120425. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120426. };
  120427. static static_codebook _huff_book_line_256x7_0sub3 = {
  120428. 1, 64,
  120429. _huff_lengthlist_line_256x7_0sub3,
  120430. 0, 0, 0, 0, 0,
  120431. NULL,
  120432. NULL,
  120433. NULL,
  120434. NULL,
  120435. 0
  120436. };
  120437. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120438. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120439. };
  120440. static static_codebook _huff_book_line_256x7_1sub1 = {
  120441. 1, 9,
  120442. _huff_lengthlist_line_256x7_1sub1,
  120443. 0, 0, 0, 0, 0,
  120444. NULL,
  120445. NULL,
  120446. NULL,
  120447. NULL,
  120448. 0
  120449. };
  120450. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120452. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120453. };
  120454. static static_codebook _huff_book_line_256x7_1sub2 = {
  120455. 1, 25,
  120456. _huff_lengthlist_line_256x7_1sub2,
  120457. 0, 0, 0, 0, 0,
  120458. NULL,
  120459. NULL,
  120460. NULL,
  120461. NULL,
  120462. 0
  120463. };
  120464. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120467. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120468. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120469. };
  120470. static static_codebook _huff_book_line_256x7_1sub3 = {
  120471. 1, 64,
  120472. _huff_lengthlist_line_256x7_1sub3,
  120473. 0, 0, 0, 0, 0,
  120474. NULL,
  120475. NULL,
  120476. NULL,
  120477. NULL,
  120478. 0
  120479. };
  120480. static long _huff_lengthlist_line_256x7_class0[] = {
  120481. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120482. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120483. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120484. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120485. };
  120486. static static_codebook _huff_book_line_256x7_class0 = {
  120487. 1, 64,
  120488. _huff_lengthlist_line_256x7_class0,
  120489. 0, 0, 0, 0, 0,
  120490. NULL,
  120491. NULL,
  120492. NULL,
  120493. NULL,
  120494. 0
  120495. };
  120496. static long _huff_lengthlist_line_256x7_class1[] = {
  120497. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120498. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120499. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120500. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120501. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120502. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120503. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120504. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120505. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120506. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120507. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120508. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120509. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120510. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120511. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120512. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120513. };
  120514. static static_codebook _huff_book_line_256x7_class1 = {
  120515. 1, 256,
  120516. _huff_lengthlist_line_256x7_class1,
  120517. 0, 0, 0, 0, 0,
  120518. NULL,
  120519. NULL,
  120520. NULL,
  120521. NULL,
  120522. 0
  120523. };
  120524. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120525. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120526. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120527. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120528. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120529. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120530. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120531. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120532. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120533. };
  120534. static static_codebook _huff_book_line_512x17_0sub0 = {
  120535. 1, 128,
  120536. _huff_lengthlist_line_512x17_0sub0,
  120537. 0, 0, 0, 0, 0,
  120538. NULL,
  120539. NULL,
  120540. NULL,
  120541. NULL,
  120542. 0
  120543. };
  120544. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120545. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120546. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120547. };
  120548. static static_codebook _huff_book_line_512x17_1sub0 = {
  120549. 1, 32,
  120550. _huff_lengthlist_line_512x17_1sub0,
  120551. 0, 0, 0, 0, 0,
  120552. NULL,
  120553. NULL,
  120554. NULL,
  120555. NULL,
  120556. 0
  120557. };
  120558. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120561. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120562. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120563. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120564. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120565. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120566. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120567. };
  120568. static static_codebook _huff_book_line_512x17_1sub1 = {
  120569. 1, 128,
  120570. _huff_lengthlist_line_512x17_1sub1,
  120571. 0, 0, 0, 0, 0,
  120572. NULL,
  120573. NULL,
  120574. NULL,
  120575. NULL,
  120576. 0
  120577. };
  120578. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120579. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120580. 5, 3,
  120581. };
  120582. static static_codebook _huff_book_line_512x17_2sub1 = {
  120583. 1, 18,
  120584. _huff_lengthlist_line_512x17_2sub1,
  120585. 0, 0, 0, 0, 0,
  120586. NULL,
  120587. NULL,
  120588. NULL,
  120589. NULL,
  120590. 0
  120591. };
  120592. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120594. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120595. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120596. 9, 8,
  120597. };
  120598. static static_codebook _huff_book_line_512x17_2sub2 = {
  120599. 1, 50,
  120600. _huff_lengthlist_line_512x17_2sub2,
  120601. 0, 0, 0, 0, 0,
  120602. NULL,
  120603. NULL,
  120604. NULL,
  120605. NULL,
  120606. 0
  120607. };
  120608. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120612. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120613. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120614. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120617. };
  120618. static static_codebook _huff_book_line_512x17_2sub3 = {
  120619. 1, 128,
  120620. _huff_lengthlist_line_512x17_2sub3,
  120621. 0, 0, 0, 0, 0,
  120622. NULL,
  120623. NULL,
  120624. NULL,
  120625. NULL,
  120626. 0
  120627. };
  120628. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120629. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120630. 5, 5,
  120631. };
  120632. static static_codebook _huff_book_line_512x17_3sub1 = {
  120633. 1, 18,
  120634. _huff_lengthlist_line_512x17_3sub1,
  120635. 0, 0, 0, 0, 0,
  120636. NULL,
  120637. NULL,
  120638. NULL,
  120639. NULL,
  120640. 0
  120641. };
  120642. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120644. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120645. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120646. 11,14,
  120647. };
  120648. static static_codebook _huff_book_line_512x17_3sub2 = {
  120649. 1, 50,
  120650. _huff_lengthlist_line_512x17_3sub2,
  120651. 0, 0, 0, 0, 0,
  120652. NULL,
  120653. NULL,
  120654. NULL,
  120655. NULL,
  120656. 0
  120657. };
  120658. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120662. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120663. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120664. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120665. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120666. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120667. };
  120668. static static_codebook _huff_book_line_512x17_3sub3 = {
  120669. 1, 128,
  120670. _huff_lengthlist_line_512x17_3sub3,
  120671. 0, 0, 0, 0, 0,
  120672. NULL,
  120673. NULL,
  120674. NULL,
  120675. NULL,
  120676. 0
  120677. };
  120678. static long _huff_lengthlist_line_512x17_class1[] = {
  120679. 1, 2, 3, 6, 5, 4, 7, 7,
  120680. };
  120681. static static_codebook _huff_book_line_512x17_class1 = {
  120682. 1, 8,
  120683. _huff_lengthlist_line_512x17_class1,
  120684. 0, 0, 0, 0, 0,
  120685. NULL,
  120686. NULL,
  120687. NULL,
  120688. NULL,
  120689. 0
  120690. };
  120691. static long _huff_lengthlist_line_512x17_class2[] = {
  120692. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120693. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120694. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120695. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120696. };
  120697. static static_codebook _huff_book_line_512x17_class2 = {
  120698. 1, 64,
  120699. _huff_lengthlist_line_512x17_class2,
  120700. 0, 0, 0, 0, 0,
  120701. NULL,
  120702. NULL,
  120703. NULL,
  120704. NULL,
  120705. 0
  120706. };
  120707. static long _huff_lengthlist_line_512x17_class3[] = {
  120708. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120709. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120710. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120711. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120712. };
  120713. static static_codebook _huff_book_line_512x17_class3 = {
  120714. 1, 64,
  120715. _huff_lengthlist_line_512x17_class3,
  120716. 0, 0, 0, 0, 0,
  120717. NULL,
  120718. NULL,
  120719. NULL,
  120720. NULL,
  120721. 0
  120722. };
  120723. static long _huff_lengthlist_line_128x4_class0[] = {
  120724. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120725. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120726. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120727. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120728. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120729. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120730. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120731. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120732. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120733. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120734. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120735. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120736. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120737. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120738. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120739. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120740. };
  120741. static static_codebook _huff_book_line_128x4_class0 = {
  120742. 1, 256,
  120743. _huff_lengthlist_line_128x4_class0,
  120744. 0, 0, 0, 0, 0,
  120745. NULL,
  120746. NULL,
  120747. NULL,
  120748. NULL,
  120749. 0
  120750. };
  120751. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120752. 2, 2, 2, 2,
  120753. };
  120754. static static_codebook _huff_book_line_128x4_0sub0 = {
  120755. 1, 4,
  120756. _huff_lengthlist_line_128x4_0sub0,
  120757. 0, 0, 0, 0, 0,
  120758. NULL,
  120759. NULL,
  120760. NULL,
  120761. NULL,
  120762. 0
  120763. };
  120764. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120765. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120766. };
  120767. static static_codebook _huff_book_line_128x4_0sub1 = {
  120768. 1, 10,
  120769. _huff_lengthlist_line_128x4_0sub1,
  120770. 0, 0, 0, 0, 0,
  120771. NULL,
  120772. NULL,
  120773. NULL,
  120774. NULL,
  120775. 0
  120776. };
  120777. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120779. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120780. };
  120781. static static_codebook _huff_book_line_128x4_0sub2 = {
  120782. 1, 25,
  120783. _huff_lengthlist_line_128x4_0sub2,
  120784. 0, 0, 0, 0, 0,
  120785. NULL,
  120786. NULL,
  120787. NULL,
  120788. NULL,
  120789. 0
  120790. };
  120791. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120794. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120795. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120796. };
  120797. static static_codebook _huff_book_line_128x4_0sub3 = {
  120798. 1, 64,
  120799. _huff_lengthlist_line_128x4_0sub3,
  120800. 0, 0, 0, 0, 0,
  120801. NULL,
  120802. NULL,
  120803. NULL,
  120804. NULL,
  120805. 0
  120806. };
  120807. static long _huff_lengthlist_line_256x4_class0[] = {
  120808. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120809. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120810. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120811. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120812. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120813. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120814. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120815. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120816. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120817. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120818. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120819. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120820. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120821. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120822. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120823. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120824. };
  120825. static static_codebook _huff_book_line_256x4_class0 = {
  120826. 1, 256,
  120827. _huff_lengthlist_line_256x4_class0,
  120828. 0, 0, 0, 0, 0,
  120829. NULL,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. 0
  120834. };
  120835. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120836. 2, 2, 2, 2,
  120837. };
  120838. static static_codebook _huff_book_line_256x4_0sub0 = {
  120839. 1, 4,
  120840. _huff_lengthlist_line_256x4_0sub0,
  120841. 0, 0, 0, 0, 0,
  120842. NULL,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120849. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120850. };
  120851. static static_codebook _huff_book_line_256x4_0sub1 = {
  120852. 1, 10,
  120853. _huff_lengthlist_line_256x4_0sub1,
  120854. 0, 0, 0, 0, 0,
  120855. NULL,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. 0
  120860. };
  120861. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120863. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120864. };
  120865. static static_codebook _huff_book_line_256x4_0sub2 = {
  120866. 1, 25,
  120867. _huff_lengthlist_line_256x4_0sub2,
  120868. 0, 0, 0, 0, 0,
  120869. NULL,
  120870. NULL,
  120871. NULL,
  120872. NULL,
  120873. 0
  120874. };
  120875. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120878. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120879. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120880. };
  120881. static static_codebook _huff_book_line_256x4_0sub3 = {
  120882. 1, 64,
  120883. _huff_lengthlist_line_256x4_0sub3,
  120884. 0, 0, 0, 0, 0,
  120885. NULL,
  120886. NULL,
  120887. NULL,
  120888. NULL,
  120889. 0
  120890. };
  120891. static long _huff_lengthlist_line_128x7_class0[] = {
  120892. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120893. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120894. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120895. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120896. };
  120897. static static_codebook _huff_book_line_128x7_class0 = {
  120898. 1, 64,
  120899. _huff_lengthlist_line_128x7_class0,
  120900. 0, 0, 0, 0, 0,
  120901. NULL,
  120902. NULL,
  120903. NULL,
  120904. NULL,
  120905. 0
  120906. };
  120907. static long _huff_lengthlist_line_128x7_class1[] = {
  120908. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120909. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120910. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120911. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120912. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120913. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120914. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120915. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120916. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120917. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120918. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120919. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120920. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120921. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120922. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120923. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120924. };
  120925. static static_codebook _huff_book_line_128x7_class1 = {
  120926. 1, 256,
  120927. _huff_lengthlist_line_128x7_class1,
  120928. 0, 0, 0, 0, 0,
  120929. NULL,
  120930. NULL,
  120931. NULL,
  120932. NULL,
  120933. 0
  120934. };
  120935. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120936. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120937. };
  120938. static static_codebook _huff_book_line_128x7_0sub1 = {
  120939. 1, 9,
  120940. _huff_lengthlist_line_128x7_0sub1,
  120941. 0, 0, 0, 0, 0,
  120942. NULL,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. 0
  120947. };
  120948. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120950. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120951. };
  120952. static static_codebook _huff_book_line_128x7_0sub2 = {
  120953. 1, 25,
  120954. _huff_lengthlist_line_128x7_0sub2,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120965. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120966. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120967. };
  120968. static static_codebook _huff_book_line_128x7_0sub3 = {
  120969. 1, 64,
  120970. _huff_lengthlist_line_128x7_0sub3,
  120971. 0, 0, 0, 0, 0,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. NULL,
  120976. 0
  120977. };
  120978. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120979. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120980. };
  120981. static static_codebook _huff_book_line_128x7_1sub1 = {
  120982. 1, 9,
  120983. _huff_lengthlist_line_128x7_1sub1,
  120984. 0, 0, 0, 0, 0,
  120985. NULL,
  120986. NULL,
  120987. NULL,
  120988. NULL,
  120989. 0
  120990. };
  120991. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120993. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120994. };
  120995. static static_codebook _huff_book_line_128x7_1sub2 = {
  120996. 1, 25,
  120997. _huff_lengthlist_line_128x7_1sub2,
  120998. 0, 0, 0, 0, 0,
  120999. NULL,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. 0
  121004. };
  121005. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121008. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121009. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121010. };
  121011. static static_codebook _huff_book_line_128x7_1sub3 = {
  121012. 1, 64,
  121013. _huff_lengthlist_line_128x7_1sub3,
  121014. 0, 0, 0, 0, 0,
  121015. NULL,
  121016. NULL,
  121017. NULL,
  121018. NULL,
  121019. 0
  121020. };
  121021. static long _huff_lengthlist_line_128x11_class1[] = {
  121022. 1, 6, 3, 7, 2, 4, 5, 7,
  121023. };
  121024. static static_codebook _huff_book_line_128x11_class1 = {
  121025. 1, 8,
  121026. _huff_lengthlist_line_128x11_class1,
  121027. 0, 0, 0, 0, 0,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. NULL,
  121032. 0
  121033. };
  121034. static long _huff_lengthlist_line_128x11_class2[] = {
  121035. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121036. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121037. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121038. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121039. };
  121040. static static_codebook _huff_book_line_128x11_class2 = {
  121041. 1, 64,
  121042. _huff_lengthlist_line_128x11_class2,
  121043. 0, 0, 0, 0, 0,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. NULL,
  121048. 0
  121049. };
  121050. static long _huff_lengthlist_line_128x11_class3[] = {
  121051. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121052. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121053. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121054. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121055. };
  121056. static static_codebook _huff_book_line_128x11_class3 = {
  121057. 1, 64,
  121058. _huff_lengthlist_line_128x11_class3,
  121059. 0, 0, 0, 0, 0,
  121060. NULL,
  121061. NULL,
  121062. NULL,
  121063. NULL,
  121064. 0
  121065. };
  121066. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121067. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121068. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121069. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121070. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121071. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121072. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121073. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121074. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121075. };
  121076. static static_codebook _huff_book_line_128x11_0sub0 = {
  121077. 1, 128,
  121078. _huff_lengthlist_line_128x11_0sub0,
  121079. 0, 0, 0, 0, 0,
  121080. NULL,
  121081. NULL,
  121082. NULL,
  121083. NULL,
  121084. 0
  121085. };
  121086. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121087. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121088. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121089. };
  121090. static static_codebook _huff_book_line_128x11_1sub0 = {
  121091. 1, 32,
  121092. _huff_lengthlist_line_128x11_1sub0,
  121093. 0, 0, 0, 0, 0,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. NULL,
  121098. 0
  121099. };
  121100. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121104. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121105. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121106. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121107. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121108. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121109. };
  121110. static static_codebook _huff_book_line_128x11_1sub1 = {
  121111. 1, 128,
  121112. _huff_lengthlist_line_128x11_1sub1,
  121113. 0, 0, 0, 0, 0,
  121114. NULL,
  121115. NULL,
  121116. NULL,
  121117. NULL,
  121118. 0
  121119. };
  121120. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121121. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121122. 5, 5,
  121123. };
  121124. static static_codebook _huff_book_line_128x11_2sub1 = {
  121125. 1, 18,
  121126. _huff_lengthlist_line_128x11_2sub1,
  121127. 0, 0, 0, 0, 0,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. NULL,
  121132. 0
  121133. };
  121134. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121136. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121137. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121138. 8,11,
  121139. };
  121140. static static_codebook _huff_book_line_128x11_2sub2 = {
  121141. 1, 50,
  121142. _huff_lengthlist_line_128x11_2sub2,
  121143. 0, 0, 0, 0, 0,
  121144. NULL,
  121145. NULL,
  121146. NULL,
  121147. NULL,
  121148. 0
  121149. };
  121150. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121154. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121155. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121156. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121157. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121158. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121159. };
  121160. static static_codebook _huff_book_line_128x11_2sub3 = {
  121161. 1, 128,
  121162. _huff_lengthlist_line_128x11_2sub3,
  121163. 0, 0, 0, 0, 0,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. 0
  121169. };
  121170. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121171. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121172. 5, 4,
  121173. };
  121174. static static_codebook _huff_book_line_128x11_3sub1 = {
  121175. 1, 18,
  121176. _huff_lengthlist_line_128x11_3sub1,
  121177. 0, 0, 0, 0, 0,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. 0
  121183. };
  121184. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121187. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121188. 12, 6,
  121189. };
  121190. static static_codebook _huff_book_line_128x11_3sub2 = {
  121191. 1, 50,
  121192. _huff_lengthlist_line_128x11_3sub2,
  121193. 0, 0, 0, 0, 0,
  121194. NULL,
  121195. NULL,
  121196. NULL,
  121197. NULL,
  121198. 0
  121199. };
  121200. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121204. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121205. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121206. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121207. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121208. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121209. };
  121210. static static_codebook _huff_book_line_128x11_3sub3 = {
  121211. 1, 128,
  121212. _huff_lengthlist_line_128x11_3sub3,
  121213. 0, 0, 0, 0, 0,
  121214. NULL,
  121215. NULL,
  121216. NULL,
  121217. NULL,
  121218. 0
  121219. };
  121220. static long _huff_lengthlist_line_128x17_class1[] = {
  121221. 1, 3, 4, 7, 2, 5, 6, 7,
  121222. };
  121223. static static_codebook _huff_book_line_128x17_class1 = {
  121224. 1, 8,
  121225. _huff_lengthlist_line_128x17_class1,
  121226. 0, 0, 0, 0, 0,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. 0
  121232. };
  121233. static long _huff_lengthlist_line_128x17_class2[] = {
  121234. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121235. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121236. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121237. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121238. };
  121239. static static_codebook _huff_book_line_128x17_class2 = {
  121240. 1, 64,
  121241. _huff_lengthlist_line_128x17_class2,
  121242. 0, 0, 0, 0, 0,
  121243. NULL,
  121244. NULL,
  121245. NULL,
  121246. NULL,
  121247. 0
  121248. };
  121249. static long _huff_lengthlist_line_128x17_class3[] = {
  121250. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121251. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121252. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121253. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121254. };
  121255. static static_codebook _huff_book_line_128x17_class3 = {
  121256. 1, 64,
  121257. _huff_lengthlist_line_128x17_class3,
  121258. 0, 0, 0, 0, 0,
  121259. NULL,
  121260. NULL,
  121261. NULL,
  121262. NULL,
  121263. 0
  121264. };
  121265. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121266. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121267. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121268. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121269. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121270. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121271. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121272. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121273. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121274. };
  121275. static static_codebook _huff_book_line_128x17_0sub0 = {
  121276. 1, 128,
  121277. _huff_lengthlist_line_128x17_0sub0,
  121278. 0, 0, 0, 0, 0,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. 0
  121284. };
  121285. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121286. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121287. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121288. };
  121289. static static_codebook _huff_book_line_128x17_1sub0 = {
  121290. 1, 32,
  121291. _huff_lengthlist_line_128x17_1sub0,
  121292. 0, 0, 0, 0, 0,
  121293. NULL,
  121294. NULL,
  121295. NULL,
  121296. NULL,
  121297. 0
  121298. };
  121299. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121302. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121303. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121304. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121305. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121306. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121307. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121308. };
  121309. static static_codebook _huff_book_line_128x17_1sub1 = {
  121310. 1, 128,
  121311. _huff_lengthlist_line_128x17_1sub1,
  121312. 0, 0, 0, 0, 0,
  121313. NULL,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. 0
  121318. };
  121319. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121320. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121321. 9, 4,
  121322. };
  121323. static static_codebook _huff_book_line_128x17_2sub1 = {
  121324. 1, 18,
  121325. _huff_lengthlist_line_128x17_2sub1,
  121326. 0, 0, 0, 0, 0,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. 0
  121332. };
  121333. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121335. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121336. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121337. 13,13,
  121338. };
  121339. static static_codebook _huff_book_line_128x17_2sub2 = {
  121340. 1, 50,
  121341. _huff_lengthlist_line_128x17_2sub2,
  121342. 0, 0, 0, 0, 0,
  121343. NULL,
  121344. NULL,
  121345. NULL,
  121346. NULL,
  121347. 0
  121348. };
  121349. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121353. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121354. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121355. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121356. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121357. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121358. };
  121359. static static_codebook _huff_book_line_128x17_2sub3 = {
  121360. 1, 128,
  121361. _huff_lengthlist_line_128x17_2sub3,
  121362. 0, 0, 0, 0, 0,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. 0
  121368. };
  121369. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121370. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121371. 6, 4,
  121372. };
  121373. static static_codebook _huff_book_line_128x17_3sub1 = {
  121374. 1, 18,
  121375. _huff_lengthlist_line_128x17_3sub1,
  121376. 0, 0, 0, 0, 0,
  121377. NULL,
  121378. NULL,
  121379. NULL,
  121380. NULL,
  121381. 0
  121382. };
  121383. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121386. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121387. 10, 8,
  121388. };
  121389. static static_codebook _huff_book_line_128x17_3sub2 = {
  121390. 1, 50,
  121391. _huff_lengthlist_line_128x17_3sub2,
  121392. 0, 0, 0, 0, 0,
  121393. NULL,
  121394. NULL,
  121395. NULL,
  121396. NULL,
  121397. 0
  121398. };
  121399. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121403. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121404. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121405. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121408. };
  121409. static static_codebook _huff_book_line_128x17_3sub3 = {
  121410. 1, 128,
  121411. _huff_lengthlist_line_128x17_3sub3,
  121412. 0, 0, 0, 0, 0,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. 0
  121418. };
  121419. static long _huff_lengthlist_line_1024x27_class1[] = {
  121420. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121421. };
  121422. static static_codebook _huff_book_line_1024x27_class1 = {
  121423. 1, 16,
  121424. _huff_lengthlist_line_1024x27_class1,
  121425. 0, 0, 0, 0, 0,
  121426. NULL,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. 0
  121431. };
  121432. static long _huff_lengthlist_line_1024x27_class2[] = {
  121433. 1, 4, 2, 6, 3, 7, 5, 7,
  121434. };
  121435. static static_codebook _huff_book_line_1024x27_class2 = {
  121436. 1, 8,
  121437. _huff_lengthlist_line_1024x27_class2,
  121438. 0, 0, 0, 0, 0,
  121439. NULL,
  121440. NULL,
  121441. NULL,
  121442. NULL,
  121443. 0
  121444. };
  121445. static long _huff_lengthlist_line_1024x27_class3[] = {
  121446. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121447. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121448. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121449. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121450. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121451. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121452. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121453. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121454. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121455. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121456. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121457. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121458. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121459. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121460. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121461. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121462. };
  121463. static static_codebook _huff_book_line_1024x27_class3 = {
  121464. 1, 256,
  121465. _huff_lengthlist_line_1024x27_class3,
  121466. 0, 0, 0, 0, 0,
  121467. NULL,
  121468. NULL,
  121469. NULL,
  121470. NULL,
  121471. 0
  121472. };
  121473. static long _huff_lengthlist_line_1024x27_class4[] = {
  121474. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121475. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121476. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121477. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121478. };
  121479. static static_codebook _huff_book_line_1024x27_class4 = {
  121480. 1, 64,
  121481. _huff_lengthlist_line_1024x27_class4,
  121482. 0, 0, 0, 0, 0,
  121483. NULL,
  121484. NULL,
  121485. NULL,
  121486. NULL,
  121487. 0
  121488. };
  121489. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121490. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121491. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121492. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121493. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121494. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121495. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121496. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121497. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121498. };
  121499. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121500. 1, 128,
  121501. _huff_lengthlist_line_1024x27_0sub0,
  121502. 0, 0, 0, 0, 0,
  121503. NULL,
  121504. NULL,
  121505. NULL,
  121506. NULL,
  121507. 0
  121508. };
  121509. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121510. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121511. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121512. };
  121513. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121514. 1, 32,
  121515. _huff_lengthlist_line_1024x27_1sub0,
  121516. 0, 0, 0, 0, 0,
  121517. NULL,
  121518. NULL,
  121519. NULL,
  121520. NULL,
  121521. 0
  121522. };
  121523. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121526. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121527. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121528. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121529. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121530. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121531. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121532. };
  121533. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121534. 1, 128,
  121535. _huff_lengthlist_line_1024x27_1sub1,
  121536. 0, 0, 0, 0, 0,
  121537. NULL,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. 0
  121542. };
  121543. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121544. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121545. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121546. };
  121547. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121548. 1, 32,
  121549. _huff_lengthlist_line_1024x27_2sub0,
  121550. 0, 0, 0, 0, 0,
  121551. NULL,
  121552. NULL,
  121553. NULL,
  121554. NULL,
  121555. 0
  121556. };
  121557. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121560. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121561. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121562. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121563. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121564. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121565. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121566. };
  121567. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121568. 1, 128,
  121569. _huff_lengthlist_line_1024x27_2sub1,
  121570. 0, 0, 0, 0, 0,
  121571. NULL,
  121572. NULL,
  121573. NULL,
  121574. NULL,
  121575. 0
  121576. };
  121577. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121578. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121579. 5, 5,
  121580. };
  121581. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121582. 1, 18,
  121583. _huff_lengthlist_line_1024x27_3sub1,
  121584. 0, 0, 0, 0, 0,
  121585. NULL,
  121586. NULL,
  121587. NULL,
  121588. NULL,
  121589. 0
  121590. };
  121591. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121594. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121595. 9,11,
  121596. };
  121597. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121598. 1, 50,
  121599. _huff_lengthlist_line_1024x27_3sub2,
  121600. 0, 0, 0, 0, 0,
  121601. NULL,
  121602. NULL,
  121603. NULL,
  121604. NULL,
  121605. 0
  121606. };
  121607. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121612. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121613. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121614. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121615. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121616. };
  121617. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121618. 1, 128,
  121619. _huff_lengthlist_line_1024x27_3sub3,
  121620. 0, 0, 0, 0, 0,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. NULL,
  121625. 0
  121626. };
  121627. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121628. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121629. 5, 4,
  121630. };
  121631. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121632. 1, 18,
  121633. _huff_lengthlist_line_1024x27_4sub1,
  121634. 0, 0, 0, 0, 0,
  121635. NULL,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. 0
  121640. };
  121641. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121644. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121645. 9,12,
  121646. };
  121647. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121648. 1, 50,
  121649. _huff_lengthlist_line_1024x27_4sub2,
  121650. 0, 0, 0, 0, 0,
  121651. NULL,
  121652. NULL,
  121653. NULL,
  121654. NULL,
  121655. 0
  121656. };
  121657. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121661. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121662. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121665. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121666. };
  121667. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121668. 1, 128,
  121669. _huff_lengthlist_line_1024x27_4sub3,
  121670. 0, 0, 0, 0, 0,
  121671. NULL,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. 0
  121676. };
  121677. static long _huff_lengthlist_line_2048x27_class1[] = {
  121678. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121679. };
  121680. static static_codebook _huff_book_line_2048x27_class1 = {
  121681. 1, 16,
  121682. _huff_lengthlist_line_2048x27_class1,
  121683. 0, 0, 0, 0, 0,
  121684. NULL,
  121685. NULL,
  121686. NULL,
  121687. NULL,
  121688. 0
  121689. };
  121690. static long _huff_lengthlist_line_2048x27_class2[] = {
  121691. 1, 2, 3, 6, 4, 7, 5, 7,
  121692. };
  121693. static static_codebook _huff_book_line_2048x27_class2 = {
  121694. 1, 8,
  121695. _huff_lengthlist_line_2048x27_class2,
  121696. 0, 0, 0, 0, 0,
  121697. NULL,
  121698. NULL,
  121699. NULL,
  121700. NULL,
  121701. 0
  121702. };
  121703. static long _huff_lengthlist_line_2048x27_class3[] = {
  121704. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121705. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121706. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121707. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121708. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121709. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121710. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121711. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121712. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121713. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121714. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121715. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121716. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121717. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121718. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121719. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121720. };
  121721. static static_codebook _huff_book_line_2048x27_class3 = {
  121722. 1, 256,
  121723. _huff_lengthlist_line_2048x27_class3,
  121724. 0, 0, 0, 0, 0,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. NULL,
  121729. 0
  121730. };
  121731. static long _huff_lengthlist_line_2048x27_class4[] = {
  121732. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121733. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121734. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121735. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121736. };
  121737. static static_codebook _huff_book_line_2048x27_class4 = {
  121738. 1, 64,
  121739. _huff_lengthlist_line_2048x27_class4,
  121740. 0, 0, 0, 0, 0,
  121741. NULL,
  121742. NULL,
  121743. NULL,
  121744. NULL,
  121745. 0
  121746. };
  121747. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121748. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121749. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121750. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121751. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121752. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121753. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121754. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121755. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121756. };
  121757. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121758. 1, 128,
  121759. _huff_lengthlist_line_2048x27_0sub0,
  121760. 0, 0, 0, 0, 0,
  121761. NULL,
  121762. NULL,
  121763. NULL,
  121764. NULL,
  121765. 0
  121766. };
  121767. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121768. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121769. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121770. };
  121771. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121772. 1, 32,
  121773. _huff_lengthlist_line_2048x27_1sub0,
  121774. 0, 0, 0, 0, 0,
  121775. NULL,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. 0
  121780. };
  121781. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121785. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121786. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121787. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121788. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121789. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121790. };
  121791. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121792. 1, 128,
  121793. _huff_lengthlist_line_2048x27_1sub1,
  121794. 0, 0, 0, 0, 0,
  121795. NULL,
  121796. NULL,
  121797. NULL,
  121798. NULL,
  121799. 0
  121800. };
  121801. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121802. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121803. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121804. };
  121805. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121806. 1, 32,
  121807. _huff_lengthlist_line_2048x27_2sub0,
  121808. 0, 0, 0, 0, 0,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. NULL,
  121813. 0
  121814. };
  121815. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121819. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121820. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121821. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121822. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121823. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121824. };
  121825. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121826. 1, 128,
  121827. _huff_lengthlist_line_2048x27_2sub1,
  121828. 0, 0, 0, 0, 0,
  121829. NULL,
  121830. NULL,
  121831. NULL,
  121832. NULL,
  121833. 0
  121834. };
  121835. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121836. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121837. 5, 5,
  121838. };
  121839. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121840. 1, 18,
  121841. _huff_lengthlist_line_2048x27_3sub1,
  121842. 0, 0, 0, 0, 0,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. NULL,
  121847. 0
  121848. };
  121849. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121851. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121852. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121853. 10,12,
  121854. };
  121855. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121856. 1, 50,
  121857. _huff_lengthlist_line_2048x27_3sub2,
  121858. 0, 0, 0, 0, 0,
  121859. NULL,
  121860. NULL,
  121861. NULL,
  121862. NULL,
  121863. 0
  121864. };
  121865. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121869. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121870. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121871. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121872. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121873. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121874. };
  121875. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121876. 1, 128,
  121877. _huff_lengthlist_line_2048x27_3sub3,
  121878. 0, 0, 0, 0, 0,
  121879. NULL,
  121880. NULL,
  121881. NULL,
  121882. NULL,
  121883. 0
  121884. };
  121885. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121886. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121887. 4, 5,
  121888. };
  121889. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121890. 1, 18,
  121891. _huff_lengthlist_line_2048x27_4sub1,
  121892. 0, 0, 0, 0, 0,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. NULL,
  121897. 0
  121898. };
  121899. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121902. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121903. 10,10,
  121904. };
  121905. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121906. 1, 50,
  121907. _huff_lengthlist_line_2048x27_4sub2,
  121908. 0, 0, 0, 0, 0,
  121909. NULL,
  121910. NULL,
  121911. NULL,
  121912. NULL,
  121913. 0
  121914. };
  121915. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121920. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121921. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121922. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121923. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121924. };
  121925. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121926. 1, 128,
  121927. _huff_lengthlist_line_2048x27_4sub3,
  121928. 0, 0, 0, 0, 0,
  121929. NULL,
  121930. NULL,
  121931. NULL,
  121932. NULL,
  121933. 0
  121934. };
  121935. static long _huff_lengthlist_line_256x4low_class0[] = {
  121936. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121937. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121938. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121939. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121940. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121941. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121942. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121943. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121944. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121945. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121946. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121947. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121948. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121949. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121950. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121951. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121952. };
  121953. static static_codebook _huff_book_line_256x4low_class0 = {
  121954. 1, 256,
  121955. _huff_lengthlist_line_256x4low_class0,
  121956. 0, 0, 0, 0, 0,
  121957. NULL,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. 0
  121962. };
  121963. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121964. 1, 3, 2, 3,
  121965. };
  121966. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121967. 1, 4,
  121968. _huff_lengthlist_line_256x4low_0sub0,
  121969. 0, 0, 0, 0, 0,
  121970. NULL,
  121971. NULL,
  121972. NULL,
  121973. NULL,
  121974. 0
  121975. };
  121976. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121977. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121978. };
  121979. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121980. 1, 10,
  121981. _huff_lengthlist_line_256x4low_0sub1,
  121982. 0, 0, 0, 0, 0,
  121983. NULL,
  121984. NULL,
  121985. NULL,
  121986. NULL,
  121987. 0
  121988. };
  121989. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121991. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121992. };
  121993. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121994. 1, 25,
  121995. _huff_lengthlist_line_256x4low_0sub2,
  121996. 0, 0, 0, 0, 0,
  121997. NULL,
  121998. NULL,
  121999. NULL,
  122000. NULL,
  122001. 0
  122002. };
  122003. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122006. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122007. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122008. };
  122009. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122010. 1, 64,
  122011. _huff_lengthlist_line_256x4low_0sub3,
  122012. 0, 0, 0, 0, 0,
  122013. NULL,
  122014. NULL,
  122015. NULL,
  122016. NULL,
  122017. 0
  122018. };
  122019. /*** End of inlined file: floor_books.h ***/
  122020. static static_codebook *_floor_128x4_books[]={
  122021. &_huff_book_line_128x4_class0,
  122022. &_huff_book_line_128x4_0sub0,
  122023. &_huff_book_line_128x4_0sub1,
  122024. &_huff_book_line_128x4_0sub2,
  122025. &_huff_book_line_128x4_0sub3,
  122026. };
  122027. static static_codebook *_floor_256x4_books[]={
  122028. &_huff_book_line_256x4_class0,
  122029. &_huff_book_line_256x4_0sub0,
  122030. &_huff_book_line_256x4_0sub1,
  122031. &_huff_book_line_256x4_0sub2,
  122032. &_huff_book_line_256x4_0sub3,
  122033. };
  122034. static static_codebook *_floor_128x7_books[]={
  122035. &_huff_book_line_128x7_class0,
  122036. &_huff_book_line_128x7_class1,
  122037. &_huff_book_line_128x7_0sub1,
  122038. &_huff_book_line_128x7_0sub2,
  122039. &_huff_book_line_128x7_0sub3,
  122040. &_huff_book_line_128x7_1sub1,
  122041. &_huff_book_line_128x7_1sub2,
  122042. &_huff_book_line_128x7_1sub3,
  122043. };
  122044. static static_codebook *_floor_256x7_books[]={
  122045. &_huff_book_line_256x7_class0,
  122046. &_huff_book_line_256x7_class1,
  122047. &_huff_book_line_256x7_0sub1,
  122048. &_huff_book_line_256x7_0sub2,
  122049. &_huff_book_line_256x7_0sub3,
  122050. &_huff_book_line_256x7_1sub1,
  122051. &_huff_book_line_256x7_1sub2,
  122052. &_huff_book_line_256x7_1sub3,
  122053. };
  122054. static static_codebook *_floor_128x11_books[]={
  122055. &_huff_book_line_128x11_class1,
  122056. &_huff_book_line_128x11_class2,
  122057. &_huff_book_line_128x11_class3,
  122058. &_huff_book_line_128x11_0sub0,
  122059. &_huff_book_line_128x11_1sub0,
  122060. &_huff_book_line_128x11_1sub1,
  122061. &_huff_book_line_128x11_2sub1,
  122062. &_huff_book_line_128x11_2sub2,
  122063. &_huff_book_line_128x11_2sub3,
  122064. &_huff_book_line_128x11_3sub1,
  122065. &_huff_book_line_128x11_3sub2,
  122066. &_huff_book_line_128x11_3sub3,
  122067. };
  122068. static static_codebook *_floor_128x17_books[]={
  122069. &_huff_book_line_128x17_class1,
  122070. &_huff_book_line_128x17_class2,
  122071. &_huff_book_line_128x17_class3,
  122072. &_huff_book_line_128x17_0sub0,
  122073. &_huff_book_line_128x17_1sub0,
  122074. &_huff_book_line_128x17_1sub1,
  122075. &_huff_book_line_128x17_2sub1,
  122076. &_huff_book_line_128x17_2sub2,
  122077. &_huff_book_line_128x17_2sub3,
  122078. &_huff_book_line_128x17_3sub1,
  122079. &_huff_book_line_128x17_3sub2,
  122080. &_huff_book_line_128x17_3sub3,
  122081. };
  122082. static static_codebook *_floor_256x4low_books[]={
  122083. &_huff_book_line_256x4low_class0,
  122084. &_huff_book_line_256x4low_0sub0,
  122085. &_huff_book_line_256x4low_0sub1,
  122086. &_huff_book_line_256x4low_0sub2,
  122087. &_huff_book_line_256x4low_0sub3,
  122088. };
  122089. static static_codebook *_floor_1024x27_books[]={
  122090. &_huff_book_line_1024x27_class1,
  122091. &_huff_book_line_1024x27_class2,
  122092. &_huff_book_line_1024x27_class3,
  122093. &_huff_book_line_1024x27_class4,
  122094. &_huff_book_line_1024x27_0sub0,
  122095. &_huff_book_line_1024x27_1sub0,
  122096. &_huff_book_line_1024x27_1sub1,
  122097. &_huff_book_line_1024x27_2sub0,
  122098. &_huff_book_line_1024x27_2sub1,
  122099. &_huff_book_line_1024x27_3sub1,
  122100. &_huff_book_line_1024x27_3sub2,
  122101. &_huff_book_line_1024x27_3sub3,
  122102. &_huff_book_line_1024x27_4sub1,
  122103. &_huff_book_line_1024x27_4sub2,
  122104. &_huff_book_line_1024x27_4sub3,
  122105. };
  122106. static static_codebook *_floor_2048x27_books[]={
  122107. &_huff_book_line_2048x27_class1,
  122108. &_huff_book_line_2048x27_class2,
  122109. &_huff_book_line_2048x27_class3,
  122110. &_huff_book_line_2048x27_class4,
  122111. &_huff_book_line_2048x27_0sub0,
  122112. &_huff_book_line_2048x27_1sub0,
  122113. &_huff_book_line_2048x27_1sub1,
  122114. &_huff_book_line_2048x27_2sub0,
  122115. &_huff_book_line_2048x27_2sub1,
  122116. &_huff_book_line_2048x27_3sub1,
  122117. &_huff_book_line_2048x27_3sub2,
  122118. &_huff_book_line_2048x27_3sub3,
  122119. &_huff_book_line_2048x27_4sub1,
  122120. &_huff_book_line_2048x27_4sub2,
  122121. &_huff_book_line_2048x27_4sub3,
  122122. };
  122123. static static_codebook *_floor_512x17_books[]={
  122124. &_huff_book_line_512x17_class1,
  122125. &_huff_book_line_512x17_class2,
  122126. &_huff_book_line_512x17_class3,
  122127. &_huff_book_line_512x17_0sub0,
  122128. &_huff_book_line_512x17_1sub0,
  122129. &_huff_book_line_512x17_1sub1,
  122130. &_huff_book_line_512x17_2sub1,
  122131. &_huff_book_line_512x17_2sub2,
  122132. &_huff_book_line_512x17_2sub3,
  122133. &_huff_book_line_512x17_3sub1,
  122134. &_huff_book_line_512x17_3sub2,
  122135. &_huff_book_line_512x17_3sub3,
  122136. };
  122137. static static_codebook **_floor_books[10]={
  122138. _floor_128x4_books,
  122139. _floor_256x4_books,
  122140. _floor_128x7_books,
  122141. _floor_256x7_books,
  122142. _floor_128x11_books,
  122143. _floor_128x17_books,
  122144. _floor_256x4low_books,
  122145. _floor_1024x27_books,
  122146. _floor_2048x27_books,
  122147. _floor_512x17_books,
  122148. };
  122149. static vorbis_info_floor1 _floor[10]={
  122150. /* 128 x 4 */
  122151. {
  122152. 1,{0},{4},{2},{0},
  122153. {{1,2,3,4}},
  122154. 4,{0,128, 33,8,16,70},
  122155. 60,30,500, 1.,18., -1
  122156. },
  122157. /* 256 x 4 */
  122158. {
  122159. 1,{0},{4},{2},{0},
  122160. {{1,2,3,4}},
  122161. 4,{0,256, 66,16,32,140},
  122162. 60,30,500, 1.,18., -1
  122163. },
  122164. /* 128 x 7 */
  122165. {
  122166. 2,{0,1},{3,4},{2,2},{0,1},
  122167. {{-1,2,3,4},{-1,5,6,7}},
  122168. 4,{0,128, 14,4,58, 2,8,28,90},
  122169. 60,30,500, 1.,18., -1
  122170. },
  122171. /* 256 x 7 */
  122172. {
  122173. 2,{0,1},{3,4},{2,2},{0,1},
  122174. {{-1,2,3,4},{-1,5,6,7}},
  122175. 4,{0,256, 28,8,116, 4,16,56,180},
  122176. 60,30,500, 1.,18., -1
  122177. },
  122178. /* 128 x 11 */
  122179. {
  122180. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122181. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122182. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122183. 60,30,500, 1,18., -1
  122184. },
  122185. /* 128 x 17 */
  122186. {
  122187. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122188. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122189. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122190. 60,30,500, 1,18., -1
  122191. },
  122192. /* 256 x 4 (low bitrate version) */
  122193. {
  122194. 1,{0},{4},{2},{0},
  122195. {{1,2,3,4}},
  122196. 4,{0,256, 66,16,32,140},
  122197. 60,30,500, 1.,18., -1
  122198. },
  122199. /* 1024 x 27 */
  122200. {
  122201. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122202. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122203. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122204. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122205. 60,30,500, 3,18., -1 /* lowpass */
  122206. },
  122207. /* 2048 x 27 */
  122208. {
  122209. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122210. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122211. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122212. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122213. 60,30,500, 3,18., -1 /* lowpass */
  122214. },
  122215. /* 512 x 17 */
  122216. {
  122217. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122218. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122219. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122220. 7,23,39, 55,79,110, 156,232,360},
  122221. 60,30,500, 1,18., -1 /* lowpass! */
  122222. },
  122223. };
  122224. /*** End of inlined file: floor_all.h ***/
  122225. /*** Start of inlined file: residue_44.h ***/
  122226. /*** Start of inlined file: res_books_stereo.h ***/
  122227. static long _vq_quantlist__16c0_s_p1_0[] = {
  122228. 1,
  122229. 0,
  122230. 2,
  122231. };
  122232. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122233. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122234. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122239. 0, 0, 0, 7, 9,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122244. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122279. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122284. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122289. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122325. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122330. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122335. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0,
  122644. };
  122645. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122646. -0.5, 0.5,
  122647. };
  122648. static long _vq_quantmap__16c0_s_p1_0[] = {
  122649. 1, 0, 2,
  122650. };
  122651. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122652. _vq_quantthresh__16c0_s_p1_0,
  122653. _vq_quantmap__16c0_s_p1_0,
  122654. 3,
  122655. 3
  122656. };
  122657. static static_codebook _16c0_s_p1_0 = {
  122658. 8, 6561,
  122659. _vq_lengthlist__16c0_s_p1_0,
  122660. 1, -535822336, 1611661312, 2, 0,
  122661. _vq_quantlist__16c0_s_p1_0,
  122662. NULL,
  122663. &_vq_auxt__16c0_s_p1_0,
  122664. NULL,
  122665. 0
  122666. };
  122667. static long _vq_quantlist__16c0_s_p2_0[] = {
  122668. 2,
  122669. 1,
  122670. 3,
  122671. 0,
  122672. 4,
  122673. };
  122674. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0,
  122715. };
  122716. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122717. -1.5, -0.5, 0.5, 1.5,
  122718. };
  122719. static long _vq_quantmap__16c0_s_p2_0[] = {
  122720. 3, 1, 0, 2, 4,
  122721. };
  122722. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122723. _vq_quantthresh__16c0_s_p2_0,
  122724. _vq_quantmap__16c0_s_p2_0,
  122725. 5,
  122726. 5
  122727. };
  122728. static static_codebook _16c0_s_p2_0 = {
  122729. 4, 625,
  122730. _vq_lengthlist__16c0_s_p2_0,
  122731. 1, -533725184, 1611661312, 3, 0,
  122732. _vq_quantlist__16c0_s_p2_0,
  122733. NULL,
  122734. &_vq_auxt__16c0_s_p2_0,
  122735. NULL,
  122736. 0
  122737. };
  122738. static long _vq_quantlist__16c0_s_p3_0[] = {
  122739. 2,
  122740. 1,
  122741. 3,
  122742. 0,
  122743. 4,
  122744. };
  122745. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122746. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0,
  122786. };
  122787. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122788. -1.5, -0.5, 0.5, 1.5,
  122789. };
  122790. static long _vq_quantmap__16c0_s_p3_0[] = {
  122791. 3, 1, 0, 2, 4,
  122792. };
  122793. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122794. _vq_quantthresh__16c0_s_p3_0,
  122795. _vq_quantmap__16c0_s_p3_0,
  122796. 5,
  122797. 5
  122798. };
  122799. static static_codebook _16c0_s_p3_0 = {
  122800. 4, 625,
  122801. _vq_lengthlist__16c0_s_p3_0,
  122802. 1, -533725184, 1611661312, 3, 0,
  122803. _vq_quantlist__16c0_s_p3_0,
  122804. NULL,
  122805. &_vq_auxt__16c0_s_p3_0,
  122806. NULL,
  122807. 0
  122808. };
  122809. static long _vq_quantlist__16c0_s_p4_0[] = {
  122810. 4,
  122811. 3,
  122812. 5,
  122813. 2,
  122814. 6,
  122815. 1,
  122816. 7,
  122817. 0,
  122818. 8,
  122819. };
  122820. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122821. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122822. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122823. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122824. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122825. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0,
  122827. };
  122828. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122829. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122830. };
  122831. static long _vq_quantmap__16c0_s_p4_0[] = {
  122832. 7, 5, 3, 1, 0, 2, 4, 6,
  122833. 8,
  122834. };
  122835. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122836. _vq_quantthresh__16c0_s_p4_0,
  122837. _vq_quantmap__16c0_s_p4_0,
  122838. 9,
  122839. 9
  122840. };
  122841. static static_codebook _16c0_s_p4_0 = {
  122842. 2, 81,
  122843. _vq_lengthlist__16c0_s_p4_0,
  122844. 1, -531628032, 1611661312, 4, 0,
  122845. _vq_quantlist__16c0_s_p4_0,
  122846. NULL,
  122847. &_vq_auxt__16c0_s_p4_0,
  122848. NULL,
  122849. 0
  122850. };
  122851. static long _vq_quantlist__16c0_s_p5_0[] = {
  122852. 4,
  122853. 3,
  122854. 5,
  122855. 2,
  122856. 6,
  122857. 1,
  122858. 7,
  122859. 0,
  122860. 8,
  122861. };
  122862. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122863. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122864. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122865. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122866. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122867. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122868. 10,
  122869. };
  122870. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122871. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122872. };
  122873. static long _vq_quantmap__16c0_s_p5_0[] = {
  122874. 7, 5, 3, 1, 0, 2, 4, 6,
  122875. 8,
  122876. };
  122877. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122878. _vq_quantthresh__16c0_s_p5_0,
  122879. _vq_quantmap__16c0_s_p5_0,
  122880. 9,
  122881. 9
  122882. };
  122883. static static_codebook _16c0_s_p5_0 = {
  122884. 2, 81,
  122885. _vq_lengthlist__16c0_s_p5_0,
  122886. 1, -531628032, 1611661312, 4, 0,
  122887. _vq_quantlist__16c0_s_p5_0,
  122888. NULL,
  122889. &_vq_auxt__16c0_s_p5_0,
  122890. NULL,
  122891. 0
  122892. };
  122893. static long _vq_quantlist__16c0_s_p6_0[] = {
  122894. 8,
  122895. 7,
  122896. 9,
  122897. 6,
  122898. 10,
  122899. 5,
  122900. 11,
  122901. 4,
  122902. 12,
  122903. 3,
  122904. 13,
  122905. 2,
  122906. 14,
  122907. 1,
  122908. 15,
  122909. 0,
  122910. 16,
  122911. };
  122912. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122913. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122914. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122915. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122916. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122917. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122918. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122919. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122920. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122921. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122922. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122923. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122924. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122925. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122926. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122927. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122928. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122929. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122931. 14,
  122932. };
  122933. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122934. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122935. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122936. };
  122937. static long _vq_quantmap__16c0_s_p6_0[] = {
  122938. 15, 13, 11, 9, 7, 5, 3, 1,
  122939. 0, 2, 4, 6, 8, 10, 12, 14,
  122940. 16,
  122941. };
  122942. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122943. _vq_quantthresh__16c0_s_p6_0,
  122944. _vq_quantmap__16c0_s_p6_0,
  122945. 17,
  122946. 17
  122947. };
  122948. static static_codebook _16c0_s_p6_0 = {
  122949. 2, 289,
  122950. _vq_lengthlist__16c0_s_p6_0,
  122951. 1, -529530880, 1611661312, 5, 0,
  122952. _vq_quantlist__16c0_s_p6_0,
  122953. NULL,
  122954. &_vq_auxt__16c0_s_p6_0,
  122955. NULL,
  122956. 0
  122957. };
  122958. static long _vq_quantlist__16c0_s_p7_0[] = {
  122959. 1,
  122960. 0,
  122961. 2,
  122962. };
  122963. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122964. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122965. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122966. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122967. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122968. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122969. 13,
  122970. };
  122971. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122972. -5.5, 5.5,
  122973. };
  122974. static long _vq_quantmap__16c0_s_p7_0[] = {
  122975. 1, 0, 2,
  122976. };
  122977. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122978. _vq_quantthresh__16c0_s_p7_0,
  122979. _vq_quantmap__16c0_s_p7_0,
  122980. 3,
  122981. 3
  122982. };
  122983. static static_codebook _16c0_s_p7_0 = {
  122984. 4, 81,
  122985. _vq_lengthlist__16c0_s_p7_0,
  122986. 1, -529137664, 1618345984, 2, 0,
  122987. _vq_quantlist__16c0_s_p7_0,
  122988. NULL,
  122989. &_vq_auxt__16c0_s_p7_0,
  122990. NULL,
  122991. 0
  122992. };
  122993. static long _vq_quantlist__16c0_s_p7_1[] = {
  122994. 5,
  122995. 4,
  122996. 6,
  122997. 3,
  122998. 7,
  122999. 2,
  123000. 8,
  123001. 1,
  123002. 9,
  123003. 0,
  123004. 10,
  123005. };
  123006. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123007. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123008. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123009. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123010. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123011. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123012. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123013. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123014. 11,11,11, 9, 9, 9, 9,10,10,
  123015. };
  123016. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123017. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123018. 3.5, 4.5,
  123019. };
  123020. static long _vq_quantmap__16c0_s_p7_1[] = {
  123021. 9, 7, 5, 3, 1, 0, 2, 4,
  123022. 6, 8, 10,
  123023. };
  123024. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123025. _vq_quantthresh__16c0_s_p7_1,
  123026. _vq_quantmap__16c0_s_p7_1,
  123027. 11,
  123028. 11
  123029. };
  123030. static static_codebook _16c0_s_p7_1 = {
  123031. 2, 121,
  123032. _vq_lengthlist__16c0_s_p7_1,
  123033. 1, -531365888, 1611661312, 4, 0,
  123034. _vq_quantlist__16c0_s_p7_1,
  123035. NULL,
  123036. &_vq_auxt__16c0_s_p7_1,
  123037. NULL,
  123038. 0
  123039. };
  123040. static long _vq_quantlist__16c0_s_p8_0[] = {
  123041. 6,
  123042. 5,
  123043. 7,
  123044. 4,
  123045. 8,
  123046. 3,
  123047. 9,
  123048. 2,
  123049. 10,
  123050. 1,
  123051. 11,
  123052. 0,
  123053. 12,
  123054. };
  123055. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123056. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123057. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123058. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123059. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123060. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123061. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123062. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123063. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123064. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123065. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123066. 0,12,13,13,12,13,14,14,14,
  123067. };
  123068. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123069. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123070. 12.5, 17.5, 22.5, 27.5,
  123071. };
  123072. static long _vq_quantmap__16c0_s_p8_0[] = {
  123073. 11, 9, 7, 5, 3, 1, 0, 2,
  123074. 4, 6, 8, 10, 12,
  123075. };
  123076. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123077. _vq_quantthresh__16c0_s_p8_0,
  123078. _vq_quantmap__16c0_s_p8_0,
  123079. 13,
  123080. 13
  123081. };
  123082. static static_codebook _16c0_s_p8_0 = {
  123083. 2, 169,
  123084. _vq_lengthlist__16c0_s_p8_0,
  123085. 1, -526516224, 1616117760, 4, 0,
  123086. _vq_quantlist__16c0_s_p8_0,
  123087. NULL,
  123088. &_vq_auxt__16c0_s_p8_0,
  123089. NULL,
  123090. 0
  123091. };
  123092. static long _vq_quantlist__16c0_s_p8_1[] = {
  123093. 2,
  123094. 1,
  123095. 3,
  123096. 0,
  123097. 4,
  123098. };
  123099. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123100. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123101. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123102. };
  123103. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123104. -1.5, -0.5, 0.5, 1.5,
  123105. };
  123106. static long _vq_quantmap__16c0_s_p8_1[] = {
  123107. 3, 1, 0, 2, 4,
  123108. };
  123109. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123110. _vq_quantthresh__16c0_s_p8_1,
  123111. _vq_quantmap__16c0_s_p8_1,
  123112. 5,
  123113. 5
  123114. };
  123115. static static_codebook _16c0_s_p8_1 = {
  123116. 2, 25,
  123117. _vq_lengthlist__16c0_s_p8_1,
  123118. 1, -533725184, 1611661312, 3, 0,
  123119. _vq_quantlist__16c0_s_p8_1,
  123120. NULL,
  123121. &_vq_auxt__16c0_s_p8_1,
  123122. NULL,
  123123. 0
  123124. };
  123125. static long _vq_quantlist__16c0_s_p9_0[] = {
  123126. 1,
  123127. 0,
  123128. 2,
  123129. };
  123130. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123131. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123132. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123133. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123134. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123135. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123136. 7,
  123137. };
  123138. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123139. -157.5, 157.5,
  123140. };
  123141. static long _vq_quantmap__16c0_s_p9_0[] = {
  123142. 1, 0, 2,
  123143. };
  123144. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123145. _vq_quantthresh__16c0_s_p9_0,
  123146. _vq_quantmap__16c0_s_p9_0,
  123147. 3,
  123148. 3
  123149. };
  123150. static static_codebook _16c0_s_p9_0 = {
  123151. 4, 81,
  123152. _vq_lengthlist__16c0_s_p9_0,
  123153. 1, -518803456, 1628680192, 2, 0,
  123154. _vq_quantlist__16c0_s_p9_0,
  123155. NULL,
  123156. &_vq_auxt__16c0_s_p9_0,
  123157. NULL,
  123158. 0
  123159. };
  123160. static long _vq_quantlist__16c0_s_p9_1[] = {
  123161. 7,
  123162. 6,
  123163. 8,
  123164. 5,
  123165. 9,
  123166. 4,
  123167. 10,
  123168. 3,
  123169. 11,
  123170. 2,
  123171. 12,
  123172. 1,
  123173. 13,
  123174. 0,
  123175. 14,
  123176. };
  123177. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123178. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123179. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123180. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123181. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123182. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123183. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123184. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123185. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123186. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123187. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123188. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123189. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123190. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123191. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123192. 10,
  123193. };
  123194. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123195. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123196. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123197. };
  123198. static long _vq_quantmap__16c0_s_p9_1[] = {
  123199. 13, 11, 9, 7, 5, 3, 1, 0,
  123200. 2, 4, 6, 8, 10, 12, 14,
  123201. };
  123202. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123203. _vq_quantthresh__16c0_s_p9_1,
  123204. _vq_quantmap__16c0_s_p9_1,
  123205. 15,
  123206. 15
  123207. };
  123208. static static_codebook _16c0_s_p9_1 = {
  123209. 2, 225,
  123210. _vq_lengthlist__16c0_s_p9_1,
  123211. 1, -520986624, 1620377600, 4, 0,
  123212. _vq_quantlist__16c0_s_p9_1,
  123213. NULL,
  123214. &_vq_auxt__16c0_s_p9_1,
  123215. NULL,
  123216. 0
  123217. };
  123218. static long _vq_quantlist__16c0_s_p9_2[] = {
  123219. 10,
  123220. 9,
  123221. 11,
  123222. 8,
  123223. 12,
  123224. 7,
  123225. 13,
  123226. 6,
  123227. 14,
  123228. 5,
  123229. 15,
  123230. 4,
  123231. 16,
  123232. 3,
  123233. 17,
  123234. 2,
  123235. 18,
  123236. 1,
  123237. 19,
  123238. 0,
  123239. 20,
  123240. };
  123241. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123242. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123243. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123244. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123245. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123246. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123247. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123248. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123249. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123250. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123251. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123252. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123253. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123254. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123255. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123256. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123257. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123258. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123259. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123260. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123261. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123262. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123263. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123264. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123265. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123266. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123267. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123268. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123269. 10,11,10,10,11, 9,10,10,10,
  123270. };
  123271. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123272. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123273. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123274. 6.5, 7.5, 8.5, 9.5,
  123275. };
  123276. static long _vq_quantmap__16c0_s_p9_2[] = {
  123277. 19, 17, 15, 13, 11, 9, 7, 5,
  123278. 3, 1, 0, 2, 4, 6, 8, 10,
  123279. 12, 14, 16, 18, 20,
  123280. };
  123281. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123282. _vq_quantthresh__16c0_s_p9_2,
  123283. _vq_quantmap__16c0_s_p9_2,
  123284. 21,
  123285. 21
  123286. };
  123287. static static_codebook _16c0_s_p9_2 = {
  123288. 2, 441,
  123289. _vq_lengthlist__16c0_s_p9_2,
  123290. 1, -529268736, 1611661312, 5, 0,
  123291. _vq_quantlist__16c0_s_p9_2,
  123292. NULL,
  123293. &_vq_auxt__16c0_s_p9_2,
  123294. NULL,
  123295. 0
  123296. };
  123297. static long _huff_lengthlist__16c0_s_single[] = {
  123298. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123299. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123300. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123301. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123302. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123303. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123304. 16,16,18,18,
  123305. };
  123306. static static_codebook _huff_book__16c0_s_single = {
  123307. 2, 100,
  123308. _huff_lengthlist__16c0_s_single,
  123309. 0, 0, 0, 0, 0,
  123310. NULL,
  123311. NULL,
  123312. NULL,
  123313. NULL,
  123314. 0
  123315. };
  123316. static long _huff_lengthlist__16c1_s_long[] = {
  123317. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123318. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123319. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123320. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123321. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123322. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123323. 12,11,11,13,
  123324. };
  123325. static static_codebook _huff_book__16c1_s_long = {
  123326. 2, 100,
  123327. _huff_lengthlist__16c1_s_long,
  123328. 0, 0, 0, 0, 0,
  123329. NULL,
  123330. NULL,
  123331. NULL,
  123332. NULL,
  123333. 0
  123334. };
  123335. static long _vq_quantlist__16c1_s_p1_0[] = {
  123336. 1,
  123337. 0,
  123338. 2,
  123339. };
  123340. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123341. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123342. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123347. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123352. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123387. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123392. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123397. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123433. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123438. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123443. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0,
  123752. };
  123753. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123754. -0.5, 0.5,
  123755. };
  123756. static long _vq_quantmap__16c1_s_p1_0[] = {
  123757. 1, 0, 2,
  123758. };
  123759. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123760. _vq_quantthresh__16c1_s_p1_0,
  123761. _vq_quantmap__16c1_s_p1_0,
  123762. 3,
  123763. 3
  123764. };
  123765. static static_codebook _16c1_s_p1_0 = {
  123766. 8, 6561,
  123767. _vq_lengthlist__16c1_s_p1_0,
  123768. 1, -535822336, 1611661312, 2, 0,
  123769. _vq_quantlist__16c1_s_p1_0,
  123770. NULL,
  123771. &_vq_auxt__16c1_s_p1_0,
  123772. NULL,
  123773. 0
  123774. };
  123775. static long _vq_quantlist__16c1_s_p2_0[] = {
  123776. 2,
  123777. 1,
  123778. 3,
  123779. 0,
  123780. 4,
  123781. };
  123782. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0,
  123823. };
  123824. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123825. -1.5, -0.5, 0.5, 1.5,
  123826. };
  123827. static long _vq_quantmap__16c1_s_p2_0[] = {
  123828. 3, 1, 0, 2, 4,
  123829. };
  123830. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123831. _vq_quantthresh__16c1_s_p2_0,
  123832. _vq_quantmap__16c1_s_p2_0,
  123833. 5,
  123834. 5
  123835. };
  123836. static static_codebook _16c1_s_p2_0 = {
  123837. 4, 625,
  123838. _vq_lengthlist__16c1_s_p2_0,
  123839. 1, -533725184, 1611661312, 3, 0,
  123840. _vq_quantlist__16c1_s_p2_0,
  123841. NULL,
  123842. &_vq_auxt__16c1_s_p2_0,
  123843. NULL,
  123844. 0
  123845. };
  123846. static long _vq_quantlist__16c1_s_p3_0[] = {
  123847. 2,
  123848. 1,
  123849. 3,
  123850. 0,
  123851. 4,
  123852. };
  123853. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123854. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0,
  123894. };
  123895. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123896. -1.5, -0.5, 0.5, 1.5,
  123897. };
  123898. static long _vq_quantmap__16c1_s_p3_0[] = {
  123899. 3, 1, 0, 2, 4,
  123900. };
  123901. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123902. _vq_quantthresh__16c1_s_p3_0,
  123903. _vq_quantmap__16c1_s_p3_0,
  123904. 5,
  123905. 5
  123906. };
  123907. static static_codebook _16c1_s_p3_0 = {
  123908. 4, 625,
  123909. _vq_lengthlist__16c1_s_p3_0,
  123910. 1, -533725184, 1611661312, 3, 0,
  123911. _vq_quantlist__16c1_s_p3_0,
  123912. NULL,
  123913. &_vq_auxt__16c1_s_p3_0,
  123914. NULL,
  123915. 0
  123916. };
  123917. static long _vq_quantlist__16c1_s_p4_0[] = {
  123918. 4,
  123919. 3,
  123920. 5,
  123921. 2,
  123922. 6,
  123923. 1,
  123924. 7,
  123925. 0,
  123926. 8,
  123927. };
  123928. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123929. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123930. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123931. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123932. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123933. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0,
  123935. };
  123936. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123937. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123938. };
  123939. static long _vq_quantmap__16c1_s_p4_0[] = {
  123940. 7, 5, 3, 1, 0, 2, 4, 6,
  123941. 8,
  123942. };
  123943. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123944. _vq_quantthresh__16c1_s_p4_0,
  123945. _vq_quantmap__16c1_s_p4_0,
  123946. 9,
  123947. 9
  123948. };
  123949. static static_codebook _16c1_s_p4_0 = {
  123950. 2, 81,
  123951. _vq_lengthlist__16c1_s_p4_0,
  123952. 1, -531628032, 1611661312, 4, 0,
  123953. _vq_quantlist__16c1_s_p4_0,
  123954. NULL,
  123955. &_vq_auxt__16c1_s_p4_0,
  123956. NULL,
  123957. 0
  123958. };
  123959. static long _vq_quantlist__16c1_s_p5_0[] = {
  123960. 4,
  123961. 3,
  123962. 5,
  123963. 2,
  123964. 6,
  123965. 1,
  123966. 7,
  123967. 0,
  123968. 8,
  123969. };
  123970. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123971. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123972. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123973. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123974. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123975. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123976. 10,
  123977. };
  123978. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123979. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123980. };
  123981. static long _vq_quantmap__16c1_s_p5_0[] = {
  123982. 7, 5, 3, 1, 0, 2, 4, 6,
  123983. 8,
  123984. };
  123985. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123986. _vq_quantthresh__16c1_s_p5_0,
  123987. _vq_quantmap__16c1_s_p5_0,
  123988. 9,
  123989. 9
  123990. };
  123991. static static_codebook _16c1_s_p5_0 = {
  123992. 2, 81,
  123993. _vq_lengthlist__16c1_s_p5_0,
  123994. 1, -531628032, 1611661312, 4, 0,
  123995. _vq_quantlist__16c1_s_p5_0,
  123996. NULL,
  123997. &_vq_auxt__16c1_s_p5_0,
  123998. NULL,
  123999. 0
  124000. };
  124001. static long _vq_quantlist__16c1_s_p6_0[] = {
  124002. 8,
  124003. 7,
  124004. 9,
  124005. 6,
  124006. 10,
  124007. 5,
  124008. 11,
  124009. 4,
  124010. 12,
  124011. 3,
  124012. 13,
  124013. 2,
  124014. 14,
  124015. 1,
  124016. 15,
  124017. 0,
  124018. 16,
  124019. };
  124020. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124021. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124022. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124023. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124024. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124025. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124026. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124027. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124028. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124029. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124030. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124031. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124032. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124033. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124034. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124035. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124036. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124037. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124039. 14,
  124040. };
  124041. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124042. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124043. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124044. };
  124045. static long _vq_quantmap__16c1_s_p6_0[] = {
  124046. 15, 13, 11, 9, 7, 5, 3, 1,
  124047. 0, 2, 4, 6, 8, 10, 12, 14,
  124048. 16,
  124049. };
  124050. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124051. _vq_quantthresh__16c1_s_p6_0,
  124052. _vq_quantmap__16c1_s_p6_0,
  124053. 17,
  124054. 17
  124055. };
  124056. static static_codebook _16c1_s_p6_0 = {
  124057. 2, 289,
  124058. _vq_lengthlist__16c1_s_p6_0,
  124059. 1, -529530880, 1611661312, 5, 0,
  124060. _vq_quantlist__16c1_s_p6_0,
  124061. NULL,
  124062. &_vq_auxt__16c1_s_p6_0,
  124063. NULL,
  124064. 0
  124065. };
  124066. static long _vq_quantlist__16c1_s_p7_0[] = {
  124067. 1,
  124068. 0,
  124069. 2,
  124070. };
  124071. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124072. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124073. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124074. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124075. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124076. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124077. 11,
  124078. };
  124079. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124080. -5.5, 5.5,
  124081. };
  124082. static long _vq_quantmap__16c1_s_p7_0[] = {
  124083. 1, 0, 2,
  124084. };
  124085. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124086. _vq_quantthresh__16c1_s_p7_0,
  124087. _vq_quantmap__16c1_s_p7_0,
  124088. 3,
  124089. 3
  124090. };
  124091. static static_codebook _16c1_s_p7_0 = {
  124092. 4, 81,
  124093. _vq_lengthlist__16c1_s_p7_0,
  124094. 1, -529137664, 1618345984, 2, 0,
  124095. _vq_quantlist__16c1_s_p7_0,
  124096. NULL,
  124097. &_vq_auxt__16c1_s_p7_0,
  124098. NULL,
  124099. 0
  124100. };
  124101. static long _vq_quantlist__16c1_s_p7_1[] = {
  124102. 5,
  124103. 4,
  124104. 6,
  124105. 3,
  124106. 7,
  124107. 2,
  124108. 8,
  124109. 1,
  124110. 9,
  124111. 0,
  124112. 10,
  124113. };
  124114. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124115. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124116. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124117. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124118. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124119. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124120. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124121. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124122. 10,10,10, 8, 8, 8, 8, 9, 9,
  124123. };
  124124. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124125. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124126. 3.5, 4.5,
  124127. };
  124128. static long _vq_quantmap__16c1_s_p7_1[] = {
  124129. 9, 7, 5, 3, 1, 0, 2, 4,
  124130. 6, 8, 10,
  124131. };
  124132. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124133. _vq_quantthresh__16c1_s_p7_1,
  124134. _vq_quantmap__16c1_s_p7_1,
  124135. 11,
  124136. 11
  124137. };
  124138. static static_codebook _16c1_s_p7_1 = {
  124139. 2, 121,
  124140. _vq_lengthlist__16c1_s_p7_1,
  124141. 1, -531365888, 1611661312, 4, 0,
  124142. _vq_quantlist__16c1_s_p7_1,
  124143. NULL,
  124144. &_vq_auxt__16c1_s_p7_1,
  124145. NULL,
  124146. 0
  124147. };
  124148. static long _vq_quantlist__16c1_s_p8_0[] = {
  124149. 6,
  124150. 5,
  124151. 7,
  124152. 4,
  124153. 8,
  124154. 3,
  124155. 9,
  124156. 2,
  124157. 10,
  124158. 1,
  124159. 11,
  124160. 0,
  124161. 12,
  124162. };
  124163. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124164. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124165. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124166. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124167. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124168. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124169. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124170. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124171. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124172. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124173. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124174. 0,12,12,12,12,13,13,14,15,
  124175. };
  124176. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124177. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124178. 12.5, 17.5, 22.5, 27.5,
  124179. };
  124180. static long _vq_quantmap__16c1_s_p8_0[] = {
  124181. 11, 9, 7, 5, 3, 1, 0, 2,
  124182. 4, 6, 8, 10, 12,
  124183. };
  124184. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124185. _vq_quantthresh__16c1_s_p8_0,
  124186. _vq_quantmap__16c1_s_p8_0,
  124187. 13,
  124188. 13
  124189. };
  124190. static static_codebook _16c1_s_p8_0 = {
  124191. 2, 169,
  124192. _vq_lengthlist__16c1_s_p8_0,
  124193. 1, -526516224, 1616117760, 4, 0,
  124194. _vq_quantlist__16c1_s_p8_0,
  124195. NULL,
  124196. &_vq_auxt__16c1_s_p8_0,
  124197. NULL,
  124198. 0
  124199. };
  124200. static long _vq_quantlist__16c1_s_p8_1[] = {
  124201. 2,
  124202. 1,
  124203. 3,
  124204. 0,
  124205. 4,
  124206. };
  124207. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124208. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124209. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124210. };
  124211. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124212. -1.5, -0.5, 0.5, 1.5,
  124213. };
  124214. static long _vq_quantmap__16c1_s_p8_1[] = {
  124215. 3, 1, 0, 2, 4,
  124216. };
  124217. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124218. _vq_quantthresh__16c1_s_p8_1,
  124219. _vq_quantmap__16c1_s_p8_1,
  124220. 5,
  124221. 5
  124222. };
  124223. static static_codebook _16c1_s_p8_1 = {
  124224. 2, 25,
  124225. _vq_lengthlist__16c1_s_p8_1,
  124226. 1, -533725184, 1611661312, 3, 0,
  124227. _vq_quantlist__16c1_s_p8_1,
  124228. NULL,
  124229. &_vq_auxt__16c1_s_p8_1,
  124230. NULL,
  124231. 0
  124232. };
  124233. static long _vq_quantlist__16c1_s_p9_0[] = {
  124234. 6,
  124235. 5,
  124236. 7,
  124237. 4,
  124238. 8,
  124239. 3,
  124240. 9,
  124241. 2,
  124242. 10,
  124243. 1,
  124244. 11,
  124245. 0,
  124246. 12,
  124247. };
  124248. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124249. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124250. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124251. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124252. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124253. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124254. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124255. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124256. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124257. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124258. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124259. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124260. };
  124261. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124262. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124263. 787.5, 1102.5, 1417.5, 1732.5,
  124264. };
  124265. static long _vq_quantmap__16c1_s_p9_0[] = {
  124266. 11, 9, 7, 5, 3, 1, 0, 2,
  124267. 4, 6, 8, 10, 12,
  124268. };
  124269. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124270. _vq_quantthresh__16c1_s_p9_0,
  124271. _vq_quantmap__16c1_s_p9_0,
  124272. 13,
  124273. 13
  124274. };
  124275. static static_codebook _16c1_s_p9_0 = {
  124276. 2, 169,
  124277. _vq_lengthlist__16c1_s_p9_0,
  124278. 1, -513964032, 1628680192, 4, 0,
  124279. _vq_quantlist__16c1_s_p9_0,
  124280. NULL,
  124281. &_vq_auxt__16c1_s_p9_0,
  124282. NULL,
  124283. 0
  124284. };
  124285. static long _vq_quantlist__16c1_s_p9_1[] = {
  124286. 7,
  124287. 6,
  124288. 8,
  124289. 5,
  124290. 9,
  124291. 4,
  124292. 10,
  124293. 3,
  124294. 11,
  124295. 2,
  124296. 12,
  124297. 1,
  124298. 13,
  124299. 0,
  124300. 14,
  124301. };
  124302. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124303. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124304. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124305. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124306. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124307. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124308. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124309. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124310. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124311. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124312. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124313. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124314. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124315. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124316. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124317. 13,
  124318. };
  124319. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124320. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124321. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124322. };
  124323. static long _vq_quantmap__16c1_s_p9_1[] = {
  124324. 13, 11, 9, 7, 5, 3, 1, 0,
  124325. 2, 4, 6, 8, 10, 12, 14,
  124326. };
  124327. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124328. _vq_quantthresh__16c1_s_p9_1,
  124329. _vq_quantmap__16c1_s_p9_1,
  124330. 15,
  124331. 15
  124332. };
  124333. static static_codebook _16c1_s_p9_1 = {
  124334. 2, 225,
  124335. _vq_lengthlist__16c1_s_p9_1,
  124336. 1, -520986624, 1620377600, 4, 0,
  124337. _vq_quantlist__16c1_s_p9_1,
  124338. NULL,
  124339. &_vq_auxt__16c1_s_p9_1,
  124340. NULL,
  124341. 0
  124342. };
  124343. static long _vq_quantlist__16c1_s_p9_2[] = {
  124344. 10,
  124345. 9,
  124346. 11,
  124347. 8,
  124348. 12,
  124349. 7,
  124350. 13,
  124351. 6,
  124352. 14,
  124353. 5,
  124354. 15,
  124355. 4,
  124356. 16,
  124357. 3,
  124358. 17,
  124359. 2,
  124360. 18,
  124361. 1,
  124362. 19,
  124363. 0,
  124364. 20,
  124365. };
  124366. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124367. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124368. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124369. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124370. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124371. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124372. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124373. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124374. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124375. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124376. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124377. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124378. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124379. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124380. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124381. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124382. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124383. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124384. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124385. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124386. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124387. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124388. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124389. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124390. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124391. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124392. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124393. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124394. 11,11,11,11,12,11,11,12,11,
  124395. };
  124396. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124397. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124398. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124399. 6.5, 7.5, 8.5, 9.5,
  124400. };
  124401. static long _vq_quantmap__16c1_s_p9_2[] = {
  124402. 19, 17, 15, 13, 11, 9, 7, 5,
  124403. 3, 1, 0, 2, 4, 6, 8, 10,
  124404. 12, 14, 16, 18, 20,
  124405. };
  124406. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124407. _vq_quantthresh__16c1_s_p9_2,
  124408. _vq_quantmap__16c1_s_p9_2,
  124409. 21,
  124410. 21
  124411. };
  124412. static static_codebook _16c1_s_p9_2 = {
  124413. 2, 441,
  124414. _vq_lengthlist__16c1_s_p9_2,
  124415. 1, -529268736, 1611661312, 5, 0,
  124416. _vq_quantlist__16c1_s_p9_2,
  124417. NULL,
  124418. &_vq_auxt__16c1_s_p9_2,
  124419. NULL,
  124420. 0
  124421. };
  124422. static long _huff_lengthlist__16c1_s_short[] = {
  124423. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124424. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124425. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124426. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124427. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124428. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124429. 9, 9,10,13,
  124430. };
  124431. static static_codebook _huff_book__16c1_s_short = {
  124432. 2, 100,
  124433. _huff_lengthlist__16c1_s_short,
  124434. 0, 0, 0, 0, 0,
  124435. NULL,
  124436. NULL,
  124437. NULL,
  124438. NULL,
  124439. 0
  124440. };
  124441. static long _huff_lengthlist__16c2_s_long[] = {
  124442. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124443. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124444. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124445. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124446. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124447. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124448. 14,14,16,18,
  124449. };
  124450. static static_codebook _huff_book__16c2_s_long = {
  124451. 2, 100,
  124452. _huff_lengthlist__16c2_s_long,
  124453. 0, 0, 0, 0, 0,
  124454. NULL,
  124455. NULL,
  124456. NULL,
  124457. NULL,
  124458. 0
  124459. };
  124460. static long _vq_quantlist__16c2_s_p1_0[] = {
  124461. 1,
  124462. 0,
  124463. 2,
  124464. };
  124465. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124466. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124467. 0, 0, 4, 5, 5, 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,
  124472. };
  124473. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124474. -0.5, 0.5,
  124475. };
  124476. static long _vq_quantmap__16c2_s_p1_0[] = {
  124477. 1, 0, 2,
  124478. };
  124479. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124480. _vq_quantthresh__16c2_s_p1_0,
  124481. _vq_quantmap__16c2_s_p1_0,
  124482. 3,
  124483. 3
  124484. };
  124485. static static_codebook _16c2_s_p1_0 = {
  124486. 4, 81,
  124487. _vq_lengthlist__16c2_s_p1_0,
  124488. 1, -535822336, 1611661312, 2, 0,
  124489. _vq_quantlist__16c2_s_p1_0,
  124490. NULL,
  124491. &_vq_auxt__16c2_s_p1_0,
  124492. NULL,
  124493. 0
  124494. };
  124495. static long _vq_quantlist__16c2_s_p2_0[] = {
  124496. 2,
  124497. 1,
  124498. 3,
  124499. 0,
  124500. 4,
  124501. };
  124502. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124503. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124504. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124505. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124506. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124507. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124508. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124509. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124510. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124516. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124517. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124518. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124523. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124524. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124525. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124526. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124531. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124532. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124533. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124534. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124539. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124540. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124541. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124542. 13,
  124543. };
  124544. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124545. -1.5, -0.5, 0.5, 1.5,
  124546. };
  124547. static long _vq_quantmap__16c2_s_p2_0[] = {
  124548. 3, 1, 0, 2, 4,
  124549. };
  124550. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124551. _vq_quantthresh__16c2_s_p2_0,
  124552. _vq_quantmap__16c2_s_p2_0,
  124553. 5,
  124554. 5
  124555. };
  124556. static static_codebook _16c2_s_p2_0 = {
  124557. 4, 625,
  124558. _vq_lengthlist__16c2_s_p2_0,
  124559. 1, -533725184, 1611661312, 3, 0,
  124560. _vq_quantlist__16c2_s_p2_0,
  124561. NULL,
  124562. &_vq_auxt__16c2_s_p2_0,
  124563. NULL,
  124564. 0
  124565. };
  124566. static long _vq_quantlist__16c2_s_p3_0[] = {
  124567. 4,
  124568. 3,
  124569. 5,
  124570. 2,
  124571. 6,
  124572. 1,
  124573. 7,
  124574. 0,
  124575. 8,
  124576. };
  124577. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124578. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124579. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124580. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124581. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0,
  124584. };
  124585. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124586. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124587. };
  124588. static long _vq_quantmap__16c2_s_p3_0[] = {
  124589. 7, 5, 3, 1, 0, 2, 4, 6,
  124590. 8,
  124591. };
  124592. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124593. _vq_quantthresh__16c2_s_p3_0,
  124594. _vq_quantmap__16c2_s_p3_0,
  124595. 9,
  124596. 9
  124597. };
  124598. static static_codebook _16c2_s_p3_0 = {
  124599. 2, 81,
  124600. _vq_lengthlist__16c2_s_p3_0,
  124601. 1, -531628032, 1611661312, 4, 0,
  124602. _vq_quantlist__16c2_s_p3_0,
  124603. NULL,
  124604. &_vq_auxt__16c2_s_p3_0,
  124605. NULL,
  124606. 0
  124607. };
  124608. static long _vq_quantlist__16c2_s_p4_0[] = {
  124609. 8,
  124610. 7,
  124611. 9,
  124612. 6,
  124613. 10,
  124614. 5,
  124615. 11,
  124616. 4,
  124617. 12,
  124618. 3,
  124619. 13,
  124620. 2,
  124621. 14,
  124622. 1,
  124623. 15,
  124624. 0,
  124625. 16,
  124626. };
  124627. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124628. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124629. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124630. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124631. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124632. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124633. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124634. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124635. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124636. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124637. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0,
  124647. };
  124648. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124649. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124650. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124651. };
  124652. static long _vq_quantmap__16c2_s_p4_0[] = {
  124653. 15, 13, 11, 9, 7, 5, 3, 1,
  124654. 0, 2, 4, 6, 8, 10, 12, 14,
  124655. 16,
  124656. };
  124657. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124658. _vq_quantthresh__16c2_s_p4_0,
  124659. _vq_quantmap__16c2_s_p4_0,
  124660. 17,
  124661. 17
  124662. };
  124663. static static_codebook _16c2_s_p4_0 = {
  124664. 2, 289,
  124665. _vq_lengthlist__16c2_s_p4_0,
  124666. 1, -529530880, 1611661312, 5, 0,
  124667. _vq_quantlist__16c2_s_p4_0,
  124668. NULL,
  124669. &_vq_auxt__16c2_s_p4_0,
  124670. NULL,
  124671. 0
  124672. };
  124673. static long _vq_quantlist__16c2_s_p5_0[] = {
  124674. 1,
  124675. 0,
  124676. 2,
  124677. };
  124678. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124679. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124680. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124681. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124682. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124683. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124684. 12,
  124685. };
  124686. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124687. -5.5, 5.5,
  124688. };
  124689. static long _vq_quantmap__16c2_s_p5_0[] = {
  124690. 1, 0, 2,
  124691. };
  124692. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124693. _vq_quantthresh__16c2_s_p5_0,
  124694. _vq_quantmap__16c2_s_p5_0,
  124695. 3,
  124696. 3
  124697. };
  124698. static static_codebook _16c2_s_p5_0 = {
  124699. 4, 81,
  124700. _vq_lengthlist__16c2_s_p5_0,
  124701. 1, -529137664, 1618345984, 2, 0,
  124702. _vq_quantlist__16c2_s_p5_0,
  124703. NULL,
  124704. &_vq_auxt__16c2_s_p5_0,
  124705. NULL,
  124706. 0
  124707. };
  124708. static long _vq_quantlist__16c2_s_p5_1[] = {
  124709. 5,
  124710. 4,
  124711. 6,
  124712. 3,
  124713. 7,
  124714. 2,
  124715. 8,
  124716. 1,
  124717. 9,
  124718. 0,
  124719. 10,
  124720. };
  124721. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124722. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124723. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124724. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124725. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124726. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124727. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124728. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124729. 11,11,11, 7, 7, 8, 8, 8, 8,
  124730. };
  124731. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124732. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124733. 3.5, 4.5,
  124734. };
  124735. static long _vq_quantmap__16c2_s_p5_1[] = {
  124736. 9, 7, 5, 3, 1, 0, 2, 4,
  124737. 6, 8, 10,
  124738. };
  124739. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124740. _vq_quantthresh__16c2_s_p5_1,
  124741. _vq_quantmap__16c2_s_p5_1,
  124742. 11,
  124743. 11
  124744. };
  124745. static static_codebook _16c2_s_p5_1 = {
  124746. 2, 121,
  124747. _vq_lengthlist__16c2_s_p5_1,
  124748. 1, -531365888, 1611661312, 4, 0,
  124749. _vq_quantlist__16c2_s_p5_1,
  124750. NULL,
  124751. &_vq_auxt__16c2_s_p5_1,
  124752. NULL,
  124753. 0
  124754. };
  124755. static long _vq_quantlist__16c2_s_p6_0[] = {
  124756. 6,
  124757. 5,
  124758. 7,
  124759. 4,
  124760. 8,
  124761. 3,
  124762. 9,
  124763. 2,
  124764. 10,
  124765. 1,
  124766. 11,
  124767. 0,
  124768. 12,
  124769. };
  124770. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124771. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124772. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124773. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124774. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124775. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124776. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. };
  124783. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124784. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124785. 12.5, 17.5, 22.5, 27.5,
  124786. };
  124787. static long _vq_quantmap__16c2_s_p6_0[] = {
  124788. 11, 9, 7, 5, 3, 1, 0, 2,
  124789. 4, 6, 8, 10, 12,
  124790. };
  124791. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124792. _vq_quantthresh__16c2_s_p6_0,
  124793. _vq_quantmap__16c2_s_p6_0,
  124794. 13,
  124795. 13
  124796. };
  124797. static static_codebook _16c2_s_p6_0 = {
  124798. 2, 169,
  124799. _vq_lengthlist__16c2_s_p6_0,
  124800. 1, -526516224, 1616117760, 4, 0,
  124801. _vq_quantlist__16c2_s_p6_0,
  124802. NULL,
  124803. &_vq_auxt__16c2_s_p6_0,
  124804. NULL,
  124805. 0
  124806. };
  124807. static long _vq_quantlist__16c2_s_p6_1[] = {
  124808. 2,
  124809. 1,
  124810. 3,
  124811. 0,
  124812. 4,
  124813. };
  124814. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124815. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124816. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124817. };
  124818. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124819. -1.5, -0.5, 0.5, 1.5,
  124820. };
  124821. static long _vq_quantmap__16c2_s_p6_1[] = {
  124822. 3, 1, 0, 2, 4,
  124823. };
  124824. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124825. _vq_quantthresh__16c2_s_p6_1,
  124826. _vq_quantmap__16c2_s_p6_1,
  124827. 5,
  124828. 5
  124829. };
  124830. static static_codebook _16c2_s_p6_1 = {
  124831. 2, 25,
  124832. _vq_lengthlist__16c2_s_p6_1,
  124833. 1, -533725184, 1611661312, 3, 0,
  124834. _vq_quantlist__16c2_s_p6_1,
  124835. NULL,
  124836. &_vq_auxt__16c2_s_p6_1,
  124837. NULL,
  124838. 0
  124839. };
  124840. static long _vq_quantlist__16c2_s_p7_0[] = {
  124841. 6,
  124842. 5,
  124843. 7,
  124844. 4,
  124845. 8,
  124846. 3,
  124847. 9,
  124848. 2,
  124849. 10,
  124850. 1,
  124851. 11,
  124852. 0,
  124853. 12,
  124854. };
  124855. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124856. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124857. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124858. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124859. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124860. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124861. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124862. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124863. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124864. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124865. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124866. 18,13,14,13,13,14,13,15,14,
  124867. };
  124868. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124869. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124870. 27.5, 38.5, 49.5, 60.5,
  124871. };
  124872. static long _vq_quantmap__16c2_s_p7_0[] = {
  124873. 11, 9, 7, 5, 3, 1, 0, 2,
  124874. 4, 6, 8, 10, 12,
  124875. };
  124876. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124877. _vq_quantthresh__16c2_s_p7_0,
  124878. _vq_quantmap__16c2_s_p7_0,
  124879. 13,
  124880. 13
  124881. };
  124882. static static_codebook _16c2_s_p7_0 = {
  124883. 2, 169,
  124884. _vq_lengthlist__16c2_s_p7_0,
  124885. 1, -523206656, 1618345984, 4, 0,
  124886. _vq_quantlist__16c2_s_p7_0,
  124887. NULL,
  124888. &_vq_auxt__16c2_s_p7_0,
  124889. NULL,
  124890. 0
  124891. };
  124892. static long _vq_quantlist__16c2_s_p7_1[] = {
  124893. 5,
  124894. 4,
  124895. 6,
  124896. 3,
  124897. 7,
  124898. 2,
  124899. 8,
  124900. 1,
  124901. 9,
  124902. 0,
  124903. 10,
  124904. };
  124905. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124906. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124907. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124908. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124909. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124910. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124911. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124912. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124913. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124914. };
  124915. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124916. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124917. 3.5, 4.5,
  124918. };
  124919. static long _vq_quantmap__16c2_s_p7_1[] = {
  124920. 9, 7, 5, 3, 1, 0, 2, 4,
  124921. 6, 8, 10,
  124922. };
  124923. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124924. _vq_quantthresh__16c2_s_p7_1,
  124925. _vq_quantmap__16c2_s_p7_1,
  124926. 11,
  124927. 11
  124928. };
  124929. static static_codebook _16c2_s_p7_1 = {
  124930. 2, 121,
  124931. _vq_lengthlist__16c2_s_p7_1,
  124932. 1, -531365888, 1611661312, 4, 0,
  124933. _vq_quantlist__16c2_s_p7_1,
  124934. NULL,
  124935. &_vq_auxt__16c2_s_p7_1,
  124936. NULL,
  124937. 0
  124938. };
  124939. static long _vq_quantlist__16c2_s_p8_0[] = {
  124940. 7,
  124941. 6,
  124942. 8,
  124943. 5,
  124944. 9,
  124945. 4,
  124946. 10,
  124947. 3,
  124948. 11,
  124949. 2,
  124950. 12,
  124951. 1,
  124952. 13,
  124953. 0,
  124954. 14,
  124955. };
  124956. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124957. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124958. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124959. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124960. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124961. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124962. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124963. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124964. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124965. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124966. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124967. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124968. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124969. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124970. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124971. 13,
  124972. };
  124973. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124974. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124975. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124976. };
  124977. static long _vq_quantmap__16c2_s_p8_0[] = {
  124978. 13, 11, 9, 7, 5, 3, 1, 0,
  124979. 2, 4, 6, 8, 10, 12, 14,
  124980. };
  124981. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124982. _vq_quantthresh__16c2_s_p8_0,
  124983. _vq_quantmap__16c2_s_p8_0,
  124984. 15,
  124985. 15
  124986. };
  124987. static static_codebook _16c2_s_p8_0 = {
  124988. 2, 225,
  124989. _vq_lengthlist__16c2_s_p8_0,
  124990. 1, -520986624, 1620377600, 4, 0,
  124991. _vq_quantlist__16c2_s_p8_0,
  124992. NULL,
  124993. &_vq_auxt__16c2_s_p8_0,
  124994. NULL,
  124995. 0
  124996. };
  124997. static long _vq_quantlist__16c2_s_p8_1[] = {
  124998. 10,
  124999. 9,
  125000. 11,
  125001. 8,
  125002. 12,
  125003. 7,
  125004. 13,
  125005. 6,
  125006. 14,
  125007. 5,
  125008. 15,
  125009. 4,
  125010. 16,
  125011. 3,
  125012. 17,
  125013. 2,
  125014. 18,
  125015. 1,
  125016. 19,
  125017. 0,
  125018. 20,
  125019. };
  125020. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125021. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125022. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125023. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125024. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125025. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125026. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125027. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125028. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125029. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125030. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125031. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125032. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125033. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125034. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125035. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125036. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125037. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125038. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125039. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125040. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125041. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125042. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125043. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125044. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125045. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125046. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125047. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125048. 10,11,10,10,10,10,10,10,10,
  125049. };
  125050. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125051. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125052. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125053. 6.5, 7.5, 8.5, 9.5,
  125054. };
  125055. static long _vq_quantmap__16c2_s_p8_1[] = {
  125056. 19, 17, 15, 13, 11, 9, 7, 5,
  125057. 3, 1, 0, 2, 4, 6, 8, 10,
  125058. 12, 14, 16, 18, 20,
  125059. };
  125060. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125061. _vq_quantthresh__16c2_s_p8_1,
  125062. _vq_quantmap__16c2_s_p8_1,
  125063. 21,
  125064. 21
  125065. };
  125066. static static_codebook _16c2_s_p8_1 = {
  125067. 2, 441,
  125068. _vq_lengthlist__16c2_s_p8_1,
  125069. 1, -529268736, 1611661312, 5, 0,
  125070. _vq_quantlist__16c2_s_p8_1,
  125071. NULL,
  125072. &_vq_auxt__16c2_s_p8_1,
  125073. NULL,
  125074. 0
  125075. };
  125076. static long _vq_quantlist__16c2_s_p9_0[] = {
  125077. 6,
  125078. 5,
  125079. 7,
  125080. 4,
  125081. 8,
  125082. 3,
  125083. 9,
  125084. 2,
  125085. 10,
  125086. 1,
  125087. 11,
  125088. 0,
  125089. 12,
  125090. };
  125091. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125092. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125093. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125094. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125095. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125096. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125097. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125098. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125099. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125100. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125101. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125102. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125103. };
  125104. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125105. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125106. 2327.5, 3258.5, 4189.5, 5120.5,
  125107. };
  125108. static long _vq_quantmap__16c2_s_p9_0[] = {
  125109. 11, 9, 7, 5, 3, 1, 0, 2,
  125110. 4, 6, 8, 10, 12,
  125111. };
  125112. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125113. _vq_quantthresh__16c2_s_p9_0,
  125114. _vq_quantmap__16c2_s_p9_0,
  125115. 13,
  125116. 13
  125117. };
  125118. static static_codebook _16c2_s_p9_0 = {
  125119. 2, 169,
  125120. _vq_lengthlist__16c2_s_p9_0,
  125121. 1, -510275072, 1631393792, 4, 0,
  125122. _vq_quantlist__16c2_s_p9_0,
  125123. NULL,
  125124. &_vq_auxt__16c2_s_p9_0,
  125125. NULL,
  125126. 0
  125127. };
  125128. static long _vq_quantlist__16c2_s_p9_1[] = {
  125129. 8,
  125130. 7,
  125131. 9,
  125132. 6,
  125133. 10,
  125134. 5,
  125135. 11,
  125136. 4,
  125137. 12,
  125138. 3,
  125139. 13,
  125140. 2,
  125141. 14,
  125142. 1,
  125143. 15,
  125144. 0,
  125145. 16,
  125146. };
  125147. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125148. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125149. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125150. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125151. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125152. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125153. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125154. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125155. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125156. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125157. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125159. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125162. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125163. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125164. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125166. 10,
  125167. };
  125168. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125169. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125170. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125171. };
  125172. static long _vq_quantmap__16c2_s_p9_1[] = {
  125173. 15, 13, 11, 9, 7, 5, 3, 1,
  125174. 0, 2, 4, 6, 8, 10, 12, 14,
  125175. 16,
  125176. };
  125177. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125178. _vq_quantthresh__16c2_s_p9_1,
  125179. _vq_quantmap__16c2_s_p9_1,
  125180. 17,
  125181. 17
  125182. };
  125183. static static_codebook _16c2_s_p9_1 = {
  125184. 2, 289,
  125185. _vq_lengthlist__16c2_s_p9_1,
  125186. 1, -518488064, 1622704128, 5, 0,
  125187. _vq_quantlist__16c2_s_p9_1,
  125188. NULL,
  125189. &_vq_auxt__16c2_s_p9_1,
  125190. NULL,
  125191. 0
  125192. };
  125193. static long _vq_quantlist__16c2_s_p9_2[] = {
  125194. 13,
  125195. 12,
  125196. 14,
  125197. 11,
  125198. 15,
  125199. 10,
  125200. 16,
  125201. 9,
  125202. 17,
  125203. 8,
  125204. 18,
  125205. 7,
  125206. 19,
  125207. 6,
  125208. 20,
  125209. 5,
  125210. 21,
  125211. 4,
  125212. 22,
  125213. 3,
  125214. 23,
  125215. 2,
  125216. 24,
  125217. 1,
  125218. 25,
  125219. 0,
  125220. 26,
  125221. };
  125222. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125223. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125224. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125225. };
  125226. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125227. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125228. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125229. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125230. 11.5, 12.5,
  125231. };
  125232. static long _vq_quantmap__16c2_s_p9_2[] = {
  125233. 25, 23, 21, 19, 17, 15, 13, 11,
  125234. 9, 7, 5, 3, 1, 0, 2, 4,
  125235. 6, 8, 10, 12, 14, 16, 18, 20,
  125236. 22, 24, 26,
  125237. };
  125238. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125239. _vq_quantthresh__16c2_s_p9_2,
  125240. _vq_quantmap__16c2_s_p9_2,
  125241. 27,
  125242. 27
  125243. };
  125244. static static_codebook _16c2_s_p9_2 = {
  125245. 1, 27,
  125246. _vq_lengthlist__16c2_s_p9_2,
  125247. 1, -528875520, 1611661312, 5, 0,
  125248. _vq_quantlist__16c2_s_p9_2,
  125249. NULL,
  125250. &_vq_auxt__16c2_s_p9_2,
  125251. NULL,
  125252. 0
  125253. };
  125254. static long _huff_lengthlist__16c2_s_short[] = {
  125255. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125256. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125257. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125258. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125259. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125260. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125261. 15,12,14,14,
  125262. };
  125263. static static_codebook _huff_book__16c2_s_short = {
  125264. 2, 100,
  125265. _huff_lengthlist__16c2_s_short,
  125266. 0, 0, 0, 0, 0,
  125267. NULL,
  125268. NULL,
  125269. NULL,
  125270. NULL,
  125271. 0
  125272. };
  125273. static long _vq_quantlist__8c0_s_p1_0[] = {
  125274. 1,
  125275. 0,
  125276. 2,
  125277. };
  125278. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125279. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125280. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125285. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125290. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125325. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125330. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125335. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125371. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125376. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125381. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0,
  125690. };
  125691. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125692. -0.5, 0.5,
  125693. };
  125694. static long _vq_quantmap__8c0_s_p1_0[] = {
  125695. 1, 0, 2,
  125696. };
  125697. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125698. _vq_quantthresh__8c0_s_p1_0,
  125699. _vq_quantmap__8c0_s_p1_0,
  125700. 3,
  125701. 3
  125702. };
  125703. static static_codebook _8c0_s_p1_0 = {
  125704. 8, 6561,
  125705. _vq_lengthlist__8c0_s_p1_0,
  125706. 1, -535822336, 1611661312, 2, 0,
  125707. _vq_quantlist__8c0_s_p1_0,
  125708. NULL,
  125709. &_vq_auxt__8c0_s_p1_0,
  125710. NULL,
  125711. 0
  125712. };
  125713. static long _vq_quantlist__8c0_s_p2_0[] = {
  125714. 2,
  125715. 1,
  125716. 3,
  125717. 0,
  125718. 4,
  125719. };
  125720. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0,
  125761. };
  125762. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125763. -1.5, -0.5, 0.5, 1.5,
  125764. };
  125765. static long _vq_quantmap__8c0_s_p2_0[] = {
  125766. 3, 1, 0, 2, 4,
  125767. };
  125768. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125769. _vq_quantthresh__8c0_s_p2_0,
  125770. _vq_quantmap__8c0_s_p2_0,
  125771. 5,
  125772. 5
  125773. };
  125774. static static_codebook _8c0_s_p2_0 = {
  125775. 4, 625,
  125776. _vq_lengthlist__8c0_s_p2_0,
  125777. 1, -533725184, 1611661312, 3, 0,
  125778. _vq_quantlist__8c0_s_p2_0,
  125779. NULL,
  125780. &_vq_auxt__8c0_s_p2_0,
  125781. NULL,
  125782. 0
  125783. };
  125784. static long _vq_quantlist__8c0_s_p3_0[] = {
  125785. 2,
  125786. 1,
  125787. 3,
  125788. 0,
  125789. 4,
  125790. };
  125791. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125792. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0,
  125832. };
  125833. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125834. -1.5, -0.5, 0.5, 1.5,
  125835. };
  125836. static long _vq_quantmap__8c0_s_p3_0[] = {
  125837. 3, 1, 0, 2, 4,
  125838. };
  125839. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125840. _vq_quantthresh__8c0_s_p3_0,
  125841. _vq_quantmap__8c0_s_p3_0,
  125842. 5,
  125843. 5
  125844. };
  125845. static static_codebook _8c0_s_p3_0 = {
  125846. 4, 625,
  125847. _vq_lengthlist__8c0_s_p3_0,
  125848. 1, -533725184, 1611661312, 3, 0,
  125849. _vq_quantlist__8c0_s_p3_0,
  125850. NULL,
  125851. &_vq_auxt__8c0_s_p3_0,
  125852. NULL,
  125853. 0
  125854. };
  125855. static long _vq_quantlist__8c0_s_p4_0[] = {
  125856. 4,
  125857. 3,
  125858. 5,
  125859. 2,
  125860. 6,
  125861. 1,
  125862. 7,
  125863. 0,
  125864. 8,
  125865. };
  125866. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125867. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125868. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125869. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125870. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125871. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0,
  125873. };
  125874. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125875. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125876. };
  125877. static long _vq_quantmap__8c0_s_p4_0[] = {
  125878. 7, 5, 3, 1, 0, 2, 4, 6,
  125879. 8,
  125880. };
  125881. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125882. _vq_quantthresh__8c0_s_p4_0,
  125883. _vq_quantmap__8c0_s_p4_0,
  125884. 9,
  125885. 9
  125886. };
  125887. static static_codebook _8c0_s_p4_0 = {
  125888. 2, 81,
  125889. _vq_lengthlist__8c0_s_p4_0,
  125890. 1, -531628032, 1611661312, 4, 0,
  125891. _vq_quantlist__8c0_s_p4_0,
  125892. NULL,
  125893. &_vq_auxt__8c0_s_p4_0,
  125894. NULL,
  125895. 0
  125896. };
  125897. static long _vq_quantlist__8c0_s_p5_0[] = {
  125898. 4,
  125899. 3,
  125900. 5,
  125901. 2,
  125902. 6,
  125903. 1,
  125904. 7,
  125905. 0,
  125906. 8,
  125907. };
  125908. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125909. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125910. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125911. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125912. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125913. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125914. 10,
  125915. };
  125916. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125917. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125918. };
  125919. static long _vq_quantmap__8c0_s_p5_0[] = {
  125920. 7, 5, 3, 1, 0, 2, 4, 6,
  125921. 8,
  125922. };
  125923. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125924. _vq_quantthresh__8c0_s_p5_0,
  125925. _vq_quantmap__8c0_s_p5_0,
  125926. 9,
  125927. 9
  125928. };
  125929. static static_codebook _8c0_s_p5_0 = {
  125930. 2, 81,
  125931. _vq_lengthlist__8c0_s_p5_0,
  125932. 1, -531628032, 1611661312, 4, 0,
  125933. _vq_quantlist__8c0_s_p5_0,
  125934. NULL,
  125935. &_vq_auxt__8c0_s_p5_0,
  125936. NULL,
  125937. 0
  125938. };
  125939. static long _vq_quantlist__8c0_s_p6_0[] = {
  125940. 8,
  125941. 7,
  125942. 9,
  125943. 6,
  125944. 10,
  125945. 5,
  125946. 11,
  125947. 4,
  125948. 12,
  125949. 3,
  125950. 13,
  125951. 2,
  125952. 14,
  125953. 1,
  125954. 15,
  125955. 0,
  125956. 16,
  125957. };
  125958. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125959. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125960. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125961. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125962. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125963. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125964. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125965. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125966. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125967. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125968. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125969. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125970. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125971. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125972. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125973. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125974. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125975. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125977. 14,
  125978. };
  125979. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125980. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125981. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125982. };
  125983. static long _vq_quantmap__8c0_s_p6_0[] = {
  125984. 15, 13, 11, 9, 7, 5, 3, 1,
  125985. 0, 2, 4, 6, 8, 10, 12, 14,
  125986. 16,
  125987. };
  125988. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125989. _vq_quantthresh__8c0_s_p6_0,
  125990. _vq_quantmap__8c0_s_p6_0,
  125991. 17,
  125992. 17
  125993. };
  125994. static static_codebook _8c0_s_p6_0 = {
  125995. 2, 289,
  125996. _vq_lengthlist__8c0_s_p6_0,
  125997. 1, -529530880, 1611661312, 5, 0,
  125998. _vq_quantlist__8c0_s_p6_0,
  125999. NULL,
  126000. &_vq_auxt__8c0_s_p6_0,
  126001. NULL,
  126002. 0
  126003. };
  126004. static long _vq_quantlist__8c0_s_p7_0[] = {
  126005. 1,
  126006. 0,
  126007. 2,
  126008. };
  126009. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126010. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126011. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126012. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126013. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126014. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126015. 10,
  126016. };
  126017. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126018. -5.5, 5.5,
  126019. };
  126020. static long _vq_quantmap__8c0_s_p7_0[] = {
  126021. 1, 0, 2,
  126022. };
  126023. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126024. _vq_quantthresh__8c0_s_p7_0,
  126025. _vq_quantmap__8c0_s_p7_0,
  126026. 3,
  126027. 3
  126028. };
  126029. static static_codebook _8c0_s_p7_0 = {
  126030. 4, 81,
  126031. _vq_lengthlist__8c0_s_p7_0,
  126032. 1, -529137664, 1618345984, 2, 0,
  126033. _vq_quantlist__8c0_s_p7_0,
  126034. NULL,
  126035. &_vq_auxt__8c0_s_p7_0,
  126036. NULL,
  126037. 0
  126038. };
  126039. static long _vq_quantlist__8c0_s_p7_1[] = {
  126040. 5,
  126041. 4,
  126042. 6,
  126043. 3,
  126044. 7,
  126045. 2,
  126046. 8,
  126047. 1,
  126048. 9,
  126049. 0,
  126050. 10,
  126051. };
  126052. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126053. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126054. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126055. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126056. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126057. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126058. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126059. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126060. 10,10,10, 9, 9, 9,10,10,10,
  126061. };
  126062. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126063. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126064. 3.5, 4.5,
  126065. };
  126066. static long _vq_quantmap__8c0_s_p7_1[] = {
  126067. 9, 7, 5, 3, 1, 0, 2, 4,
  126068. 6, 8, 10,
  126069. };
  126070. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126071. _vq_quantthresh__8c0_s_p7_1,
  126072. _vq_quantmap__8c0_s_p7_1,
  126073. 11,
  126074. 11
  126075. };
  126076. static static_codebook _8c0_s_p7_1 = {
  126077. 2, 121,
  126078. _vq_lengthlist__8c0_s_p7_1,
  126079. 1, -531365888, 1611661312, 4, 0,
  126080. _vq_quantlist__8c0_s_p7_1,
  126081. NULL,
  126082. &_vq_auxt__8c0_s_p7_1,
  126083. NULL,
  126084. 0
  126085. };
  126086. static long _vq_quantlist__8c0_s_p8_0[] = {
  126087. 6,
  126088. 5,
  126089. 7,
  126090. 4,
  126091. 8,
  126092. 3,
  126093. 9,
  126094. 2,
  126095. 10,
  126096. 1,
  126097. 11,
  126098. 0,
  126099. 12,
  126100. };
  126101. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126102. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126103. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126104. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126105. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126106. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126107. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126108. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126109. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126110. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126111. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126112. 0, 0,13,13,11,13,13,11,12,
  126113. };
  126114. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126115. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126116. 12.5, 17.5, 22.5, 27.5,
  126117. };
  126118. static long _vq_quantmap__8c0_s_p8_0[] = {
  126119. 11, 9, 7, 5, 3, 1, 0, 2,
  126120. 4, 6, 8, 10, 12,
  126121. };
  126122. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126123. _vq_quantthresh__8c0_s_p8_0,
  126124. _vq_quantmap__8c0_s_p8_0,
  126125. 13,
  126126. 13
  126127. };
  126128. static static_codebook _8c0_s_p8_0 = {
  126129. 2, 169,
  126130. _vq_lengthlist__8c0_s_p8_0,
  126131. 1, -526516224, 1616117760, 4, 0,
  126132. _vq_quantlist__8c0_s_p8_0,
  126133. NULL,
  126134. &_vq_auxt__8c0_s_p8_0,
  126135. NULL,
  126136. 0
  126137. };
  126138. static long _vq_quantlist__8c0_s_p8_1[] = {
  126139. 2,
  126140. 1,
  126141. 3,
  126142. 0,
  126143. 4,
  126144. };
  126145. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126146. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126147. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126148. };
  126149. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126150. -1.5, -0.5, 0.5, 1.5,
  126151. };
  126152. static long _vq_quantmap__8c0_s_p8_1[] = {
  126153. 3, 1, 0, 2, 4,
  126154. };
  126155. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126156. _vq_quantthresh__8c0_s_p8_1,
  126157. _vq_quantmap__8c0_s_p8_1,
  126158. 5,
  126159. 5
  126160. };
  126161. static static_codebook _8c0_s_p8_1 = {
  126162. 2, 25,
  126163. _vq_lengthlist__8c0_s_p8_1,
  126164. 1, -533725184, 1611661312, 3, 0,
  126165. _vq_quantlist__8c0_s_p8_1,
  126166. NULL,
  126167. &_vq_auxt__8c0_s_p8_1,
  126168. NULL,
  126169. 0
  126170. };
  126171. static long _vq_quantlist__8c0_s_p9_0[] = {
  126172. 1,
  126173. 0,
  126174. 2,
  126175. };
  126176. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126177. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126178. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126179. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126180. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126181. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126182. 7,
  126183. };
  126184. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126185. -157.5, 157.5,
  126186. };
  126187. static long _vq_quantmap__8c0_s_p9_0[] = {
  126188. 1, 0, 2,
  126189. };
  126190. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126191. _vq_quantthresh__8c0_s_p9_0,
  126192. _vq_quantmap__8c0_s_p9_0,
  126193. 3,
  126194. 3
  126195. };
  126196. static static_codebook _8c0_s_p9_0 = {
  126197. 4, 81,
  126198. _vq_lengthlist__8c0_s_p9_0,
  126199. 1, -518803456, 1628680192, 2, 0,
  126200. _vq_quantlist__8c0_s_p9_0,
  126201. NULL,
  126202. &_vq_auxt__8c0_s_p9_0,
  126203. NULL,
  126204. 0
  126205. };
  126206. static long _vq_quantlist__8c0_s_p9_1[] = {
  126207. 7,
  126208. 6,
  126209. 8,
  126210. 5,
  126211. 9,
  126212. 4,
  126213. 10,
  126214. 3,
  126215. 11,
  126216. 2,
  126217. 12,
  126218. 1,
  126219. 13,
  126220. 0,
  126221. 14,
  126222. };
  126223. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126224. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126225. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126226. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126227. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126228. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126229. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126238. 11,
  126239. };
  126240. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126241. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126242. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126243. };
  126244. static long _vq_quantmap__8c0_s_p9_1[] = {
  126245. 13, 11, 9, 7, 5, 3, 1, 0,
  126246. 2, 4, 6, 8, 10, 12, 14,
  126247. };
  126248. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126249. _vq_quantthresh__8c0_s_p9_1,
  126250. _vq_quantmap__8c0_s_p9_1,
  126251. 15,
  126252. 15
  126253. };
  126254. static static_codebook _8c0_s_p9_1 = {
  126255. 2, 225,
  126256. _vq_lengthlist__8c0_s_p9_1,
  126257. 1, -520986624, 1620377600, 4, 0,
  126258. _vq_quantlist__8c0_s_p9_1,
  126259. NULL,
  126260. &_vq_auxt__8c0_s_p9_1,
  126261. NULL,
  126262. 0
  126263. };
  126264. static long _vq_quantlist__8c0_s_p9_2[] = {
  126265. 10,
  126266. 9,
  126267. 11,
  126268. 8,
  126269. 12,
  126270. 7,
  126271. 13,
  126272. 6,
  126273. 14,
  126274. 5,
  126275. 15,
  126276. 4,
  126277. 16,
  126278. 3,
  126279. 17,
  126280. 2,
  126281. 18,
  126282. 1,
  126283. 19,
  126284. 0,
  126285. 20,
  126286. };
  126287. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126288. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126289. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126290. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126291. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126292. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126293. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126294. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126295. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126296. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126297. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126298. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126299. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126300. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126301. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126302. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126303. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126304. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126305. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126306. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126307. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126308. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126309. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126310. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126311. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126312. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126313. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126314. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126315. 10,11, 9,11,10, 9,10, 9,10,
  126316. };
  126317. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126318. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126319. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126320. 6.5, 7.5, 8.5, 9.5,
  126321. };
  126322. static long _vq_quantmap__8c0_s_p9_2[] = {
  126323. 19, 17, 15, 13, 11, 9, 7, 5,
  126324. 3, 1, 0, 2, 4, 6, 8, 10,
  126325. 12, 14, 16, 18, 20,
  126326. };
  126327. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126328. _vq_quantthresh__8c0_s_p9_2,
  126329. _vq_quantmap__8c0_s_p9_2,
  126330. 21,
  126331. 21
  126332. };
  126333. static static_codebook _8c0_s_p9_2 = {
  126334. 2, 441,
  126335. _vq_lengthlist__8c0_s_p9_2,
  126336. 1, -529268736, 1611661312, 5, 0,
  126337. _vq_quantlist__8c0_s_p9_2,
  126338. NULL,
  126339. &_vq_auxt__8c0_s_p9_2,
  126340. NULL,
  126341. 0
  126342. };
  126343. static long _huff_lengthlist__8c0_s_single[] = {
  126344. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126345. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126346. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126347. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126348. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126349. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126350. 17,16,17,17,
  126351. };
  126352. static static_codebook _huff_book__8c0_s_single = {
  126353. 2, 100,
  126354. _huff_lengthlist__8c0_s_single,
  126355. 0, 0, 0, 0, 0,
  126356. NULL,
  126357. NULL,
  126358. NULL,
  126359. NULL,
  126360. 0
  126361. };
  126362. static long _vq_quantlist__8c1_s_p1_0[] = {
  126363. 1,
  126364. 0,
  126365. 2,
  126366. };
  126367. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126368. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126369. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126374. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126379. 0, 0, 0, 0, 7, 9, 8, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126414. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126419. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126424. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126460. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126465. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126470. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0,
  126779. };
  126780. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126781. -0.5, 0.5,
  126782. };
  126783. static long _vq_quantmap__8c1_s_p1_0[] = {
  126784. 1, 0, 2,
  126785. };
  126786. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126787. _vq_quantthresh__8c1_s_p1_0,
  126788. _vq_quantmap__8c1_s_p1_0,
  126789. 3,
  126790. 3
  126791. };
  126792. static static_codebook _8c1_s_p1_0 = {
  126793. 8, 6561,
  126794. _vq_lengthlist__8c1_s_p1_0,
  126795. 1, -535822336, 1611661312, 2, 0,
  126796. _vq_quantlist__8c1_s_p1_0,
  126797. NULL,
  126798. &_vq_auxt__8c1_s_p1_0,
  126799. NULL,
  126800. 0
  126801. };
  126802. static long _vq_quantlist__8c1_s_p2_0[] = {
  126803. 2,
  126804. 1,
  126805. 3,
  126806. 0,
  126807. 4,
  126808. };
  126809. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0,
  126850. };
  126851. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126852. -1.5, -0.5, 0.5, 1.5,
  126853. };
  126854. static long _vq_quantmap__8c1_s_p2_0[] = {
  126855. 3, 1, 0, 2, 4,
  126856. };
  126857. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126858. _vq_quantthresh__8c1_s_p2_0,
  126859. _vq_quantmap__8c1_s_p2_0,
  126860. 5,
  126861. 5
  126862. };
  126863. static static_codebook _8c1_s_p2_0 = {
  126864. 4, 625,
  126865. _vq_lengthlist__8c1_s_p2_0,
  126866. 1, -533725184, 1611661312, 3, 0,
  126867. _vq_quantlist__8c1_s_p2_0,
  126868. NULL,
  126869. &_vq_auxt__8c1_s_p2_0,
  126870. NULL,
  126871. 0
  126872. };
  126873. static long _vq_quantlist__8c1_s_p3_0[] = {
  126874. 2,
  126875. 1,
  126876. 3,
  126877. 0,
  126878. 4,
  126879. };
  126880. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126881. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0,
  126921. };
  126922. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126923. -1.5, -0.5, 0.5, 1.5,
  126924. };
  126925. static long _vq_quantmap__8c1_s_p3_0[] = {
  126926. 3, 1, 0, 2, 4,
  126927. };
  126928. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126929. _vq_quantthresh__8c1_s_p3_0,
  126930. _vq_quantmap__8c1_s_p3_0,
  126931. 5,
  126932. 5
  126933. };
  126934. static static_codebook _8c1_s_p3_0 = {
  126935. 4, 625,
  126936. _vq_lengthlist__8c1_s_p3_0,
  126937. 1, -533725184, 1611661312, 3, 0,
  126938. _vq_quantlist__8c1_s_p3_0,
  126939. NULL,
  126940. &_vq_auxt__8c1_s_p3_0,
  126941. NULL,
  126942. 0
  126943. };
  126944. static long _vq_quantlist__8c1_s_p4_0[] = {
  126945. 4,
  126946. 3,
  126947. 5,
  126948. 2,
  126949. 6,
  126950. 1,
  126951. 7,
  126952. 0,
  126953. 8,
  126954. };
  126955. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126956. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126957. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126958. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126959. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126960. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0,
  126962. };
  126963. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126964. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126965. };
  126966. static long _vq_quantmap__8c1_s_p4_0[] = {
  126967. 7, 5, 3, 1, 0, 2, 4, 6,
  126968. 8,
  126969. };
  126970. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126971. _vq_quantthresh__8c1_s_p4_0,
  126972. _vq_quantmap__8c1_s_p4_0,
  126973. 9,
  126974. 9
  126975. };
  126976. static static_codebook _8c1_s_p4_0 = {
  126977. 2, 81,
  126978. _vq_lengthlist__8c1_s_p4_0,
  126979. 1, -531628032, 1611661312, 4, 0,
  126980. _vq_quantlist__8c1_s_p4_0,
  126981. NULL,
  126982. &_vq_auxt__8c1_s_p4_0,
  126983. NULL,
  126984. 0
  126985. };
  126986. static long _vq_quantlist__8c1_s_p5_0[] = {
  126987. 4,
  126988. 3,
  126989. 5,
  126990. 2,
  126991. 6,
  126992. 1,
  126993. 7,
  126994. 0,
  126995. 8,
  126996. };
  126997. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126998. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126999. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127000. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127001. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127002. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127003. 10,
  127004. };
  127005. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127006. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127007. };
  127008. static long _vq_quantmap__8c1_s_p5_0[] = {
  127009. 7, 5, 3, 1, 0, 2, 4, 6,
  127010. 8,
  127011. };
  127012. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127013. _vq_quantthresh__8c1_s_p5_0,
  127014. _vq_quantmap__8c1_s_p5_0,
  127015. 9,
  127016. 9
  127017. };
  127018. static static_codebook _8c1_s_p5_0 = {
  127019. 2, 81,
  127020. _vq_lengthlist__8c1_s_p5_0,
  127021. 1, -531628032, 1611661312, 4, 0,
  127022. _vq_quantlist__8c1_s_p5_0,
  127023. NULL,
  127024. &_vq_auxt__8c1_s_p5_0,
  127025. NULL,
  127026. 0
  127027. };
  127028. static long _vq_quantlist__8c1_s_p6_0[] = {
  127029. 8,
  127030. 7,
  127031. 9,
  127032. 6,
  127033. 10,
  127034. 5,
  127035. 11,
  127036. 4,
  127037. 12,
  127038. 3,
  127039. 13,
  127040. 2,
  127041. 14,
  127042. 1,
  127043. 15,
  127044. 0,
  127045. 16,
  127046. };
  127047. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127048. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127049. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127050. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127051. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127052. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127053. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127054. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127055. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127056. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127057. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127058. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127059. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127060. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127061. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127062. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127063. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127064. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127066. 14,
  127067. };
  127068. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127069. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127070. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127071. };
  127072. static long _vq_quantmap__8c1_s_p6_0[] = {
  127073. 15, 13, 11, 9, 7, 5, 3, 1,
  127074. 0, 2, 4, 6, 8, 10, 12, 14,
  127075. 16,
  127076. };
  127077. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127078. _vq_quantthresh__8c1_s_p6_0,
  127079. _vq_quantmap__8c1_s_p6_0,
  127080. 17,
  127081. 17
  127082. };
  127083. static static_codebook _8c1_s_p6_0 = {
  127084. 2, 289,
  127085. _vq_lengthlist__8c1_s_p6_0,
  127086. 1, -529530880, 1611661312, 5, 0,
  127087. _vq_quantlist__8c1_s_p6_0,
  127088. NULL,
  127089. &_vq_auxt__8c1_s_p6_0,
  127090. NULL,
  127091. 0
  127092. };
  127093. static long _vq_quantlist__8c1_s_p7_0[] = {
  127094. 1,
  127095. 0,
  127096. 2,
  127097. };
  127098. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127099. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127100. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127101. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127102. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127103. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127104. 9,
  127105. };
  127106. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127107. -5.5, 5.5,
  127108. };
  127109. static long _vq_quantmap__8c1_s_p7_0[] = {
  127110. 1, 0, 2,
  127111. };
  127112. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127113. _vq_quantthresh__8c1_s_p7_0,
  127114. _vq_quantmap__8c1_s_p7_0,
  127115. 3,
  127116. 3
  127117. };
  127118. static static_codebook _8c1_s_p7_0 = {
  127119. 4, 81,
  127120. _vq_lengthlist__8c1_s_p7_0,
  127121. 1, -529137664, 1618345984, 2, 0,
  127122. _vq_quantlist__8c1_s_p7_0,
  127123. NULL,
  127124. &_vq_auxt__8c1_s_p7_0,
  127125. NULL,
  127126. 0
  127127. };
  127128. static long _vq_quantlist__8c1_s_p7_1[] = {
  127129. 5,
  127130. 4,
  127131. 6,
  127132. 3,
  127133. 7,
  127134. 2,
  127135. 8,
  127136. 1,
  127137. 9,
  127138. 0,
  127139. 10,
  127140. };
  127141. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127142. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127143. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127144. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127145. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127146. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127147. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127148. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127149. 10,10,10, 8, 8, 8, 8, 8, 8,
  127150. };
  127151. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127152. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127153. 3.5, 4.5,
  127154. };
  127155. static long _vq_quantmap__8c1_s_p7_1[] = {
  127156. 9, 7, 5, 3, 1, 0, 2, 4,
  127157. 6, 8, 10,
  127158. };
  127159. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127160. _vq_quantthresh__8c1_s_p7_1,
  127161. _vq_quantmap__8c1_s_p7_1,
  127162. 11,
  127163. 11
  127164. };
  127165. static static_codebook _8c1_s_p7_1 = {
  127166. 2, 121,
  127167. _vq_lengthlist__8c1_s_p7_1,
  127168. 1, -531365888, 1611661312, 4, 0,
  127169. _vq_quantlist__8c1_s_p7_1,
  127170. NULL,
  127171. &_vq_auxt__8c1_s_p7_1,
  127172. NULL,
  127173. 0
  127174. };
  127175. static long _vq_quantlist__8c1_s_p8_0[] = {
  127176. 6,
  127177. 5,
  127178. 7,
  127179. 4,
  127180. 8,
  127181. 3,
  127182. 9,
  127183. 2,
  127184. 10,
  127185. 1,
  127186. 11,
  127187. 0,
  127188. 12,
  127189. };
  127190. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127191. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127192. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127193. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127194. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127195. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127196. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127197. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127198. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127199. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127200. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127201. 0,12,12,11,10,12,11,13,12,
  127202. };
  127203. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127204. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127205. 12.5, 17.5, 22.5, 27.5,
  127206. };
  127207. static long _vq_quantmap__8c1_s_p8_0[] = {
  127208. 11, 9, 7, 5, 3, 1, 0, 2,
  127209. 4, 6, 8, 10, 12,
  127210. };
  127211. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127212. _vq_quantthresh__8c1_s_p8_0,
  127213. _vq_quantmap__8c1_s_p8_0,
  127214. 13,
  127215. 13
  127216. };
  127217. static static_codebook _8c1_s_p8_0 = {
  127218. 2, 169,
  127219. _vq_lengthlist__8c1_s_p8_0,
  127220. 1, -526516224, 1616117760, 4, 0,
  127221. _vq_quantlist__8c1_s_p8_0,
  127222. NULL,
  127223. &_vq_auxt__8c1_s_p8_0,
  127224. NULL,
  127225. 0
  127226. };
  127227. static long _vq_quantlist__8c1_s_p8_1[] = {
  127228. 2,
  127229. 1,
  127230. 3,
  127231. 0,
  127232. 4,
  127233. };
  127234. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127235. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127236. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127237. };
  127238. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127239. -1.5, -0.5, 0.5, 1.5,
  127240. };
  127241. static long _vq_quantmap__8c1_s_p8_1[] = {
  127242. 3, 1, 0, 2, 4,
  127243. };
  127244. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127245. _vq_quantthresh__8c1_s_p8_1,
  127246. _vq_quantmap__8c1_s_p8_1,
  127247. 5,
  127248. 5
  127249. };
  127250. static static_codebook _8c1_s_p8_1 = {
  127251. 2, 25,
  127252. _vq_lengthlist__8c1_s_p8_1,
  127253. 1, -533725184, 1611661312, 3, 0,
  127254. _vq_quantlist__8c1_s_p8_1,
  127255. NULL,
  127256. &_vq_auxt__8c1_s_p8_1,
  127257. NULL,
  127258. 0
  127259. };
  127260. static long _vq_quantlist__8c1_s_p9_0[] = {
  127261. 6,
  127262. 5,
  127263. 7,
  127264. 4,
  127265. 8,
  127266. 3,
  127267. 9,
  127268. 2,
  127269. 10,
  127270. 1,
  127271. 11,
  127272. 0,
  127273. 12,
  127274. };
  127275. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127276. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127277. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127281. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127283. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127286. 10,10,10,10,10, 9, 9, 9, 9,
  127287. };
  127288. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127289. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127290. 787.5, 1102.5, 1417.5, 1732.5,
  127291. };
  127292. static long _vq_quantmap__8c1_s_p9_0[] = {
  127293. 11, 9, 7, 5, 3, 1, 0, 2,
  127294. 4, 6, 8, 10, 12,
  127295. };
  127296. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127297. _vq_quantthresh__8c1_s_p9_0,
  127298. _vq_quantmap__8c1_s_p9_0,
  127299. 13,
  127300. 13
  127301. };
  127302. static static_codebook _8c1_s_p9_0 = {
  127303. 2, 169,
  127304. _vq_lengthlist__8c1_s_p9_0,
  127305. 1, -513964032, 1628680192, 4, 0,
  127306. _vq_quantlist__8c1_s_p9_0,
  127307. NULL,
  127308. &_vq_auxt__8c1_s_p9_0,
  127309. NULL,
  127310. 0
  127311. };
  127312. static long _vq_quantlist__8c1_s_p9_1[] = {
  127313. 7,
  127314. 6,
  127315. 8,
  127316. 5,
  127317. 9,
  127318. 4,
  127319. 10,
  127320. 3,
  127321. 11,
  127322. 2,
  127323. 12,
  127324. 1,
  127325. 13,
  127326. 0,
  127327. 14,
  127328. };
  127329. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127330. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127331. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127332. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127333. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127334. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127335. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127336. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127337. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127338. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127339. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127340. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127341. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127342. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127343. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127344. 15,
  127345. };
  127346. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127347. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127348. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127349. };
  127350. static long _vq_quantmap__8c1_s_p9_1[] = {
  127351. 13, 11, 9, 7, 5, 3, 1, 0,
  127352. 2, 4, 6, 8, 10, 12, 14,
  127353. };
  127354. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127355. _vq_quantthresh__8c1_s_p9_1,
  127356. _vq_quantmap__8c1_s_p9_1,
  127357. 15,
  127358. 15
  127359. };
  127360. static static_codebook _8c1_s_p9_1 = {
  127361. 2, 225,
  127362. _vq_lengthlist__8c1_s_p9_1,
  127363. 1, -520986624, 1620377600, 4, 0,
  127364. _vq_quantlist__8c1_s_p9_1,
  127365. NULL,
  127366. &_vq_auxt__8c1_s_p9_1,
  127367. NULL,
  127368. 0
  127369. };
  127370. static long _vq_quantlist__8c1_s_p9_2[] = {
  127371. 10,
  127372. 9,
  127373. 11,
  127374. 8,
  127375. 12,
  127376. 7,
  127377. 13,
  127378. 6,
  127379. 14,
  127380. 5,
  127381. 15,
  127382. 4,
  127383. 16,
  127384. 3,
  127385. 17,
  127386. 2,
  127387. 18,
  127388. 1,
  127389. 19,
  127390. 0,
  127391. 20,
  127392. };
  127393. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127394. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127395. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127396. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127397. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127398. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127399. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127400. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127401. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127402. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127403. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127404. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127405. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127406. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127407. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127408. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127409. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127410. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127411. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127412. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127413. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127414. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127415. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127416. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127417. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127418. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127419. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127420. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127421. 10,10,10,10,10,10,10,10,10,
  127422. };
  127423. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127424. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127425. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127426. 6.5, 7.5, 8.5, 9.5,
  127427. };
  127428. static long _vq_quantmap__8c1_s_p9_2[] = {
  127429. 19, 17, 15, 13, 11, 9, 7, 5,
  127430. 3, 1, 0, 2, 4, 6, 8, 10,
  127431. 12, 14, 16, 18, 20,
  127432. };
  127433. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127434. _vq_quantthresh__8c1_s_p9_2,
  127435. _vq_quantmap__8c1_s_p9_2,
  127436. 21,
  127437. 21
  127438. };
  127439. static static_codebook _8c1_s_p9_2 = {
  127440. 2, 441,
  127441. _vq_lengthlist__8c1_s_p9_2,
  127442. 1, -529268736, 1611661312, 5, 0,
  127443. _vq_quantlist__8c1_s_p9_2,
  127444. NULL,
  127445. &_vq_auxt__8c1_s_p9_2,
  127446. NULL,
  127447. 0
  127448. };
  127449. static long _huff_lengthlist__8c1_s_single[] = {
  127450. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127451. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127452. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127453. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127454. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127455. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127456. 9, 7, 7, 8,
  127457. };
  127458. static static_codebook _huff_book__8c1_s_single = {
  127459. 2, 100,
  127460. _huff_lengthlist__8c1_s_single,
  127461. 0, 0, 0, 0, 0,
  127462. NULL,
  127463. NULL,
  127464. NULL,
  127465. NULL,
  127466. 0
  127467. };
  127468. static long _huff_lengthlist__44c2_s_long[] = {
  127469. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127470. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127471. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127472. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127473. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127474. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127475. 10, 8, 8, 9,
  127476. };
  127477. static static_codebook _huff_book__44c2_s_long = {
  127478. 2, 100,
  127479. _huff_lengthlist__44c2_s_long,
  127480. 0, 0, 0, 0, 0,
  127481. NULL,
  127482. NULL,
  127483. NULL,
  127484. NULL,
  127485. 0
  127486. };
  127487. static long _vq_quantlist__44c2_s_p1_0[] = {
  127488. 1,
  127489. 0,
  127490. 2,
  127491. };
  127492. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127493. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127494. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127499. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127504. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127539. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127544. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127549. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127585. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127590. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127595. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0,
  127904. };
  127905. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127906. -0.5, 0.5,
  127907. };
  127908. static long _vq_quantmap__44c2_s_p1_0[] = {
  127909. 1, 0, 2,
  127910. };
  127911. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127912. _vq_quantthresh__44c2_s_p1_0,
  127913. _vq_quantmap__44c2_s_p1_0,
  127914. 3,
  127915. 3
  127916. };
  127917. static static_codebook _44c2_s_p1_0 = {
  127918. 8, 6561,
  127919. _vq_lengthlist__44c2_s_p1_0,
  127920. 1, -535822336, 1611661312, 2, 0,
  127921. _vq_quantlist__44c2_s_p1_0,
  127922. NULL,
  127923. &_vq_auxt__44c2_s_p1_0,
  127924. NULL,
  127925. 0
  127926. };
  127927. static long _vq_quantlist__44c2_s_p2_0[] = {
  127928. 2,
  127929. 1,
  127930. 3,
  127931. 0,
  127932. 4,
  127933. };
  127934. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127935. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127936. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127937. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127938. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127939. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127945. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127946. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127947. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127953. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127954. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127961. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127962. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0,
  127975. };
  127976. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127977. -1.5, -0.5, 0.5, 1.5,
  127978. };
  127979. static long _vq_quantmap__44c2_s_p2_0[] = {
  127980. 3, 1, 0, 2, 4,
  127981. };
  127982. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127983. _vq_quantthresh__44c2_s_p2_0,
  127984. _vq_quantmap__44c2_s_p2_0,
  127985. 5,
  127986. 5
  127987. };
  127988. static static_codebook _44c2_s_p2_0 = {
  127989. 4, 625,
  127990. _vq_lengthlist__44c2_s_p2_0,
  127991. 1, -533725184, 1611661312, 3, 0,
  127992. _vq_quantlist__44c2_s_p2_0,
  127993. NULL,
  127994. &_vq_auxt__44c2_s_p2_0,
  127995. NULL,
  127996. 0
  127997. };
  127998. static long _vq_quantlist__44c2_s_p3_0[] = {
  127999. 2,
  128000. 1,
  128001. 3,
  128002. 0,
  128003. 4,
  128004. };
  128005. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128006. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0,
  128046. };
  128047. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128048. -1.5, -0.5, 0.5, 1.5,
  128049. };
  128050. static long _vq_quantmap__44c2_s_p3_0[] = {
  128051. 3, 1, 0, 2, 4,
  128052. };
  128053. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128054. _vq_quantthresh__44c2_s_p3_0,
  128055. _vq_quantmap__44c2_s_p3_0,
  128056. 5,
  128057. 5
  128058. };
  128059. static static_codebook _44c2_s_p3_0 = {
  128060. 4, 625,
  128061. _vq_lengthlist__44c2_s_p3_0,
  128062. 1, -533725184, 1611661312, 3, 0,
  128063. _vq_quantlist__44c2_s_p3_0,
  128064. NULL,
  128065. &_vq_auxt__44c2_s_p3_0,
  128066. NULL,
  128067. 0
  128068. };
  128069. static long _vq_quantlist__44c2_s_p4_0[] = {
  128070. 4,
  128071. 3,
  128072. 5,
  128073. 2,
  128074. 6,
  128075. 1,
  128076. 7,
  128077. 0,
  128078. 8,
  128079. };
  128080. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128081. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128082. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128083. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128084. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128085. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0,
  128087. };
  128088. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128089. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128090. };
  128091. static long _vq_quantmap__44c2_s_p4_0[] = {
  128092. 7, 5, 3, 1, 0, 2, 4, 6,
  128093. 8,
  128094. };
  128095. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128096. _vq_quantthresh__44c2_s_p4_0,
  128097. _vq_quantmap__44c2_s_p4_0,
  128098. 9,
  128099. 9
  128100. };
  128101. static static_codebook _44c2_s_p4_0 = {
  128102. 2, 81,
  128103. _vq_lengthlist__44c2_s_p4_0,
  128104. 1, -531628032, 1611661312, 4, 0,
  128105. _vq_quantlist__44c2_s_p4_0,
  128106. NULL,
  128107. &_vq_auxt__44c2_s_p4_0,
  128108. NULL,
  128109. 0
  128110. };
  128111. static long _vq_quantlist__44c2_s_p5_0[] = {
  128112. 4,
  128113. 3,
  128114. 5,
  128115. 2,
  128116. 6,
  128117. 1,
  128118. 7,
  128119. 0,
  128120. 8,
  128121. };
  128122. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128123. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128124. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128125. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128126. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128127. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128128. 11,
  128129. };
  128130. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128131. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128132. };
  128133. static long _vq_quantmap__44c2_s_p5_0[] = {
  128134. 7, 5, 3, 1, 0, 2, 4, 6,
  128135. 8,
  128136. };
  128137. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128138. _vq_quantthresh__44c2_s_p5_0,
  128139. _vq_quantmap__44c2_s_p5_0,
  128140. 9,
  128141. 9
  128142. };
  128143. static static_codebook _44c2_s_p5_0 = {
  128144. 2, 81,
  128145. _vq_lengthlist__44c2_s_p5_0,
  128146. 1, -531628032, 1611661312, 4, 0,
  128147. _vq_quantlist__44c2_s_p5_0,
  128148. NULL,
  128149. &_vq_auxt__44c2_s_p5_0,
  128150. NULL,
  128151. 0
  128152. };
  128153. static long _vq_quantlist__44c2_s_p6_0[] = {
  128154. 8,
  128155. 7,
  128156. 9,
  128157. 6,
  128158. 10,
  128159. 5,
  128160. 11,
  128161. 4,
  128162. 12,
  128163. 3,
  128164. 13,
  128165. 2,
  128166. 14,
  128167. 1,
  128168. 15,
  128169. 0,
  128170. 16,
  128171. };
  128172. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128173. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128174. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128175. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128176. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128177. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128178. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128179. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128180. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128181. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128182. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128183. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128184. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128185. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128186. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128187. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128188. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128189. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128191. 14,
  128192. };
  128193. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128194. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128195. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128196. };
  128197. static long _vq_quantmap__44c2_s_p6_0[] = {
  128198. 15, 13, 11, 9, 7, 5, 3, 1,
  128199. 0, 2, 4, 6, 8, 10, 12, 14,
  128200. 16,
  128201. };
  128202. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128203. _vq_quantthresh__44c2_s_p6_0,
  128204. _vq_quantmap__44c2_s_p6_0,
  128205. 17,
  128206. 17
  128207. };
  128208. static static_codebook _44c2_s_p6_0 = {
  128209. 2, 289,
  128210. _vq_lengthlist__44c2_s_p6_0,
  128211. 1, -529530880, 1611661312, 5, 0,
  128212. _vq_quantlist__44c2_s_p6_0,
  128213. NULL,
  128214. &_vq_auxt__44c2_s_p6_0,
  128215. NULL,
  128216. 0
  128217. };
  128218. static long _vq_quantlist__44c2_s_p7_0[] = {
  128219. 1,
  128220. 0,
  128221. 2,
  128222. };
  128223. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128224. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128225. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128226. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128227. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128228. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128229. 11,
  128230. };
  128231. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128232. -5.5, 5.5,
  128233. };
  128234. static long _vq_quantmap__44c2_s_p7_0[] = {
  128235. 1, 0, 2,
  128236. };
  128237. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128238. _vq_quantthresh__44c2_s_p7_0,
  128239. _vq_quantmap__44c2_s_p7_0,
  128240. 3,
  128241. 3
  128242. };
  128243. static static_codebook _44c2_s_p7_0 = {
  128244. 4, 81,
  128245. _vq_lengthlist__44c2_s_p7_0,
  128246. 1, -529137664, 1618345984, 2, 0,
  128247. _vq_quantlist__44c2_s_p7_0,
  128248. NULL,
  128249. &_vq_auxt__44c2_s_p7_0,
  128250. NULL,
  128251. 0
  128252. };
  128253. static long _vq_quantlist__44c2_s_p7_1[] = {
  128254. 5,
  128255. 4,
  128256. 6,
  128257. 3,
  128258. 7,
  128259. 2,
  128260. 8,
  128261. 1,
  128262. 9,
  128263. 0,
  128264. 10,
  128265. };
  128266. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128267. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128268. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128269. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128270. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128271. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128272. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128273. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128274. 10,10,10, 8, 8, 8, 8, 8, 8,
  128275. };
  128276. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128277. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128278. 3.5, 4.5,
  128279. };
  128280. static long _vq_quantmap__44c2_s_p7_1[] = {
  128281. 9, 7, 5, 3, 1, 0, 2, 4,
  128282. 6, 8, 10,
  128283. };
  128284. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128285. _vq_quantthresh__44c2_s_p7_1,
  128286. _vq_quantmap__44c2_s_p7_1,
  128287. 11,
  128288. 11
  128289. };
  128290. static static_codebook _44c2_s_p7_1 = {
  128291. 2, 121,
  128292. _vq_lengthlist__44c2_s_p7_1,
  128293. 1, -531365888, 1611661312, 4, 0,
  128294. _vq_quantlist__44c2_s_p7_1,
  128295. NULL,
  128296. &_vq_auxt__44c2_s_p7_1,
  128297. NULL,
  128298. 0
  128299. };
  128300. static long _vq_quantlist__44c2_s_p8_0[] = {
  128301. 6,
  128302. 5,
  128303. 7,
  128304. 4,
  128305. 8,
  128306. 3,
  128307. 9,
  128308. 2,
  128309. 10,
  128310. 1,
  128311. 11,
  128312. 0,
  128313. 12,
  128314. };
  128315. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128316. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128317. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128318. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128319. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128320. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128321. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128322. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128323. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128324. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128325. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128326. 0,12,12,12,12,13,12,14,14,
  128327. };
  128328. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128329. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128330. 12.5, 17.5, 22.5, 27.5,
  128331. };
  128332. static long _vq_quantmap__44c2_s_p8_0[] = {
  128333. 11, 9, 7, 5, 3, 1, 0, 2,
  128334. 4, 6, 8, 10, 12,
  128335. };
  128336. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128337. _vq_quantthresh__44c2_s_p8_0,
  128338. _vq_quantmap__44c2_s_p8_0,
  128339. 13,
  128340. 13
  128341. };
  128342. static static_codebook _44c2_s_p8_0 = {
  128343. 2, 169,
  128344. _vq_lengthlist__44c2_s_p8_0,
  128345. 1, -526516224, 1616117760, 4, 0,
  128346. _vq_quantlist__44c2_s_p8_0,
  128347. NULL,
  128348. &_vq_auxt__44c2_s_p8_0,
  128349. NULL,
  128350. 0
  128351. };
  128352. static long _vq_quantlist__44c2_s_p8_1[] = {
  128353. 2,
  128354. 1,
  128355. 3,
  128356. 0,
  128357. 4,
  128358. };
  128359. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128360. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128361. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128362. };
  128363. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128364. -1.5, -0.5, 0.5, 1.5,
  128365. };
  128366. static long _vq_quantmap__44c2_s_p8_1[] = {
  128367. 3, 1, 0, 2, 4,
  128368. };
  128369. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128370. _vq_quantthresh__44c2_s_p8_1,
  128371. _vq_quantmap__44c2_s_p8_1,
  128372. 5,
  128373. 5
  128374. };
  128375. static static_codebook _44c2_s_p8_1 = {
  128376. 2, 25,
  128377. _vq_lengthlist__44c2_s_p8_1,
  128378. 1, -533725184, 1611661312, 3, 0,
  128379. _vq_quantlist__44c2_s_p8_1,
  128380. NULL,
  128381. &_vq_auxt__44c2_s_p8_1,
  128382. NULL,
  128383. 0
  128384. };
  128385. static long _vq_quantlist__44c2_s_p9_0[] = {
  128386. 6,
  128387. 5,
  128388. 7,
  128389. 4,
  128390. 8,
  128391. 3,
  128392. 9,
  128393. 2,
  128394. 10,
  128395. 1,
  128396. 11,
  128397. 0,
  128398. 12,
  128399. };
  128400. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128401. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128402. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128404. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128405. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128408. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128409. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128411. 11,11,11,11,11,11,11,11,11,
  128412. };
  128413. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128414. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128415. 552.5, 773.5, 994.5, 1215.5,
  128416. };
  128417. static long _vq_quantmap__44c2_s_p9_0[] = {
  128418. 11, 9, 7, 5, 3, 1, 0, 2,
  128419. 4, 6, 8, 10, 12,
  128420. };
  128421. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128422. _vq_quantthresh__44c2_s_p9_0,
  128423. _vq_quantmap__44c2_s_p9_0,
  128424. 13,
  128425. 13
  128426. };
  128427. static static_codebook _44c2_s_p9_0 = {
  128428. 2, 169,
  128429. _vq_lengthlist__44c2_s_p9_0,
  128430. 1, -514541568, 1627103232, 4, 0,
  128431. _vq_quantlist__44c2_s_p9_0,
  128432. NULL,
  128433. &_vq_auxt__44c2_s_p9_0,
  128434. NULL,
  128435. 0
  128436. };
  128437. static long _vq_quantlist__44c2_s_p9_1[] = {
  128438. 6,
  128439. 5,
  128440. 7,
  128441. 4,
  128442. 8,
  128443. 3,
  128444. 9,
  128445. 2,
  128446. 10,
  128447. 1,
  128448. 11,
  128449. 0,
  128450. 12,
  128451. };
  128452. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128453. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128454. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128455. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128456. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128457. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128458. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128459. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128460. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128461. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128462. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128463. 17,13,12,12,10,13,11,14,14,
  128464. };
  128465. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128466. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128467. 42.5, 59.5, 76.5, 93.5,
  128468. };
  128469. static long _vq_quantmap__44c2_s_p9_1[] = {
  128470. 11, 9, 7, 5, 3, 1, 0, 2,
  128471. 4, 6, 8, 10, 12,
  128472. };
  128473. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128474. _vq_quantthresh__44c2_s_p9_1,
  128475. _vq_quantmap__44c2_s_p9_1,
  128476. 13,
  128477. 13
  128478. };
  128479. static static_codebook _44c2_s_p9_1 = {
  128480. 2, 169,
  128481. _vq_lengthlist__44c2_s_p9_1,
  128482. 1, -522616832, 1620115456, 4, 0,
  128483. _vq_quantlist__44c2_s_p9_1,
  128484. NULL,
  128485. &_vq_auxt__44c2_s_p9_1,
  128486. NULL,
  128487. 0
  128488. };
  128489. static long _vq_quantlist__44c2_s_p9_2[] = {
  128490. 8,
  128491. 7,
  128492. 9,
  128493. 6,
  128494. 10,
  128495. 5,
  128496. 11,
  128497. 4,
  128498. 12,
  128499. 3,
  128500. 13,
  128501. 2,
  128502. 14,
  128503. 1,
  128504. 15,
  128505. 0,
  128506. 16,
  128507. };
  128508. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128509. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128510. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128511. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128512. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128513. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128514. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128515. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128516. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128517. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128518. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128519. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128520. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128521. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128522. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128523. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128524. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128525. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128526. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128527. 10,
  128528. };
  128529. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128530. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128531. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128532. };
  128533. static long _vq_quantmap__44c2_s_p9_2[] = {
  128534. 15, 13, 11, 9, 7, 5, 3, 1,
  128535. 0, 2, 4, 6, 8, 10, 12, 14,
  128536. 16,
  128537. };
  128538. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128539. _vq_quantthresh__44c2_s_p9_2,
  128540. _vq_quantmap__44c2_s_p9_2,
  128541. 17,
  128542. 17
  128543. };
  128544. static static_codebook _44c2_s_p9_2 = {
  128545. 2, 289,
  128546. _vq_lengthlist__44c2_s_p9_2,
  128547. 1, -529530880, 1611661312, 5, 0,
  128548. _vq_quantlist__44c2_s_p9_2,
  128549. NULL,
  128550. &_vq_auxt__44c2_s_p9_2,
  128551. NULL,
  128552. 0
  128553. };
  128554. static long _huff_lengthlist__44c2_s_short[] = {
  128555. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128556. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128557. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128558. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128559. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128560. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128561. 6, 8, 9,12,
  128562. };
  128563. static static_codebook _huff_book__44c2_s_short = {
  128564. 2, 100,
  128565. _huff_lengthlist__44c2_s_short,
  128566. 0, 0, 0, 0, 0,
  128567. NULL,
  128568. NULL,
  128569. NULL,
  128570. NULL,
  128571. 0
  128572. };
  128573. static long _huff_lengthlist__44c3_s_long[] = {
  128574. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128575. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128576. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128577. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128578. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128579. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128580. 9, 8, 8, 8,
  128581. };
  128582. static static_codebook _huff_book__44c3_s_long = {
  128583. 2, 100,
  128584. _huff_lengthlist__44c3_s_long,
  128585. 0, 0, 0, 0, 0,
  128586. NULL,
  128587. NULL,
  128588. NULL,
  128589. NULL,
  128590. 0
  128591. };
  128592. static long _vq_quantlist__44c3_s_p1_0[] = {
  128593. 1,
  128594. 0,
  128595. 2,
  128596. };
  128597. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128598. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128599. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128604. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128609. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128644. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128649. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128654. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128690. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128695. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128700. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0,
  129009. };
  129010. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129011. -0.5, 0.5,
  129012. };
  129013. static long _vq_quantmap__44c3_s_p1_0[] = {
  129014. 1, 0, 2,
  129015. };
  129016. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129017. _vq_quantthresh__44c3_s_p1_0,
  129018. _vq_quantmap__44c3_s_p1_0,
  129019. 3,
  129020. 3
  129021. };
  129022. static static_codebook _44c3_s_p1_0 = {
  129023. 8, 6561,
  129024. _vq_lengthlist__44c3_s_p1_0,
  129025. 1, -535822336, 1611661312, 2, 0,
  129026. _vq_quantlist__44c3_s_p1_0,
  129027. NULL,
  129028. &_vq_auxt__44c3_s_p1_0,
  129029. NULL,
  129030. 0
  129031. };
  129032. static long _vq_quantlist__44c3_s_p2_0[] = {
  129033. 2,
  129034. 1,
  129035. 3,
  129036. 0,
  129037. 4,
  129038. };
  129039. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129040. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129041. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129042. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129043. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129044. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129050. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129051. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129052. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129058. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129059. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129066. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129067. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0,
  129080. };
  129081. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129082. -1.5, -0.5, 0.5, 1.5,
  129083. };
  129084. static long _vq_quantmap__44c3_s_p2_0[] = {
  129085. 3, 1, 0, 2, 4,
  129086. };
  129087. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129088. _vq_quantthresh__44c3_s_p2_0,
  129089. _vq_quantmap__44c3_s_p2_0,
  129090. 5,
  129091. 5
  129092. };
  129093. static static_codebook _44c3_s_p2_0 = {
  129094. 4, 625,
  129095. _vq_lengthlist__44c3_s_p2_0,
  129096. 1, -533725184, 1611661312, 3, 0,
  129097. _vq_quantlist__44c3_s_p2_0,
  129098. NULL,
  129099. &_vq_auxt__44c3_s_p2_0,
  129100. NULL,
  129101. 0
  129102. };
  129103. static long _vq_quantlist__44c3_s_p3_0[] = {
  129104. 2,
  129105. 1,
  129106. 3,
  129107. 0,
  129108. 4,
  129109. };
  129110. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129111. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0,
  129151. };
  129152. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129153. -1.5, -0.5, 0.5, 1.5,
  129154. };
  129155. static long _vq_quantmap__44c3_s_p3_0[] = {
  129156. 3, 1, 0, 2, 4,
  129157. };
  129158. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129159. _vq_quantthresh__44c3_s_p3_0,
  129160. _vq_quantmap__44c3_s_p3_0,
  129161. 5,
  129162. 5
  129163. };
  129164. static static_codebook _44c3_s_p3_0 = {
  129165. 4, 625,
  129166. _vq_lengthlist__44c3_s_p3_0,
  129167. 1, -533725184, 1611661312, 3, 0,
  129168. _vq_quantlist__44c3_s_p3_0,
  129169. NULL,
  129170. &_vq_auxt__44c3_s_p3_0,
  129171. NULL,
  129172. 0
  129173. };
  129174. static long _vq_quantlist__44c3_s_p4_0[] = {
  129175. 4,
  129176. 3,
  129177. 5,
  129178. 2,
  129179. 6,
  129180. 1,
  129181. 7,
  129182. 0,
  129183. 8,
  129184. };
  129185. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129186. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129187. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129188. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129189. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129190. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0,
  129192. };
  129193. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129194. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129195. };
  129196. static long _vq_quantmap__44c3_s_p4_0[] = {
  129197. 7, 5, 3, 1, 0, 2, 4, 6,
  129198. 8,
  129199. };
  129200. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129201. _vq_quantthresh__44c3_s_p4_0,
  129202. _vq_quantmap__44c3_s_p4_0,
  129203. 9,
  129204. 9
  129205. };
  129206. static static_codebook _44c3_s_p4_0 = {
  129207. 2, 81,
  129208. _vq_lengthlist__44c3_s_p4_0,
  129209. 1, -531628032, 1611661312, 4, 0,
  129210. _vq_quantlist__44c3_s_p4_0,
  129211. NULL,
  129212. &_vq_auxt__44c3_s_p4_0,
  129213. NULL,
  129214. 0
  129215. };
  129216. static long _vq_quantlist__44c3_s_p5_0[] = {
  129217. 4,
  129218. 3,
  129219. 5,
  129220. 2,
  129221. 6,
  129222. 1,
  129223. 7,
  129224. 0,
  129225. 8,
  129226. };
  129227. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129228. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129229. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129230. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129231. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129232. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129233. 11,
  129234. };
  129235. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129236. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129237. };
  129238. static long _vq_quantmap__44c3_s_p5_0[] = {
  129239. 7, 5, 3, 1, 0, 2, 4, 6,
  129240. 8,
  129241. };
  129242. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129243. _vq_quantthresh__44c3_s_p5_0,
  129244. _vq_quantmap__44c3_s_p5_0,
  129245. 9,
  129246. 9
  129247. };
  129248. static static_codebook _44c3_s_p5_0 = {
  129249. 2, 81,
  129250. _vq_lengthlist__44c3_s_p5_0,
  129251. 1, -531628032, 1611661312, 4, 0,
  129252. _vq_quantlist__44c3_s_p5_0,
  129253. NULL,
  129254. &_vq_auxt__44c3_s_p5_0,
  129255. NULL,
  129256. 0
  129257. };
  129258. static long _vq_quantlist__44c3_s_p6_0[] = {
  129259. 8,
  129260. 7,
  129261. 9,
  129262. 6,
  129263. 10,
  129264. 5,
  129265. 11,
  129266. 4,
  129267. 12,
  129268. 3,
  129269. 13,
  129270. 2,
  129271. 14,
  129272. 1,
  129273. 15,
  129274. 0,
  129275. 16,
  129276. };
  129277. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129278. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129279. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129280. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129281. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129282. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129283. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129284. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129285. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129286. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129287. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129288. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129289. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129290. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129291. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129292. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129293. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129294. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129296. 13,
  129297. };
  129298. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129299. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129300. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129301. };
  129302. static long _vq_quantmap__44c3_s_p6_0[] = {
  129303. 15, 13, 11, 9, 7, 5, 3, 1,
  129304. 0, 2, 4, 6, 8, 10, 12, 14,
  129305. 16,
  129306. };
  129307. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129308. _vq_quantthresh__44c3_s_p6_0,
  129309. _vq_quantmap__44c3_s_p6_0,
  129310. 17,
  129311. 17
  129312. };
  129313. static static_codebook _44c3_s_p6_0 = {
  129314. 2, 289,
  129315. _vq_lengthlist__44c3_s_p6_0,
  129316. 1, -529530880, 1611661312, 5, 0,
  129317. _vq_quantlist__44c3_s_p6_0,
  129318. NULL,
  129319. &_vq_auxt__44c3_s_p6_0,
  129320. NULL,
  129321. 0
  129322. };
  129323. static long _vq_quantlist__44c3_s_p7_0[] = {
  129324. 1,
  129325. 0,
  129326. 2,
  129327. };
  129328. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129329. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129330. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129331. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129332. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129333. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129334. 10,
  129335. };
  129336. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129337. -5.5, 5.5,
  129338. };
  129339. static long _vq_quantmap__44c3_s_p7_0[] = {
  129340. 1, 0, 2,
  129341. };
  129342. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129343. _vq_quantthresh__44c3_s_p7_0,
  129344. _vq_quantmap__44c3_s_p7_0,
  129345. 3,
  129346. 3
  129347. };
  129348. static static_codebook _44c3_s_p7_0 = {
  129349. 4, 81,
  129350. _vq_lengthlist__44c3_s_p7_0,
  129351. 1, -529137664, 1618345984, 2, 0,
  129352. _vq_quantlist__44c3_s_p7_0,
  129353. NULL,
  129354. &_vq_auxt__44c3_s_p7_0,
  129355. NULL,
  129356. 0
  129357. };
  129358. static long _vq_quantlist__44c3_s_p7_1[] = {
  129359. 5,
  129360. 4,
  129361. 6,
  129362. 3,
  129363. 7,
  129364. 2,
  129365. 8,
  129366. 1,
  129367. 9,
  129368. 0,
  129369. 10,
  129370. };
  129371. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129372. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129373. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129374. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129375. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129376. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129377. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129378. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129379. 10,10,10, 8, 8, 8, 8, 8, 8,
  129380. };
  129381. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129382. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129383. 3.5, 4.5,
  129384. };
  129385. static long _vq_quantmap__44c3_s_p7_1[] = {
  129386. 9, 7, 5, 3, 1, 0, 2, 4,
  129387. 6, 8, 10,
  129388. };
  129389. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129390. _vq_quantthresh__44c3_s_p7_1,
  129391. _vq_quantmap__44c3_s_p7_1,
  129392. 11,
  129393. 11
  129394. };
  129395. static static_codebook _44c3_s_p7_1 = {
  129396. 2, 121,
  129397. _vq_lengthlist__44c3_s_p7_1,
  129398. 1, -531365888, 1611661312, 4, 0,
  129399. _vq_quantlist__44c3_s_p7_1,
  129400. NULL,
  129401. &_vq_auxt__44c3_s_p7_1,
  129402. NULL,
  129403. 0
  129404. };
  129405. static long _vq_quantlist__44c3_s_p8_0[] = {
  129406. 6,
  129407. 5,
  129408. 7,
  129409. 4,
  129410. 8,
  129411. 3,
  129412. 9,
  129413. 2,
  129414. 10,
  129415. 1,
  129416. 11,
  129417. 0,
  129418. 12,
  129419. };
  129420. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129421. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129422. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129423. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129424. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129425. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129426. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129427. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129428. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129429. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129430. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129431. 0,13,13,12,12,13,12,14,13,
  129432. };
  129433. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129434. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129435. 12.5, 17.5, 22.5, 27.5,
  129436. };
  129437. static long _vq_quantmap__44c3_s_p8_0[] = {
  129438. 11, 9, 7, 5, 3, 1, 0, 2,
  129439. 4, 6, 8, 10, 12,
  129440. };
  129441. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129442. _vq_quantthresh__44c3_s_p8_0,
  129443. _vq_quantmap__44c3_s_p8_0,
  129444. 13,
  129445. 13
  129446. };
  129447. static static_codebook _44c3_s_p8_0 = {
  129448. 2, 169,
  129449. _vq_lengthlist__44c3_s_p8_0,
  129450. 1, -526516224, 1616117760, 4, 0,
  129451. _vq_quantlist__44c3_s_p8_0,
  129452. NULL,
  129453. &_vq_auxt__44c3_s_p8_0,
  129454. NULL,
  129455. 0
  129456. };
  129457. static long _vq_quantlist__44c3_s_p8_1[] = {
  129458. 2,
  129459. 1,
  129460. 3,
  129461. 0,
  129462. 4,
  129463. };
  129464. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129465. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129466. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129467. };
  129468. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129469. -1.5, -0.5, 0.5, 1.5,
  129470. };
  129471. static long _vq_quantmap__44c3_s_p8_1[] = {
  129472. 3, 1, 0, 2, 4,
  129473. };
  129474. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129475. _vq_quantthresh__44c3_s_p8_1,
  129476. _vq_quantmap__44c3_s_p8_1,
  129477. 5,
  129478. 5
  129479. };
  129480. static static_codebook _44c3_s_p8_1 = {
  129481. 2, 25,
  129482. _vq_lengthlist__44c3_s_p8_1,
  129483. 1, -533725184, 1611661312, 3, 0,
  129484. _vq_quantlist__44c3_s_p8_1,
  129485. NULL,
  129486. &_vq_auxt__44c3_s_p8_1,
  129487. NULL,
  129488. 0
  129489. };
  129490. static long _vq_quantlist__44c3_s_p9_0[] = {
  129491. 6,
  129492. 5,
  129493. 7,
  129494. 4,
  129495. 8,
  129496. 3,
  129497. 9,
  129498. 2,
  129499. 10,
  129500. 1,
  129501. 11,
  129502. 0,
  129503. 12,
  129504. };
  129505. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129506. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129507. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129508. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129509. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129510. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129511. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129512. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129513. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129514. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129516. 11,11,11,11,11,11,11,11,11,
  129517. };
  129518. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129519. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129520. 637.5, 892.5, 1147.5, 1402.5,
  129521. };
  129522. static long _vq_quantmap__44c3_s_p9_0[] = {
  129523. 11, 9, 7, 5, 3, 1, 0, 2,
  129524. 4, 6, 8, 10, 12,
  129525. };
  129526. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129527. _vq_quantthresh__44c3_s_p9_0,
  129528. _vq_quantmap__44c3_s_p9_0,
  129529. 13,
  129530. 13
  129531. };
  129532. static static_codebook _44c3_s_p9_0 = {
  129533. 2, 169,
  129534. _vq_lengthlist__44c3_s_p9_0,
  129535. 1, -514332672, 1627381760, 4, 0,
  129536. _vq_quantlist__44c3_s_p9_0,
  129537. NULL,
  129538. &_vq_auxt__44c3_s_p9_0,
  129539. NULL,
  129540. 0
  129541. };
  129542. static long _vq_quantlist__44c3_s_p9_1[] = {
  129543. 7,
  129544. 6,
  129545. 8,
  129546. 5,
  129547. 9,
  129548. 4,
  129549. 10,
  129550. 3,
  129551. 11,
  129552. 2,
  129553. 12,
  129554. 1,
  129555. 13,
  129556. 0,
  129557. 14,
  129558. };
  129559. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129560. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129561. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129562. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129563. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129564. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129565. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129566. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129567. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129568. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129569. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129570. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129571. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129572. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129573. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129574. 15,
  129575. };
  129576. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129577. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129578. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129579. };
  129580. static long _vq_quantmap__44c3_s_p9_1[] = {
  129581. 13, 11, 9, 7, 5, 3, 1, 0,
  129582. 2, 4, 6, 8, 10, 12, 14,
  129583. };
  129584. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129585. _vq_quantthresh__44c3_s_p9_1,
  129586. _vq_quantmap__44c3_s_p9_1,
  129587. 15,
  129588. 15
  129589. };
  129590. static static_codebook _44c3_s_p9_1 = {
  129591. 2, 225,
  129592. _vq_lengthlist__44c3_s_p9_1,
  129593. 1, -522338304, 1620115456, 4, 0,
  129594. _vq_quantlist__44c3_s_p9_1,
  129595. NULL,
  129596. &_vq_auxt__44c3_s_p9_1,
  129597. NULL,
  129598. 0
  129599. };
  129600. static long _vq_quantlist__44c3_s_p9_2[] = {
  129601. 8,
  129602. 7,
  129603. 9,
  129604. 6,
  129605. 10,
  129606. 5,
  129607. 11,
  129608. 4,
  129609. 12,
  129610. 3,
  129611. 13,
  129612. 2,
  129613. 14,
  129614. 1,
  129615. 15,
  129616. 0,
  129617. 16,
  129618. };
  129619. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129620. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129621. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129622. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129623. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129624. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129625. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129626. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129627. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129628. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129629. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129630. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129631. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129632. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129633. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129634. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129635. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129636. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129637. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129638. 10,
  129639. };
  129640. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129641. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129642. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129643. };
  129644. static long _vq_quantmap__44c3_s_p9_2[] = {
  129645. 15, 13, 11, 9, 7, 5, 3, 1,
  129646. 0, 2, 4, 6, 8, 10, 12, 14,
  129647. 16,
  129648. };
  129649. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129650. _vq_quantthresh__44c3_s_p9_2,
  129651. _vq_quantmap__44c3_s_p9_2,
  129652. 17,
  129653. 17
  129654. };
  129655. static static_codebook _44c3_s_p9_2 = {
  129656. 2, 289,
  129657. _vq_lengthlist__44c3_s_p9_2,
  129658. 1, -529530880, 1611661312, 5, 0,
  129659. _vq_quantlist__44c3_s_p9_2,
  129660. NULL,
  129661. &_vq_auxt__44c3_s_p9_2,
  129662. NULL,
  129663. 0
  129664. };
  129665. static long _huff_lengthlist__44c3_s_short[] = {
  129666. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129667. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129668. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129669. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129670. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129671. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129672. 6, 8, 9,11,
  129673. };
  129674. static static_codebook _huff_book__44c3_s_short = {
  129675. 2, 100,
  129676. _huff_lengthlist__44c3_s_short,
  129677. 0, 0, 0, 0, 0,
  129678. NULL,
  129679. NULL,
  129680. NULL,
  129681. NULL,
  129682. 0
  129683. };
  129684. static long _huff_lengthlist__44c4_s_long[] = {
  129685. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129686. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129687. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129688. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129689. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129690. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129691. 9, 8, 7, 7,
  129692. };
  129693. static static_codebook _huff_book__44c4_s_long = {
  129694. 2, 100,
  129695. _huff_lengthlist__44c4_s_long,
  129696. 0, 0, 0, 0, 0,
  129697. NULL,
  129698. NULL,
  129699. NULL,
  129700. NULL,
  129701. 0
  129702. };
  129703. static long _vq_quantlist__44c4_s_p1_0[] = {
  129704. 1,
  129705. 0,
  129706. 2,
  129707. };
  129708. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129709. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129710. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129715. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129720. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129755. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129760. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129765. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129801. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129806. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129811. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0,
  130120. };
  130121. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130122. -0.5, 0.5,
  130123. };
  130124. static long _vq_quantmap__44c4_s_p1_0[] = {
  130125. 1, 0, 2,
  130126. };
  130127. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130128. _vq_quantthresh__44c4_s_p1_0,
  130129. _vq_quantmap__44c4_s_p1_0,
  130130. 3,
  130131. 3
  130132. };
  130133. static static_codebook _44c4_s_p1_0 = {
  130134. 8, 6561,
  130135. _vq_lengthlist__44c4_s_p1_0,
  130136. 1, -535822336, 1611661312, 2, 0,
  130137. _vq_quantlist__44c4_s_p1_0,
  130138. NULL,
  130139. &_vq_auxt__44c4_s_p1_0,
  130140. NULL,
  130141. 0
  130142. };
  130143. static long _vq_quantlist__44c4_s_p2_0[] = {
  130144. 2,
  130145. 1,
  130146. 3,
  130147. 0,
  130148. 4,
  130149. };
  130150. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130151. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130152. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130153. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130154. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130155. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130161. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130162. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130163. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130169. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130170. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130177. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130178. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0,
  130191. };
  130192. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130193. -1.5, -0.5, 0.5, 1.5,
  130194. };
  130195. static long _vq_quantmap__44c4_s_p2_0[] = {
  130196. 3, 1, 0, 2, 4,
  130197. };
  130198. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130199. _vq_quantthresh__44c4_s_p2_0,
  130200. _vq_quantmap__44c4_s_p2_0,
  130201. 5,
  130202. 5
  130203. };
  130204. static static_codebook _44c4_s_p2_0 = {
  130205. 4, 625,
  130206. _vq_lengthlist__44c4_s_p2_0,
  130207. 1, -533725184, 1611661312, 3, 0,
  130208. _vq_quantlist__44c4_s_p2_0,
  130209. NULL,
  130210. &_vq_auxt__44c4_s_p2_0,
  130211. NULL,
  130212. 0
  130213. };
  130214. static long _vq_quantlist__44c4_s_p3_0[] = {
  130215. 2,
  130216. 1,
  130217. 3,
  130218. 0,
  130219. 4,
  130220. };
  130221. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130222. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0,
  130262. };
  130263. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130264. -1.5, -0.5, 0.5, 1.5,
  130265. };
  130266. static long _vq_quantmap__44c4_s_p3_0[] = {
  130267. 3, 1, 0, 2, 4,
  130268. };
  130269. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130270. _vq_quantthresh__44c4_s_p3_0,
  130271. _vq_quantmap__44c4_s_p3_0,
  130272. 5,
  130273. 5
  130274. };
  130275. static static_codebook _44c4_s_p3_0 = {
  130276. 4, 625,
  130277. _vq_lengthlist__44c4_s_p3_0,
  130278. 1, -533725184, 1611661312, 3, 0,
  130279. _vq_quantlist__44c4_s_p3_0,
  130280. NULL,
  130281. &_vq_auxt__44c4_s_p3_0,
  130282. NULL,
  130283. 0
  130284. };
  130285. static long _vq_quantlist__44c4_s_p4_0[] = {
  130286. 4,
  130287. 3,
  130288. 5,
  130289. 2,
  130290. 6,
  130291. 1,
  130292. 7,
  130293. 0,
  130294. 8,
  130295. };
  130296. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130297. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130298. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130299. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130300. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130301. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0,
  130303. };
  130304. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130306. };
  130307. static long _vq_quantmap__44c4_s_p4_0[] = {
  130308. 7, 5, 3, 1, 0, 2, 4, 6,
  130309. 8,
  130310. };
  130311. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130312. _vq_quantthresh__44c4_s_p4_0,
  130313. _vq_quantmap__44c4_s_p4_0,
  130314. 9,
  130315. 9
  130316. };
  130317. static static_codebook _44c4_s_p4_0 = {
  130318. 2, 81,
  130319. _vq_lengthlist__44c4_s_p4_0,
  130320. 1, -531628032, 1611661312, 4, 0,
  130321. _vq_quantlist__44c4_s_p4_0,
  130322. NULL,
  130323. &_vq_auxt__44c4_s_p4_0,
  130324. NULL,
  130325. 0
  130326. };
  130327. static long _vq_quantlist__44c4_s_p5_0[] = {
  130328. 4,
  130329. 3,
  130330. 5,
  130331. 2,
  130332. 6,
  130333. 1,
  130334. 7,
  130335. 0,
  130336. 8,
  130337. };
  130338. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130339. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130340. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130341. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130342. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130343. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130344. 10,
  130345. };
  130346. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130347. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130348. };
  130349. static long _vq_quantmap__44c4_s_p5_0[] = {
  130350. 7, 5, 3, 1, 0, 2, 4, 6,
  130351. 8,
  130352. };
  130353. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130354. _vq_quantthresh__44c4_s_p5_0,
  130355. _vq_quantmap__44c4_s_p5_0,
  130356. 9,
  130357. 9
  130358. };
  130359. static static_codebook _44c4_s_p5_0 = {
  130360. 2, 81,
  130361. _vq_lengthlist__44c4_s_p5_0,
  130362. 1, -531628032, 1611661312, 4, 0,
  130363. _vq_quantlist__44c4_s_p5_0,
  130364. NULL,
  130365. &_vq_auxt__44c4_s_p5_0,
  130366. NULL,
  130367. 0
  130368. };
  130369. static long _vq_quantlist__44c4_s_p6_0[] = {
  130370. 8,
  130371. 7,
  130372. 9,
  130373. 6,
  130374. 10,
  130375. 5,
  130376. 11,
  130377. 4,
  130378. 12,
  130379. 3,
  130380. 13,
  130381. 2,
  130382. 14,
  130383. 1,
  130384. 15,
  130385. 0,
  130386. 16,
  130387. };
  130388. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130389. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130390. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130391. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130392. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130393. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130394. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130395. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130396. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130397. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130398. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130399. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130400. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130401. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130402. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130403. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130404. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130405. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130407. 13,
  130408. };
  130409. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130410. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130411. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130412. };
  130413. static long _vq_quantmap__44c4_s_p6_0[] = {
  130414. 15, 13, 11, 9, 7, 5, 3, 1,
  130415. 0, 2, 4, 6, 8, 10, 12, 14,
  130416. 16,
  130417. };
  130418. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130419. _vq_quantthresh__44c4_s_p6_0,
  130420. _vq_quantmap__44c4_s_p6_0,
  130421. 17,
  130422. 17
  130423. };
  130424. static static_codebook _44c4_s_p6_0 = {
  130425. 2, 289,
  130426. _vq_lengthlist__44c4_s_p6_0,
  130427. 1, -529530880, 1611661312, 5, 0,
  130428. _vq_quantlist__44c4_s_p6_0,
  130429. NULL,
  130430. &_vq_auxt__44c4_s_p6_0,
  130431. NULL,
  130432. 0
  130433. };
  130434. static long _vq_quantlist__44c4_s_p7_0[] = {
  130435. 1,
  130436. 0,
  130437. 2,
  130438. };
  130439. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130440. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130441. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130442. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130443. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130444. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130445. 10,
  130446. };
  130447. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130448. -5.5, 5.5,
  130449. };
  130450. static long _vq_quantmap__44c4_s_p7_0[] = {
  130451. 1, 0, 2,
  130452. };
  130453. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130454. _vq_quantthresh__44c4_s_p7_0,
  130455. _vq_quantmap__44c4_s_p7_0,
  130456. 3,
  130457. 3
  130458. };
  130459. static static_codebook _44c4_s_p7_0 = {
  130460. 4, 81,
  130461. _vq_lengthlist__44c4_s_p7_0,
  130462. 1, -529137664, 1618345984, 2, 0,
  130463. _vq_quantlist__44c4_s_p7_0,
  130464. NULL,
  130465. &_vq_auxt__44c4_s_p7_0,
  130466. NULL,
  130467. 0
  130468. };
  130469. static long _vq_quantlist__44c4_s_p7_1[] = {
  130470. 5,
  130471. 4,
  130472. 6,
  130473. 3,
  130474. 7,
  130475. 2,
  130476. 8,
  130477. 1,
  130478. 9,
  130479. 0,
  130480. 10,
  130481. };
  130482. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130483. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130484. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130485. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130486. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130487. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130488. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130489. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130490. 10,10,10, 8, 8, 8, 8, 9, 9,
  130491. };
  130492. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130493. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130494. 3.5, 4.5,
  130495. };
  130496. static long _vq_quantmap__44c4_s_p7_1[] = {
  130497. 9, 7, 5, 3, 1, 0, 2, 4,
  130498. 6, 8, 10,
  130499. };
  130500. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130501. _vq_quantthresh__44c4_s_p7_1,
  130502. _vq_quantmap__44c4_s_p7_1,
  130503. 11,
  130504. 11
  130505. };
  130506. static static_codebook _44c4_s_p7_1 = {
  130507. 2, 121,
  130508. _vq_lengthlist__44c4_s_p7_1,
  130509. 1, -531365888, 1611661312, 4, 0,
  130510. _vq_quantlist__44c4_s_p7_1,
  130511. NULL,
  130512. &_vq_auxt__44c4_s_p7_1,
  130513. NULL,
  130514. 0
  130515. };
  130516. static long _vq_quantlist__44c4_s_p8_0[] = {
  130517. 6,
  130518. 5,
  130519. 7,
  130520. 4,
  130521. 8,
  130522. 3,
  130523. 9,
  130524. 2,
  130525. 10,
  130526. 1,
  130527. 11,
  130528. 0,
  130529. 12,
  130530. };
  130531. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130532. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130533. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130534. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130535. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130536. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130537. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130538. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130539. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130540. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130541. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130542. 0,13,12,12,12,12,12,13,13,
  130543. };
  130544. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130545. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130546. 12.5, 17.5, 22.5, 27.5,
  130547. };
  130548. static long _vq_quantmap__44c4_s_p8_0[] = {
  130549. 11, 9, 7, 5, 3, 1, 0, 2,
  130550. 4, 6, 8, 10, 12,
  130551. };
  130552. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130553. _vq_quantthresh__44c4_s_p8_0,
  130554. _vq_quantmap__44c4_s_p8_0,
  130555. 13,
  130556. 13
  130557. };
  130558. static static_codebook _44c4_s_p8_0 = {
  130559. 2, 169,
  130560. _vq_lengthlist__44c4_s_p8_0,
  130561. 1, -526516224, 1616117760, 4, 0,
  130562. _vq_quantlist__44c4_s_p8_0,
  130563. NULL,
  130564. &_vq_auxt__44c4_s_p8_0,
  130565. NULL,
  130566. 0
  130567. };
  130568. static long _vq_quantlist__44c4_s_p8_1[] = {
  130569. 2,
  130570. 1,
  130571. 3,
  130572. 0,
  130573. 4,
  130574. };
  130575. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130576. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130577. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130578. };
  130579. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130580. -1.5, -0.5, 0.5, 1.5,
  130581. };
  130582. static long _vq_quantmap__44c4_s_p8_1[] = {
  130583. 3, 1, 0, 2, 4,
  130584. };
  130585. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130586. _vq_quantthresh__44c4_s_p8_1,
  130587. _vq_quantmap__44c4_s_p8_1,
  130588. 5,
  130589. 5
  130590. };
  130591. static static_codebook _44c4_s_p8_1 = {
  130592. 2, 25,
  130593. _vq_lengthlist__44c4_s_p8_1,
  130594. 1, -533725184, 1611661312, 3, 0,
  130595. _vq_quantlist__44c4_s_p8_1,
  130596. NULL,
  130597. &_vq_auxt__44c4_s_p8_1,
  130598. NULL,
  130599. 0
  130600. };
  130601. static long _vq_quantlist__44c4_s_p9_0[] = {
  130602. 6,
  130603. 5,
  130604. 7,
  130605. 4,
  130606. 8,
  130607. 3,
  130608. 9,
  130609. 2,
  130610. 10,
  130611. 1,
  130612. 11,
  130613. 0,
  130614. 12,
  130615. };
  130616. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130617. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130618. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130619. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130620. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130621. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130622. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130623. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130624. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130625. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130626. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130627. 12,12,12,12,12,12,12,12,12,
  130628. };
  130629. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130630. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130631. 787.5, 1102.5, 1417.5, 1732.5,
  130632. };
  130633. static long _vq_quantmap__44c4_s_p9_0[] = {
  130634. 11, 9, 7, 5, 3, 1, 0, 2,
  130635. 4, 6, 8, 10, 12,
  130636. };
  130637. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130638. _vq_quantthresh__44c4_s_p9_0,
  130639. _vq_quantmap__44c4_s_p9_0,
  130640. 13,
  130641. 13
  130642. };
  130643. static static_codebook _44c4_s_p9_0 = {
  130644. 2, 169,
  130645. _vq_lengthlist__44c4_s_p9_0,
  130646. 1, -513964032, 1628680192, 4, 0,
  130647. _vq_quantlist__44c4_s_p9_0,
  130648. NULL,
  130649. &_vq_auxt__44c4_s_p9_0,
  130650. NULL,
  130651. 0
  130652. };
  130653. static long _vq_quantlist__44c4_s_p9_1[] = {
  130654. 7,
  130655. 6,
  130656. 8,
  130657. 5,
  130658. 9,
  130659. 4,
  130660. 10,
  130661. 3,
  130662. 11,
  130663. 2,
  130664. 12,
  130665. 1,
  130666. 13,
  130667. 0,
  130668. 14,
  130669. };
  130670. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130671. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130672. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130673. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130674. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130675. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130676. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130677. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130678. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130679. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130680. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130681. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130682. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130683. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130684. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130685. 15,
  130686. };
  130687. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130688. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130689. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130690. };
  130691. static long _vq_quantmap__44c4_s_p9_1[] = {
  130692. 13, 11, 9, 7, 5, 3, 1, 0,
  130693. 2, 4, 6, 8, 10, 12, 14,
  130694. };
  130695. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130696. _vq_quantthresh__44c4_s_p9_1,
  130697. _vq_quantmap__44c4_s_p9_1,
  130698. 15,
  130699. 15
  130700. };
  130701. static static_codebook _44c4_s_p9_1 = {
  130702. 2, 225,
  130703. _vq_lengthlist__44c4_s_p9_1,
  130704. 1, -520986624, 1620377600, 4, 0,
  130705. _vq_quantlist__44c4_s_p9_1,
  130706. NULL,
  130707. &_vq_auxt__44c4_s_p9_1,
  130708. NULL,
  130709. 0
  130710. };
  130711. static long _vq_quantlist__44c4_s_p9_2[] = {
  130712. 10,
  130713. 9,
  130714. 11,
  130715. 8,
  130716. 12,
  130717. 7,
  130718. 13,
  130719. 6,
  130720. 14,
  130721. 5,
  130722. 15,
  130723. 4,
  130724. 16,
  130725. 3,
  130726. 17,
  130727. 2,
  130728. 18,
  130729. 1,
  130730. 19,
  130731. 0,
  130732. 20,
  130733. };
  130734. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130735. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130736. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130737. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130738. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130739. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130740. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130741. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130742. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130743. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130744. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130745. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130746. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130747. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130748. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130749. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130750. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130751. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130752. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130753. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130754. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130755. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130756. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130757. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130758. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130759. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130760. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130761. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130762. 10,10,10,10,10,10,10,10,10,
  130763. };
  130764. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130765. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130766. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130767. 6.5, 7.5, 8.5, 9.5,
  130768. };
  130769. static long _vq_quantmap__44c4_s_p9_2[] = {
  130770. 19, 17, 15, 13, 11, 9, 7, 5,
  130771. 3, 1, 0, 2, 4, 6, 8, 10,
  130772. 12, 14, 16, 18, 20,
  130773. };
  130774. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130775. _vq_quantthresh__44c4_s_p9_2,
  130776. _vq_quantmap__44c4_s_p9_2,
  130777. 21,
  130778. 21
  130779. };
  130780. static static_codebook _44c4_s_p9_2 = {
  130781. 2, 441,
  130782. _vq_lengthlist__44c4_s_p9_2,
  130783. 1, -529268736, 1611661312, 5, 0,
  130784. _vq_quantlist__44c4_s_p9_2,
  130785. NULL,
  130786. &_vq_auxt__44c4_s_p9_2,
  130787. NULL,
  130788. 0
  130789. };
  130790. static long _huff_lengthlist__44c4_s_short[] = {
  130791. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130792. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130793. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130794. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130795. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130796. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130797. 7, 9,12,17,
  130798. };
  130799. static static_codebook _huff_book__44c4_s_short = {
  130800. 2, 100,
  130801. _huff_lengthlist__44c4_s_short,
  130802. 0, 0, 0, 0, 0,
  130803. NULL,
  130804. NULL,
  130805. NULL,
  130806. NULL,
  130807. 0
  130808. };
  130809. static long _huff_lengthlist__44c5_s_long[] = {
  130810. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130811. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130812. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130813. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130814. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130815. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130816. 9, 8, 7, 7,
  130817. };
  130818. static static_codebook _huff_book__44c5_s_long = {
  130819. 2, 100,
  130820. _huff_lengthlist__44c5_s_long,
  130821. 0, 0, 0, 0, 0,
  130822. NULL,
  130823. NULL,
  130824. NULL,
  130825. NULL,
  130826. 0
  130827. };
  130828. static long _vq_quantlist__44c5_s_p1_0[] = {
  130829. 1,
  130830. 0,
  130831. 2,
  130832. };
  130833. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130834. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130835. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130840. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130845. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130880. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130885. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130890. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130926. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130931. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130936. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0,
  131245. };
  131246. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131247. -0.5, 0.5,
  131248. };
  131249. static long _vq_quantmap__44c5_s_p1_0[] = {
  131250. 1, 0, 2,
  131251. };
  131252. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131253. _vq_quantthresh__44c5_s_p1_0,
  131254. _vq_quantmap__44c5_s_p1_0,
  131255. 3,
  131256. 3
  131257. };
  131258. static static_codebook _44c5_s_p1_0 = {
  131259. 8, 6561,
  131260. _vq_lengthlist__44c5_s_p1_0,
  131261. 1, -535822336, 1611661312, 2, 0,
  131262. _vq_quantlist__44c5_s_p1_0,
  131263. NULL,
  131264. &_vq_auxt__44c5_s_p1_0,
  131265. NULL,
  131266. 0
  131267. };
  131268. static long _vq_quantlist__44c5_s_p2_0[] = {
  131269. 2,
  131270. 1,
  131271. 3,
  131272. 0,
  131273. 4,
  131274. };
  131275. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131276. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131277. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131278. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131279. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131280. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131286. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131287. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131288. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131294. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131295. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131302. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131303. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0,
  131316. };
  131317. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131318. -1.5, -0.5, 0.5, 1.5,
  131319. };
  131320. static long _vq_quantmap__44c5_s_p2_0[] = {
  131321. 3, 1, 0, 2, 4,
  131322. };
  131323. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131324. _vq_quantthresh__44c5_s_p2_0,
  131325. _vq_quantmap__44c5_s_p2_0,
  131326. 5,
  131327. 5
  131328. };
  131329. static static_codebook _44c5_s_p2_0 = {
  131330. 4, 625,
  131331. _vq_lengthlist__44c5_s_p2_0,
  131332. 1, -533725184, 1611661312, 3, 0,
  131333. _vq_quantlist__44c5_s_p2_0,
  131334. NULL,
  131335. &_vq_auxt__44c5_s_p2_0,
  131336. NULL,
  131337. 0
  131338. };
  131339. static long _vq_quantlist__44c5_s_p3_0[] = {
  131340. 2,
  131341. 1,
  131342. 3,
  131343. 0,
  131344. 4,
  131345. };
  131346. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131347. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0,
  131387. };
  131388. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131389. -1.5, -0.5, 0.5, 1.5,
  131390. };
  131391. static long _vq_quantmap__44c5_s_p3_0[] = {
  131392. 3, 1, 0, 2, 4,
  131393. };
  131394. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131395. _vq_quantthresh__44c5_s_p3_0,
  131396. _vq_quantmap__44c5_s_p3_0,
  131397. 5,
  131398. 5
  131399. };
  131400. static static_codebook _44c5_s_p3_0 = {
  131401. 4, 625,
  131402. _vq_lengthlist__44c5_s_p3_0,
  131403. 1, -533725184, 1611661312, 3, 0,
  131404. _vq_quantlist__44c5_s_p3_0,
  131405. NULL,
  131406. &_vq_auxt__44c5_s_p3_0,
  131407. NULL,
  131408. 0
  131409. };
  131410. static long _vq_quantlist__44c5_s_p4_0[] = {
  131411. 4,
  131412. 3,
  131413. 5,
  131414. 2,
  131415. 6,
  131416. 1,
  131417. 7,
  131418. 0,
  131419. 8,
  131420. };
  131421. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131422. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131423. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131424. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131425. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131426. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0,
  131428. };
  131429. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131431. };
  131432. static long _vq_quantmap__44c5_s_p4_0[] = {
  131433. 7, 5, 3, 1, 0, 2, 4, 6,
  131434. 8,
  131435. };
  131436. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131437. _vq_quantthresh__44c5_s_p4_0,
  131438. _vq_quantmap__44c5_s_p4_0,
  131439. 9,
  131440. 9
  131441. };
  131442. static static_codebook _44c5_s_p4_0 = {
  131443. 2, 81,
  131444. _vq_lengthlist__44c5_s_p4_0,
  131445. 1, -531628032, 1611661312, 4, 0,
  131446. _vq_quantlist__44c5_s_p4_0,
  131447. NULL,
  131448. &_vq_auxt__44c5_s_p4_0,
  131449. NULL,
  131450. 0
  131451. };
  131452. static long _vq_quantlist__44c5_s_p5_0[] = {
  131453. 4,
  131454. 3,
  131455. 5,
  131456. 2,
  131457. 6,
  131458. 1,
  131459. 7,
  131460. 0,
  131461. 8,
  131462. };
  131463. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131464. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131465. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131466. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131467. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131468. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131469. 10,
  131470. };
  131471. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131472. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131473. };
  131474. static long _vq_quantmap__44c5_s_p5_0[] = {
  131475. 7, 5, 3, 1, 0, 2, 4, 6,
  131476. 8,
  131477. };
  131478. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131479. _vq_quantthresh__44c5_s_p5_0,
  131480. _vq_quantmap__44c5_s_p5_0,
  131481. 9,
  131482. 9
  131483. };
  131484. static static_codebook _44c5_s_p5_0 = {
  131485. 2, 81,
  131486. _vq_lengthlist__44c5_s_p5_0,
  131487. 1, -531628032, 1611661312, 4, 0,
  131488. _vq_quantlist__44c5_s_p5_0,
  131489. NULL,
  131490. &_vq_auxt__44c5_s_p5_0,
  131491. NULL,
  131492. 0
  131493. };
  131494. static long _vq_quantlist__44c5_s_p6_0[] = {
  131495. 8,
  131496. 7,
  131497. 9,
  131498. 6,
  131499. 10,
  131500. 5,
  131501. 11,
  131502. 4,
  131503. 12,
  131504. 3,
  131505. 13,
  131506. 2,
  131507. 14,
  131508. 1,
  131509. 15,
  131510. 0,
  131511. 16,
  131512. };
  131513. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131514. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131515. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131516. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131517. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131518. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131519. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131520. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131521. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131522. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131523. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131524. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131525. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131526. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131527. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131528. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131529. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131530. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131532. 13,
  131533. };
  131534. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131535. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131536. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131537. };
  131538. static long _vq_quantmap__44c5_s_p6_0[] = {
  131539. 15, 13, 11, 9, 7, 5, 3, 1,
  131540. 0, 2, 4, 6, 8, 10, 12, 14,
  131541. 16,
  131542. };
  131543. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131544. _vq_quantthresh__44c5_s_p6_0,
  131545. _vq_quantmap__44c5_s_p6_0,
  131546. 17,
  131547. 17
  131548. };
  131549. static static_codebook _44c5_s_p6_0 = {
  131550. 2, 289,
  131551. _vq_lengthlist__44c5_s_p6_0,
  131552. 1, -529530880, 1611661312, 5, 0,
  131553. _vq_quantlist__44c5_s_p6_0,
  131554. NULL,
  131555. &_vq_auxt__44c5_s_p6_0,
  131556. NULL,
  131557. 0
  131558. };
  131559. static long _vq_quantlist__44c5_s_p7_0[] = {
  131560. 1,
  131561. 0,
  131562. 2,
  131563. };
  131564. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131565. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131566. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131567. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131568. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131569. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131570. 10,
  131571. };
  131572. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131573. -5.5, 5.5,
  131574. };
  131575. static long _vq_quantmap__44c5_s_p7_0[] = {
  131576. 1, 0, 2,
  131577. };
  131578. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131579. _vq_quantthresh__44c5_s_p7_0,
  131580. _vq_quantmap__44c5_s_p7_0,
  131581. 3,
  131582. 3
  131583. };
  131584. static static_codebook _44c5_s_p7_0 = {
  131585. 4, 81,
  131586. _vq_lengthlist__44c5_s_p7_0,
  131587. 1, -529137664, 1618345984, 2, 0,
  131588. _vq_quantlist__44c5_s_p7_0,
  131589. NULL,
  131590. &_vq_auxt__44c5_s_p7_0,
  131591. NULL,
  131592. 0
  131593. };
  131594. static long _vq_quantlist__44c5_s_p7_1[] = {
  131595. 5,
  131596. 4,
  131597. 6,
  131598. 3,
  131599. 7,
  131600. 2,
  131601. 8,
  131602. 1,
  131603. 9,
  131604. 0,
  131605. 10,
  131606. };
  131607. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131608. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131609. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131610. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131611. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131612. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131613. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131614. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131615. 10,10,10, 8, 8, 8, 8, 8, 8,
  131616. };
  131617. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131618. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131619. 3.5, 4.5,
  131620. };
  131621. static long _vq_quantmap__44c5_s_p7_1[] = {
  131622. 9, 7, 5, 3, 1, 0, 2, 4,
  131623. 6, 8, 10,
  131624. };
  131625. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131626. _vq_quantthresh__44c5_s_p7_1,
  131627. _vq_quantmap__44c5_s_p7_1,
  131628. 11,
  131629. 11
  131630. };
  131631. static static_codebook _44c5_s_p7_1 = {
  131632. 2, 121,
  131633. _vq_lengthlist__44c5_s_p7_1,
  131634. 1, -531365888, 1611661312, 4, 0,
  131635. _vq_quantlist__44c5_s_p7_1,
  131636. NULL,
  131637. &_vq_auxt__44c5_s_p7_1,
  131638. NULL,
  131639. 0
  131640. };
  131641. static long _vq_quantlist__44c5_s_p8_0[] = {
  131642. 6,
  131643. 5,
  131644. 7,
  131645. 4,
  131646. 8,
  131647. 3,
  131648. 9,
  131649. 2,
  131650. 10,
  131651. 1,
  131652. 11,
  131653. 0,
  131654. 12,
  131655. };
  131656. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131657. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131658. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131659. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131660. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131661. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131662. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131663. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131664. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131665. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131666. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131667. 0,12,12,12,12,12,12,13,13,
  131668. };
  131669. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131670. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131671. 12.5, 17.5, 22.5, 27.5,
  131672. };
  131673. static long _vq_quantmap__44c5_s_p8_0[] = {
  131674. 11, 9, 7, 5, 3, 1, 0, 2,
  131675. 4, 6, 8, 10, 12,
  131676. };
  131677. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131678. _vq_quantthresh__44c5_s_p8_0,
  131679. _vq_quantmap__44c5_s_p8_0,
  131680. 13,
  131681. 13
  131682. };
  131683. static static_codebook _44c5_s_p8_0 = {
  131684. 2, 169,
  131685. _vq_lengthlist__44c5_s_p8_0,
  131686. 1, -526516224, 1616117760, 4, 0,
  131687. _vq_quantlist__44c5_s_p8_0,
  131688. NULL,
  131689. &_vq_auxt__44c5_s_p8_0,
  131690. NULL,
  131691. 0
  131692. };
  131693. static long _vq_quantlist__44c5_s_p8_1[] = {
  131694. 2,
  131695. 1,
  131696. 3,
  131697. 0,
  131698. 4,
  131699. };
  131700. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131701. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131702. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131703. };
  131704. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131705. -1.5, -0.5, 0.5, 1.5,
  131706. };
  131707. static long _vq_quantmap__44c5_s_p8_1[] = {
  131708. 3, 1, 0, 2, 4,
  131709. };
  131710. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131711. _vq_quantthresh__44c5_s_p8_1,
  131712. _vq_quantmap__44c5_s_p8_1,
  131713. 5,
  131714. 5
  131715. };
  131716. static static_codebook _44c5_s_p8_1 = {
  131717. 2, 25,
  131718. _vq_lengthlist__44c5_s_p8_1,
  131719. 1, -533725184, 1611661312, 3, 0,
  131720. _vq_quantlist__44c5_s_p8_1,
  131721. NULL,
  131722. &_vq_auxt__44c5_s_p8_1,
  131723. NULL,
  131724. 0
  131725. };
  131726. static long _vq_quantlist__44c5_s_p9_0[] = {
  131727. 7,
  131728. 6,
  131729. 8,
  131730. 5,
  131731. 9,
  131732. 4,
  131733. 10,
  131734. 3,
  131735. 11,
  131736. 2,
  131737. 12,
  131738. 1,
  131739. 13,
  131740. 0,
  131741. 14,
  131742. };
  131743. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131744. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131745. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131746. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131747. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131748. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131749. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131750. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131751. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131752. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131753. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131754. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131755. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131756. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131757. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131758. 12,
  131759. };
  131760. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131761. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131762. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131763. };
  131764. static long _vq_quantmap__44c5_s_p9_0[] = {
  131765. 13, 11, 9, 7, 5, 3, 1, 0,
  131766. 2, 4, 6, 8, 10, 12, 14,
  131767. };
  131768. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131769. _vq_quantthresh__44c5_s_p9_0,
  131770. _vq_quantmap__44c5_s_p9_0,
  131771. 15,
  131772. 15
  131773. };
  131774. static static_codebook _44c5_s_p9_0 = {
  131775. 2, 225,
  131776. _vq_lengthlist__44c5_s_p9_0,
  131777. 1, -512522752, 1628852224, 4, 0,
  131778. _vq_quantlist__44c5_s_p9_0,
  131779. NULL,
  131780. &_vq_auxt__44c5_s_p9_0,
  131781. NULL,
  131782. 0
  131783. };
  131784. static long _vq_quantlist__44c5_s_p9_1[] = {
  131785. 8,
  131786. 7,
  131787. 9,
  131788. 6,
  131789. 10,
  131790. 5,
  131791. 11,
  131792. 4,
  131793. 12,
  131794. 3,
  131795. 13,
  131796. 2,
  131797. 14,
  131798. 1,
  131799. 15,
  131800. 0,
  131801. 16,
  131802. };
  131803. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131804. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131805. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131806. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131807. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131808. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131809. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131810. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131811. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131812. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131813. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131814. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131815. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131816. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131817. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131818. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131819. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131820. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131821. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131822. 15,
  131823. };
  131824. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131825. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131826. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131827. };
  131828. static long _vq_quantmap__44c5_s_p9_1[] = {
  131829. 15, 13, 11, 9, 7, 5, 3, 1,
  131830. 0, 2, 4, 6, 8, 10, 12, 14,
  131831. 16,
  131832. };
  131833. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131834. _vq_quantthresh__44c5_s_p9_1,
  131835. _vq_quantmap__44c5_s_p9_1,
  131836. 17,
  131837. 17
  131838. };
  131839. static static_codebook _44c5_s_p9_1 = {
  131840. 2, 289,
  131841. _vq_lengthlist__44c5_s_p9_1,
  131842. 1, -520814592, 1620377600, 5, 0,
  131843. _vq_quantlist__44c5_s_p9_1,
  131844. NULL,
  131845. &_vq_auxt__44c5_s_p9_1,
  131846. NULL,
  131847. 0
  131848. };
  131849. static long _vq_quantlist__44c5_s_p9_2[] = {
  131850. 10,
  131851. 9,
  131852. 11,
  131853. 8,
  131854. 12,
  131855. 7,
  131856. 13,
  131857. 6,
  131858. 14,
  131859. 5,
  131860. 15,
  131861. 4,
  131862. 16,
  131863. 3,
  131864. 17,
  131865. 2,
  131866. 18,
  131867. 1,
  131868. 19,
  131869. 0,
  131870. 20,
  131871. };
  131872. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131873. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131874. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131876. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131877. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131878. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131879. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131880. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131881. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131882. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131883. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131884. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131885. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131886. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131887. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131888. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131889. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131890. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131891. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131892. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131893. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131894. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131895. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131896. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131897. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131898. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131899. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131900. 10,10,10,10,10,10,10,10,10,
  131901. };
  131902. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131903. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131904. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131905. 6.5, 7.5, 8.5, 9.5,
  131906. };
  131907. static long _vq_quantmap__44c5_s_p9_2[] = {
  131908. 19, 17, 15, 13, 11, 9, 7, 5,
  131909. 3, 1, 0, 2, 4, 6, 8, 10,
  131910. 12, 14, 16, 18, 20,
  131911. };
  131912. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131913. _vq_quantthresh__44c5_s_p9_2,
  131914. _vq_quantmap__44c5_s_p9_2,
  131915. 21,
  131916. 21
  131917. };
  131918. static static_codebook _44c5_s_p9_2 = {
  131919. 2, 441,
  131920. _vq_lengthlist__44c5_s_p9_2,
  131921. 1, -529268736, 1611661312, 5, 0,
  131922. _vq_quantlist__44c5_s_p9_2,
  131923. NULL,
  131924. &_vq_auxt__44c5_s_p9_2,
  131925. NULL,
  131926. 0
  131927. };
  131928. static long _huff_lengthlist__44c5_s_short[] = {
  131929. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131930. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131931. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131932. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131933. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131934. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131935. 6, 8,11,16,
  131936. };
  131937. static static_codebook _huff_book__44c5_s_short = {
  131938. 2, 100,
  131939. _huff_lengthlist__44c5_s_short,
  131940. 0, 0, 0, 0, 0,
  131941. NULL,
  131942. NULL,
  131943. NULL,
  131944. NULL,
  131945. 0
  131946. };
  131947. static long _huff_lengthlist__44c6_s_long[] = {
  131948. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131949. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131950. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131951. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131952. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131953. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131954. 11,10,10,12,
  131955. };
  131956. static static_codebook _huff_book__44c6_s_long = {
  131957. 2, 100,
  131958. _huff_lengthlist__44c6_s_long,
  131959. 0, 0, 0, 0, 0,
  131960. NULL,
  131961. NULL,
  131962. NULL,
  131963. NULL,
  131964. 0
  131965. };
  131966. static long _vq_quantlist__44c6_s_p1_0[] = {
  131967. 1,
  131968. 0,
  131969. 2,
  131970. };
  131971. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131972. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131973. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131975. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131976. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131977. 8,
  131978. };
  131979. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131980. -0.5, 0.5,
  131981. };
  131982. static long _vq_quantmap__44c6_s_p1_0[] = {
  131983. 1, 0, 2,
  131984. };
  131985. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131986. _vq_quantthresh__44c6_s_p1_0,
  131987. _vq_quantmap__44c6_s_p1_0,
  131988. 3,
  131989. 3
  131990. };
  131991. static static_codebook _44c6_s_p1_0 = {
  131992. 4, 81,
  131993. _vq_lengthlist__44c6_s_p1_0,
  131994. 1, -535822336, 1611661312, 2, 0,
  131995. _vq_quantlist__44c6_s_p1_0,
  131996. NULL,
  131997. &_vq_auxt__44c6_s_p1_0,
  131998. NULL,
  131999. 0
  132000. };
  132001. static long _vq_quantlist__44c6_s_p2_0[] = {
  132002. 2,
  132003. 1,
  132004. 3,
  132005. 0,
  132006. 4,
  132007. };
  132008. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132009. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132010. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132011. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132012. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132013. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132014. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132015. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132016. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132019. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132020. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132021. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132022. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132023. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132024. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132027. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132028. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132029. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132030. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132031. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132032. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132035. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132036. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132037. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132038. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132039. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132040. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132045. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132046. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132047. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132048. 13,
  132049. };
  132050. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132051. -1.5, -0.5, 0.5, 1.5,
  132052. };
  132053. static long _vq_quantmap__44c6_s_p2_0[] = {
  132054. 3, 1, 0, 2, 4,
  132055. };
  132056. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132057. _vq_quantthresh__44c6_s_p2_0,
  132058. _vq_quantmap__44c6_s_p2_0,
  132059. 5,
  132060. 5
  132061. };
  132062. static static_codebook _44c6_s_p2_0 = {
  132063. 4, 625,
  132064. _vq_lengthlist__44c6_s_p2_0,
  132065. 1, -533725184, 1611661312, 3, 0,
  132066. _vq_quantlist__44c6_s_p2_0,
  132067. NULL,
  132068. &_vq_auxt__44c6_s_p2_0,
  132069. NULL,
  132070. 0
  132071. };
  132072. static long _vq_quantlist__44c6_s_p3_0[] = {
  132073. 4,
  132074. 3,
  132075. 5,
  132076. 2,
  132077. 6,
  132078. 1,
  132079. 7,
  132080. 0,
  132081. 8,
  132082. };
  132083. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132084. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132085. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132086. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132087. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0,
  132090. };
  132091. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132092. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132093. };
  132094. static long _vq_quantmap__44c6_s_p3_0[] = {
  132095. 7, 5, 3, 1, 0, 2, 4, 6,
  132096. 8,
  132097. };
  132098. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132099. _vq_quantthresh__44c6_s_p3_0,
  132100. _vq_quantmap__44c6_s_p3_0,
  132101. 9,
  132102. 9
  132103. };
  132104. static static_codebook _44c6_s_p3_0 = {
  132105. 2, 81,
  132106. _vq_lengthlist__44c6_s_p3_0,
  132107. 1, -531628032, 1611661312, 4, 0,
  132108. _vq_quantlist__44c6_s_p3_0,
  132109. NULL,
  132110. &_vq_auxt__44c6_s_p3_0,
  132111. NULL,
  132112. 0
  132113. };
  132114. static long _vq_quantlist__44c6_s_p4_0[] = {
  132115. 8,
  132116. 7,
  132117. 9,
  132118. 6,
  132119. 10,
  132120. 5,
  132121. 11,
  132122. 4,
  132123. 12,
  132124. 3,
  132125. 13,
  132126. 2,
  132127. 14,
  132128. 1,
  132129. 15,
  132130. 0,
  132131. 16,
  132132. };
  132133. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132134. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132135. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132136. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132137. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132138. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132139. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132140. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132141. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132142. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132143. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132152. 0,
  132153. };
  132154. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132155. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132156. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132157. };
  132158. static long _vq_quantmap__44c6_s_p4_0[] = {
  132159. 15, 13, 11, 9, 7, 5, 3, 1,
  132160. 0, 2, 4, 6, 8, 10, 12, 14,
  132161. 16,
  132162. };
  132163. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132164. _vq_quantthresh__44c6_s_p4_0,
  132165. _vq_quantmap__44c6_s_p4_0,
  132166. 17,
  132167. 17
  132168. };
  132169. static static_codebook _44c6_s_p4_0 = {
  132170. 2, 289,
  132171. _vq_lengthlist__44c6_s_p4_0,
  132172. 1, -529530880, 1611661312, 5, 0,
  132173. _vq_quantlist__44c6_s_p4_0,
  132174. NULL,
  132175. &_vq_auxt__44c6_s_p4_0,
  132176. NULL,
  132177. 0
  132178. };
  132179. static long _vq_quantlist__44c6_s_p5_0[] = {
  132180. 1,
  132181. 0,
  132182. 2,
  132183. };
  132184. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132185. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132186. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132187. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132188. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132189. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132190. 12,
  132191. };
  132192. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132193. -5.5, 5.5,
  132194. };
  132195. static long _vq_quantmap__44c6_s_p5_0[] = {
  132196. 1, 0, 2,
  132197. };
  132198. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132199. _vq_quantthresh__44c6_s_p5_0,
  132200. _vq_quantmap__44c6_s_p5_0,
  132201. 3,
  132202. 3
  132203. };
  132204. static static_codebook _44c6_s_p5_0 = {
  132205. 4, 81,
  132206. _vq_lengthlist__44c6_s_p5_0,
  132207. 1, -529137664, 1618345984, 2, 0,
  132208. _vq_quantlist__44c6_s_p5_0,
  132209. NULL,
  132210. &_vq_auxt__44c6_s_p5_0,
  132211. NULL,
  132212. 0
  132213. };
  132214. static long _vq_quantlist__44c6_s_p5_1[] = {
  132215. 5,
  132216. 4,
  132217. 6,
  132218. 3,
  132219. 7,
  132220. 2,
  132221. 8,
  132222. 1,
  132223. 9,
  132224. 0,
  132225. 10,
  132226. };
  132227. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132228. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132229. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132230. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132231. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132232. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132233. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132234. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132235. 11,10,10, 7, 7, 8, 8, 8, 8,
  132236. };
  132237. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132238. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132239. 3.5, 4.5,
  132240. };
  132241. static long _vq_quantmap__44c6_s_p5_1[] = {
  132242. 9, 7, 5, 3, 1, 0, 2, 4,
  132243. 6, 8, 10,
  132244. };
  132245. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132246. _vq_quantthresh__44c6_s_p5_1,
  132247. _vq_quantmap__44c6_s_p5_1,
  132248. 11,
  132249. 11
  132250. };
  132251. static static_codebook _44c6_s_p5_1 = {
  132252. 2, 121,
  132253. _vq_lengthlist__44c6_s_p5_1,
  132254. 1, -531365888, 1611661312, 4, 0,
  132255. _vq_quantlist__44c6_s_p5_1,
  132256. NULL,
  132257. &_vq_auxt__44c6_s_p5_1,
  132258. NULL,
  132259. 0
  132260. };
  132261. static long _vq_quantlist__44c6_s_p6_0[] = {
  132262. 6,
  132263. 5,
  132264. 7,
  132265. 4,
  132266. 8,
  132267. 3,
  132268. 9,
  132269. 2,
  132270. 10,
  132271. 1,
  132272. 11,
  132273. 0,
  132274. 12,
  132275. };
  132276. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132277. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132278. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132279. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132280. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132281. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132282. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. };
  132289. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132290. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132291. 12.5, 17.5, 22.5, 27.5,
  132292. };
  132293. static long _vq_quantmap__44c6_s_p6_0[] = {
  132294. 11, 9, 7, 5, 3, 1, 0, 2,
  132295. 4, 6, 8, 10, 12,
  132296. };
  132297. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132298. _vq_quantthresh__44c6_s_p6_0,
  132299. _vq_quantmap__44c6_s_p6_0,
  132300. 13,
  132301. 13
  132302. };
  132303. static static_codebook _44c6_s_p6_0 = {
  132304. 2, 169,
  132305. _vq_lengthlist__44c6_s_p6_0,
  132306. 1, -526516224, 1616117760, 4, 0,
  132307. _vq_quantlist__44c6_s_p6_0,
  132308. NULL,
  132309. &_vq_auxt__44c6_s_p6_0,
  132310. NULL,
  132311. 0
  132312. };
  132313. static long _vq_quantlist__44c6_s_p6_1[] = {
  132314. 2,
  132315. 1,
  132316. 3,
  132317. 0,
  132318. 4,
  132319. };
  132320. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132321. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132322. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132323. };
  132324. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132325. -1.5, -0.5, 0.5, 1.5,
  132326. };
  132327. static long _vq_quantmap__44c6_s_p6_1[] = {
  132328. 3, 1, 0, 2, 4,
  132329. };
  132330. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132331. _vq_quantthresh__44c6_s_p6_1,
  132332. _vq_quantmap__44c6_s_p6_1,
  132333. 5,
  132334. 5
  132335. };
  132336. static static_codebook _44c6_s_p6_1 = {
  132337. 2, 25,
  132338. _vq_lengthlist__44c6_s_p6_1,
  132339. 1, -533725184, 1611661312, 3, 0,
  132340. _vq_quantlist__44c6_s_p6_1,
  132341. NULL,
  132342. &_vq_auxt__44c6_s_p6_1,
  132343. NULL,
  132344. 0
  132345. };
  132346. static long _vq_quantlist__44c6_s_p7_0[] = {
  132347. 6,
  132348. 5,
  132349. 7,
  132350. 4,
  132351. 8,
  132352. 3,
  132353. 9,
  132354. 2,
  132355. 10,
  132356. 1,
  132357. 11,
  132358. 0,
  132359. 12,
  132360. };
  132361. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132362. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132363. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132364. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132365. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132366. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132367. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132368. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132369. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132370. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132371. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132372. 20,13,13,13,13,13,13,14,14,
  132373. };
  132374. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132375. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132376. 27.5, 38.5, 49.5, 60.5,
  132377. };
  132378. static long _vq_quantmap__44c6_s_p7_0[] = {
  132379. 11, 9, 7, 5, 3, 1, 0, 2,
  132380. 4, 6, 8, 10, 12,
  132381. };
  132382. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132383. _vq_quantthresh__44c6_s_p7_0,
  132384. _vq_quantmap__44c6_s_p7_0,
  132385. 13,
  132386. 13
  132387. };
  132388. static static_codebook _44c6_s_p7_0 = {
  132389. 2, 169,
  132390. _vq_lengthlist__44c6_s_p7_0,
  132391. 1, -523206656, 1618345984, 4, 0,
  132392. _vq_quantlist__44c6_s_p7_0,
  132393. NULL,
  132394. &_vq_auxt__44c6_s_p7_0,
  132395. NULL,
  132396. 0
  132397. };
  132398. static long _vq_quantlist__44c6_s_p7_1[] = {
  132399. 5,
  132400. 4,
  132401. 6,
  132402. 3,
  132403. 7,
  132404. 2,
  132405. 8,
  132406. 1,
  132407. 9,
  132408. 0,
  132409. 10,
  132410. };
  132411. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132412. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132413. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132414. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132415. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132416. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132417. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132418. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132419. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132420. };
  132421. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132422. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132423. 3.5, 4.5,
  132424. };
  132425. static long _vq_quantmap__44c6_s_p7_1[] = {
  132426. 9, 7, 5, 3, 1, 0, 2, 4,
  132427. 6, 8, 10,
  132428. };
  132429. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132430. _vq_quantthresh__44c6_s_p7_1,
  132431. _vq_quantmap__44c6_s_p7_1,
  132432. 11,
  132433. 11
  132434. };
  132435. static static_codebook _44c6_s_p7_1 = {
  132436. 2, 121,
  132437. _vq_lengthlist__44c6_s_p7_1,
  132438. 1, -531365888, 1611661312, 4, 0,
  132439. _vq_quantlist__44c6_s_p7_1,
  132440. NULL,
  132441. &_vq_auxt__44c6_s_p7_1,
  132442. NULL,
  132443. 0
  132444. };
  132445. static long _vq_quantlist__44c6_s_p8_0[] = {
  132446. 7,
  132447. 6,
  132448. 8,
  132449. 5,
  132450. 9,
  132451. 4,
  132452. 10,
  132453. 3,
  132454. 11,
  132455. 2,
  132456. 12,
  132457. 1,
  132458. 13,
  132459. 0,
  132460. 14,
  132461. };
  132462. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132463. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132464. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132465. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132466. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132467. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132468. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132469. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132470. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132471. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132472. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132473. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132474. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132475. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132476. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132477. 14,
  132478. };
  132479. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132480. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132481. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132482. };
  132483. static long _vq_quantmap__44c6_s_p8_0[] = {
  132484. 13, 11, 9, 7, 5, 3, 1, 0,
  132485. 2, 4, 6, 8, 10, 12, 14,
  132486. };
  132487. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132488. _vq_quantthresh__44c6_s_p8_0,
  132489. _vq_quantmap__44c6_s_p8_0,
  132490. 15,
  132491. 15
  132492. };
  132493. static static_codebook _44c6_s_p8_0 = {
  132494. 2, 225,
  132495. _vq_lengthlist__44c6_s_p8_0,
  132496. 1, -520986624, 1620377600, 4, 0,
  132497. _vq_quantlist__44c6_s_p8_0,
  132498. NULL,
  132499. &_vq_auxt__44c6_s_p8_0,
  132500. NULL,
  132501. 0
  132502. };
  132503. static long _vq_quantlist__44c6_s_p8_1[] = {
  132504. 10,
  132505. 9,
  132506. 11,
  132507. 8,
  132508. 12,
  132509. 7,
  132510. 13,
  132511. 6,
  132512. 14,
  132513. 5,
  132514. 15,
  132515. 4,
  132516. 16,
  132517. 3,
  132518. 17,
  132519. 2,
  132520. 18,
  132521. 1,
  132522. 19,
  132523. 0,
  132524. 20,
  132525. };
  132526. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132527. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132528. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132530. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132531. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132532. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132533. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132535. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132536. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132537. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132538. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132539. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132540. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132541. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132542. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132543. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132544. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132545. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132546. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132547. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132548. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132549. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132550. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132551. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132552. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132553. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132554. 10,10,10,10,10,10,10,10,10,
  132555. };
  132556. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132557. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132558. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132559. 6.5, 7.5, 8.5, 9.5,
  132560. };
  132561. static long _vq_quantmap__44c6_s_p8_1[] = {
  132562. 19, 17, 15, 13, 11, 9, 7, 5,
  132563. 3, 1, 0, 2, 4, 6, 8, 10,
  132564. 12, 14, 16, 18, 20,
  132565. };
  132566. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132567. _vq_quantthresh__44c6_s_p8_1,
  132568. _vq_quantmap__44c6_s_p8_1,
  132569. 21,
  132570. 21
  132571. };
  132572. static static_codebook _44c6_s_p8_1 = {
  132573. 2, 441,
  132574. _vq_lengthlist__44c6_s_p8_1,
  132575. 1, -529268736, 1611661312, 5, 0,
  132576. _vq_quantlist__44c6_s_p8_1,
  132577. NULL,
  132578. &_vq_auxt__44c6_s_p8_1,
  132579. NULL,
  132580. 0
  132581. };
  132582. static long _vq_quantlist__44c6_s_p9_0[] = {
  132583. 6,
  132584. 5,
  132585. 7,
  132586. 4,
  132587. 8,
  132588. 3,
  132589. 9,
  132590. 2,
  132591. 10,
  132592. 1,
  132593. 11,
  132594. 0,
  132595. 12,
  132596. };
  132597. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132598. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132599. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132601. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132608. 10,10,10,10,10,10,10,10,10,
  132609. };
  132610. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132611. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132612. 1592.5, 2229.5, 2866.5, 3503.5,
  132613. };
  132614. static long _vq_quantmap__44c6_s_p9_0[] = {
  132615. 11, 9, 7, 5, 3, 1, 0, 2,
  132616. 4, 6, 8, 10, 12,
  132617. };
  132618. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132619. _vq_quantthresh__44c6_s_p9_0,
  132620. _vq_quantmap__44c6_s_p9_0,
  132621. 13,
  132622. 13
  132623. };
  132624. static static_codebook _44c6_s_p9_0 = {
  132625. 2, 169,
  132626. _vq_lengthlist__44c6_s_p9_0,
  132627. 1, -511845376, 1630791680, 4, 0,
  132628. _vq_quantlist__44c6_s_p9_0,
  132629. NULL,
  132630. &_vq_auxt__44c6_s_p9_0,
  132631. NULL,
  132632. 0
  132633. };
  132634. static long _vq_quantlist__44c6_s_p9_1[] = {
  132635. 6,
  132636. 5,
  132637. 7,
  132638. 4,
  132639. 8,
  132640. 3,
  132641. 9,
  132642. 2,
  132643. 10,
  132644. 1,
  132645. 11,
  132646. 0,
  132647. 12,
  132648. };
  132649. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132650. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132651. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132652. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132653. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132654. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132655. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132656. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132657. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132658. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132659. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132660. 15,12,10,11,11,13,11,12,13,
  132661. };
  132662. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132663. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132664. 122.5, 171.5, 220.5, 269.5,
  132665. };
  132666. static long _vq_quantmap__44c6_s_p9_1[] = {
  132667. 11, 9, 7, 5, 3, 1, 0, 2,
  132668. 4, 6, 8, 10, 12,
  132669. };
  132670. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132671. _vq_quantthresh__44c6_s_p9_1,
  132672. _vq_quantmap__44c6_s_p9_1,
  132673. 13,
  132674. 13
  132675. };
  132676. static static_codebook _44c6_s_p9_1 = {
  132677. 2, 169,
  132678. _vq_lengthlist__44c6_s_p9_1,
  132679. 1, -518889472, 1622704128, 4, 0,
  132680. _vq_quantlist__44c6_s_p9_1,
  132681. NULL,
  132682. &_vq_auxt__44c6_s_p9_1,
  132683. NULL,
  132684. 0
  132685. };
  132686. static long _vq_quantlist__44c6_s_p9_2[] = {
  132687. 24,
  132688. 23,
  132689. 25,
  132690. 22,
  132691. 26,
  132692. 21,
  132693. 27,
  132694. 20,
  132695. 28,
  132696. 19,
  132697. 29,
  132698. 18,
  132699. 30,
  132700. 17,
  132701. 31,
  132702. 16,
  132703. 32,
  132704. 15,
  132705. 33,
  132706. 14,
  132707. 34,
  132708. 13,
  132709. 35,
  132710. 12,
  132711. 36,
  132712. 11,
  132713. 37,
  132714. 10,
  132715. 38,
  132716. 9,
  132717. 39,
  132718. 8,
  132719. 40,
  132720. 7,
  132721. 41,
  132722. 6,
  132723. 42,
  132724. 5,
  132725. 43,
  132726. 4,
  132727. 44,
  132728. 3,
  132729. 45,
  132730. 2,
  132731. 46,
  132732. 1,
  132733. 47,
  132734. 0,
  132735. 48,
  132736. };
  132737. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132738. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132739. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132740. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132741. 7,
  132742. };
  132743. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132744. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132745. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132746. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132747. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132748. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132749. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132750. };
  132751. static long _vq_quantmap__44c6_s_p9_2[] = {
  132752. 47, 45, 43, 41, 39, 37, 35, 33,
  132753. 31, 29, 27, 25, 23, 21, 19, 17,
  132754. 15, 13, 11, 9, 7, 5, 3, 1,
  132755. 0, 2, 4, 6, 8, 10, 12, 14,
  132756. 16, 18, 20, 22, 24, 26, 28, 30,
  132757. 32, 34, 36, 38, 40, 42, 44, 46,
  132758. 48,
  132759. };
  132760. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132761. _vq_quantthresh__44c6_s_p9_2,
  132762. _vq_quantmap__44c6_s_p9_2,
  132763. 49,
  132764. 49
  132765. };
  132766. static static_codebook _44c6_s_p9_2 = {
  132767. 1, 49,
  132768. _vq_lengthlist__44c6_s_p9_2,
  132769. 1, -526909440, 1611661312, 6, 0,
  132770. _vq_quantlist__44c6_s_p9_2,
  132771. NULL,
  132772. &_vq_auxt__44c6_s_p9_2,
  132773. NULL,
  132774. 0
  132775. };
  132776. static long _huff_lengthlist__44c6_s_short[] = {
  132777. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132778. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132779. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132780. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132781. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132782. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132783. 9,10,17,18,
  132784. };
  132785. static static_codebook _huff_book__44c6_s_short = {
  132786. 2, 100,
  132787. _huff_lengthlist__44c6_s_short,
  132788. 0, 0, 0, 0, 0,
  132789. NULL,
  132790. NULL,
  132791. NULL,
  132792. NULL,
  132793. 0
  132794. };
  132795. static long _huff_lengthlist__44c7_s_long[] = {
  132796. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132797. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132798. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132799. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132800. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132801. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132802. 11,10,10,12,
  132803. };
  132804. static static_codebook _huff_book__44c7_s_long = {
  132805. 2, 100,
  132806. _huff_lengthlist__44c7_s_long,
  132807. 0, 0, 0, 0, 0,
  132808. NULL,
  132809. NULL,
  132810. NULL,
  132811. NULL,
  132812. 0
  132813. };
  132814. static long _vq_quantlist__44c7_s_p1_0[] = {
  132815. 1,
  132816. 0,
  132817. 2,
  132818. };
  132819. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132820. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132821. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132822. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132823. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132824. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132825. 8,
  132826. };
  132827. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132828. -0.5, 0.5,
  132829. };
  132830. static long _vq_quantmap__44c7_s_p1_0[] = {
  132831. 1, 0, 2,
  132832. };
  132833. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132834. _vq_quantthresh__44c7_s_p1_0,
  132835. _vq_quantmap__44c7_s_p1_0,
  132836. 3,
  132837. 3
  132838. };
  132839. static static_codebook _44c7_s_p1_0 = {
  132840. 4, 81,
  132841. _vq_lengthlist__44c7_s_p1_0,
  132842. 1, -535822336, 1611661312, 2, 0,
  132843. _vq_quantlist__44c7_s_p1_0,
  132844. NULL,
  132845. &_vq_auxt__44c7_s_p1_0,
  132846. NULL,
  132847. 0
  132848. };
  132849. static long _vq_quantlist__44c7_s_p2_0[] = {
  132850. 2,
  132851. 1,
  132852. 3,
  132853. 0,
  132854. 4,
  132855. };
  132856. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132857. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132858. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132859. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132860. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132861. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132862. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132863. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132864. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132867. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132868. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132869. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132870. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132871. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132872. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132874. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132875. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132876. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132877. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132878. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132879. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132880. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132882. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132883. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132884. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132885. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132886. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132887. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132888. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132893. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132894. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132895. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132896. 13,
  132897. };
  132898. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132899. -1.5, -0.5, 0.5, 1.5,
  132900. };
  132901. static long _vq_quantmap__44c7_s_p2_0[] = {
  132902. 3, 1, 0, 2, 4,
  132903. };
  132904. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132905. _vq_quantthresh__44c7_s_p2_0,
  132906. _vq_quantmap__44c7_s_p2_0,
  132907. 5,
  132908. 5
  132909. };
  132910. static static_codebook _44c7_s_p2_0 = {
  132911. 4, 625,
  132912. _vq_lengthlist__44c7_s_p2_0,
  132913. 1, -533725184, 1611661312, 3, 0,
  132914. _vq_quantlist__44c7_s_p2_0,
  132915. NULL,
  132916. &_vq_auxt__44c7_s_p2_0,
  132917. NULL,
  132918. 0
  132919. };
  132920. static long _vq_quantlist__44c7_s_p3_0[] = {
  132921. 4,
  132922. 3,
  132923. 5,
  132924. 2,
  132925. 6,
  132926. 1,
  132927. 7,
  132928. 0,
  132929. 8,
  132930. };
  132931. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132932. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132933. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132934. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132935. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132937. 0,
  132938. };
  132939. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132940. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132941. };
  132942. static long _vq_quantmap__44c7_s_p3_0[] = {
  132943. 7, 5, 3, 1, 0, 2, 4, 6,
  132944. 8,
  132945. };
  132946. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132947. _vq_quantthresh__44c7_s_p3_0,
  132948. _vq_quantmap__44c7_s_p3_0,
  132949. 9,
  132950. 9
  132951. };
  132952. static static_codebook _44c7_s_p3_0 = {
  132953. 2, 81,
  132954. _vq_lengthlist__44c7_s_p3_0,
  132955. 1, -531628032, 1611661312, 4, 0,
  132956. _vq_quantlist__44c7_s_p3_0,
  132957. NULL,
  132958. &_vq_auxt__44c7_s_p3_0,
  132959. NULL,
  132960. 0
  132961. };
  132962. static long _vq_quantlist__44c7_s_p4_0[] = {
  132963. 8,
  132964. 7,
  132965. 9,
  132966. 6,
  132967. 10,
  132968. 5,
  132969. 11,
  132970. 4,
  132971. 12,
  132972. 3,
  132973. 13,
  132974. 2,
  132975. 14,
  132976. 1,
  132977. 15,
  132978. 0,
  132979. 16,
  132980. };
  132981. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132982. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132983. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132984. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132985. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132986. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132987. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132988. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132989. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132990. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132991. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0,
  133001. };
  133002. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133003. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133004. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133005. };
  133006. static long _vq_quantmap__44c7_s_p4_0[] = {
  133007. 15, 13, 11, 9, 7, 5, 3, 1,
  133008. 0, 2, 4, 6, 8, 10, 12, 14,
  133009. 16,
  133010. };
  133011. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133012. _vq_quantthresh__44c7_s_p4_0,
  133013. _vq_quantmap__44c7_s_p4_0,
  133014. 17,
  133015. 17
  133016. };
  133017. static static_codebook _44c7_s_p4_0 = {
  133018. 2, 289,
  133019. _vq_lengthlist__44c7_s_p4_0,
  133020. 1, -529530880, 1611661312, 5, 0,
  133021. _vq_quantlist__44c7_s_p4_0,
  133022. NULL,
  133023. &_vq_auxt__44c7_s_p4_0,
  133024. NULL,
  133025. 0
  133026. };
  133027. static long _vq_quantlist__44c7_s_p5_0[] = {
  133028. 1,
  133029. 0,
  133030. 2,
  133031. };
  133032. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133033. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133034. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133035. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133036. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133037. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133038. 12,
  133039. };
  133040. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133041. -5.5, 5.5,
  133042. };
  133043. static long _vq_quantmap__44c7_s_p5_0[] = {
  133044. 1, 0, 2,
  133045. };
  133046. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133047. _vq_quantthresh__44c7_s_p5_0,
  133048. _vq_quantmap__44c7_s_p5_0,
  133049. 3,
  133050. 3
  133051. };
  133052. static static_codebook _44c7_s_p5_0 = {
  133053. 4, 81,
  133054. _vq_lengthlist__44c7_s_p5_0,
  133055. 1, -529137664, 1618345984, 2, 0,
  133056. _vq_quantlist__44c7_s_p5_0,
  133057. NULL,
  133058. &_vq_auxt__44c7_s_p5_0,
  133059. NULL,
  133060. 0
  133061. };
  133062. static long _vq_quantlist__44c7_s_p5_1[] = {
  133063. 5,
  133064. 4,
  133065. 6,
  133066. 3,
  133067. 7,
  133068. 2,
  133069. 8,
  133070. 1,
  133071. 9,
  133072. 0,
  133073. 10,
  133074. };
  133075. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133076. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133077. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133078. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133079. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133080. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133081. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133082. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133083. 11,11,11, 7, 7, 8, 8, 8, 8,
  133084. };
  133085. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133086. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133087. 3.5, 4.5,
  133088. };
  133089. static long _vq_quantmap__44c7_s_p5_1[] = {
  133090. 9, 7, 5, 3, 1, 0, 2, 4,
  133091. 6, 8, 10,
  133092. };
  133093. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133094. _vq_quantthresh__44c7_s_p5_1,
  133095. _vq_quantmap__44c7_s_p5_1,
  133096. 11,
  133097. 11
  133098. };
  133099. static static_codebook _44c7_s_p5_1 = {
  133100. 2, 121,
  133101. _vq_lengthlist__44c7_s_p5_1,
  133102. 1, -531365888, 1611661312, 4, 0,
  133103. _vq_quantlist__44c7_s_p5_1,
  133104. NULL,
  133105. &_vq_auxt__44c7_s_p5_1,
  133106. NULL,
  133107. 0
  133108. };
  133109. static long _vq_quantlist__44c7_s_p6_0[] = {
  133110. 6,
  133111. 5,
  133112. 7,
  133113. 4,
  133114. 8,
  133115. 3,
  133116. 9,
  133117. 2,
  133118. 10,
  133119. 1,
  133120. 11,
  133121. 0,
  133122. 12,
  133123. };
  133124. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133125. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133126. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133127. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133128. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133129. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133130. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. };
  133137. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133138. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133139. 12.5, 17.5, 22.5, 27.5,
  133140. };
  133141. static long _vq_quantmap__44c7_s_p6_0[] = {
  133142. 11, 9, 7, 5, 3, 1, 0, 2,
  133143. 4, 6, 8, 10, 12,
  133144. };
  133145. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133146. _vq_quantthresh__44c7_s_p6_0,
  133147. _vq_quantmap__44c7_s_p6_0,
  133148. 13,
  133149. 13
  133150. };
  133151. static static_codebook _44c7_s_p6_0 = {
  133152. 2, 169,
  133153. _vq_lengthlist__44c7_s_p6_0,
  133154. 1, -526516224, 1616117760, 4, 0,
  133155. _vq_quantlist__44c7_s_p6_0,
  133156. NULL,
  133157. &_vq_auxt__44c7_s_p6_0,
  133158. NULL,
  133159. 0
  133160. };
  133161. static long _vq_quantlist__44c7_s_p6_1[] = {
  133162. 2,
  133163. 1,
  133164. 3,
  133165. 0,
  133166. 4,
  133167. };
  133168. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133169. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133170. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133171. };
  133172. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133173. -1.5, -0.5, 0.5, 1.5,
  133174. };
  133175. static long _vq_quantmap__44c7_s_p6_1[] = {
  133176. 3, 1, 0, 2, 4,
  133177. };
  133178. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133179. _vq_quantthresh__44c7_s_p6_1,
  133180. _vq_quantmap__44c7_s_p6_1,
  133181. 5,
  133182. 5
  133183. };
  133184. static static_codebook _44c7_s_p6_1 = {
  133185. 2, 25,
  133186. _vq_lengthlist__44c7_s_p6_1,
  133187. 1, -533725184, 1611661312, 3, 0,
  133188. _vq_quantlist__44c7_s_p6_1,
  133189. NULL,
  133190. &_vq_auxt__44c7_s_p6_1,
  133191. NULL,
  133192. 0
  133193. };
  133194. static long _vq_quantlist__44c7_s_p7_0[] = {
  133195. 6,
  133196. 5,
  133197. 7,
  133198. 4,
  133199. 8,
  133200. 3,
  133201. 9,
  133202. 2,
  133203. 10,
  133204. 1,
  133205. 11,
  133206. 0,
  133207. 12,
  133208. };
  133209. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133210. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133211. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133212. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133213. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133214. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133215. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133216. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133217. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133218. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133219. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133220. 19,13,13,13,13,14,14,15,15,
  133221. };
  133222. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133223. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133224. 27.5, 38.5, 49.5, 60.5,
  133225. };
  133226. static long _vq_quantmap__44c7_s_p7_0[] = {
  133227. 11, 9, 7, 5, 3, 1, 0, 2,
  133228. 4, 6, 8, 10, 12,
  133229. };
  133230. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133231. _vq_quantthresh__44c7_s_p7_0,
  133232. _vq_quantmap__44c7_s_p7_0,
  133233. 13,
  133234. 13
  133235. };
  133236. static static_codebook _44c7_s_p7_0 = {
  133237. 2, 169,
  133238. _vq_lengthlist__44c7_s_p7_0,
  133239. 1, -523206656, 1618345984, 4, 0,
  133240. _vq_quantlist__44c7_s_p7_0,
  133241. NULL,
  133242. &_vq_auxt__44c7_s_p7_0,
  133243. NULL,
  133244. 0
  133245. };
  133246. static long _vq_quantlist__44c7_s_p7_1[] = {
  133247. 5,
  133248. 4,
  133249. 6,
  133250. 3,
  133251. 7,
  133252. 2,
  133253. 8,
  133254. 1,
  133255. 9,
  133256. 0,
  133257. 10,
  133258. };
  133259. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133260. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133261. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133262. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133263. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133264. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133265. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133266. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133267. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133268. };
  133269. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133270. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133271. 3.5, 4.5,
  133272. };
  133273. static long _vq_quantmap__44c7_s_p7_1[] = {
  133274. 9, 7, 5, 3, 1, 0, 2, 4,
  133275. 6, 8, 10,
  133276. };
  133277. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133278. _vq_quantthresh__44c7_s_p7_1,
  133279. _vq_quantmap__44c7_s_p7_1,
  133280. 11,
  133281. 11
  133282. };
  133283. static static_codebook _44c7_s_p7_1 = {
  133284. 2, 121,
  133285. _vq_lengthlist__44c7_s_p7_1,
  133286. 1, -531365888, 1611661312, 4, 0,
  133287. _vq_quantlist__44c7_s_p7_1,
  133288. NULL,
  133289. &_vq_auxt__44c7_s_p7_1,
  133290. NULL,
  133291. 0
  133292. };
  133293. static long _vq_quantlist__44c7_s_p8_0[] = {
  133294. 7,
  133295. 6,
  133296. 8,
  133297. 5,
  133298. 9,
  133299. 4,
  133300. 10,
  133301. 3,
  133302. 11,
  133303. 2,
  133304. 12,
  133305. 1,
  133306. 13,
  133307. 0,
  133308. 14,
  133309. };
  133310. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133311. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133312. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133313. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133314. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133315. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133316. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133317. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133318. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133319. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133320. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133321. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133322. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133323. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133324. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133325. 14,
  133326. };
  133327. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133328. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133329. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133330. };
  133331. static long _vq_quantmap__44c7_s_p8_0[] = {
  133332. 13, 11, 9, 7, 5, 3, 1, 0,
  133333. 2, 4, 6, 8, 10, 12, 14,
  133334. };
  133335. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133336. _vq_quantthresh__44c7_s_p8_0,
  133337. _vq_quantmap__44c7_s_p8_0,
  133338. 15,
  133339. 15
  133340. };
  133341. static static_codebook _44c7_s_p8_0 = {
  133342. 2, 225,
  133343. _vq_lengthlist__44c7_s_p8_0,
  133344. 1, -520986624, 1620377600, 4, 0,
  133345. _vq_quantlist__44c7_s_p8_0,
  133346. NULL,
  133347. &_vq_auxt__44c7_s_p8_0,
  133348. NULL,
  133349. 0
  133350. };
  133351. static long _vq_quantlist__44c7_s_p8_1[] = {
  133352. 10,
  133353. 9,
  133354. 11,
  133355. 8,
  133356. 12,
  133357. 7,
  133358. 13,
  133359. 6,
  133360. 14,
  133361. 5,
  133362. 15,
  133363. 4,
  133364. 16,
  133365. 3,
  133366. 17,
  133367. 2,
  133368. 18,
  133369. 1,
  133370. 19,
  133371. 0,
  133372. 20,
  133373. };
  133374. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133375. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133376. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133377. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133378. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133379. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133380. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133381. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133383. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133384. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133385. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133386. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133387. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133388. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133389. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133390. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133391. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133392. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133393. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133394. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133395. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133396. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133397. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133398. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133399. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133400. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133401. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133402. 10,10,10,10,10,10,10,10,10,
  133403. };
  133404. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133405. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133406. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133407. 6.5, 7.5, 8.5, 9.5,
  133408. };
  133409. static long _vq_quantmap__44c7_s_p8_1[] = {
  133410. 19, 17, 15, 13, 11, 9, 7, 5,
  133411. 3, 1, 0, 2, 4, 6, 8, 10,
  133412. 12, 14, 16, 18, 20,
  133413. };
  133414. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133415. _vq_quantthresh__44c7_s_p8_1,
  133416. _vq_quantmap__44c7_s_p8_1,
  133417. 21,
  133418. 21
  133419. };
  133420. static static_codebook _44c7_s_p8_1 = {
  133421. 2, 441,
  133422. _vq_lengthlist__44c7_s_p8_1,
  133423. 1, -529268736, 1611661312, 5, 0,
  133424. _vq_quantlist__44c7_s_p8_1,
  133425. NULL,
  133426. &_vq_auxt__44c7_s_p8_1,
  133427. NULL,
  133428. 0
  133429. };
  133430. static long _vq_quantlist__44c7_s_p9_0[] = {
  133431. 6,
  133432. 5,
  133433. 7,
  133434. 4,
  133435. 8,
  133436. 3,
  133437. 9,
  133438. 2,
  133439. 10,
  133440. 1,
  133441. 11,
  133442. 0,
  133443. 12,
  133444. };
  133445. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133446. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133447. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133449. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133450. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133451. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133455. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133456. 11,11,11,11,11,11,11,11,11,
  133457. };
  133458. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133459. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133460. 1592.5, 2229.5, 2866.5, 3503.5,
  133461. };
  133462. static long _vq_quantmap__44c7_s_p9_0[] = {
  133463. 11, 9, 7, 5, 3, 1, 0, 2,
  133464. 4, 6, 8, 10, 12,
  133465. };
  133466. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133467. _vq_quantthresh__44c7_s_p9_0,
  133468. _vq_quantmap__44c7_s_p9_0,
  133469. 13,
  133470. 13
  133471. };
  133472. static static_codebook _44c7_s_p9_0 = {
  133473. 2, 169,
  133474. _vq_lengthlist__44c7_s_p9_0,
  133475. 1, -511845376, 1630791680, 4, 0,
  133476. _vq_quantlist__44c7_s_p9_0,
  133477. NULL,
  133478. &_vq_auxt__44c7_s_p9_0,
  133479. NULL,
  133480. 0
  133481. };
  133482. static long _vq_quantlist__44c7_s_p9_1[] = {
  133483. 6,
  133484. 5,
  133485. 7,
  133486. 4,
  133487. 8,
  133488. 3,
  133489. 9,
  133490. 2,
  133491. 10,
  133492. 1,
  133493. 11,
  133494. 0,
  133495. 12,
  133496. };
  133497. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133498. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133499. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133500. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133501. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133502. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133503. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133504. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133505. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133506. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133507. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133508. 15,11,11,10,10,12,12,12,12,
  133509. };
  133510. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133511. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133512. 122.5, 171.5, 220.5, 269.5,
  133513. };
  133514. static long _vq_quantmap__44c7_s_p9_1[] = {
  133515. 11, 9, 7, 5, 3, 1, 0, 2,
  133516. 4, 6, 8, 10, 12,
  133517. };
  133518. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133519. _vq_quantthresh__44c7_s_p9_1,
  133520. _vq_quantmap__44c7_s_p9_1,
  133521. 13,
  133522. 13
  133523. };
  133524. static static_codebook _44c7_s_p9_1 = {
  133525. 2, 169,
  133526. _vq_lengthlist__44c7_s_p9_1,
  133527. 1, -518889472, 1622704128, 4, 0,
  133528. _vq_quantlist__44c7_s_p9_1,
  133529. NULL,
  133530. &_vq_auxt__44c7_s_p9_1,
  133531. NULL,
  133532. 0
  133533. };
  133534. static long _vq_quantlist__44c7_s_p9_2[] = {
  133535. 24,
  133536. 23,
  133537. 25,
  133538. 22,
  133539. 26,
  133540. 21,
  133541. 27,
  133542. 20,
  133543. 28,
  133544. 19,
  133545. 29,
  133546. 18,
  133547. 30,
  133548. 17,
  133549. 31,
  133550. 16,
  133551. 32,
  133552. 15,
  133553. 33,
  133554. 14,
  133555. 34,
  133556. 13,
  133557. 35,
  133558. 12,
  133559. 36,
  133560. 11,
  133561. 37,
  133562. 10,
  133563. 38,
  133564. 9,
  133565. 39,
  133566. 8,
  133567. 40,
  133568. 7,
  133569. 41,
  133570. 6,
  133571. 42,
  133572. 5,
  133573. 43,
  133574. 4,
  133575. 44,
  133576. 3,
  133577. 45,
  133578. 2,
  133579. 46,
  133580. 1,
  133581. 47,
  133582. 0,
  133583. 48,
  133584. };
  133585. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133586. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133587. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133588. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133589. 7,
  133590. };
  133591. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133592. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133593. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133594. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133595. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133596. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133597. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133598. };
  133599. static long _vq_quantmap__44c7_s_p9_2[] = {
  133600. 47, 45, 43, 41, 39, 37, 35, 33,
  133601. 31, 29, 27, 25, 23, 21, 19, 17,
  133602. 15, 13, 11, 9, 7, 5, 3, 1,
  133603. 0, 2, 4, 6, 8, 10, 12, 14,
  133604. 16, 18, 20, 22, 24, 26, 28, 30,
  133605. 32, 34, 36, 38, 40, 42, 44, 46,
  133606. 48,
  133607. };
  133608. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133609. _vq_quantthresh__44c7_s_p9_2,
  133610. _vq_quantmap__44c7_s_p9_2,
  133611. 49,
  133612. 49
  133613. };
  133614. static static_codebook _44c7_s_p9_2 = {
  133615. 1, 49,
  133616. _vq_lengthlist__44c7_s_p9_2,
  133617. 1, -526909440, 1611661312, 6, 0,
  133618. _vq_quantlist__44c7_s_p9_2,
  133619. NULL,
  133620. &_vq_auxt__44c7_s_p9_2,
  133621. NULL,
  133622. 0
  133623. };
  133624. static long _huff_lengthlist__44c7_s_short[] = {
  133625. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133626. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133627. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133628. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133629. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133630. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133631. 10, 9,11,14,
  133632. };
  133633. static static_codebook _huff_book__44c7_s_short = {
  133634. 2, 100,
  133635. _huff_lengthlist__44c7_s_short,
  133636. 0, 0, 0, 0, 0,
  133637. NULL,
  133638. NULL,
  133639. NULL,
  133640. NULL,
  133641. 0
  133642. };
  133643. static long _huff_lengthlist__44c8_s_long[] = {
  133644. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133645. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133646. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133647. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133648. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133649. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133650. 11, 9, 9,10,
  133651. };
  133652. static static_codebook _huff_book__44c8_s_long = {
  133653. 2, 100,
  133654. _huff_lengthlist__44c8_s_long,
  133655. 0, 0, 0, 0, 0,
  133656. NULL,
  133657. NULL,
  133658. NULL,
  133659. NULL,
  133660. 0
  133661. };
  133662. static long _vq_quantlist__44c8_s_p1_0[] = {
  133663. 1,
  133664. 0,
  133665. 2,
  133666. };
  133667. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133668. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133669. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133670. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133671. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133672. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133673. 8,
  133674. };
  133675. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133676. -0.5, 0.5,
  133677. };
  133678. static long _vq_quantmap__44c8_s_p1_0[] = {
  133679. 1, 0, 2,
  133680. };
  133681. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133682. _vq_quantthresh__44c8_s_p1_0,
  133683. _vq_quantmap__44c8_s_p1_0,
  133684. 3,
  133685. 3
  133686. };
  133687. static static_codebook _44c8_s_p1_0 = {
  133688. 4, 81,
  133689. _vq_lengthlist__44c8_s_p1_0,
  133690. 1, -535822336, 1611661312, 2, 0,
  133691. _vq_quantlist__44c8_s_p1_0,
  133692. NULL,
  133693. &_vq_auxt__44c8_s_p1_0,
  133694. NULL,
  133695. 0
  133696. };
  133697. static long _vq_quantlist__44c8_s_p2_0[] = {
  133698. 2,
  133699. 1,
  133700. 3,
  133701. 0,
  133702. 4,
  133703. };
  133704. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133705. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133706. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133707. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133708. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133709. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133710. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133711. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133712. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133715. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133716. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133717. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133718. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133719. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133720. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133723. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133724. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133725. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133726. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133727. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133728. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133730. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133731. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133732. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133733. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133734. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133735. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133736. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133741. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133742. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133743. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133744. 13,
  133745. };
  133746. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133747. -1.5, -0.5, 0.5, 1.5,
  133748. };
  133749. static long _vq_quantmap__44c8_s_p2_0[] = {
  133750. 3, 1, 0, 2, 4,
  133751. };
  133752. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133753. _vq_quantthresh__44c8_s_p2_0,
  133754. _vq_quantmap__44c8_s_p2_0,
  133755. 5,
  133756. 5
  133757. };
  133758. static static_codebook _44c8_s_p2_0 = {
  133759. 4, 625,
  133760. _vq_lengthlist__44c8_s_p2_0,
  133761. 1, -533725184, 1611661312, 3, 0,
  133762. _vq_quantlist__44c8_s_p2_0,
  133763. NULL,
  133764. &_vq_auxt__44c8_s_p2_0,
  133765. NULL,
  133766. 0
  133767. };
  133768. static long _vq_quantlist__44c8_s_p3_0[] = {
  133769. 4,
  133770. 3,
  133771. 5,
  133772. 2,
  133773. 6,
  133774. 1,
  133775. 7,
  133776. 0,
  133777. 8,
  133778. };
  133779. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133780. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133781. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133782. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133783. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0,
  133786. };
  133787. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133788. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133789. };
  133790. static long _vq_quantmap__44c8_s_p3_0[] = {
  133791. 7, 5, 3, 1, 0, 2, 4, 6,
  133792. 8,
  133793. };
  133794. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133795. _vq_quantthresh__44c8_s_p3_0,
  133796. _vq_quantmap__44c8_s_p3_0,
  133797. 9,
  133798. 9
  133799. };
  133800. static static_codebook _44c8_s_p3_0 = {
  133801. 2, 81,
  133802. _vq_lengthlist__44c8_s_p3_0,
  133803. 1, -531628032, 1611661312, 4, 0,
  133804. _vq_quantlist__44c8_s_p3_0,
  133805. NULL,
  133806. &_vq_auxt__44c8_s_p3_0,
  133807. NULL,
  133808. 0
  133809. };
  133810. static long _vq_quantlist__44c8_s_p4_0[] = {
  133811. 8,
  133812. 7,
  133813. 9,
  133814. 6,
  133815. 10,
  133816. 5,
  133817. 11,
  133818. 4,
  133819. 12,
  133820. 3,
  133821. 13,
  133822. 2,
  133823. 14,
  133824. 1,
  133825. 15,
  133826. 0,
  133827. 16,
  133828. };
  133829. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133830. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133831. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133832. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133833. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133834. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133835. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133836. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133837. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133838. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133839. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133848. 0,
  133849. };
  133850. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133851. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133852. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133853. };
  133854. static long _vq_quantmap__44c8_s_p4_0[] = {
  133855. 15, 13, 11, 9, 7, 5, 3, 1,
  133856. 0, 2, 4, 6, 8, 10, 12, 14,
  133857. 16,
  133858. };
  133859. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133860. _vq_quantthresh__44c8_s_p4_0,
  133861. _vq_quantmap__44c8_s_p4_0,
  133862. 17,
  133863. 17
  133864. };
  133865. static static_codebook _44c8_s_p4_0 = {
  133866. 2, 289,
  133867. _vq_lengthlist__44c8_s_p4_0,
  133868. 1, -529530880, 1611661312, 5, 0,
  133869. _vq_quantlist__44c8_s_p4_0,
  133870. NULL,
  133871. &_vq_auxt__44c8_s_p4_0,
  133872. NULL,
  133873. 0
  133874. };
  133875. static long _vq_quantlist__44c8_s_p5_0[] = {
  133876. 1,
  133877. 0,
  133878. 2,
  133879. };
  133880. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133881. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133882. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133883. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133884. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133885. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133886. 12,
  133887. };
  133888. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133889. -5.5, 5.5,
  133890. };
  133891. static long _vq_quantmap__44c8_s_p5_0[] = {
  133892. 1, 0, 2,
  133893. };
  133894. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133895. _vq_quantthresh__44c8_s_p5_0,
  133896. _vq_quantmap__44c8_s_p5_0,
  133897. 3,
  133898. 3
  133899. };
  133900. static static_codebook _44c8_s_p5_0 = {
  133901. 4, 81,
  133902. _vq_lengthlist__44c8_s_p5_0,
  133903. 1, -529137664, 1618345984, 2, 0,
  133904. _vq_quantlist__44c8_s_p5_0,
  133905. NULL,
  133906. &_vq_auxt__44c8_s_p5_0,
  133907. NULL,
  133908. 0
  133909. };
  133910. static long _vq_quantlist__44c8_s_p5_1[] = {
  133911. 5,
  133912. 4,
  133913. 6,
  133914. 3,
  133915. 7,
  133916. 2,
  133917. 8,
  133918. 1,
  133919. 9,
  133920. 0,
  133921. 10,
  133922. };
  133923. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133924. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133925. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133926. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133927. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133928. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133929. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133930. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133931. 11,11,11, 7, 7, 7, 7, 8, 8,
  133932. };
  133933. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133935. 3.5, 4.5,
  133936. };
  133937. static long _vq_quantmap__44c8_s_p5_1[] = {
  133938. 9, 7, 5, 3, 1, 0, 2, 4,
  133939. 6, 8, 10,
  133940. };
  133941. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133942. _vq_quantthresh__44c8_s_p5_1,
  133943. _vq_quantmap__44c8_s_p5_1,
  133944. 11,
  133945. 11
  133946. };
  133947. static static_codebook _44c8_s_p5_1 = {
  133948. 2, 121,
  133949. _vq_lengthlist__44c8_s_p5_1,
  133950. 1, -531365888, 1611661312, 4, 0,
  133951. _vq_quantlist__44c8_s_p5_1,
  133952. NULL,
  133953. &_vq_auxt__44c8_s_p5_1,
  133954. NULL,
  133955. 0
  133956. };
  133957. static long _vq_quantlist__44c8_s_p6_0[] = {
  133958. 6,
  133959. 5,
  133960. 7,
  133961. 4,
  133962. 8,
  133963. 3,
  133964. 9,
  133965. 2,
  133966. 10,
  133967. 1,
  133968. 11,
  133969. 0,
  133970. 12,
  133971. };
  133972. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133973. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133974. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133975. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133976. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133977. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133978. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133983. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133984. };
  133985. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133986. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133987. 12.5, 17.5, 22.5, 27.5,
  133988. };
  133989. static long _vq_quantmap__44c8_s_p6_0[] = {
  133990. 11, 9, 7, 5, 3, 1, 0, 2,
  133991. 4, 6, 8, 10, 12,
  133992. };
  133993. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133994. _vq_quantthresh__44c8_s_p6_0,
  133995. _vq_quantmap__44c8_s_p6_0,
  133996. 13,
  133997. 13
  133998. };
  133999. static static_codebook _44c8_s_p6_0 = {
  134000. 2, 169,
  134001. _vq_lengthlist__44c8_s_p6_0,
  134002. 1, -526516224, 1616117760, 4, 0,
  134003. _vq_quantlist__44c8_s_p6_0,
  134004. NULL,
  134005. &_vq_auxt__44c8_s_p6_0,
  134006. NULL,
  134007. 0
  134008. };
  134009. static long _vq_quantlist__44c8_s_p6_1[] = {
  134010. 2,
  134011. 1,
  134012. 3,
  134013. 0,
  134014. 4,
  134015. };
  134016. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134017. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134018. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134019. };
  134020. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134021. -1.5, -0.5, 0.5, 1.5,
  134022. };
  134023. static long _vq_quantmap__44c8_s_p6_1[] = {
  134024. 3, 1, 0, 2, 4,
  134025. };
  134026. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134027. _vq_quantthresh__44c8_s_p6_1,
  134028. _vq_quantmap__44c8_s_p6_1,
  134029. 5,
  134030. 5
  134031. };
  134032. static static_codebook _44c8_s_p6_1 = {
  134033. 2, 25,
  134034. _vq_lengthlist__44c8_s_p6_1,
  134035. 1, -533725184, 1611661312, 3, 0,
  134036. _vq_quantlist__44c8_s_p6_1,
  134037. NULL,
  134038. &_vq_auxt__44c8_s_p6_1,
  134039. NULL,
  134040. 0
  134041. };
  134042. static long _vq_quantlist__44c8_s_p7_0[] = {
  134043. 6,
  134044. 5,
  134045. 7,
  134046. 4,
  134047. 8,
  134048. 3,
  134049. 9,
  134050. 2,
  134051. 10,
  134052. 1,
  134053. 11,
  134054. 0,
  134055. 12,
  134056. };
  134057. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134058. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134059. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134060. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134061. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134062. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134063. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134064. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134065. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134066. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134067. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134068. 20,13,13,13,13,14,13,15,15,
  134069. };
  134070. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134071. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134072. 27.5, 38.5, 49.5, 60.5,
  134073. };
  134074. static long _vq_quantmap__44c8_s_p7_0[] = {
  134075. 11, 9, 7, 5, 3, 1, 0, 2,
  134076. 4, 6, 8, 10, 12,
  134077. };
  134078. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134079. _vq_quantthresh__44c8_s_p7_0,
  134080. _vq_quantmap__44c8_s_p7_0,
  134081. 13,
  134082. 13
  134083. };
  134084. static static_codebook _44c8_s_p7_0 = {
  134085. 2, 169,
  134086. _vq_lengthlist__44c8_s_p7_0,
  134087. 1, -523206656, 1618345984, 4, 0,
  134088. _vq_quantlist__44c8_s_p7_0,
  134089. NULL,
  134090. &_vq_auxt__44c8_s_p7_0,
  134091. NULL,
  134092. 0
  134093. };
  134094. static long _vq_quantlist__44c8_s_p7_1[] = {
  134095. 5,
  134096. 4,
  134097. 6,
  134098. 3,
  134099. 7,
  134100. 2,
  134101. 8,
  134102. 1,
  134103. 9,
  134104. 0,
  134105. 10,
  134106. };
  134107. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134108. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134109. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134110. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134111. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134112. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134113. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134114. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134115. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134116. };
  134117. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134118. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134119. 3.5, 4.5,
  134120. };
  134121. static long _vq_quantmap__44c8_s_p7_1[] = {
  134122. 9, 7, 5, 3, 1, 0, 2, 4,
  134123. 6, 8, 10,
  134124. };
  134125. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134126. _vq_quantthresh__44c8_s_p7_1,
  134127. _vq_quantmap__44c8_s_p7_1,
  134128. 11,
  134129. 11
  134130. };
  134131. static static_codebook _44c8_s_p7_1 = {
  134132. 2, 121,
  134133. _vq_lengthlist__44c8_s_p7_1,
  134134. 1, -531365888, 1611661312, 4, 0,
  134135. _vq_quantlist__44c8_s_p7_1,
  134136. NULL,
  134137. &_vq_auxt__44c8_s_p7_1,
  134138. NULL,
  134139. 0
  134140. };
  134141. static long _vq_quantlist__44c8_s_p8_0[] = {
  134142. 7,
  134143. 6,
  134144. 8,
  134145. 5,
  134146. 9,
  134147. 4,
  134148. 10,
  134149. 3,
  134150. 11,
  134151. 2,
  134152. 12,
  134153. 1,
  134154. 13,
  134155. 0,
  134156. 14,
  134157. };
  134158. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134159. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134160. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134161. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134162. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134163. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134164. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134165. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134166. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134167. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134168. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134169. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134170. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134171. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134172. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134173. 15,
  134174. };
  134175. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134176. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134177. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134178. };
  134179. static long _vq_quantmap__44c8_s_p8_0[] = {
  134180. 13, 11, 9, 7, 5, 3, 1, 0,
  134181. 2, 4, 6, 8, 10, 12, 14,
  134182. };
  134183. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134184. _vq_quantthresh__44c8_s_p8_0,
  134185. _vq_quantmap__44c8_s_p8_0,
  134186. 15,
  134187. 15
  134188. };
  134189. static static_codebook _44c8_s_p8_0 = {
  134190. 2, 225,
  134191. _vq_lengthlist__44c8_s_p8_0,
  134192. 1, -520986624, 1620377600, 4, 0,
  134193. _vq_quantlist__44c8_s_p8_0,
  134194. NULL,
  134195. &_vq_auxt__44c8_s_p8_0,
  134196. NULL,
  134197. 0
  134198. };
  134199. static long _vq_quantlist__44c8_s_p8_1[] = {
  134200. 10,
  134201. 9,
  134202. 11,
  134203. 8,
  134204. 12,
  134205. 7,
  134206. 13,
  134207. 6,
  134208. 14,
  134209. 5,
  134210. 15,
  134211. 4,
  134212. 16,
  134213. 3,
  134214. 17,
  134215. 2,
  134216. 18,
  134217. 1,
  134218. 19,
  134219. 0,
  134220. 20,
  134221. };
  134222. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134223. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134224. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134225. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134226. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134227. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134228. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134229. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134230. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134231. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134232. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134233. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134234. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134235. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134236. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134237. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134238. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134239. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134240. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134241. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134242. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134243. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134244. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134245. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134246. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134247. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134248. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134249. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134250. 10, 9, 9,10,10, 9,10, 9, 9,
  134251. };
  134252. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134253. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134254. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134255. 6.5, 7.5, 8.5, 9.5,
  134256. };
  134257. static long _vq_quantmap__44c8_s_p8_1[] = {
  134258. 19, 17, 15, 13, 11, 9, 7, 5,
  134259. 3, 1, 0, 2, 4, 6, 8, 10,
  134260. 12, 14, 16, 18, 20,
  134261. };
  134262. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134263. _vq_quantthresh__44c8_s_p8_1,
  134264. _vq_quantmap__44c8_s_p8_1,
  134265. 21,
  134266. 21
  134267. };
  134268. static static_codebook _44c8_s_p8_1 = {
  134269. 2, 441,
  134270. _vq_lengthlist__44c8_s_p8_1,
  134271. 1, -529268736, 1611661312, 5, 0,
  134272. _vq_quantlist__44c8_s_p8_1,
  134273. NULL,
  134274. &_vq_auxt__44c8_s_p8_1,
  134275. NULL,
  134276. 0
  134277. };
  134278. static long _vq_quantlist__44c8_s_p9_0[] = {
  134279. 8,
  134280. 7,
  134281. 9,
  134282. 6,
  134283. 10,
  134284. 5,
  134285. 11,
  134286. 4,
  134287. 12,
  134288. 3,
  134289. 13,
  134290. 2,
  134291. 14,
  134292. 1,
  134293. 15,
  134294. 0,
  134295. 16,
  134296. };
  134297. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134298. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134299. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134300. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134301. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134303. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134304. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134305. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134306. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134307. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134309. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134312. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134313. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134314. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134316. 10,
  134317. };
  134318. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134319. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134320. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134321. };
  134322. static long _vq_quantmap__44c8_s_p9_0[] = {
  134323. 15, 13, 11, 9, 7, 5, 3, 1,
  134324. 0, 2, 4, 6, 8, 10, 12, 14,
  134325. 16,
  134326. };
  134327. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134328. _vq_quantthresh__44c8_s_p9_0,
  134329. _vq_quantmap__44c8_s_p9_0,
  134330. 17,
  134331. 17
  134332. };
  134333. static static_codebook _44c8_s_p9_0 = {
  134334. 2, 289,
  134335. _vq_lengthlist__44c8_s_p9_0,
  134336. 1, -509798400, 1631393792, 5, 0,
  134337. _vq_quantlist__44c8_s_p9_0,
  134338. NULL,
  134339. &_vq_auxt__44c8_s_p9_0,
  134340. NULL,
  134341. 0
  134342. };
  134343. static long _vq_quantlist__44c8_s_p9_1[] = {
  134344. 9,
  134345. 8,
  134346. 10,
  134347. 7,
  134348. 11,
  134349. 6,
  134350. 12,
  134351. 5,
  134352. 13,
  134353. 4,
  134354. 14,
  134355. 3,
  134356. 15,
  134357. 2,
  134358. 16,
  134359. 1,
  134360. 17,
  134361. 0,
  134362. 18,
  134363. };
  134364. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134365. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134366. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134367. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134368. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134369. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134370. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134371. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134372. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134373. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134374. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134375. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134376. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134377. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134378. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134379. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134380. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134381. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134382. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134383. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134384. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134385. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134386. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134387. 14,13,13,14,14,15,14,15,14,
  134388. };
  134389. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134390. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134391. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134392. 367.5, 416.5,
  134393. };
  134394. static long _vq_quantmap__44c8_s_p9_1[] = {
  134395. 17, 15, 13, 11, 9, 7, 5, 3,
  134396. 1, 0, 2, 4, 6, 8, 10, 12,
  134397. 14, 16, 18,
  134398. };
  134399. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134400. _vq_quantthresh__44c8_s_p9_1,
  134401. _vq_quantmap__44c8_s_p9_1,
  134402. 19,
  134403. 19
  134404. };
  134405. static static_codebook _44c8_s_p9_1 = {
  134406. 2, 361,
  134407. _vq_lengthlist__44c8_s_p9_1,
  134408. 1, -518287360, 1622704128, 5, 0,
  134409. _vq_quantlist__44c8_s_p9_1,
  134410. NULL,
  134411. &_vq_auxt__44c8_s_p9_1,
  134412. NULL,
  134413. 0
  134414. };
  134415. static long _vq_quantlist__44c8_s_p9_2[] = {
  134416. 24,
  134417. 23,
  134418. 25,
  134419. 22,
  134420. 26,
  134421. 21,
  134422. 27,
  134423. 20,
  134424. 28,
  134425. 19,
  134426. 29,
  134427. 18,
  134428. 30,
  134429. 17,
  134430. 31,
  134431. 16,
  134432. 32,
  134433. 15,
  134434. 33,
  134435. 14,
  134436. 34,
  134437. 13,
  134438. 35,
  134439. 12,
  134440. 36,
  134441. 11,
  134442. 37,
  134443. 10,
  134444. 38,
  134445. 9,
  134446. 39,
  134447. 8,
  134448. 40,
  134449. 7,
  134450. 41,
  134451. 6,
  134452. 42,
  134453. 5,
  134454. 43,
  134455. 4,
  134456. 44,
  134457. 3,
  134458. 45,
  134459. 2,
  134460. 46,
  134461. 1,
  134462. 47,
  134463. 0,
  134464. 48,
  134465. };
  134466. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134467. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134468. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134469. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134470. 7,
  134471. };
  134472. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134473. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134474. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134475. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134476. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134477. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134478. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134479. };
  134480. static long _vq_quantmap__44c8_s_p9_2[] = {
  134481. 47, 45, 43, 41, 39, 37, 35, 33,
  134482. 31, 29, 27, 25, 23, 21, 19, 17,
  134483. 15, 13, 11, 9, 7, 5, 3, 1,
  134484. 0, 2, 4, 6, 8, 10, 12, 14,
  134485. 16, 18, 20, 22, 24, 26, 28, 30,
  134486. 32, 34, 36, 38, 40, 42, 44, 46,
  134487. 48,
  134488. };
  134489. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134490. _vq_quantthresh__44c8_s_p9_2,
  134491. _vq_quantmap__44c8_s_p9_2,
  134492. 49,
  134493. 49
  134494. };
  134495. static static_codebook _44c8_s_p9_2 = {
  134496. 1, 49,
  134497. _vq_lengthlist__44c8_s_p9_2,
  134498. 1, -526909440, 1611661312, 6, 0,
  134499. _vq_quantlist__44c8_s_p9_2,
  134500. NULL,
  134501. &_vq_auxt__44c8_s_p9_2,
  134502. NULL,
  134503. 0
  134504. };
  134505. static long _huff_lengthlist__44c8_s_short[] = {
  134506. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134507. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134508. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134509. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134510. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134511. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134512. 10, 9,11,14,
  134513. };
  134514. static static_codebook _huff_book__44c8_s_short = {
  134515. 2, 100,
  134516. _huff_lengthlist__44c8_s_short,
  134517. 0, 0, 0, 0, 0,
  134518. NULL,
  134519. NULL,
  134520. NULL,
  134521. NULL,
  134522. 0
  134523. };
  134524. static long _huff_lengthlist__44c9_s_long[] = {
  134525. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134526. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134527. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134528. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134529. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134530. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134531. 10, 9, 8, 9,
  134532. };
  134533. static static_codebook _huff_book__44c9_s_long = {
  134534. 2, 100,
  134535. _huff_lengthlist__44c9_s_long,
  134536. 0, 0, 0, 0, 0,
  134537. NULL,
  134538. NULL,
  134539. NULL,
  134540. NULL,
  134541. 0
  134542. };
  134543. static long _vq_quantlist__44c9_s_p1_0[] = {
  134544. 1,
  134545. 0,
  134546. 2,
  134547. };
  134548. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134549. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134550. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134551. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134552. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134553. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134554. 7,
  134555. };
  134556. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134557. -0.5, 0.5,
  134558. };
  134559. static long _vq_quantmap__44c9_s_p1_0[] = {
  134560. 1, 0, 2,
  134561. };
  134562. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134563. _vq_quantthresh__44c9_s_p1_0,
  134564. _vq_quantmap__44c9_s_p1_0,
  134565. 3,
  134566. 3
  134567. };
  134568. static static_codebook _44c9_s_p1_0 = {
  134569. 4, 81,
  134570. _vq_lengthlist__44c9_s_p1_0,
  134571. 1, -535822336, 1611661312, 2, 0,
  134572. _vq_quantlist__44c9_s_p1_0,
  134573. NULL,
  134574. &_vq_auxt__44c9_s_p1_0,
  134575. NULL,
  134576. 0
  134577. };
  134578. static long _vq_quantlist__44c9_s_p2_0[] = {
  134579. 2,
  134580. 1,
  134581. 3,
  134582. 0,
  134583. 4,
  134584. };
  134585. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134586. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134587. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134588. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134589. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134590. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134591. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134592. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134593. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134595. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134596. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134597. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134598. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134599. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134600. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134601. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134603. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134604. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134605. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134606. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134607. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134608. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134609. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134611. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134612. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134613. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134614. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134615. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134616. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134617. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134622. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134623. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134624. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134625. 12,
  134626. };
  134627. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134628. -1.5, -0.5, 0.5, 1.5,
  134629. };
  134630. static long _vq_quantmap__44c9_s_p2_0[] = {
  134631. 3, 1, 0, 2, 4,
  134632. };
  134633. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134634. _vq_quantthresh__44c9_s_p2_0,
  134635. _vq_quantmap__44c9_s_p2_0,
  134636. 5,
  134637. 5
  134638. };
  134639. static static_codebook _44c9_s_p2_0 = {
  134640. 4, 625,
  134641. _vq_lengthlist__44c9_s_p2_0,
  134642. 1, -533725184, 1611661312, 3, 0,
  134643. _vq_quantlist__44c9_s_p2_0,
  134644. NULL,
  134645. &_vq_auxt__44c9_s_p2_0,
  134646. NULL,
  134647. 0
  134648. };
  134649. static long _vq_quantlist__44c9_s_p3_0[] = {
  134650. 4,
  134651. 3,
  134652. 5,
  134653. 2,
  134654. 6,
  134655. 1,
  134656. 7,
  134657. 0,
  134658. 8,
  134659. };
  134660. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134661. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134662. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134663. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134664. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0,
  134667. };
  134668. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134669. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134670. };
  134671. static long _vq_quantmap__44c9_s_p3_0[] = {
  134672. 7, 5, 3, 1, 0, 2, 4, 6,
  134673. 8,
  134674. };
  134675. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134676. _vq_quantthresh__44c9_s_p3_0,
  134677. _vq_quantmap__44c9_s_p3_0,
  134678. 9,
  134679. 9
  134680. };
  134681. static static_codebook _44c9_s_p3_0 = {
  134682. 2, 81,
  134683. _vq_lengthlist__44c9_s_p3_0,
  134684. 1, -531628032, 1611661312, 4, 0,
  134685. _vq_quantlist__44c9_s_p3_0,
  134686. NULL,
  134687. &_vq_auxt__44c9_s_p3_0,
  134688. NULL,
  134689. 0
  134690. };
  134691. static long _vq_quantlist__44c9_s_p4_0[] = {
  134692. 8,
  134693. 7,
  134694. 9,
  134695. 6,
  134696. 10,
  134697. 5,
  134698. 11,
  134699. 4,
  134700. 12,
  134701. 3,
  134702. 13,
  134703. 2,
  134704. 14,
  134705. 1,
  134706. 15,
  134707. 0,
  134708. 16,
  134709. };
  134710. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134711. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134712. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134713. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134714. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134715. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134716. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134717. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134718. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134719. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134720. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134729. 0,
  134730. };
  134731. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134732. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134733. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134734. };
  134735. static long _vq_quantmap__44c9_s_p4_0[] = {
  134736. 15, 13, 11, 9, 7, 5, 3, 1,
  134737. 0, 2, 4, 6, 8, 10, 12, 14,
  134738. 16,
  134739. };
  134740. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134741. _vq_quantthresh__44c9_s_p4_0,
  134742. _vq_quantmap__44c9_s_p4_0,
  134743. 17,
  134744. 17
  134745. };
  134746. static static_codebook _44c9_s_p4_0 = {
  134747. 2, 289,
  134748. _vq_lengthlist__44c9_s_p4_0,
  134749. 1, -529530880, 1611661312, 5, 0,
  134750. _vq_quantlist__44c9_s_p4_0,
  134751. NULL,
  134752. &_vq_auxt__44c9_s_p4_0,
  134753. NULL,
  134754. 0
  134755. };
  134756. static long _vq_quantlist__44c9_s_p5_0[] = {
  134757. 1,
  134758. 0,
  134759. 2,
  134760. };
  134761. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134762. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134763. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134764. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134765. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134766. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134767. 12,
  134768. };
  134769. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134770. -5.5, 5.5,
  134771. };
  134772. static long _vq_quantmap__44c9_s_p5_0[] = {
  134773. 1, 0, 2,
  134774. };
  134775. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134776. _vq_quantthresh__44c9_s_p5_0,
  134777. _vq_quantmap__44c9_s_p5_0,
  134778. 3,
  134779. 3
  134780. };
  134781. static static_codebook _44c9_s_p5_0 = {
  134782. 4, 81,
  134783. _vq_lengthlist__44c9_s_p5_0,
  134784. 1, -529137664, 1618345984, 2, 0,
  134785. _vq_quantlist__44c9_s_p5_0,
  134786. NULL,
  134787. &_vq_auxt__44c9_s_p5_0,
  134788. NULL,
  134789. 0
  134790. };
  134791. static long _vq_quantlist__44c9_s_p5_1[] = {
  134792. 5,
  134793. 4,
  134794. 6,
  134795. 3,
  134796. 7,
  134797. 2,
  134798. 8,
  134799. 1,
  134800. 9,
  134801. 0,
  134802. 10,
  134803. };
  134804. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134805. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134806. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134807. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134808. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134809. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134810. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134811. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134812. 11,11,11, 7, 7, 7, 7, 7, 7,
  134813. };
  134814. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134815. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134816. 3.5, 4.5,
  134817. };
  134818. static long _vq_quantmap__44c9_s_p5_1[] = {
  134819. 9, 7, 5, 3, 1, 0, 2, 4,
  134820. 6, 8, 10,
  134821. };
  134822. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134823. _vq_quantthresh__44c9_s_p5_1,
  134824. _vq_quantmap__44c9_s_p5_1,
  134825. 11,
  134826. 11
  134827. };
  134828. static static_codebook _44c9_s_p5_1 = {
  134829. 2, 121,
  134830. _vq_lengthlist__44c9_s_p5_1,
  134831. 1, -531365888, 1611661312, 4, 0,
  134832. _vq_quantlist__44c9_s_p5_1,
  134833. NULL,
  134834. &_vq_auxt__44c9_s_p5_1,
  134835. NULL,
  134836. 0
  134837. };
  134838. static long _vq_quantlist__44c9_s_p6_0[] = {
  134839. 6,
  134840. 5,
  134841. 7,
  134842. 4,
  134843. 8,
  134844. 3,
  134845. 9,
  134846. 2,
  134847. 10,
  134848. 1,
  134849. 11,
  134850. 0,
  134851. 12,
  134852. };
  134853. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134854. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134855. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134856. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134857. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134858. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134859. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. };
  134866. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134867. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134868. 12.5, 17.5, 22.5, 27.5,
  134869. };
  134870. static long _vq_quantmap__44c9_s_p6_0[] = {
  134871. 11, 9, 7, 5, 3, 1, 0, 2,
  134872. 4, 6, 8, 10, 12,
  134873. };
  134874. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134875. _vq_quantthresh__44c9_s_p6_0,
  134876. _vq_quantmap__44c9_s_p6_0,
  134877. 13,
  134878. 13
  134879. };
  134880. static static_codebook _44c9_s_p6_0 = {
  134881. 2, 169,
  134882. _vq_lengthlist__44c9_s_p6_0,
  134883. 1, -526516224, 1616117760, 4, 0,
  134884. _vq_quantlist__44c9_s_p6_0,
  134885. NULL,
  134886. &_vq_auxt__44c9_s_p6_0,
  134887. NULL,
  134888. 0
  134889. };
  134890. static long _vq_quantlist__44c9_s_p6_1[] = {
  134891. 2,
  134892. 1,
  134893. 3,
  134894. 0,
  134895. 4,
  134896. };
  134897. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134898. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134899. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134900. };
  134901. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134902. -1.5, -0.5, 0.5, 1.5,
  134903. };
  134904. static long _vq_quantmap__44c9_s_p6_1[] = {
  134905. 3, 1, 0, 2, 4,
  134906. };
  134907. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134908. _vq_quantthresh__44c9_s_p6_1,
  134909. _vq_quantmap__44c9_s_p6_1,
  134910. 5,
  134911. 5
  134912. };
  134913. static static_codebook _44c9_s_p6_1 = {
  134914. 2, 25,
  134915. _vq_lengthlist__44c9_s_p6_1,
  134916. 1, -533725184, 1611661312, 3, 0,
  134917. _vq_quantlist__44c9_s_p6_1,
  134918. NULL,
  134919. &_vq_auxt__44c9_s_p6_1,
  134920. NULL,
  134921. 0
  134922. };
  134923. static long _vq_quantlist__44c9_s_p7_0[] = {
  134924. 6,
  134925. 5,
  134926. 7,
  134927. 4,
  134928. 8,
  134929. 3,
  134930. 9,
  134931. 2,
  134932. 10,
  134933. 1,
  134934. 11,
  134935. 0,
  134936. 12,
  134937. };
  134938. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134939. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134940. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134941. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134942. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134943. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134944. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134945. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134946. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134947. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134948. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134949. 19,12,12,12,12,13,13,14,14,
  134950. };
  134951. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134952. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134953. 27.5, 38.5, 49.5, 60.5,
  134954. };
  134955. static long _vq_quantmap__44c9_s_p7_0[] = {
  134956. 11, 9, 7, 5, 3, 1, 0, 2,
  134957. 4, 6, 8, 10, 12,
  134958. };
  134959. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134960. _vq_quantthresh__44c9_s_p7_0,
  134961. _vq_quantmap__44c9_s_p7_0,
  134962. 13,
  134963. 13
  134964. };
  134965. static static_codebook _44c9_s_p7_0 = {
  134966. 2, 169,
  134967. _vq_lengthlist__44c9_s_p7_0,
  134968. 1, -523206656, 1618345984, 4, 0,
  134969. _vq_quantlist__44c9_s_p7_0,
  134970. NULL,
  134971. &_vq_auxt__44c9_s_p7_0,
  134972. NULL,
  134973. 0
  134974. };
  134975. static long _vq_quantlist__44c9_s_p7_1[] = {
  134976. 5,
  134977. 4,
  134978. 6,
  134979. 3,
  134980. 7,
  134981. 2,
  134982. 8,
  134983. 1,
  134984. 9,
  134985. 0,
  134986. 10,
  134987. };
  134988. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134989. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134990. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134991. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134992. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134993. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134994. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134995. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134996. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134997. };
  134998. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134999. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135000. 3.5, 4.5,
  135001. };
  135002. static long _vq_quantmap__44c9_s_p7_1[] = {
  135003. 9, 7, 5, 3, 1, 0, 2, 4,
  135004. 6, 8, 10,
  135005. };
  135006. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135007. _vq_quantthresh__44c9_s_p7_1,
  135008. _vq_quantmap__44c9_s_p7_1,
  135009. 11,
  135010. 11
  135011. };
  135012. static static_codebook _44c9_s_p7_1 = {
  135013. 2, 121,
  135014. _vq_lengthlist__44c9_s_p7_1,
  135015. 1, -531365888, 1611661312, 4, 0,
  135016. _vq_quantlist__44c9_s_p7_1,
  135017. NULL,
  135018. &_vq_auxt__44c9_s_p7_1,
  135019. NULL,
  135020. 0
  135021. };
  135022. static long _vq_quantlist__44c9_s_p8_0[] = {
  135023. 7,
  135024. 6,
  135025. 8,
  135026. 5,
  135027. 9,
  135028. 4,
  135029. 10,
  135030. 3,
  135031. 11,
  135032. 2,
  135033. 12,
  135034. 1,
  135035. 13,
  135036. 0,
  135037. 14,
  135038. };
  135039. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135040. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135041. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135042. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135043. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135044. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135045. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135046. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135047. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135048. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135049. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135050. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135051. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135052. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135053. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135054. 14,
  135055. };
  135056. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135057. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135058. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135059. };
  135060. static long _vq_quantmap__44c9_s_p8_0[] = {
  135061. 13, 11, 9, 7, 5, 3, 1, 0,
  135062. 2, 4, 6, 8, 10, 12, 14,
  135063. };
  135064. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135065. _vq_quantthresh__44c9_s_p8_0,
  135066. _vq_quantmap__44c9_s_p8_0,
  135067. 15,
  135068. 15
  135069. };
  135070. static static_codebook _44c9_s_p8_0 = {
  135071. 2, 225,
  135072. _vq_lengthlist__44c9_s_p8_0,
  135073. 1, -520986624, 1620377600, 4, 0,
  135074. _vq_quantlist__44c9_s_p8_0,
  135075. NULL,
  135076. &_vq_auxt__44c9_s_p8_0,
  135077. NULL,
  135078. 0
  135079. };
  135080. static long _vq_quantlist__44c9_s_p8_1[] = {
  135081. 10,
  135082. 9,
  135083. 11,
  135084. 8,
  135085. 12,
  135086. 7,
  135087. 13,
  135088. 6,
  135089. 14,
  135090. 5,
  135091. 15,
  135092. 4,
  135093. 16,
  135094. 3,
  135095. 17,
  135096. 2,
  135097. 18,
  135098. 1,
  135099. 19,
  135100. 0,
  135101. 20,
  135102. };
  135103. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135104. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135105. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135106. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135107. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135108. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135109. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135110. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135111. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135112. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135113. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135114. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135115. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135116. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135117. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135118. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135119. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135120. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135121. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135122. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135123. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135124. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135125. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135126. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135127. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135128. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135129. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135130. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135131. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135132. };
  135133. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135134. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135135. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135136. 6.5, 7.5, 8.5, 9.5,
  135137. };
  135138. static long _vq_quantmap__44c9_s_p8_1[] = {
  135139. 19, 17, 15, 13, 11, 9, 7, 5,
  135140. 3, 1, 0, 2, 4, 6, 8, 10,
  135141. 12, 14, 16, 18, 20,
  135142. };
  135143. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135144. _vq_quantthresh__44c9_s_p8_1,
  135145. _vq_quantmap__44c9_s_p8_1,
  135146. 21,
  135147. 21
  135148. };
  135149. static static_codebook _44c9_s_p8_1 = {
  135150. 2, 441,
  135151. _vq_lengthlist__44c9_s_p8_1,
  135152. 1, -529268736, 1611661312, 5, 0,
  135153. _vq_quantlist__44c9_s_p8_1,
  135154. NULL,
  135155. &_vq_auxt__44c9_s_p8_1,
  135156. NULL,
  135157. 0
  135158. };
  135159. static long _vq_quantlist__44c9_s_p9_0[] = {
  135160. 9,
  135161. 8,
  135162. 10,
  135163. 7,
  135164. 11,
  135165. 6,
  135166. 12,
  135167. 5,
  135168. 13,
  135169. 4,
  135170. 14,
  135171. 3,
  135172. 15,
  135173. 2,
  135174. 16,
  135175. 1,
  135176. 17,
  135177. 0,
  135178. 18,
  135179. };
  135180. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135181. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135182. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135183. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135184. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135185. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135186. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135187. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135188. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135189. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135190. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135191. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135192. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135193. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135194. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135195. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135196. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135197. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135198. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135199. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135200. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135201. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135202. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135203. 11,11,11,11,11,11,11,11,11,
  135204. };
  135205. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135206. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135207. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135208. 6982.5, 7913.5,
  135209. };
  135210. static long _vq_quantmap__44c9_s_p9_0[] = {
  135211. 17, 15, 13, 11, 9, 7, 5, 3,
  135212. 1, 0, 2, 4, 6, 8, 10, 12,
  135213. 14, 16, 18,
  135214. };
  135215. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135216. _vq_quantthresh__44c9_s_p9_0,
  135217. _vq_quantmap__44c9_s_p9_0,
  135218. 19,
  135219. 19
  135220. };
  135221. static static_codebook _44c9_s_p9_0 = {
  135222. 2, 361,
  135223. _vq_lengthlist__44c9_s_p9_0,
  135224. 1, -508535424, 1631393792, 5, 0,
  135225. _vq_quantlist__44c9_s_p9_0,
  135226. NULL,
  135227. &_vq_auxt__44c9_s_p9_0,
  135228. NULL,
  135229. 0
  135230. };
  135231. static long _vq_quantlist__44c9_s_p9_1[] = {
  135232. 9,
  135233. 8,
  135234. 10,
  135235. 7,
  135236. 11,
  135237. 6,
  135238. 12,
  135239. 5,
  135240. 13,
  135241. 4,
  135242. 14,
  135243. 3,
  135244. 15,
  135245. 2,
  135246. 16,
  135247. 1,
  135248. 17,
  135249. 0,
  135250. 18,
  135251. };
  135252. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135253. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135254. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135255. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135256. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135257. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135258. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135259. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135260. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135261. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135262. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135263. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135264. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135265. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135266. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135267. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135268. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135269. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135270. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135271. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135272. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135273. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135274. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135275. 13,13,13,14,13,14,15,15,15,
  135276. };
  135277. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135278. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135279. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135280. 367.5, 416.5,
  135281. };
  135282. static long _vq_quantmap__44c9_s_p9_1[] = {
  135283. 17, 15, 13, 11, 9, 7, 5, 3,
  135284. 1, 0, 2, 4, 6, 8, 10, 12,
  135285. 14, 16, 18,
  135286. };
  135287. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135288. _vq_quantthresh__44c9_s_p9_1,
  135289. _vq_quantmap__44c9_s_p9_1,
  135290. 19,
  135291. 19
  135292. };
  135293. static static_codebook _44c9_s_p9_1 = {
  135294. 2, 361,
  135295. _vq_lengthlist__44c9_s_p9_1,
  135296. 1, -518287360, 1622704128, 5, 0,
  135297. _vq_quantlist__44c9_s_p9_1,
  135298. NULL,
  135299. &_vq_auxt__44c9_s_p9_1,
  135300. NULL,
  135301. 0
  135302. };
  135303. static long _vq_quantlist__44c9_s_p9_2[] = {
  135304. 24,
  135305. 23,
  135306. 25,
  135307. 22,
  135308. 26,
  135309. 21,
  135310. 27,
  135311. 20,
  135312. 28,
  135313. 19,
  135314. 29,
  135315. 18,
  135316. 30,
  135317. 17,
  135318. 31,
  135319. 16,
  135320. 32,
  135321. 15,
  135322. 33,
  135323. 14,
  135324. 34,
  135325. 13,
  135326. 35,
  135327. 12,
  135328. 36,
  135329. 11,
  135330. 37,
  135331. 10,
  135332. 38,
  135333. 9,
  135334. 39,
  135335. 8,
  135336. 40,
  135337. 7,
  135338. 41,
  135339. 6,
  135340. 42,
  135341. 5,
  135342. 43,
  135343. 4,
  135344. 44,
  135345. 3,
  135346. 45,
  135347. 2,
  135348. 46,
  135349. 1,
  135350. 47,
  135351. 0,
  135352. 48,
  135353. };
  135354. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135355. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135356. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135357. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135358. 7,
  135359. };
  135360. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135361. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135362. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135363. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135364. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135365. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135366. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135367. };
  135368. static long _vq_quantmap__44c9_s_p9_2[] = {
  135369. 47, 45, 43, 41, 39, 37, 35, 33,
  135370. 31, 29, 27, 25, 23, 21, 19, 17,
  135371. 15, 13, 11, 9, 7, 5, 3, 1,
  135372. 0, 2, 4, 6, 8, 10, 12, 14,
  135373. 16, 18, 20, 22, 24, 26, 28, 30,
  135374. 32, 34, 36, 38, 40, 42, 44, 46,
  135375. 48,
  135376. };
  135377. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135378. _vq_quantthresh__44c9_s_p9_2,
  135379. _vq_quantmap__44c9_s_p9_2,
  135380. 49,
  135381. 49
  135382. };
  135383. static static_codebook _44c9_s_p9_2 = {
  135384. 1, 49,
  135385. _vq_lengthlist__44c9_s_p9_2,
  135386. 1, -526909440, 1611661312, 6, 0,
  135387. _vq_quantlist__44c9_s_p9_2,
  135388. NULL,
  135389. &_vq_auxt__44c9_s_p9_2,
  135390. NULL,
  135391. 0
  135392. };
  135393. static long _huff_lengthlist__44c9_s_short[] = {
  135394. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135395. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135396. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135397. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135398. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135399. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135400. 9, 8,10,13,
  135401. };
  135402. static static_codebook _huff_book__44c9_s_short = {
  135403. 2, 100,
  135404. _huff_lengthlist__44c9_s_short,
  135405. 0, 0, 0, 0, 0,
  135406. NULL,
  135407. NULL,
  135408. NULL,
  135409. NULL,
  135410. 0
  135411. };
  135412. static long _huff_lengthlist__44c0_s_long[] = {
  135413. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135414. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135415. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135416. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135417. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135418. 12,
  135419. };
  135420. static static_codebook _huff_book__44c0_s_long = {
  135421. 2, 81,
  135422. _huff_lengthlist__44c0_s_long,
  135423. 0, 0, 0, 0, 0,
  135424. NULL,
  135425. NULL,
  135426. NULL,
  135427. NULL,
  135428. 0
  135429. };
  135430. static long _vq_quantlist__44c0_s_p1_0[] = {
  135431. 1,
  135432. 0,
  135433. 2,
  135434. };
  135435. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135436. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135437. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135442. 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135447. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135482. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135487. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135492. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135528. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135533. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135538. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0,
  135847. };
  135848. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135849. -0.5, 0.5,
  135850. };
  135851. static long _vq_quantmap__44c0_s_p1_0[] = {
  135852. 1, 0, 2,
  135853. };
  135854. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135855. _vq_quantthresh__44c0_s_p1_0,
  135856. _vq_quantmap__44c0_s_p1_0,
  135857. 3,
  135858. 3
  135859. };
  135860. static static_codebook _44c0_s_p1_0 = {
  135861. 8, 6561,
  135862. _vq_lengthlist__44c0_s_p1_0,
  135863. 1, -535822336, 1611661312, 2, 0,
  135864. _vq_quantlist__44c0_s_p1_0,
  135865. NULL,
  135866. &_vq_auxt__44c0_s_p1_0,
  135867. NULL,
  135868. 0
  135869. };
  135870. static long _vq_quantlist__44c0_s_p2_0[] = {
  135871. 2,
  135872. 1,
  135873. 3,
  135874. 0,
  135875. 4,
  135876. };
  135877. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135878. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0,
  135918. };
  135919. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135920. -1.5, -0.5, 0.5, 1.5,
  135921. };
  135922. static long _vq_quantmap__44c0_s_p2_0[] = {
  135923. 3, 1, 0, 2, 4,
  135924. };
  135925. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135926. _vq_quantthresh__44c0_s_p2_0,
  135927. _vq_quantmap__44c0_s_p2_0,
  135928. 5,
  135929. 5
  135930. };
  135931. static static_codebook _44c0_s_p2_0 = {
  135932. 4, 625,
  135933. _vq_lengthlist__44c0_s_p2_0,
  135934. 1, -533725184, 1611661312, 3, 0,
  135935. _vq_quantlist__44c0_s_p2_0,
  135936. NULL,
  135937. &_vq_auxt__44c0_s_p2_0,
  135938. NULL,
  135939. 0
  135940. };
  135941. static long _vq_quantlist__44c0_s_p3_0[] = {
  135942. 4,
  135943. 3,
  135944. 5,
  135945. 2,
  135946. 6,
  135947. 1,
  135948. 7,
  135949. 0,
  135950. 8,
  135951. };
  135952. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135953. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135954. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135955. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135956. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135957. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0,
  135959. };
  135960. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135961. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135962. };
  135963. static long _vq_quantmap__44c0_s_p3_0[] = {
  135964. 7, 5, 3, 1, 0, 2, 4, 6,
  135965. 8,
  135966. };
  135967. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135968. _vq_quantthresh__44c0_s_p3_0,
  135969. _vq_quantmap__44c0_s_p3_0,
  135970. 9,
  135971. 9
  135972. };
  135973. static static_codebook _44c0_s_p3_0 = {
  135974. 2, 81,
  135975. _vq_lengthlist__44c0_s_p3_0,
  135976. 1, -531628032, 1611661312, 4, 0,
  135977. _vq_quantlist__44c0_s_p3_0,
  135978. NULL,
  135979. &_vq_auxt__44c0_s_p3_0,
  135980. NULL,
  135981. 0
  135982. };
  135983. static long _vq_quantlist__44c0_s_p4_0[] = {
  135984. 4,
  135985. 3,
  135986. 5,
  135987. 2,
  135988. 6,
  135989. 1,
  135990. 7,
  135991. 0,
  135992. 8,
  135993. };
  135994. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135995. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135996. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135997. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135998. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135999. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136000. 10,
  136001. };
  136002. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136004. };
  136005. static long _vq_quantmap__44c0_s_p4_0[] = {
  136006. 7, 5, 3, 1, 0, 2, 4, 6,
  136007. 8,
  136008. };
  136009. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136010. _vq_quantthresh__44c0_s_p4_0,
  136011. _vq_quantmap__44c0_s_p4_0,
  136012. 9,
  136013. 9
  136014. };
  136015. static static_codebook _44c0_s_p4_0 = {
  136016. 2, 81,
  136017. _vq_lengthlist__44c0_s_p4_0,
  136018. 1, -531628032, 1611661312, 4, 0,
  136019. _vq_quantlist__44c0_s_p4_0,
  136020. NULL,
  136021. &_vq_auxt__44c0_s_p4_0,
  136022. NULL,
  136023. 0
  136024. };
  136025. static long _vq_quantlist__44c0_s_p5_0[] = {
  136026. 8,
  136027. 7,
  136028. 9,
  136029. 6,
  136030. 10,
  136031. 5,
  136032. 11,
  136033. 4,
  136034. 12,
  136035. 3,
  136036. 13,
  136037. 2,
  136038. 14,
  136039. 1,
  136040. 15,
  136041. 0,
  136042. 16,
  136043. };
  136044. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136045. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136046. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136047. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136048. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136049. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136050. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136051. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136052. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136053. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136054. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136055. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136056. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136057. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136058. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136059. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136060. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136061. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136063. 14,
  136064. };
  136065. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136068. };
  136069. static long _vq_quantmap__44c0_s_p5_0[] = {
  136070. 15, 13, 11, 9, 7, 5, 3, 1,
  136071. 0, 2, 4, 6, 8, 10, 12, 14,
  136072. 16,
  136073. };
  136074. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136075. _vq_quantthresh__44c0_s_p5_0,
  136076. _vq_quantmap__44c0_s_p5_0,
  136077. 17,
  136078. 17
  136079. };
  136080. static static_codebook _44c0_s_p5_0 = {
  136081. 2, 289,
  136082. _vq_lengthlist__44c0_s_p5_0,
  136083. 1, -529530880, 1611661312, 5, 0,
  136084. _vq_quantlist__44c0_s_p5_0,
  136085. NULL,
  136086. &_vq_auxt__44c0_s_p5_0,
  136087. NULL,
  136088. 0
  136089. };
  136090. static long _vq_quantlist__44c0_s_p6_0[] = {
  136091. 1,
  136092. 0,
  136093. 2,
  136094. };
  136095. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136096. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136097. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136098. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136099. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136100. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136101. 10,
  136102. };
  136103. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136104. -5.5, 5.5,
  136105. };
  136106. static long _vq_quantmap__44c0_s_p6_0[] = {
  136107. 1, 0, 2,
  136108. };
  136109. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136110. _vq_quantthresh__44c0_s_p6_0,
  136111. _vq_quantmap__44c0_s_p6_0,
  136112. 3,
  136113. 3
  136114. };
  136115. static static_codebook _44c0_s_p6_0 = {
  136116. 4, 81,
  136117. _vq_lengthlist__44c0_s_p6_0,
  136118. 1, -529137664, 1618345984, 2, 0,
  136119. _vq_quantlist__44c0_s_p6_0,
  136120. NULL,
  136121. &_vq_auxt__44c0_s_p6_0,
  136122. NULL,
  136123. 0
  136124. };
  136125. static long _vq_quantlist__44c0_s_p6_1[] = {
  136126. 5,
  136127. 4,
  136128. 6,
  136129. 3,
  136130. 7,
  136131. 2,
  136132. 8,
  136133. 1,
  136134. 9,
  136135. 0,
  136136. 10,
  136137. };
  136138. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136139. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136140. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136141. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136142. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136143. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136144. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136145. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136146. 10,10,10, 8, 8, 8, 8, 8, 8,
  136147. };
  136148. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136149. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136150. 3.5, 4.5,
  136151. };
  136152. static long _vq_quantmap__44c0_s_p6_1[] = {
  136153. 9, 7, 5, 3, 1, 0, 2, 4,
  136154. 6, 8, 10,
  136155. };
  136156. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136157. _vq_quantthresh__44c0_s_p6_1,
  136158. _vq_quantmap__44c0_s_p6_1,
  136159. 11,
  136160. 11
  136161. };
  136162. static static_codebook _44c0_s_p6_1 = {
  136163. 2, 121,
  136164. _vq_lengthlist__44c0_s_p6_1,
  136165. 1, -531365888, 1611661312, 4, 0,
  136166. _vq_quantlist__44c0_s_p6_1,
  136167. NULL,
  136168. &_vq_auxt__44c0_s_p6_1,
  136169. NULL,
  136170. 0
  136171. };
  136172. static long _vq_quantlist__44c0_s_p7_0[] = {
  136173. 6,
  136174. 5,
  136175. 7,
  136176. 4,
  136177. 8,
  136178. 3,
  136179. 9,
  136180. 2,
  136181. 10,
  136182. 1,
  136183. 11,
  136184. 0,
  136185. 12,
  136186. };
  136187. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136188. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136189. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136190. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136191. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136192. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136193. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136194. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136195. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136196. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136197. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136198. 0,12,12,11,11,12,12,13,13,
  136199. };
  136200. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136201. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136202. 12.5, 17.5, 22.5, 27.5,
  136203. };
  136204. static long _vq_quantmap__44c0_s_p7_0[] = {
  136205. 11, 9, 7, 5, 3, 1, 0, 2,
  136206. 4, 6, 8, 10, 12,
  136207. };
  136208. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136209. _vq_quantthresh__44c0_s_p7_0,
  136210. _vq_quantmap__44c0_s_p7_0,
  136211. 13,
  136212. 13
  136213. };
  136214. static static_codebook _44c0_s_p7_0 = {
  136215. 2, 169,
  136216. _vq_lengthlist__44c0_s_p7_0,
  136217. 1, -526516224, 1616117760, 4, 0,
  136218. _vq_quantlist__44c0_s_p7_0,
  136219. NULL,
  136220. &_vq_auxt__44c0_s_p7_0,
  136221. NULL,
  136222. 0
  136223. };
  136224. static long _vq_quantlist__44c0_s_p7_1[] = {
  136225. 2,
  136226. 1,
  136227. 3,
  136228. 0,
  136229. 4,
  136230. };
  136231. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136232. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136233. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136234. };
  136235. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136236. -1.5, -0.5, 0.5, 1.5,
  136237. };
  136238. static long _vq_quantmap__44c0_s_p7_1[] = {
  136239. 3, 1, 0, 2, 4,
  136240. };
  136241. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136242. _vq_quantthresh__44c0_s_p7_1,
  136243. _vq_quantmap__44c0_s_p7_1,
  136244. 5,
  136245. 5
  136246. };
  136247. static static_codebook _44c0_s_p7_1 = {
  136248. 2, 25,
  136249. _vq_lengthlist__44c0_s_p7_1,
  136250. 1, -533725184, 1611661312, 3, 0,
  136251. _vq_quantlist__44c0_s_p7_1,
  136252. NULL,
  136253. &_vq_auxt__44c0_s_p7_1,
  136254. NULL,
  136255. 0
  136256. };
  136257. static long _vq_quantlist__44c0_s_p8_0[] = {
  136258. 2,
  136259. 1,
  136260. 3,
  136261. 0,
  136262. 4,
  136263. };
  136264. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136265. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136266. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136268. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136272. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136276. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136277. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136280. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136301. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136303. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136304. 11,
  136305. };
  136306. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136307. -331.5, -110.5, 110.5, 331.5,
  136308. };
  136309. static long _vq_quantmap__44c0_s_p8_0[] = {
  136310. 3, 1, 0, 2, 4,
  136311. };
  136312. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136313. _vq_quantthresh__44c0_s_p8_0,
  136314. _vq_quantmap__44c0_s_p8_0,
  136315. 5,
  136316. 5
  136317. };
  136318. static static_codebook _44c0_s_p8_0 = {
  136319. 4, 625,
  136320. _vq_lengthlist__44c0_s_p8_0,
  136321. 1, -518283264, 1627103232, 3, 0,
  136322. _vq_quantlist__44c0_s_p8_0,
  136323. NULL,
  136324. &_vq_auxt__44c0_s_p8_0,
  136325. NULL,
  136326. 0
  136327. };
  136328. static long _vq_quantlist__44c0_s_p8_1[] = {
  136329. 6,
  136330. 5,
  136331. 7,
  136332. 4,
  136333. 8,
  136334. 3,
  136335. 9,
  136336. 2,
  136337. 10,
  136338. 1,
  136339. 11,
  136340. 0,
  136341. 12,
  136342. };
  136343. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136344. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136345. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136346. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136347. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136348. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136349. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136350. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136351. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136352. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136353. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136354. 16,13,13,12,12,14,14,15,13,
  136355. };
  136356. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136357. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136358. 42.5, 59.5, 76.5, 93.5,
  136359. };
  136360. static long _vq_quantmap__44c0_s_p8_1[] = {
  136361. 11, 9, 7, 5, 3, 1, 0, 2,
  136362. 4, 6, 8, 10, 12,
  136363. };
  136364. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136365. _vq_quantthresh__44c0_s_p8_1,
  136366. _vq_quantmap__44c0_s_p8_1,
  136367. 13,
  136368. 13
  136369. };
  136370. static static_codebook _44c0_s_p8_1 = {
  136371. 2, 169,
  136372. _vq_lengthlist__44c0_s_p8_1,
  136373. 1, -522616832, 1620115456, 4, 0,
  136374. _vq_quantlist__44c0_s_p8_1,
  136375. NULL,
  136376. &_vq_auxt__44c0_s_p8_1,
  136377. NULL,
  136378. 0
  136379. };
  136380. static long _vq_quantlist__44c0_s_p8_2[] = {
  136381. 8,
  136382. 7,
  136383. 9,
  136384. 6,
  136385. 10,
  136386. 5,
  136387. 11,
  136388. 4,
  136389. 12,
  136390. 3,
  136391. 13,
  136392. 2,
  136393. 14,
  136394. 1,
  136395. 15,
  136396. 0,
  136397. 16,
  136398. };
  136399. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136400. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136401. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136402. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136403. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136404. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136405. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136406. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136407. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136408. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136409. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136410. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136411. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136412. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136413. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136414. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136415. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136416. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136417. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136418. 10,
  136419. };
  136420. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136421. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136422. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136423. };
  136424. static long _vq_quantmap__44c0_s_p8_2[] = {
  136425. 15, 13, 11, 9, 7, 5, 3, 1,
  136426. 0, 2, 4, 6, 8, 10, 12, 14,
  136427. 16,
  136428. };
  136429. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136430. _vq_quantthresh__44c0_s_p8_2,
  136431. _vq_quantmap__44c0_s_p8_2,
  136432. 17,
  136433. 17
  136434. };
  136435. static static_codebook _44c0_s_p8_2 = {
  136436. 2, 289,
  136437. _vq_lengthlist__44c0_s_p8_2,
  136438. 1, -529530880, 1611661312, 5, 0,
  136439. _vq_quantlist__44c0_s_p8_2,
  136440. NULL,
  136441. &_vq_auxt__44c0_s_p8_2,
  136442. NULL,
  136443. 0
  136444. };
  136445. static long _huff_lengthlist__44c0_s_short[] = {
  136446. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136447. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136448. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136449. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136450. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136451. 12,
  136452. };
  136453. static static_codebook _huff_book__44c0_s_short = {
  136454. 2, 81,
  136455. _huff_lengthlist__44c0_s_short,
  136456. 0, 0, 0, 0, 0,
  136457. NULL,
  136458. NULL,
  136459. NULL,
  136460. NULL,
  136461. 0
  136462. };
  136463. static long _huff_lengthlist__44c0_sm_long[] = {
  136464. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136465. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136466. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136467. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136468. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136469. 13,
  136470. };
  136471. static static_codebook _huff_book__44c0_sm_long = {
  136472. 2, 81,
  136473. _huff_lengthlist__44c0_sm_long,
  136474. 0, 0, 0, 0, 0,
  136475. NULL,
  136476. NULL,
  136477. NULL,
  136478. NULL,
  136479. 0
  136480. };
  136481. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136482. 1,
  136483. 0,
  136484. 2,
  136485. };
  136486. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136487. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136488. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136493. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136498. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136533. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136538. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136543. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136579. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136584. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136589. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0,
  136898. };
  136899. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136900. -0.5, 0.5,
  136901. };
  136902. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136903. 1, 0, 2,
  136904. };
  136905. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136906. _vq_quantthresh__44c0_sm_p1_0,
  136907. _vq_quantmap__44c0_sm_p1_0,
  136908. 3,
  136909. 3
  136910. };
  136911. static static_codebook _44c0_sm_p1_0 = {
  136912. 8, 6561,
  136913. _vq_lengthlist__44c0_sm_p1_0,
  136914. 1, -535822336, 1611661312, 2, 0,
  136915. _vq_quantlist__44c0_sm_p1_0,
  136916. NULL,
  136917. &_vq_auxt__44c0_sm_p1_0,
  136918. NULL,
  136919. 0
  136920. };
  136921. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136922. 2,
  136923. 1,
  136924. 3,
  136925. 0,
  136926. 4,
  136927. };
  136928. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136929. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0,
  136969. };
  136970. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136971. -1.5, -0.5, 0.5, 1.5,
  136972. };
  136973. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136974. 3, 1, 0, 2, 4,
  136975. };
  136976. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136977. _vq_quantthresh__44c0_sm_p2_0,
  136978. _vq_quantmap__44c0_sm_p2_0,
  136979. 5,
  136980. 5
  136981. };
  136982. static static_codebook _44c0_sm_p2_0 = {
  136983. 4, 625,
  136984. _vq_lengthlist__44c0_sm_p2_0,
  136985. 1, -533725184, 1611661312, 3, 0,
  136986. _vq_quantlist__44c0_sm_p2_0,
  136987. NULL,
  136988. &_vq_auxt__44c0_sm_p2_0,
  136989. NULL,
  136990. 0
  136991. };
  136992. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136993. 4,
  136994. 3,
  136995. 5,
  136996. 2,
  136997. 6,
  136998. 1,
  136999. 7,
  137000. 0,
  137001. 8,
  137002. };
  137003. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137004. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137005. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137006. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137007. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137008. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0,
  137010. };
  137011. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137012. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137013. };
  137014. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137015. 7, 5, 3, 1, 0, 2, 4, 6,
  137016. 8,
  137017. };
  137018. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137019. _vq_quantthresh__44c0_sm_p3_0,
  137020. _vq_quantmap__44c0_sm_p3_0,
  137021. 9,
  137022. 9
  137023. };
  137024. static static_codebook _44c0_sm_p3_0 = {
  137025. 2, 81,
  137026. _vq_lengthlist__44c0_sm_p3_0,
  137027. 1, -531628032, 1611661312, 4, 0,
  137028. _vq_quantlist__44c0_sm_p3_0,
  137029. NULL,
  137030. &_vq_auxt__44c0_sm_p3_0,
  137031. NULL,
  137032. 0
  137033. };
  137034. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137035. 4,
  137036. 3,
  137037. 5,
  137038. 2,
  137039. 6,
  137040. 1,
  137041. 7,
  137042. 0,
  137043. 8,
  137044. };
  137045. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137046. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137047. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137048. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137049. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137050. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137051. 11,
  137052. };
  137053. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137054. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137055. };
  137056. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137057. 7, 5, 3, 1, 0, 2, 4, 6,
  137058. 8,
  137059. };
  137060. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137061. _vq_quantthresh__44c0_sm_p4_0,
  137062. _vq_quantmap__44c0_sm_p4_0,
  137063. 9,
  137064. 9
  137065. };
  137066. static static_codebook _44c0_sm_p4_0 = {
  137067. 2, 81,
  137068. _vq_lengthlist__44c0_sm_p4_0,
  137069. 1, -531628032, 1611661312, 4, 0,
  137070. _vq_quantlist__44c0_sm_p4_0,
  137071. NULL,
  137072. &_vq_auxt__44c0_sm_p4_0,
  137073. NULL,
  137074. 0
  137075. };
  137076. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137077. 8,
  137078. 7,
  137079. 9,
  137080. 6,
  137081. 10,
  137082. 5,
  137083. 11,
  137084. 4,
  137085. 12,
  137086. 3,
  137087. 13,
  137088. 2,
  137089. 14,
  137090. 1,
  137091. 15,
  137092. 0,
  137093. 16,
  137094. };
  137095. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137096. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137097. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137098. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137099. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137100. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137101. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137102. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137103. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137104. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137105. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137106. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137107. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137108. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137109. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137110. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137111. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137112. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137114. 14,
  137115. };
  137116. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137117. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137118. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137119. };
  137120. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137121. 15, 13, 11, 9, 7, 5, 3, 1,
  137122. 0, 2, 4, 6, 8, 10, 12, 14,
  137123. 16,
  137124. };
  137125. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137126. _vq_quantthresh__44c0_sm_p5_0,
  137127. _vq_quantmap__44c0_sm_p5_0,
  137128. 17,
  137129. 17
  137130. };
  137131. static static_codebook _44c0_sm_p5_0 = {
  137132. 2, 289,
  137133. _vq_lengthlist__44c0_sm_p5_0,
  137134. 1, -529530880, 1611661312, 5, 0,
  137135. _vq_quantlist__44c0_sm_p5_0,
  137136. NULL,
  137137. &_vq_auxt__44c0_sm_p5_0,
  137138. NULL,
  137139. 0
  137140. };
  137141. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137142. 1,
  137143. 0,
  137144. 2,
  137145. };
  137146. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137147. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137148. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137149. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137150. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137151. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137152. 11,
  137153. };
  137154. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137155. -5.5, 5.5,
  137156. };
  137157. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137158. 1, 0, 2,
  137159. };
  137160. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137161. _vq_quantthresh__44c0_sm_p6_0,
  137162. _vq_quantmap__44c0_sm_p6_0,
  137163. 3,
  137164. 3
  137165. };
  137166. static static_codebook _44c0_sm_p6_0 = {
  137167. 4, 81,
  137168. _vq_lengthlist__44c0_sm_p6_0,
  137169. 1, -529137664, 1618345984, 2, 0,
  137170. _vq_quantlist__44c0_sm_p6_0,
  137171. NULL,
  137172. &_vq_auxt__44c0_sm_p6_0,
  137173. NULL,
  137174. 0
  137175. };
  137176. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137177. 5,
  137178. 4,
  137179. 6,
  137180. 3,
  137181. 7,
  137182. 2,
  137183. 8,
  137184. 1,
  137185. 9,
  137186. 0,
  137187. 10,
  137188. };
  137189. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137190. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137191. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137192. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137193. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137194. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137195. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137196. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137197. 10,10,10, 8, 8, 8, 8, 8, 8,
  137198. };
  137199. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137200. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137201. 3.5, 4.5,
  137202. };
  137203. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137204. 9, 7, 5, 3, 1, 0, 2, 4,
  137205. 6, 8, 10,
  137206. };
  137207. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137208. _vq_quantthresh__44c0_sm_p6_1,
  137209. _vq_quantmap__44c0_sm_p6_1,
  137210. 11,
  137211. 11
  137212. };
  137213. static static_codebook _44c0_sm_p6_1 = {
  137214. 2, 121,
  137215. _vq_lengthlist__44c0_sm_p6_1,
  137216. 1, -531365888, 1611661312, 4, 0,
  137217. _vq_quantlist__44c0_sm_p6_1,
  137218. NULL,
  137219. &_vq_auxt__44c0_sm_p6_1,
  137220. NULL,
  137221. 0
  137222. };
  137223. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137224. 6,
  137225. 5,
  137226. 7,
  137227. 4,
  137228. 8,
  137229. 3,
  137230. 9,
  137231. 2,
  137232. 10,
  137233. 1,
  137234. 11,
  137235. 0,
  137236. 12,
  137237. };
  137238. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137239. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137240. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137241. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137242. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137243. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137244. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137245. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137246. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137247. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137248. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137249. 0,12,12,11,11,13,12,14,14,
  137250. };
  137251. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137252. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137253. 12.5, 17.5, 22.5, 27.5,
  137254. };
  137255. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137256. 11, 9, 7, 5, 3, 1, 0, 2,
  137257. 4, 6, 8, 10, 12,
  137258. };
  137259. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137260. _vq_quantthresh__44c0_sm_p7_0,
  137261. _vq_quantmap__44c0_sm_p7_0,
  137262. 13,
  137263. 13
  137264. };
  137265. static static_codebook _44c0_sm_p7_0 = {
  137266. 2, 169,
  137267. _vq_lengthlist__44c0_sm_p7_0,
  137268. 1, -526516224, 1616117760, 4, 0,
  137269. _vq_quantlist__44c0_sm_p7_0,
  137270. NULL,
  137271. &_vq_auxt__44c0_sm_p7_0,
  137272. NULL,
  137273. 0
  137274. };
  137275. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137276. 2,
  137277. 1,
  137278. 3,
  137279. 0,
  137280. 4,
  137281. };
  137282. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137283. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137284. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137285. };
  137286. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137287. -1.5, -0.5, 0.5, 1.5,
  137288. };
  137289. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137290. 3, 1, 0, 2, 4,
  137291. };
  137292. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137293. _vq_quantthresh__44c0_sm_p7_1,
  137294. _vq_quantmap__44c0_sm_p7_1,
  137295. 5,
  137296. 5
  137297. };
  137298. static static_codebook _44c0_sm_p7_1 = {
  137299. 2, 25,
  137300. _vq_lengthlist__44c0_sm_p7_1,
  137301. 1, -533725184, 1611661312, 3, 0,
  137302. _vq_quantlist__44c0_sm_p7_1,
  137303. NULL,
  137304. &_vq_auxt__44c0_sm_p7_1,
  137305. NULL,
  137306. 0
  137307. };
  137308. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137309. 4,
  137310. 3,
  137311. 5,
  137312. 2,
  137313. 6,
  137314. 1,
  137315. 7,
  137316. 0,
  137317. 8,
  137318. };
  137319. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137320. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137321. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137322. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137323. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137324. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137325. 12,
  137326. };
  137327. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137328. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137329. };
  137330. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137331. 7, 5, 3, 1, 0, 2, 4, 6,
  137332. 8,
  137333. };
  137334. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137335. _vq_quantthresh__44c0_sm_p8_0,
  137336. _vq_quantmap__44c0_sm_p8_0,
  137337. 9,
  137338. 9
  137339. };
  137340. static static_codebook _44c0_sm_p8_0 = {
  137341. 2, 81,
  137342. _vq_lengthlist__44c0_sm_p8_0,
  137343. 1, -516186112, 1627103232, 4, 0,
  137344. _vq_quantlist__44c0_sm_p8_0,
  137345. NULL,
  137346. &_vq_auxt__44c0_sm_p8_0,
  137347. NULL,
  137348. 0
  137349. };
  137350. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137351. 6,
  137352. 5,
  137353. 7,
  137354. 4,
  137355. 8,
  137356. 3,
  137357. 9,
  137358. 2,
  137359. 10,
  137360. 1,
  137361. 11,
  137362. 0,
  137363. 12,
  137364. };
  137365. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137366. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137367. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137368. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137369. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137370. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137371. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137372. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137373. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137374. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137375. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137376. 20,13,13,12,12,16,13,15,13,
  137377. };
  137378. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137379. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137380. 42.5, 59.5, 76.5, 93.5,
  137381. };
  137382. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137383. 11, 9, 7, 5, 3, 1, 0, 2,
  137384. 4, 6, 8, 10, 12,
  137385. };
  137386. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137387. _vq_quantthresh__44c0_sm_p8_1,
  137388. _vq_quantmap__44c0_sm_p8_1,
  137389. 13,
  137390. 13
  137391. };
  137392. static static_codebook _44c0_sm_p8_1 = {
  137393. 2, 169,
  137394. _vq_lengthlist__44c0_sm_p8_1,
  137395. 1, -522616832, 1620115456, 4, 0,
  137396. _vq_quantlist__44c0_sm_p8_1,
  137397. NULL,
  137398. &_vq_auxt__44c0_sm_p8_1,
  137399. NULL,
  137400. 0
  137401. };
  137402. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137403. 8,
  137404. 7,
  137405. 9,
  137406. 6,
  137407. 10,
  137408. 5,
  137409. 11,
  137410. 4,
  137411. 12,
  137412. 3,
  137413. 13,
  137414. 2,
  137415. 14,
  137416. 1,
  137417. 15,
  137418. 0,
  137419. 16,
  137420. };
  137421. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137422. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137423. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137424. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137425. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137426. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137427. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137428. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137429. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137430. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137431. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137432. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137433. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137434. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137435. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137436. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137437. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137438. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137439. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137440. 9,
  137441. };
  137442. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137443. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137444. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137445. };
  137446. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137447. 15, 13, 11, 9, 7, 5, 3, 1,
  137448. 0, 2, 4, 6, 8, 10, 12, 14,
  137449. 16,
  137450. };
  137451. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137452. _vq_quantthresh__44c0_sm_p8_2,
  137453. _vq_quantmap__44c0_sm_p8_2,
  137454. 17,
  137455. 17
  137456. };
  137457. static static_codebook _44c0_sm_p8_2 = {
  137458. 2, 289,
  137459. _vq_lengthlist__44c0_sm_p8_2,
  137460. 1, -529530880, 1611661312, 5, 0,
  137461. _vq_quantlist__44c0_sm_p8_2,
  137462. NULL,
  137463. &_vq_auxt__44c0_sm_p8_2,
  137464. NULL,
  137465. 0
  137466. };
  137467. static long _huff_lengthlist__44c0_sm_short[] = {
  137468. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137469. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137470. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137471. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137472. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137473. 12,
  137474. };
  137475. static static_codebook _huff_book__44c0_sm_short = {
  137476. 2, 81,
  137477. _huff_lengthlist__44c0_sm_short,
  137478. 0, 0, 0, 0, 0,
  137479. NULL,
  137480. NULL,
  137481. NULL,
  137482. NULL,
  137483. 0
  137484. };
  137485. static long _huff_lengthlist__44c1_s_long[] = {
  137486. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137487. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137488. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137489. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137490. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137491. 11,
  137492. };
  137493. static static_codebook _huff_book__44c1_s_long = {
  137494. 2, 81,
  137495. _huff_lengthlist__44c1_s_long,
  137496. 0, 0, 0, 0, 0,
  137497. NULL,
  137498. NULL,
  137499. NULL,
  137500. NULL,
  137501. 0
  137502. };
  137503. static long _vq_quantlist__44c1_s_p1_0[] = {
  137504. 1,
  137505. 0,
  137506. 2,
  137507. };
  137508. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137509. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137510. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137515. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137520. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137555. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137560. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137565. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137601. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137606. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137611. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0,
  137920. };
  137921. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137922. -0.5, 0.5,
  137923. };
  137924. static long _vq_quantmap__44c1_s_p1_0[] = {
  137925. 1, 0, 2,
  137926. };
  137927. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137928. _vq_quantthresh__44c1_s_p1_0,
  137929. _vq_quantmap__44c1_s_p1_0,
  137930. 3,
  137931. 3
  137932. };
  137933. static static_codebook _44c1_s_p1_0 = {
  137934. 8, 6561,
  137935. _vq_lengthlist__44c1_s_p1_0,
  137936. 1, -535822336, 1611661312, 2, 0,
  137937. _vq_quantlist__44c1_s_p1_0,
  137938. NULL,
  137939. &_vq_auxt__44c1_s_p1_0,
  137940. NULL,
  137941. 0
  137942. };
  137943. static long _vq_quantlist__44c1_s_p2_0[] = {
  137944. 2,
  137945. 1,
  137946. 3,
  137947. 0,
  137948. 4,
  137949. };
  137950. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137951. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0,
  137991. };
  137992. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137993. -1.5, -0.5, 0.5, 1.5,
  137994. };
  137995. static long _vq_quantmap__44c1_s_p2_0[] = {
  137996. 3, 1, 0, 2, 4,
  137997. };
  137998. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137999. _vq_quantthresh__44c1_s_p2_0,
  138000. _vq_quantmap__44c1_s_p2_0,
  138001. 5,
  138002. 5
  138003. };
  138004. static static_codebook _44c1_s_p2_0 = {
  138005. 4, 625,
  138006. _vq_lengthlist__44c1_s_p2_0,
  138007. 1, -533725184, 1611661312, 3, 0,
  138008. _vq_quantlist__44c1_s_p2_0,
  138009. NULL,
  138010. &_vq_auxt__44c1_s_p2_0,
  138011. NULL,
  138012. 0
  138013. };
  138014. static long _vq_quantlist__44c1_s_p3_0[] = {
  138015. 4,
  138016. 3,
  138017. 5,
  138018. 2,
  138019. 6,
  138020. 1,
  138021. 7,
  138022. 0,
  138023. 8,
  138024. };
  138025. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138026. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138027. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138028. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138029. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138030. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0,
  138032. };
  138033. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138034. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138035. };
  138036. static long _vq_quantmap__44c1_s_p3_0[] = {
  138037. 7, 5, 3, 1, 0, 2, 4, 6,
  138038. 8,
  138039. };
  138040. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138041. _vq_quantthresh__44c1_s_p3_0,
  138042. _vq_quantmap__44c1_s_p3_0,
  138043. 9,
  138044. 9
  138045. };
  138046. static static_codebook _44c1_s_p3_0 = {
  138047. 2, 81,
  138048. _vq_lengthlist__44c1_s_p3_0,
  138049. 1, -531628032, 1611661312, 4, 0,
  138050. _vq_quantlist__44c1_s_p3_0,
  138051. NULL,
  138052. &_vq_auxt__44c1_s_p3_0,
  138053. NULL,
  138054. 0
  138055. };
  138056. static long _vq_quantlist__44c1_s_p4_0[] = {
  138057. 4,
  138058. 3,
  138059. 5,
  138060. 2,
  138061. 6,
  138062. 1,
  138063. 7,
  138064. 0,
  138065. 8,
  138066. };
  138067. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138068. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138069. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138070. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138071. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138072. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138073. 11,
  138074. };
  138075. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138076. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138077. };
  138078. static long _vq_quantmap__44c1_s_p4_0[] = {
  138079. 7, 5, 3, 1, 0, 2, 4, 6,
  138080. 8,
  138081. };
  138082. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138083. _vq_quantthresh__44c1_s_p4_0,
  138084. _vq_quantmap__44c1_s_p4_0,
  138085. 9,
  138086. 9
  138087. };
  138088. static static_codebook _44c1_s_p4_0 = {
  138089. 2, 81,
  138090. _vq_lengthlist__44c1_s_p4_0,
  138091. 1, -531628032, 1611661312, 4, 0,
  138092. _vq_quantlist__44c1_s_p4_0,
  138093. NULL,
  138094. &_vq_auxt__44c1_s_p4_0,
  138095. NULL,
  138096. 0
  138097. };
  138098. static long _vq_quantlist__44c1_s_p5_0[] = {
  138099. 8,
  138100. 7,
  138101. 9,
  138102. 6,
  138103. 10,
  138104. 5,
  138105. 11,
  138106. 4,
  138107. 12,
  138108. 3,
  138109. 13,
  138110. 2,
  138111. 14,
  138112. 1,
  138113. 15,
  138114. 0,
  138115. 16,
  138116. };
  138117. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138118. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138119. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138120. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138121. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138122. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138123. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138124. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138125. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138126. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138127. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138128. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138129. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138130. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138131. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138132. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138133. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138134. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138136. 14,
  138137. };
  138138. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138139. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138140. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138141. };
  138142. static long _vq_quantmap__44c1_s_p5_0[] = {
  138143. 15, 13, 11, 9, 7, 5, 3, 1,
  138144. 0, 2, 4, 6, 8, 10, 12, 14,
  138145. 16,
  138146. };
  138147. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138148. _vq_quantthresh__44c1_s_p5_0,
  138149. _vq_quantmap__44c1_s_p5_0,
  138150. 17,
  138151. 17
  138152. };
  138153. static static_codebook _44c1_s_p5_0 = {
  138154. 2, 289,
  138155. _vq_lengthlist__44c1_s_p5_0,
  138156. 1, -529530880, 1611661312, 5, 0,
  138157. _vq_quantlist__44c1_s_p5_0,
  138158. NULL,
  138159. &_vq_auxt__44c1_s_p5_0,
  138160. NULL,
  138161. 0
  138162. };
  138163. static long _vq_quantlist__44c1_s_p6_0[] = {
  138164. 1,
  138165. 0,
  138166. 2,
  138167. };
  138168. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138169. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138170. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138171. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138172. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138173. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138174. 11,
  138175. };
  138176. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138177. -5.5, 5.5,
  138178. };
  138179. static long _vq_quantmap__44c1_s_p6_0[] = {
  138180. 1, 0, 2,
  138181. };
  138182. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138183. _vq_quantthresh__44c1_s_p6_0,
  138184. _vq_quantmap__44c1_s_p6_0,
  138185. 3,
  138186. 3
  138187. };
  138188. static static_codebook _44c1_s_p6_0 = {
  138189. 4, 81,
  138190. _vq_lengthlist__44c1_s_p6_0,
  138191. 1, -529137664, 1618345984, 2, 0,
  138192. _vq_quantlist__44c1_s_p6_0,
  138193. NULL,
  138194. &_vq_auxt__44c1_s_p6_0,
  138195. NULL,
  138196. 0
  138197. };
  138198. static long _vq_quantlist__44c1_s_p6_1[] = {
  138199. 5,
  138200. 4,
  138201. 6,
  138202. 3,
  138203. 7,
  138204. 2,
  138205. 8,
  138206. 1,
  138207. 9,
  138208. 0,
  138209. 10,
  138210. };
  138211. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138212. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138213. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138214. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138215. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138216. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138217. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138218. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138219. 10,10,10, 8, 8, 8, 8, 8, 8,
  138220. };
  138221. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138222. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138223. 3.5, 4.5,
  138224. };
  138225. static long _vq_quantmap__44c1_s_p6_1[] = {
  138226. 9, 7, 5, 3, 1, 0, 2, 4,
  138227. 6, 8, 10,
  138228. };
  138229. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138230. _vq_quantthresh__44c1_s_p6_1,
  138231. _vq_quantmap__44c1_s_p6_1,
  138232. 11,
  138233. 11
  138234. };
  138235. static static_codebook _44c1_s_p6_1 = {
  138236. 2, 121,
  138237. _vq_lengthlist__44c1_s_p6_1,
  138238. 1, -531365888, 1611661312, 4, 0,
  138239. _vq_quantlist__44c1_s_p6_1,
  138240. NULL,
  138241. &_vq_auxt__44c1_s_p6_1,
  138242. NULL,
  138243. 0
  138244. };
  138245. static long _vq_quantlist__44c1_s_p7_0[] = {
  138246. 6,
  138247. 5,
  138248. 7,
  138249. 4,
  138250. 8,
  138251. 3,
  138252. 9,
  138253. 2,
  138254. 10,
  138255. 1,
  138256. 11,
  138257. 0,
  138258. 12,
  138259. };
  138260. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138261. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138262. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138263. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138264. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138265. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138266. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138267. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138268. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138269. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138270. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138271. 0,12,11,11,11,13,10,14,13,
  138272. };
  138273. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138274. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138275. 12.5, 17.5, 22.5, 27.5,
  138276. };
  138277. static long _vq_quantmap__44c1_s_p7_0[] = {
  138278. 11, 9, 7, 5, 3, 1, 0, 2,
  138279. 4, 6, 8, 10, 12,
  138280. };
  138281. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138282. _vq_quantthresh__44c1_s_p7_0,
  138283. _vq_quantmap__44c1_s_p7_0,
  138284. 13,
  138285. 13
  138286. };
  138287. static static_codebook _44c1_s_p7_0 = {
  138288. 2, 169,
  138289. _vq_lengthlist__44c1_s_p7_0,
  138290. 1, -526516224, 1616117760, 4, 0,
  138291. _vq_quantlist__44c1_s_p7_0,
  138292. NULL,
  138293. &_vq_auxt__44c1_s_p7_0,
  138294. NULL,
  138295. 0
  138296. };
  138297. static long _vq_quantlist__44c1_s_p7_1[] = {
  138298. 2,
  138299. 1,
  138300. 3,
  138301. 0,
  138302. 4,
  138303. };
  138304. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138305. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138306. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138307. };
  138308. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138309. -1.5, -0.5, 0.5, 1.5,
  138310. };
  138311. static long _vq_quantmap__44c1_s_p7_1[] = {
  138312. 3, 1, 0, 2, 4,
  138313. };
  138314. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138315. _vq_quantthresh__44c1_s_p7_1,
  138316. _vq_quantmap__44c1_s_p7_1,
  138317. 5,
  138318. 5
  138319. };
  138320. static static_codebook _44c1_s_p7_1 = {
  138321. 2, 25,
  138322. _vq_lengthlist__44c1_s_p7_1,
  138323. 1, -533725184, 1611661312, 3, 0,
  138324. _vq_quantlist__44c1_s_p7_1,
  138325. NULL,
  138326. &_vq_auxt__44c1_s_p7_1,
  138327. NULL,
  138328. 0
  138329. };
  138330. static long _vq_quantlist__44c1_s_p8_0[] = {
  138331. 6,
  138332. 5,
  138333. 7,
  138334. 4,
  138335. 8,
  138336. 3,
  138337. 9,
  138338. 2,
  138339. 10,
  138340. 1,
  138341. 11,
  138342. 0,
  138343. 12,
  138344. };
  138345. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138346. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138347. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138348. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138349. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138350. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138351. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138352. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138355. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138356. 10,10,10,10,10,10,10,10,10,
  138357. };
  138358. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138359. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138360. 552.5, 773.5, 994.5, 1215.5,
  138361. };
  138362. static long _vq_quantmap__44c1_s_p8_0[] = {
  138363. 11, 9, 7, 5, 3, 1, 0, 2,
  138364. 4, 6, 8, 10, 12,
  138365. };
  138366. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138367. _vq_quantthresh__44c1_s_p8_0,
  138368. _vq_quantmap__44c1_s_p8_0,
  138369. 13,
  138370. 13
  138371. };
  138372. static static_codebook _44c1_s_p8_0 = {
  138373. 2, 169,
  138374. _vq_lengthlist__44c1_s_p8_0,
  138375. 1, -514541568, 1627103232, 4, 0,
  138376. _vq_quantlist__44c1_s_p8_0,
  138377. NULL,
  138378. &_vq_auxt__44c1_s_p8_0,
  138379. NULL,
  138380. 0
  138381. };
  138382. static long _vq_quantlist__44c1_s_p8_1[] = {
  138383. 6,
  138384. 5,
  138385. 7,
  138386. 4,
  138387. 8,
  138388. 3,
  138389. 9,
  138390. 2,
  138391. 10,
  138392. 1,
  138393. 11,
  138394. 0,
  138395. 12,
  138396. };
  138397. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138398. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138399. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138400. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138401. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138402. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138403. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138404. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138405. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138406. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138407. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138408. 16,13,12,12,11,14,12,15,13,
  138409. };
  138410. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138411. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138412. 42.5, 59.5, 76.5, 93.5,
  138413. };
  138414. static long _vq_quantmap__44c1_s_p8_1[] = {
  138415. 11, 9, 7, 5, 3, 1, 0, 2,
  138416. 4, 6, 8, 10, 12,
  138417. };
  138418. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138419. _vq_quantthresh__44c1_s_p8_1,
  138420. _vq_quantmap__44c1_s_p8_1,
  138421. 13,
  138422. 13
  138423. };
  138424. static static_codebook _44c1_s_p8_1 = {
  138425. 2, 169,
  138426. _vq_lengthlist__44c1_s_p8_1,
  138427. 1, -522616832, 1620115456, 4, 0,
  138428. _vq_quantlist__44c1_s_p8_1,
  138429. NULL,
  138430. &_vq_auxt__44c1_s_p8_1,
  138431. NULL,
  138432. 0
  138433. };
  138434. static long _vq_quantlist__44c1_s_p8_2[] = {
  138435. 8,
  138436. 7,
  138437. 9,
  138438. 6,
  138439. 10,
  138440. 5,
  138441. 11,
  138442. 4,
  138443. 12,
  138444. 3,
  138445. 13,
  138446. 2,
  138447. 14,
  138448. 1,
  138449. 15,
  138450. 0,
  138451. 16,
  138452. };
  138453. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138454. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138455. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138456. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138457. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138458. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138459. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138460. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138461. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138462. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138463. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138464. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138465. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138466. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138467. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138468. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138469. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138470. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138471. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138472. 9,
  138473. };
  138474. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138475. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138476. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138477. };
  138478. static long _vq_quantmap__44c1_s_p8_2[] = {
  138479. 15, 13, 11, 9, 7, 5, 3, 1,
  138480. 0, 2, 4, 6, 8, 10, 12, 14,
  138481. 16,
  138482. };
  138483. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138484. _vq_quantthresh__44c1_s_p8_2,
  138485. _vq_quantmap__44c1_s_p8_2,
  138486. 17,
  138487. 17
  138488. };
  138489. static static_codebook _44c1_s_p8_2 = {
  138490. 2, 289,
  138491. _vq_lengthlist__44c1_s_p8_2,
  138492. 1, -529530880, 1611661312, 5, 0,
  138493. _vq_quantlist__44c1_s_p8_2,
  138494. NULL,
  138495. &_vq_auxt__44c1_s_p8_2,
  138496. NULL,
  138497. 0
  138498. };
  138499. static long _huff_lengthlist__44c1_s_short[] = {
  138500. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138501. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138502. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138503. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138504. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138505. 11,
  138506. };
  138507. static static_codebook _huff_book__44c1_s_short = {
  138508. 2, 81,
  138509. _huff_lengthlist__44c1_s_short,
  138510. 0, 0, 0, 0, 0,
  138511. NULL,
  138512. NULL,
  138513. NULL,
  138514. NULL,
  138515. 0
  138516. };
  138517. static long _huff_lengthlist__44c1_sm_long[] = {
  138518. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138519. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138520. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138521. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138522. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138523. 11,
  138524. };
  138525. static static_codebook _huff_book__44c1_sm_long = {
  138526. 2, 81,
  138527. _huff_lengthlist__44c1_sm_long,
  138528. 0, 0, 0, 0, 0,
  138529. NULL,
  138530. NULL,
  138531. NULL,
  138532. NULL,
  138533. 0
  138534. };
  138535. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138536. 1,
  138537. 0,
  138538. 2,
  138539. };
  138540. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138541. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138542. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138547. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138552. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138587. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138592. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138597. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138633. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138638. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138643. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0,
  138952. };
  138953. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138954. -0.5, 0.5,
  138955. };
  138956. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138957. 1, 0, 2,
  138958. };
  138959. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138960. _vq_quantthresh__44c1_sm_p1_0,
  138961. _vq_quantmap__44c1_sm_p1_0,
  138962. 3,
  138963. 3
  138964. };
  138965. static static_codebook _44c1_sm_p1_0 = {
  138966. 8, 6561,
  138967. _vq_lengthlist__44c1_sm_p1_0,
  138968. 1, -535822336, 1611661312, 2, 0,
  138969. _vq_quantlist__44c1_sm_p1_0,
  138970. NULL,
  138971. &_vq_auxt__44c1_sm_p1_0,
  138972. NULL,
  138973. 0
  138974. };
  138975. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138976. 2,
  138977. 1,
  138978. 3,
  138979. 0,
  138980. 4,
  138981. };
  138982. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138983. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0,
  139023. };
  139024. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139025. -1.5, -0.5, 0.5, 1.5,
  139026. };
  139027. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139028. 3, 1, 0, 2, 4,
  139029. };
  139030. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139031. _vq_quantthresh__44c1_sm_p2_0,
  139032. _vq_quantmap__44c1_sm_p2_0,
  139033. 5,
  139034. 5
  139035. };
  139036. static static_codebook _44c1_sm_p2_0 = {
  139037. 4, 625,
  139038. _vq_lengthlist__44c1_sm_p2_0,
  139039. 1, -533725184, 1611661312, 3, 0,
  139040. _vq_quantlist__44c1_sm_p2_0,
  139041. NULL,
  139042. &_vq_auxt__44c1_sm_p2_0,
  139043. NULL,
  139044. 0
  139045. };
  139046. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139047. 4,
  139048. 3,
  139049. 5,
  139050. 2,
  139051. 6,
  139052. 1,
  139053. 7,
  139054. 0,
  139055. 8,
  139056. };
  139057. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139058. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139059. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139060. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139061. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139062. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0,
  139064. };
  139065. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139066. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139067. };
  139068. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139069. 7, 5, 3, 1, 0, 2, 4, 6,
  139070. 8,
  139071. };
  139072. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139073. _vq_quantthresh__44c1_sm_p3_0,
  139074. _vq_quantmap__44c1_sm_p3_0,
  139075. 9,
  139076. 9
  139077. };
  139078. static static_codebook _44c1_sm_p3_0 = {
  139079. 2, 81,
  139080. _vq_lengthlist__44c1_sm_p3_0,
  139081. 1, -531628032, 1611661312, 4, 0,
  139082. _vq_quantlist__44c1_sm_p3_0,
  139083. NULL,
  139084. &_vq_auxt__44c1_sm_p3_0,
  139085. NULL,
  139086. 0
  139087. };
  139088. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139089. 4,
  139090. 3,
  139091. 5,
  139092. 2,
  139093. 6,
  139094. 1,
  139095. 7,
  139096. 0,
  139097. 8,
  139098. };
  139099. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139100. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139101. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139102. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139103. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139104. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139105. 11,
  139106. };
  139107. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139108. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139109. };
  139110. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139111. 7, 5, 3, 1, 0, 2, 4, 6,
  139112. 8,
  139113. };
  139114. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139115. _vq_quantthresh__44c1_sm_p4_0,
  139116. _vq_quantmap__44c1_sm_p4_0,
  139117. 9,
  139118. 9
  139119. };
  139120. static static_codebook _44c1_sm_p4_0 = {
  139121. 2, 81,
  139122. _vq_lengthlist__44c1_sm_p4_0,
  139123. 1, -531628032, 1611661312, 4, 0,
  139124. _vq_quantlist__44c1_sm_p4_0,
  139125. NULL,
  139126. &_vq_auxt__44c1_sm_p4_0,
  139127. NULL,
  139128. 0
  139129. };
  139130. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139131. 8,
  139132. 7,
  139133. 9,
  139134. 6,
  139135. 10,
  139136. 5,
  139137. 11,
  139138. 4,
  139139. 12,
  139140. 3,
  139141. 13,
  139142. 2,
  139143. 14,
  139144. 1,
  139145. 15,
  139146. 0,
  139147. 16,
  139148. };
  139149. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139150. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139151. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139152. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139153. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139154. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139155. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139156. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139157. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139158. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139159. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139160. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139161. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139162. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139163. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139164. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139165. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139166. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139168. 14,
  139169. };
  139170. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139171. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139172. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139173. };
  139174. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139175. 15, 13, 11, 9, 7, 5, 3, 1,
  139176. 0, 2, 4, 6, 8, 10, 12, 14,
  139177. 16,
  139178. };
  139179. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139180. _vq_quantthresh__44c1_sm_p5_0,
  139181. _vq_quantmap__44c1_sm_p5_0,
  139182. 17,
  139183. 17
  139184. };
  139185. static static_codebook _44c1_sm_p5_0 = {
  139186. 2, 289,
  139187. _vq_lengthlist__44c1_sm_p5_0,
  139188. 1, -529530880, 1611661312, 5, 0,
  139189. _vq_quantlist__44c1_sm_p5_0,
  139190. NULL,
  139191. &_vq_auxt__44c1_sm_p5_0,
  139192. NULL,
  139193. 0
  139194. };
  139195. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139196. 1,
  139197. 0,
  139198. 2,
  139199. };
  139200. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139201. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139202. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139203. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139204. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139205. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139206. 11,
  139207. };
  139208. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139209. -5.5, 5.5,
  139210. };
  139211. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139212. 1, 0, 2,
  139213. };
  139214. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139215. _vq_quantthresh__44c1_sm_p6_0,
  139216. _vq_quantmap__44c1_sm_p6_0,
  139217. 3,
  139218. 3
  139219. };
  139220. static static_codebook _44c1_sm_p6_0 = {
  139221. 4, 81,
  139222. _vq_lengthlist__44c1_sm_p6_0,
  139223. 1, -529137664, 1618345984, 2, 0,
  139224. _vq_quantlist__44c1_sm_p6_0,
  139225. NULL,
  139226. &_vq_auxt__44c1_sm_p6_0,
  139227. NULL,
  139228. 0
  139229. };
  139230. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139231. 5,
  139232. 4,
  139233. 6,
  139234. 3,
  139235. 7,
  139236. 2,
  139237. 8,
  139238. 1,
  139239. 9,
  139240. 0,
  139241. 10,
  139242. };
  139243. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139244. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139245. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139246. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139247. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139248. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139249. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139250. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139251. 10,10,10, 8, 8, 8, 8, 8, 8,
  139252. };
  139253. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139254. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139255. 3.5, 4.5,
  139256. };
  139257. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139258. 9, 7, 5, 3, 1, 0, 2, 4,
  139259. 6, 8, 10,
  139260. };
  139261. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139262. _vq_quantthresh__44c1_sm_p6_1,
  139263. _vq_quantmap__44c1_sm_p6_1,
  139264. 11,
  139265. 11
  139266. };
  139267. static static_codebook _44c1_sm_p6_1 = {
  139268. 2, 121,
  139269. _vq_lengthlist__44c1_sm_p6_1,
  139270. 1, -531365888, 1611661312, 4, 0,
  139271. _vq_quantlist__44c1_sm_p6_1,
  139272. NULL,
  139273. &_vq_auxt__44c1_sm_p6_1,
  139274. NULL,
  139275. 0
  139276. };
  139277. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139278. 6,
  139279. 5,
  139280. 7,
  139281. 4,
  139282. 8,
  139283. 3,
  139284. 9,
  139285. 2,
  139286. 10,
  139287. 1,
  139288. 11,
  139289. 0,
  139290. 12,
  139291. };
  139292. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139293. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139294. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139295. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139296. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139297. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139298. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139299. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139300. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139301. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139302. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139303. 0,12,12,11,11,13,12,14,13,
  139304. };
  139305. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139306. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139307. 12.5, 17.5, 22.5, 27.5,
  139308. };
  139309. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139310. 11, 9, 7, 5, 3, 1, 0, 2,
  139311. 4, 6, 8, 10, 12,
  139312. };
  139313. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139314. _vq_quantthresh__44c1_sm_p7_0,
  139315. _vq_quantmap__44c1_sm_p7_0,
  139316. 13,
  139317. 13
  139318. };
  139319. static static_codebook _44c1_sm_p7_0 = {
  139320. 2, 169,
  139321. _vq_lengthlist__44c1_sm_p7_0,
  139322. 1, -526516224, 1616117760, 4, 0,
  139323. _vq_quantlist__44c1_sm_p7_0,
  139324. NULL,
  139325. &_vq_auxt__44c1_sm_p7_0,
  139326. NULL,
  139327. 0
  139328. };
  139329. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139330. 2,
  139331. 1,
  139332. 3,
  139333. 0,
  139334. 4,
  139335. };
  139336. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139337. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139338. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139339. };
  139340. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139341. -1.5, -0.5, 0.5, 1.5,
  139342. };
  139343. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139344. 3, 1, 0, 2, 4,
  139345. };
  139346. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139347. _vq_quantthresh__44c1_sm_p7_1,
  139348. _vq_quantmap__44c1_sm_p7_1,
  139349. 5,
  139350. 5
  139351. };
  139352. static static_codebook _44c1_sm_p7_1 = {
  139353. 2, 25,
  139354. _vq_lengthlist__44c1_sm_p7_1,
  139355. 1, -533725184, 1611661312, 3, 0,
  139356. _vq_quantlist__44c1_sm_p7_1,
  139357. NULL,
  139358. &_vq_auxt__44c1_sm_p7_1,
  139359. NULL,
  139360. 0
  139361. };
  139362. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139363. 6,
  139364. 5,
  139365. 7,
  139366. 4,
  139367. 8,
  139368. 3,
  139369. 9,
  139370. 2,
  139371. 10,
  139372. 1,
  139373. 11,
  139374. 0,
  139375. 12,
  139376. };
  139377. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139378. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139379. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139380. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139381. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139382. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139383. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139384. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139385. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139386. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139387. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139388. 13,13,13,13,13,13,13,13,13,
  139389. };
  139390. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139391. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139392. 552.5, 773.5, 994.5, 1215.5,
  139393. };
  139394. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139395. 11, 9, 7, 5, 3, 1, 0, 2,
  139396. 4, 6, 8, 10, 12,
  139397. };
  139398. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139399. _vq_quantthresh__44c1_sm_p8_0,
  139400. _vq_quantmap__44c1_sm_p8_0,
  139401. 13,
  139402. 13
  139403. };
  139404. static static_codebook _44c1_sm_p8_0 = {
  139405. 2, 169,
  139406. _vq_lengthlist__44c1_sm_p8_0,
  139407. 1, -514541568, 1627103232, 4, 0,
  139408. _vq_quantlist__44c1_sm_p8_0,
  139409. NULL,
  139410. &_vq_auxt__44c1_sm_p8_0,
  139411. NULL,
  139412. 0
  139413. };
  139414. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139415. 6,
  139416. 5,
  139417. 7,
  139418. 4,
  139419. 8,
  139420. 3,
  139421. 9,
  139422. 2,
  139423. 10,
  139424. 1,
  139425. 11,
  139426. 0,
  139427. 12,
  139428. };
  139429. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139430. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139431. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139432. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139433. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139434. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139435. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139436. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139437. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139438. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139439. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139440. 20,13,12,12,12,14,12,14,13,
  139441. };
  139442. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139443. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139444. 42.5, 59.5, 76.5, 93.5,
  139445. };
  139446. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139447. 11, 9, 7, 5, 3, 1, 0, 2,
  139448. 4, 6, 8, 10, 12,
  139449. };
  139450. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139451. _vq_quantthresh__44c1_sm_p8_1,
  139452. _vq_quantmap__44c1_sm_p8_1,
  139453. 13,
  139454. 13
  139455. };
  139456. static static_codebook _44c1_sm_p8_1 = {
  139457. 2, 169,
  139458. _vq_lengthlist__44c1_sm_p8_1,
  139459. 1, -522616832, 1620115456, 4, 0,
  139460. _vq_quantlist__44c1_sm_p8_1,
  139461. NULL,
  139462. &_vq_auxt__44c1_sm_p8_1,
  139463. NULL,
  139464. 0
  139465. };
  139466. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139467. 8,
  139468. 7,
  139469. 9,
  139470. 6,
  139471. 10,
  139472. 5,
  139473. 11,
  139474. 4,
  139475. 12,
  139476. 3,
  139477. 13,
  139478. 2,
  139479. 14,
  139480. 1,
  139481. 15,
  139482. 0,
  139483. 16,
  139484. };
  139485. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139486. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139487. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139488. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139489. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139490. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139491. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139492. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139493. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139494. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139495. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139496. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139497. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139498. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139499. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139500. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139501. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139502. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139503. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139504. 9,
  139505. };
  139506. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139509. };
  139510. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139511. 15, 13, 11, 9, 7, 5, 3, 1,
  139512. 0, 2, 4, 6, 8, 10, 12, 14,
  139513. 16,
  139514. };
  139515. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139516. _vq_quantthresh__44c1_sm_p8_2,
  139517. _vq_quantmap__44c1_sm_p8_2,
  139518. 17,
  139519. 17
  139520. };
  139521. static static_codebook _44c1_sm_p8_2 = {
  139522. 2, 289,
  139523. _vq_lengthlist__44c1_sm_p8_2,
  139524. 1, -529530880, 1611661312, 5, 0,
  139525. _vq_quantlist__44c1_sm_p8_2,
  139526. NULL,
  139527. &_vq_auxt__44c1_sm_p8_2,
  139528. NULL,
  139529. 0
  139530. };
  139531. static long _huff_lengthlist__44c1_sm_short[] = {
  139532. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139533. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139534. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139535. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139536. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139537. 11,
  139538. };
  139539. static static_codebook _huff_book__44c1_sm_short = {
  139540. 2, 81,
  139541. _huff_lengthlist__44c1_sm_short,
  139542. 0, 0, 0, 0, 0,
  139543. NULL,
  139544. NULL,
  139545. NULL,
  139546. NULL,
  139547. 0
  139548. };
  139549. static long _huff_lengthlist__44cn1_s_long[] = {
  139550. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139551. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139552. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139553. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139554. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139555. 20,
  139556. };
  139557. static static_codebook _huff_book__44cn1_s_long = {
  139558. 2, 81,
  139559. _huff_lengthlist__44cn1_s_long,
  139560. 0, 0, 0, 0, 0,
  139561. NULL,
  139562. NULL,
  139563. NULL,
  139564. NULL,
  139565. 0
  139566. };
  139567. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139568. 1,
  139569. 0,
  139570. 2,
  139571. };
  139572. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139573. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139574. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139579. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139584. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139619. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139624. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139629. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139665. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139670. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139675. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0,
  139984. };
  139985. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139986. -0.5, 0.5,
  139987. };
  139988. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139989. 1, 0, 2,
  139990. };
  139991. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139992. _vq_quantthresh__44cn1_s_p1_0,
  139993. _vq_quantmap__44cn1_s_p1_0,
  139994. 3,
  139995. 3
  139996. };
  139997. static static_codebook _44cn1_s_p1_0 = {
  139998. 8, 6561,
  139999. _vq_lengthlist__44cn1_s_p1_0,
  140000. 1, -535822336, 1611661312, 2, 0,
  140001. _vq_quantlist__44cn1_s_p1_0,
  140002. NULL,
  140003. &_vq_auxt__44cn1_s_p1_0,
  140004. NULL,
  140005. 0
  140006. };
  140007. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140008. 2,
  140009. 1,
  140010. 3,
  140011. 0,
  140012. 4,
  140013. };
  140014. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140015. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0,
  140055. };
  140056. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140057. -1.5, -0.5, 0.5, 1.5,
  140058. };
  140059. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140060. 3, 1, 0, 2, 4,
  140061. };
  140062. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140063. _vq_quantthresh__44cn1_s_p2_0,
  140064. _vq_quantmap__44cn1_s_p2_0,
  140065. 5,
  140066. 5
  140067. };
  140068. static static_codebook _44cn1_s_p2_0 = {
  140069. 4, 625,
  140070. _vq_lengthlist__44cn1_s_p2_0,
  140071. 1, -533725184, 1611661312, 3, 0,
  140072. _vq_quantlist__44cn1_s_p2_0,
  140073. NULL,
  140074. &_vq_auxt__44cn1_s_p2_0,
  140075. NULL,
  140076. 0
  140077. };
  140078. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140079. 4,
  140080. 3,
  140081. 5,
  140082. 2,
  140083. 6,
  140084. 1,
  140085. 7,
  140086. 0,
  140087. 8,
  140088. };
  140089. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140090. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140091. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140092. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140093. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140094. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0,
  140096. };
  140097. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140098. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140099. };
  140100. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140101. 7, 5, 3, 1, 0, 2, 4, 6,
  140102. 8,
  140103. };
  140104. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140105. _vq_quantthresh__44cn1_s_p3_0,
  140106. _vq_quantmap__44cn1_s_p3_0,
  140107. 9,
  140108. 9
  140109. };
  140110. static static_codebook _44cn1_s_p3_0 = {
  140111. 2, 81,
  140112. _vq_lengthlist__44cn1_s_p3_0,
  140113. 1, -531628032, 1611661312, 4, 0,
  140114. _vq_quantlist__44cn1_s_p3_0,
  140115. NULL,
  140116. &_vq_auxt__44cn1_s_p3_0,
  140117. NULL,
  140118. 0
  140119. };
  140120. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140121. 4,
  140122. 3,
  140123. 5,
  140124. 2,
  140125. 6,
  140126. 1,
  140127. 7,
  140128. 0,
  140129. 8,
  140130. };
  140131. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140132. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140133. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140134. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140135. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140136. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140137. 11,
  140138. };
  140139. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140140. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140141. };
  140142. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140143. 7, 5, 3, 1, 0, 2, 4, 6,
  140144. 8,
  140145. };
  140146. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140147. _vq_quantthresh__44cn1_s_p4_0,
  140148. _vq_quantmap__44cn1_s_p4_0,
  140149. 9,
  140150. 9
  140151. };
  140152. static static_codebook _44cn1_s_p4_0 = {
  140153. 2, 81,
  140154. _vq_lengthlist__44cn1_s_p4_0,
  140155. 1, -531628032, 1611661312, 4, 0,
  140156. _vq_quantlist__44cn1_s_p4_0,
  140157. NULL,
  140158. &_vq_auxt__44cn1_s_p4_0,
  140159. NULL,
  140160. 0
  140161. };
  140162. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140163. 8,
  140164. 7,
  140165. 9,
  140166. 6,
  140167. 10,
  140168. 5,
  140169. 11,
  140170. 4,
  140171. 12,
  140172. 3,
  140173. 13,
  140174. 2,
  140175. 14,
  140176. 1,
  140177. 15,
  140178. 0,
  140179. 16,
  140180. };
  140181. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140182. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140183. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140184. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140185. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140186. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140187. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140188. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140189. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140190. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140191. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140192. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140193. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140194. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140195. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140196. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140197. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140198. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140200. 14,
  140201. };
  140202. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140203. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140204. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140205. };
  140206. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140207. 15, 13, 11, 9, 7, 5, 3, 1,
  140208. 0, 2, 4, 6, 8, 10, 12, 14,
  140209. 16,
  140210. };
  140211. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140212. _vq_quantthresh__44cn1_s_p5_0,
  140213. _vq_quantmap__44cn1_s_p5_0,
  140214. 17,
  140215. 17
  140216. };
  140217. static static_codebook _44cn1_s_p5_0 = {
  140218. 2, 289,
  140219. _vq_lengthlist__44cn1_s_p5_0,
  140220. 1, -529530880, 1611661312, 5, 0,
  140221. _vq_quantlist__44cn1_s_p5_0,
  140222. NULL,
  140223. &_vq_auxt__44cn1_s_p5_0,
  140224. NULL,
  140225. 0
  140226. };
  140227. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140228. 1,
  140229. 0,
  140230. 2,
  140231. };
  140232. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140233. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140234. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140235. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140236. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140237. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140238. 10,
  140239. };
  140240. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140241. -5.5, 5.5,
  140242. };
  140243. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140244. 1, 0, 2,
  140245. };
  140246. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140247. _vq_quantthresh__44cn1_s_p6_0,
  140248. _vq_quantmap__44cn1_s_p6_0,
  140249. 3,
  140250. 3
  140251. };
  140252. static static_codebook _44cn1_s_p6_0 = {
  140253. 4, 81,
  140254. _vq_lengthlist__44cn1_s_p6_0,
  140255. 1, -529137664, 1618345984, 2, 0,
  140256. _vq_quantlist__44cn1_s_p6_0,
  140257. NULL,
  140258. &_vq_auxt__44cn1_s_p6_0,
  140259. NULL,
  140260. 0
  140261. };
  140262. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140263. 5,
  140264. 4,
  140265. 6,
  140266. 3,
  140267. 7,
  140268. 2,
  140269. 8,
  140270. 1,
  140271. 9,
  140272. 0,
  140273. 10,
  140274. };
  140275. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140276. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140277. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140278. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140279. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140280. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140281. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140282. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140283. 10,10,10, 9, 9, 9, 9, 9, 9,
  140284. };
  140285. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140286. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140287. 3.5, 4.5,
  140288. };
  140289. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140290. 9, 7, 5, 3, 1, 0, 2, 4,
  140291. 6, 8, 10,
  140292. };
  140293. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140294. _vq_quantthresh__44cn1_s_p6_1,
  140295. _vq_quantmap__44cn1_s_p6_1,
  140296. 11,
  140297. 11
  140298. };
  140299. static static_codebook _44cn1_s_p6_1 = {
  140300. 2, 121,
  140301. _vq_lengthlist__44cn1_s_p6_1,
  140302. 1, -531365888, 1611661312, 4, 0,
  140303. _vq_quantlist__44cn1_s_p6_1,
  140304. NULL,
  140305. &_vq_auxt__44cn1_s_p6_1,
  140306. NULL,
  140307. 0
  140308. };
  140309. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140310. 6,
  140311. 5,
  140312. 7,
  140313. 4,
  140314. 8,
  140315. 3,
  140316. 9,
  140317. 2,
  140318. 10,
  140319. 1,
  140320. 11,
  140321. 0,
  140322. 12,
  140323. };
  140324. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140325. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140326. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140327. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140328. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140329. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140330. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140331. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140332. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140333. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140334. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140335. 0,13,13,12,12,13,13,13,14,
  140336. };
  140337. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140338. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140339. 12.5, 17.5, 22.5, 27.5,
  140340. };
  140341. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140342. 11, 9, 7, 5, 3, 1, 0, 2,
  140343. 4, 6, 8, 10, 12,
  140344. };
  140345. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140346. _vq_quantthresh__44cn1_s_p7_0,
  140347. _vq_quantmap__44cn1_s_p7_0,
  140348. 13,
  140349. 13
  140350. };
  140351. static static_codebook _44cn1_s_p7_0 = {
  140352. 2, 169,
  140353. _vq_lengthlist__44cn1_s_p7_0,
  140354. 1, -526516224, 1616117760, 4, 0,
  140355. _vq_quantlist__44cn1_s_p7_0,
  140356. NULL,
  140357. &_vq_auxt__44cn1_s_p7_0,
  140358. NULL,
  140359. 0
  140360. };
  140361. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140362. 2,
  140363. 1,
  140364. 3,
  140365. 0,
  140366. 4,
  140367. };
  140368. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140369. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140370. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140371. };
  140372. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140373. -1.5, -0.5, 0.5, 1.5,
  140374. };
  140375. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140376. 3, 1, 0, 2, 4,
  140377. };
  140378. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140379. _vq_quantthresh__44cn1_s_p7_1,
  140380. _vq_quantmap__44cn1_s_p7_1,
  140381. 5,
  140382. 5
  140383. };
  140384. static static_codebook _44cn1_s_p7_1 = {
  140385. 2, 25,
  140386. _vq_lengthlist__44cn1_s_p7_1,
  140387. 1, -533725184, 1611661312, 3, 0,
  140388. _vq_quantlist__44cn1_s_p7_1,
  140389. NULL,
  140390. &_vq_auxt__44cn1_s_p7_1,
  140391. NULL,
  140392. 0
  140393. };
  140394. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140395. 2,
  140396. 1,
  140397. 3,
  140398. 0,
  140399. 4,
  140400. };
  140401. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140402. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140403. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140405. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140408. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140409. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140411. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140414. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140415. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140416. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140417. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140419. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140420. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140421. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140422. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140423. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140424. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140425. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140426. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140427. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140428. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140429. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140430. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140431. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140432. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140433. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140434. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140435. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140436. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140437. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140438. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140439. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140440. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140441. 12,
  140442. };
  140443. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140444. -331.5, -110.5, 110.5, 331.5,
  140445. };
  140446. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140447. 3, 1, 0, 2, 4,
  140448. };
  140449. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140450. _vq_quantthresh__44cn1_s_p8_0,
  140451. _vq_quantmap__44cn1_s_p8_0,
  140452. 5,
  140453. 5
  140454. };
  140455. static static_codebook _44cn1_s_p8_0 = {
  140456. 4, 625,
  140457. _vq_lengthlist__44cn1_s_p8_0,
  140458. 1, -518283264, 1627103232, 3, 0,
  140459. _vq_quantlist__44cn1_s_p8_0,
  140460. NULL,
  140461. &_vq_auxt__44cn1_s_p8_0,
  140462. NULL,
  140463. 0
  140464. };
  140465. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140466. 6,
  140467. 5,
  140468. 7,
  140469. 4,
  140470. 8,
  140471. 3,
  140472. 9,
  140473. 2,
  140474. 10,
  140475. 1,
  140476. 11,
  140477. 0,
  140478. 12,
  140479. };
  140480. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140481. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140482. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140483. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140484. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140485. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140486. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140487. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140488. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140489. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140490. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140491. 15,12,12,11,11,14,12,13,14,
  140492. };
  140493. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140494. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140495. 42.5, 59.5, 76.5, 93.5,
  140496. };
  140497. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140498. 11, 9, 7, 5, 3, 1, 0, 2,
  140499. 4, 6, 8, 10, 12,
  140500. };
  140501. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140502. _vq_quantthresh__44cn1_s_p8_1,
  140503. _vq_quantmap__44cn1_s_p8_1,
  140504. 13,
  140505. 13
  140506. };
  140507. static static_codebook _44cn1_s_p8_1 = {
  140508. 2, 169,
  140509. _vq_lengthlist__44cn1_s_p8_1,
  140510. 1, -522616832, 1620115456, 4, 0,
  140511. _vq_quantlist__44cn1_s_p8_1,
  140512. NULL,
  140513. &_vq_auxt__44cn1_s_p8_1,
  140514. NULL,
  140515. 0
  140516. };
  140517. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140518. 8,
  140519. 7,
  140520. 9,
  140521. 6,
  140522. 10,
  140523. 5,
  140524. 11,
  140525. 4,
  140526. 12,
  140527. 3,
  140528. 13,
  140529. 2,
  140530. 14,
  140531. 1,
  140532. 15,
  140533. 0,
  140534. 16,
  140535. };
  140536. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140537. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140538. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140539. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140540. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140541. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140542. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140543. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140544. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140545. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140546. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140547. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140548. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140549. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140550. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140551. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140552. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140553. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140554. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140555. 9,
  140556. };
  140557. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140560. };
  140561. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140562. 15, 13, 11, 9, 7, 5, 3, 1,
  140563. 0, 2, 4, 6, 8, 10, 12, 14,
  140564. 16,
  140565. };
  140566. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140567. _vq_quantthresh__44cn1_s_p8_2,
  140568. _vq_quantmap__44cn1_s_p8_2,
  140569. 17,
  140570. 17
  140571. };
  140572. static static_codebook _44cn1_s_p8_2 = {
  140573. 2, 289,
  140574. _vq_lengthlist__44cn1_s_p8_2,
  140575. 1, -529530880, 1611661312, 5, 0,
  140576. _vq_quantlist__44cn1_s_p8_2,
  140577. NULL,
  140578. &_vq_auxt__44cn1_s_p8_2,
  140579. NULL,
  140580. 0
  140581. };
  140582. static long _huff_lengthlist__44cn1_s_short[] = {
  140583. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140584. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140585. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140586. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140587. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140588. 10,
  140589. };
  140590. static static_codebook _huff_book__44cn1_s_short = {
  140591. 2, 81,
  140592. _huff_lengthlist__44cn1_s_short,
  140593. 0, 0, 0, 0, 0,
  140594. NULL,
  140595. NULL,
  140596. NULL,
  140597. NULL,
  140598. 0
  140599. };
  140600. static long _huff_lengthlist__44cn1_sm_long[] = {
  140601. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140602. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140603. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140604. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140605. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140606. 17,
  140607. };
  140608. static static_codebook _huff_book__44cn1_sm_long = {
  140609. 2, 81,
  140610. _huff_lengthlist__44cn1_sm_long,
  140611. 0, 0, 0, 0, 0,
  140612. NULL,
  140613. NULL,
  140614. NULL,
  140615. NULL,
  140616. 0
  140617. };
  140618. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140619. 1,
  140620. 0,
  140621. 2,
  140622. };
  140623. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140624. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140625. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140630. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140635. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140670. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140675. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140680. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140716. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140721. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140726. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0,
  141035. };
  141036. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141037. -0.5, 0.5,
  141038. };
  141039. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141040. 1, 0, 2,
  141041. };
  141042. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141043. _vq_quantthresh__44cn1_sm_p1_0,
  141044. _vq_quantmap__44cn1_sm_p1_0,
  141045. 3,
  141046. 3
  141047. };
  141048. static static_codebook _44cn1_sm_p1_0 = {
  141049. 8, 6561,
  141050. _vq_lengthlist__44cn1_sm_p1_0,
  141051. 1, -535822336, 1611661312, 2, 0,
  141052. _vq_quantlist__44cn1_sm_p1_0,
  141053. NULL,
  141054. &_vq_auxt__44cn1_sm_p1_0,
  141055. NULL,
  141056. 0
  141057. };
  141058. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141059. 2,
  141060. 1,
  141061. 3,
  141062. 0,
  141063. 4,
  141064. };
  141065. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141066. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0,
  141106. };
  141107. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141108. -1.5, -0.5, 0.5, 1.5,
  141109. };
  141110. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141111. 3, 1, 0, 2, 4,
  141112. };
  141113. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141114. _vq_quantthresh__44cn1_sm_p2_0,
  141115. _vq_quantmap__44cn1_sm_p2_0,
  141116. 5,
  141117. 5
  141118. };
  141119. static static_codebook _44cn1_sm_p2_0 = {
  141120. 4, 625,
  141121. _vq_lengthlist__44cn1_sm_p2_0,
  141122. 1, -533725184, 1611661312, 3, 0,
  141123. _vq_quantlist__44cn1_sm_p2_0,
  141124. NULL,
  141125. &_vq_auxt__44cn1_sm_p2_0,
  141126. NULL,
  141127. 0
  141128. };
  141129. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141130. 4,
  141131. 3,
  141132. 5,
  141133. 2,
  141134. 6,
  141135. 1,
  141136. 7,
  141137. 0,
  141138. 8,
  141139. };
  141140. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141141. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141142. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141143. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141144. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141145. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0,
  141147. };
  141148. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141149. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141150. };
  141151. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141152. 7, 5, 3, 1, 0, 2, 4, 6,
  141153. 8,
  141154. };
  141155. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141156. _vq_quantthresh__44cn1_sm_p3_0,
  141157. _vq_quantmap__44cn1_sm_p3_0,
  141158. 9,
  141159. 9
  141160. };
  141161. static static_codebook _44cn1_sm_p3_0 = {
  141162. 2, 81,
  141163. _vq_lengthlist__44cn1_sm_p3_0,
  141164. 1, -531628032, 1611661312, 4, 0,
  141165. _vq_quantlist__44cn1_sm_p3_0,
  141166. NULL,
  141167. &_vq_auxt__44cn1_sm_p3_0,
  141168. NULL,
  141169. 0
  141170. };
  141171. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141172. 4,
  141173. 3,
  141174. 5,
  141175. 2,
  141176. 6,
  141177. 1,
  141178. 7,
  141179. 0,
  141180. 8,
  141181. };
  141182. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141183. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141184. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141185. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141186. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141187. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141188. 11,
  141189. };
  141190. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141192. };
  141193. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141194. 7, 5, 3, 1, 0, 2, 4, 6,
  141195. 8,
  141196. };
  141197. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141198. _vq_quantthresh__44cn1_sm_p4_0,
  141199. _vq_quantmap__44cn1_sm_p4_0,
  141200. 9,
  141201. 9
  141202. };
  141203. static static_codebook _44cn1_sm_p4_0 = {
  141204. 2, 81,
  141205. _vq_lengthlist__44cn1_sm_p4_0,
  141206. 1, -531628032, 1611661312, 4, 0,
  141207. _vq_quantlist__44cn1_sm_p4_0,
  141208. NULL,
  141209. &_vq_auxt__44cn1_sm_p4_0,
  141210. NULL,
  141211. 0
  141212. };
  141213. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141214. 8,
  141215. 7,
  141216. 9,
  141217. 6,
  141218. 10,
  141219. 5,
  141220. 11,
  141221. 4,
  141222. 12,
  141223. 3,
  141224. 13,
  141225. 2,
  141226. 14,
  141227. 1,
  141228. 15,
  141229. 0,
  141230. 16,
  141231. };
  141232. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141233. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141234. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141235. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141236. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141237. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141238. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141239. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141240. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141241. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141242. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141243. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141244. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141245. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141246. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141247. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141248. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141249. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141251. 14,
  141252. };
  141253. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141256. };
  141257. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141258. 15, 13, 11, 9, 7, 5, 3, 1,
  141259. 0, 2, 4, 6, 8, 10, 12, 14,
  141260. 16,
  141261. };
  141262. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141263. _vq_quantthresh__44cn1_sm_p5_0,
  141264. _vq_quantmap__44cn1_sm_p5_0,
  141265. 17,
  141266. 17
  141267. };
  141268. static static_codebook _44cn1_sm_p5_0 = {
  141269. 2, 289,
  141270. _vq_lengthlist__44cn1_sm_p5_0,
  141271. 1, -529530880, 1611661312, 5, 0,
  141272. _vq_quantlist__44cn1_sm_p5_0,
  141273. NULL,
  141274. &_vq_auxt__44cn1_sm_p5_0,
  141275. NULL,
  141276. 0
  141277. };
  141278. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141279. 1,
  141280. 0,
  141281. 2,
  141282. };
  141283. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141284. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141285. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141286. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141287. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141288. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141289. 10,
  141290. };
  141291. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141292. -5.5, 5.5,
  141293. };
  141294. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141295. 1, 0, 2,
  141296. };
  141297. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141298. _vq_quantthresh__44cn1_sm_p6_0,
  141299. _vq_quantmap__44cn1_sm_p6_0,
  141300. 3,
  141301. 3
  141302. };
  141303. static static_codebook _44cn1_sm_p6_0 = {
  141304. 4, 81,
  141305. _vq_lengthlist__44cn1_sm_p6_0,
  141306. 1, -529137664, 1618345984, 2, 0,
  141307. _vq_quantlist__44cn1_sm_p6_0,
  141308. NULL,
  141309. &_vq_auxt__44cn1_sm_p6_0,
  141310. NULL,
  141311. 0
  141312. };
  141313. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141314. 5,
  141315. 4,
  141316. 6,
  141317. 3,
  141318. 7,
  141319. 2,
  141320. 8,
  141321. 1,
  141322. 9,
  141323. 0,
  141324. 10,
  141325. };
  141326. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141327. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141328. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141329. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141330. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141331. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141332. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141333. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141334. 10,10,10, 8, 9, 8, 8, 9, 8,
  141335. };
  141336. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141337. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141338. 3.5, 4.5,
  141339. };
  141340. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141341. 9, 7, 5, 3, 1, 0, 2, 4,
  141342. 6, 8, 10,
  141343. };
  141344. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141345. _vq_quantthresh__44cn1_sm_p6_1,
  141346. _vq_quantmap__44cn1_sm_p6_1,
  141347. 11,
  141348. 11
  141349. };
  141350. static static_codebook _44cn1_sm_p6_1 = {
  141351. 2, 121,
  141352. _vq_lengthlist__44cn1_sm_p6_1,
  141353. 1, -531365888, 1611661312, 4, 0,
  141354. _vq_quantlist__44cn1_sm_p6_1,
  141355. NULL,
  141356. &_vq_auxt__44cn1_sm_p6_1,
  141357. NULL,
  141358. 0
  141359. };
  141360. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141361. 6,
  141362. 5,
  141363. 7,
  141364. 4,
  141365. 8,
  141366. 3,
  141367. 9,
  141368. 2,
  141369. 10,
  141370. 1,
  141371. 11,
  141372. 0,
  141373. 12,
  141374. };
  141375. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141376. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141377. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141378. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141379. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141380. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141381. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141382. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141383. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141384. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141385. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141386. 0,13,12,12,12,13,13,13,14,
  141387. };
  141388. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141389. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141390. 12.5, 17.5, 22.5, 27.5,
  141391. };
  141392. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141393. 11, 9, 7, 5, 3, 1, 0, 2,
  141394. 4, 6, 8, 10, 12,
  141395. };
  141396. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141397. _vq_quantthresh__44cn1_sm_p7_0,
  141398. _vq_quantmap__44cn1_sm_p7_0,
  141399. 13,
  141400. 13
  141401. };
  141402. static static_codebook _44cn1_sm_p7_0 = {
  141403. 2, 169,
  141404. _vq_lengthlist__44cn1_sm_p7_0,
  141405. 1, -526516224, 1616117760, 4, 0,
  141406. _vq_quantlist__44cn1_sm_p7_0,
  141407. NULL,
  141408. &_vq_auxt__44cn1_sm_p7_0,
  141409. NULL,
  141410. 0
  141411. };
  141412. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141413. 2,
  141414. 1,
  141415. 3,
  141416. 0,
  141417. 4,
  141418. };
  141419. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141420. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141421. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141422. };
  141423. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141424. -1.5, -0.5, 0.5, 1.5,
  141425. };
  141426. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141427. 3, 1, 0, 2, 4,
  141428. };
  141429. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141430. _vq_quantthresh__44cn1_sm_p7_1,
  141431. _vq_quantmap__44cn1_sm_p7_1,
  141432. 5,
  141433. 5
  141434. };
  141435. static static_codebook _44cn1_sm_p7_1 = {
  141436. 2, 25,
  141437. _vq_lengthlist__44cn1_sm_p7_1,
  141438. 1, -533725184, 1611661312, 3, 0,
  141439. _vq_quantlist__44cn1_sm_p7_1,
  141440. NULL,
  141441. &_vq_auxt__44cn1_sm_p7_1,
  141442. NULL,
  141443. 0
  141444. };
  141445. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141446. 4,
  141447. 3,
  141448. 5,
  141449. 2,
  141450. 6,
  141451. 1,
  141452. 7,
  141453. 0,
  141454. 8,
  141455. };
  141456. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141457. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141458. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141459. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141460. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141461. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141462. 14,
  141463. };
  141464. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141465. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141466. };
  141467. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141468. 7, 5, 3, 1, 0, 2, 4, 6,
  141469. 8,
  141470. };
  141471. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141472. _vq_quantthresh__44cn1_sm_p8_0,
  141473. _vq_quantmap__44cn1_sm_p8_0,
  141474. 9,
  141475. 9
  141476. };
  141477. static static_codebook _44cn1_sm_p8_0 = {
  141478. 2, 81,
  141479. _vq_lengthlist__44cn1_sm_p8_0,
  141480. 1, -516186112, 1627103232, 4, 0,
  141481. _vq_quantlist__44cn1_sm_p8_0,
  141482. NULL,
  141483. &_vq_auxt__44cn1_sm_p8_0,
  141484. NULL,
  141485. 0
  141486. };
  141487. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141488. 6,
  141489. 5,
  141490. 7,
  141491. 4,
  141492. 8,
  141493. 3,
  141494. 9,
  141495. 2,
  141496. 10,
  141497. 1,
  141498. 11,
  141499. 0,
  141500. 12,
  141501. };
  141502. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141503. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141504. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141505. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141506. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141507. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141508. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141509. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141510. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141511. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141512. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141513. 17,12,12,11,10,13,11,13,13,
  141514. };
  141515. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141516. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141517. 42.5, 59.5, 76.5, 93.5,
  141518. };
  141519. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141520. 11, 9, 7, 5, 3, 1, 0, 2,
  141521. 4, 6, 8, 10, 12,
  141522. };
  141523. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141524. _vq_quantthresh__44cn1_sm_p8_1,
  141525. _vq_quantmap__44cn1_sm_p8_1,
  141526. 13,
  141527. 13
  141528. };
  141529. static static_codebook _44cn1_sm_p8_1 = {
  141530. 2, 169,
  141531. _vq_lengthlist__44cn1_sm_p8_1,
  141532. 1, -522616832, 1620115456, 4, 0,
  141533. _vq_quantlist__44cn1_sm_p8_1,
  141534. NULL,
  141535. &_vq_auxt__44cn1_sm_p8_1,
  141536. NULL,
  141537. 0
  141538. };
  141539. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141540. 8,
  141541. 7,
  141542. 9,
  141543. 6,
  141544. 10,
  141545. 5,
  141546. 11,
  141547. 4,
  141548. 12,
  141549. 3,
  141550. 13,
  141551. 2,
  141552. 14,
  141553. 1,
  141554. 15,
  141555. 0,
  141556. 16,
  141557. };
  141558. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141559. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141560. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141561. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141562. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141563. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141564. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141565. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141566. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141567. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141568. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141569. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141570. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141571. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141572. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141573. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141574. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141575. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141576. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141577. 9,
  141578. };
  141579. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141580. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141581. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141582. };
  141583. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141584. 15, 13, 11, 9, 7, 5, 3, 1,
  141585. 0, 2, 4, 6, 8, 10, 12, 14,
  141586. 16,
  141587. };
  141588. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141589. _vq_quantthresh__44cn1_sm_p8_2,
  141590. _vq_quantmap__44cn1_sm_p8_2,
  141591. 17,
  141592. 17
  141593. };
  141594. static static_codebook _44cn1_sm_p8_2 = {
  141595. 2, 289,
  141596. _vq_lengthlist__44cn1_sm_p8_2,
  141597. 1, -529530880, 1611661312, 5, 0,
  141598. _vq_quantlist__44cn1_sm_p8_2,
  141599. NULL,
  141600. &_vq_auxt__44cn1_sm_p8_2,
  141601. NULL,
  141602. 0
  141603. };
  141604. static long _huff_lengthlist__44cn1_sm_short[] = {
  141605. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141606. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141607. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141608. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141609. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141610. 9,
  141611. };
  141612. static static_codebook _huff_book__44cn1_sm_short = {
  141613. 2, 81,
  141614. _huff_lengthlist__44cn1_sm_short,
  141615. 0, 0, 0, 0, 0,
  141616. NULL,
  141617. NULL,
  141618. NULL,
  141619. NULL,
  141620. 0
  141621. };
  141622. /*** End of inlined file: res_books_stereo.h ***/
  141623. /***** residue backends *********************************************/
  141624. static vorbis_info_residue0 _residue_44_low={
  141625. 0,-1, -1, 9,-1,
  141626. /* 0 1 2 3 4 5 6 7 */
  141627. {0},
  141628. {-1},
  141629. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141630. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141631. };
  141632. static vorbis_info_residue0 _residue_44_mid={
  141633. 0,-1, -1, 10,-1,
  141634. /* 0 1 2 3 4 5 6 7 8 */
  141635. {0},
  141636. {-1},
  141637. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141638. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141639. };
  141640. static vorbis_info_residue0 _residue_44_high={
  141641. 0,-1, -1, 10,-1,
  141642. /* 0 1 2 3 4 5 6 7 8 */
  141643. {0},
  141644. {-1},
  141645. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141646. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141647. };
  141648. static static_bookblock _resbook_44s_n1={
  141649. {
  141650. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141651. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141652. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141653. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141654. }
  141655. };
  141656. static static_bookblock _resbook_44sm_n1={
  141657. {
  141658. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141659. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141660. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141661. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141662. }
  141663. };
  141664. static static_bookblock _resbook_44s_0={
  141665. {
  141666. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141667. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141668. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141669. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141670. }
  141671. };
  141672. static static_bookblock _resbook_44sm_0={
  141673. {
  141674. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141675. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141676. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141677. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141678. }
  141679. };
  141680. static static_bookblock _resbook_44s_1={
  141681. {
  141682. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141683. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141684. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141685. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141686. }
  141687. };
  141688. static static_bookblock _resbook_44sm_1={
  141689. {
  141690. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141691. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141692. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141693. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141694. }
  141695. };
  141696. static static_bookblock _resbook_44s_2={
  141697. {
  141698. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141699. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141700. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141701. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141702. }
  141703. };
  141704. static static_bookblock _resbook_44s_3={
  141705. {
  141706. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141707. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141708. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141709. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141710. }
  141711. };
  141712. static static_bookblock _resbook_44s_4={
  141713. {
  141714. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141715. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141716. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141717. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141718. }
  141719. };
  141720. static static_bookblock _resbook_44s_5={
  141721. {
  141722. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141723. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141724. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141725. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141726. }
  141727. };
  141728. static static_bookblock _resbook_44s_6={
  141729. {
  141730. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141731. {0,0,&_44c6_s_p4_0},
  141732. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141733. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141734. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141735. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141736. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141737. }
  141738. };
  141739. static static_bookblock _resbook_44s_7={
  141740. {
  141741. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141742. {0,0,&_44c7_s_p4_0},
  141743. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141744. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141745. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141746. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141747. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141748. }
  141749. };
  141750. static static_bookblock _resbook_44s_8={
  141751. {
  141752. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141753. {0,0,&_44c8_s_p4_0},
  141754. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141755. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141756. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141757. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141758. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141759. }
  141760. };
  141761. static static_bookblock _resbook_44s_9={
  141762. {
  141763. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141764. {0,0,&_44c9_s_p4_0},
  141765. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141766. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141767. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141768. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141769. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141770. }
  141771. };
  141772. static vorbis_residue_template _res_44s_n1[]={
  141773. {2,0, &_residue_44_low,
  141774. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141775. &_resbook_44s_n1,&_resbook_44sm_n1},
  141776. {2,0, &_residue_44_low,
  141777. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141778. &_resbook_44s_n1,&_resbook_44sm_n1}
  141779. };
  141780. static vorbis_residue_template _res_44s_0[]={
  141781. {2,0, &_residue_44_low,
  141782. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141783. &_resbook_44s_0,&_resbook_44sm_0},
  141784. {2,0, &_residue_44_low,
  141785. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141786. &_resbook_44s_0,&_resbook_44sm_0}
  141787. };
  141788. static vorbis_residue_template _res_44s_1[]={
  141789. {2,0, &_residue_44_low,
  141790. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141791. &_resbook_44s_1,&_resbook_44sm_1},
  141792. {2,0, &_residue_44_low,
  141793. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141794. &_resbook_44s_1,&_resbook_44sm_1}
  141795. };
  141796. static vorbis_residue_template _res_44s_2[]={
  141797. {2,0, &_residue_44_mid,
  141798. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141799. &_resbook_44s_2,&_resbook_44s_2},
  141800. {2,0, &_residue_44_mid,
  141801. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141802. &_resbook_44s_2,&_resbook_44s_2}
  141803. };
  141804. static vorbis_residue_template _res_44s_3[]={
  141805. {2,0, &_residue_44_mid,
  141806. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141807. &_resbook_44s_3,&_resbook_44s_3},
  141808. {2,0, &_residue_44_mid,
  141809. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141810. &_resbook_44s_3,&_resbook_44s_3}
  141811. };
  141812. static vorbis_residue_template _res_44s_4[]={
  141813. {2,0, &_residue_44_mid,
  141814. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141815. &_resbook_44s_4,&_resbook_44s_4},
  141816. {2,0, &_residue_44_mid,
  141817. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141818. &_resbook_44s_4,&_resbook_44s_4}
  141819. };
  141820. static vorbis_residue_template _res_44s_5[]={
  141821. {2,0, &_residue_44_mid,
  141822. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141823. &_resbook_44s_5,&_resbook_44s_5},
  141824. {2,0, &_residue_44_mid,
  141825. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141826. &_resbook_44s_5,&_resbook_44s_5}
  141827. };
  141828. static vorbis_residue_template _res_44s_6[]={
  141829. {2,0, &_residue_44_high,
  141830. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141831. &_resbook_44s_6,&_resbook_44s_6},
  141832. {2,0, &_residue_44_high,
  141833. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141834. &_resbook_44s_6,&_resbook_44s_6}
  141835. };
  141836. static vorbis_residue_template _res_44s_7[]={
  141837. {2,0, &_residue_44_high,
  141838. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141839. &_resbook_44s_7,&_resbook_44s_7},
  141840. {2,0, &_residue_44_high,
  141841. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141842. &_resbook_44s_7,&_resbook_44s_7}
  141843. };
  141844. static vorbis_residue_template _res_44s_8[]={
  141845. {2,0, &_residue_44_high,
  141846. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141847. &_resbook_44s_8,&_resbook_44s_8},
  141848. {2,0, &_residue_44_high,
  141849. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141850. &_resbook_44s_8,&_resbook_44s_8}
  141851. };
  141852. static vorbis_residue_template _res_44s_9[]={
  141853. {2,0, &_residue_44_high,
  141854. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141855. &_resbook_44s_9,&_resbook_44s_9},
  141856. {2,0, &_residue_44_high,
  141857. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141858. &_resbook_44s_9,&_resbook_44s_9}
  141859. };
  141860. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141861. { _map_nominal, _res_44s_n1 }, /* -1 */
  141862. { _map_nominal, _res_44s_0 }, /* 0 */
  141863. { _map_nominal, _res_44s_1 }, /* 1 */
  141864. { _map_nominal, _res_44s_2 }, /* 2 */
  141865. { _map_nominal, _res_44s_3 }, /* 3 */
  141866. { _map_nominal, _res_44s_4 }, /* 4 */
  141867. { _map_nominal, _res_44s_5 }, /* 5 */
  141868. { _map_nominal, _res_44s_6 }, /* 6 */
  141869. { _map_nominal, _res_44s_7 }, /* 7 */
  141870. { _map_nominal, _res_44s_8 }, /* 8 */
  141871. { _map_nominal, _res_44s_9 }, /* 9 */
  141872. };
  141873. /*** End of inlined file: residue_44.h ***/
  141874. /*** Start of inlined file: psych_44.h ***/
  141875. /* preecho trigger settings *****************************************/
  141876. static vorbis_info_psy_global _psy_global_44[5]={
  141877. {8, /* lines per eighth octave */
  141878. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141879. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141880. -6.f,
  141881. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141882. },
  141883. {8, /* lines per eighth octave */
  141884. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141885. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141886. -6.f,
  141887. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141888. },
  141889. {8, /* lines per eighth octave */
  141890. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141891. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141892. -6.f,
  141893. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141894. },
  141895. {8, /* lines per eighth octave */
  141896. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141897. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141898. -6.f,
  141899. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141900. },
  141901. {8, /* lines per eighth octave */
  141902. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141903. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141904. -6.f,
  141905. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141906. },
  141907. };
  141908. /* noise compander lookups * low, mid, high quality ****************/
  141909. static compandblock _psy_compand_44[6]={
  141910. /* sub-mode Z short */
  141911. {{
  141912. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141913. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141914. 16,17,18,19,20,21,22, 23, /* 23dB */
  141915. 24,25,26,27,28,29,30, 31, /* 31dB */
  141916. 32,33,34,35,36,37,38, 39, /* 39dB */
  141917. }},
  141918. /* mode_Z nominal short */
  141919. {{
  141920. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141921. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141922. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141923. 15,16,17,17,17,18,18, 19, /* 31dB */
  141924. 19,19,20,21,22,23,24, 25, /* 39dB */
  141925. }},
  141926. /* mode A short */
  141927. {{
  141928. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141929. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141930. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141931. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141932. 11,12,13,14,15,16,17, 18, /* 39dB */
  141933. }},
  141934. /* sub-mode Z long */
  141935. {{
  141936. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141937. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141938. 16,17,18,19,20,21,22, 23, /* 23dB */
  141939. 24,25,26,27,28,29,30, 31, /* 31dB */
  141940. 32,33,34,35,36,37,38, 39, /* 39dB */
  141941. }},
  141942. /* mode_Z nominal long */
  141943. {{
  141944. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141945. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141946. 13,14,14,14,15,15,15, 15, /* 23dB */
  141947. 16,16,17,17,17,18,18, 19, /* 31dB */
  141948. 19,19,20,21,22,23,24, 25, /* 39dB */
  141949. }},
  141950. /* mode A long */
  141951. {{
  141952. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141953. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141954. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141955. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141956. 11,12,13,14,15,16,17, 18, /* 39dB */
  141957. }}
  141958. };
  141959. /* tonal masking curve level adjustments *************************/
  141960. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141961. /* 63 125 250 500 1 2 4 8 16 */
  141962. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141963. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141964. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141965. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141966. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141967. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141968. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141969. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141970. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141971. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141972. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141973. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141974. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141975. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141976. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141977. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141978. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141979. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141980. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141981. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141982. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141983. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141984. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141985. };
  141986. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141987. /* 63 125 250 500 1 2 4 8 16 */
  141988. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141989. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141990. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141991. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141992. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141993. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141994. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141995. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141996. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141997. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141998. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141999. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142000. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142001. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142002. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142003. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142004. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142005. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142006. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142007. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142008. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142009. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142010. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142011. };
  142012. /* noise bias (transition block) */
  142013. static noise3 _psy_noisebias_trans[12]={
  142014. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142015. /* -1 */
  142016. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142017. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142018. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142019. /* 0
  142020. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142021. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142022. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142023. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142024. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142025. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142026. /* 1
  142027. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142028. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142029. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142030. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142031. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142032. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142033. /* 2
  142034. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142035. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142036. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142037. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142038. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142039. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142040. /* 3
  142041. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142042. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142043. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142044. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142045. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142046. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142047. /* 4
  142048. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142049. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142050. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142051. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142052. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142053. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142054. /* 5
  142055. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142056. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142057. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142058. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142059. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142060. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142061. /* 6
  142062. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142063. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142064. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142065. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142066. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142067. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142068. /* 7
  142069. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142070. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142071. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142072. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142073. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142074. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142075. /* 8
  142076. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142077. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142078. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142079. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142080. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142081. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142082. /* 9
  142083. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142084. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142085. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142086. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142087. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142088. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142089. /* 10 */
  142090. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142091. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142092. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142093. };
  142094. /* noise bias (long block) */
  142095. static noise3 _psy_noisebias_long[12]={
  142096. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142097. /* -1 */
  142098. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142099. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142100. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142101. /* 0 */
  142102. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142103. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142104. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142105. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142106. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142107. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142108. /* 1 */
  142109. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142110. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142111. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142112. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142113. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142114. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142115. /* 2 */
  142116. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142117. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142118. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142119. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142120. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142121. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142122. /* 3 */
  142123. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142124. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142125. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142126. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142127. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142128. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142129. /* 4 */
  142130. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142131. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142132. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142133. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142134. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142135. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142136. /* 5 */
  142137. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142138. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142139. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142140. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142141. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142142. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142143. /* 6 */
  142144. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142145. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142146. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142147. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142148. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142149. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142150. /* 7 */
  142151. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142152. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142153. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142154. /* 8 */
  142155. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142156. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142157. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142158. /* 9 */
  142159. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142160. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142161. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142162. /* 10 */
  142163. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142164. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142165. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142166. };
  142167. /* noise bias (impulse block) */
  142168. static noise3 _psy_noisebias_impulse[12]={
  142169. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142170. /* -1 */
  142171. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142172. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142173. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142174. /* 0 */
  142175. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142176. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142177. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142178. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142179. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142180. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142181. /* 1 */
  142182. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142183. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142184. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142185. /* 2 */
  142186. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142187. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142188. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142189. /* 3 */
  142190. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142191. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142192. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142193. /* 4 */
  142194. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142195. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142196. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142197. /* 5 */
  142198. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142199. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142200. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142201. /* 6
  142202. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142203. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142204. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142205. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142206. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142207. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142208. /* 7 */
  142209. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142210. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142211. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142212. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142213. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142214. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142215. /* 8 */
  142216. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142217. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142218. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142219. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142220. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142221. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142222. /* 9 */
  142223. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142224. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142225. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142226. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142227. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142228. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142229. /* 10 */
  142230. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142231. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142232. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142233. };
  142234. /* noise bias (padding block) */
  142235. static noise3 _psy_noisebias_padding[12]={
  142236. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142237. /* -1 */
  142238. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142239. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142240. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142241. /* 0 */
  142242. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142243. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142244. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142245. /* 1 */
  142246. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142247. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142248. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142249. /* 2 */
  142250. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142251. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142252. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142253. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142254. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142255. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142256. /* 3 */
  142257. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142258. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142259. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142260. /* 4 */
  142261. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142262. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142263. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142264. /* 5 */
  142265. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142266. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142267. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142268. /* 6 */
  142269. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142270. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142271. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142272. /* 7 */
  142273. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142274. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142275. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142276. /* 8 */
  142277. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142278. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142279. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142280. /* 9 */
  142281. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142282. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142283. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142284. /* 10 */
  142285. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142286. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142287. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142288. };
  142289. static noiseguard _psy_noiseguards_44[4]={
  142290. {3,3,15},
  142291. {3,3,15},
  142292. {10,10,100},
  142293. {10,10,100},
  142294. };
  142295. static int _psy_tone_suppress[12]={
  142296. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142297. };
  142298. static int _psy_tone_0dB[12]={
  142299. 90,90,95,95,95,95,105,105,105,105,105,105,
  142300. };
  142301. static int _psy_noise_suppress[12]={
  142302. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142303. };
  142304. static vorbis_info_psy _psy_info_template={
  142305. /* blockflag */
  142306. -1,
  142307. /* ath_adjatt, ath_maxatt */
  142308. -140.,-140.,
  142309. /* tonemask att boost/decay,suppr,curves */
  142310. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142311. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142312. 1, -0.f, .5f, .5f, 0,0,0,
  142313. /* noiseoffset*3, noisecompand, max_curve_dB */
  142314. {{-1},{-1},{-1}},{-1},105.f,
  142315. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142316. 0,0,-1,-1,0.,
  142317. };
  142318. /* ath ****************/
  142319. static int _psy_ath_floater[12]={
  142320. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142321. };
  142322. static int _psy_ath_abs[12]={
  142323. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142324. };
  142325. /* stereo setup. These don't map directly to quality level, there's
  142326. an additional indirection as several of the below may be used in a
  142327. single bitmanaged stream
  142328. ****************/
  142329. /* various stereo possibilities */
  142330. /* stereo mode by base quality level */
  142331. static adj_stereo _psy_stereo_modes_44[12]={
  142332. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142333. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142334. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142335. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142336. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142337. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142338. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142339. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142340. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142341. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142342. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142343. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142344. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142345. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142346. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142347. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142348. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142349. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142350. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142351. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142352. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142353. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142354. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142355. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142356. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142357. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142358. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142359. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142360. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142361. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142362. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142363. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142364. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142365. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142366. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142367. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142368. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142369. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142370. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142371. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142372. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142373. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142374. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142375. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142376. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142377. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142378. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142379. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142380. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142381. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142382. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142383. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142384. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142385. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142386. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142387. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142388. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142389. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142390. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142391. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142392. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142393. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142394. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142395. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142396. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142397. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142398. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142399. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142400. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142401. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142402. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142403. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142404. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142405. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142406. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142407. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142408. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142409. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142410. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142411. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142412. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142413. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142414. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142415. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142416. };
  142417. /* tone master attenuation by base quality mode and bitrate tweak */
  142418. static att3 _psy_tone_masteratt_44[12]={
  142419. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142420. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142421. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142422. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142423. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142424. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142425. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142426. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142427. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142428. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142429. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142430. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142431. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142432. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142433. };
  142434. /* lowpass by mode **************/
  142435. static double _psy_lowpass_44[12]={
  142436. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142437. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142438. };
  142439. /* noise normalization **********/
  142440. static int _noise_start_short_44[11]={
  142441. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142442. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142443. };
  142444. static int _noise_start_long_44[11]={
  142445. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142446. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142447. };
  142448. static int _noise_part_short_44[11]={
  142449. 8,8,8,8,8,8,8,8,8,8,8
  142450. };
  142451. static int _noise_part_long_44[11]={
  142452. 32,32,32,32,32,32,32,32,32,32,32
  142453. };
  142454. static double _noise_thresh_44[11]={
  142455. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142456. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142457. };
  142458. static double _noise_thresh_5only[2]={
  142459. .5,.5,
  142460. };
  142461. /*** End of inlined file: psych_44.h ***/
  142462. static double rate_mapping_44_stereo[12]={
  142463. 22500.,32000.,40000.,48000.,56000.,64000.,
  142464. 80000.,96000.,112000.,128000.,160000.,250001.
  142465. };
  142466. static double quality_mapping_44[12]={
  142467. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142468. };
  142469. static int blocksize_short_44[11]={
  142470. 512,256,256,256,256,256,256,256,256,256,256
  142471. };
  142472. static int blocksize_long_44[11]={
  142473. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142474. };
  142475. static double _psy_compand_short_mapping[12]={
  142476. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142477. };
  142478. static double _psy_compand_long_mapping[12]={
  142479. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142480. };
  142481. static double _global_mapping_44[12]={
  142482. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142483. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142484. };
  142485. static int _floor_short_mapping_44[11]={
  142486. 1,0,0,2,2,4,5,5,5,5,5
  142487. };
  142488. static int _floor_long_mapping_44[11]={
  142489. 8,7,7,7,7,7,7,7,7,7,7
  142490. };
  142491. ve_setup_data_template ve_setup_44_stereo={
  142492. 11,
  142493. rate_mapping_44_stereo,
  142494. quality_mapping_44,
  142495. 2,
  142496. 40000,
  142497. 50000,
  142498. blocksize_short_44,
  142499. blocksize_long_44,
  142500. _psy_tone_masteratt_44,
  142501. _psy_tone_0dB,
  142502. _psy_tone_suppress,
  142503. _vp_tonemask_adj_otherblock,
  142504. _vp_tonemask_adj_longblock,
  142505. _vp_tonemask_adj_otherblock,
  142506. _psy_noiseguards_44,
  142507. _psy_noisebias_impulse,
  142508. _psy_noisebias_padding,
  142509. _psy_noisebias_trans,
  142510. _psy_noisebias_long,
  142511. _psy_noise_suppress,
  142512. _psy_compand_44,
  142513. _psy_compand_short_mapping,
  142514. _psy_compand_long_mapping,
  142515. {_noise_start_short_44,_noise_start_long_44},
  142516. {_noise_part_short_44,_noise_part_long_44},
  142517. _noise_thresh_44,
  142518. _psy_ath_floater,
  142519. _psy_ath_abs,
  142520. _psy_lowpass_44,
  142521. _psy_global_44,
  142522. _global_mapping_44,
  142523. _psy_stereo_modes_44,
  142524. _floor_books,
  142525. _floor,
  142526. _floor_short_mapping_44,
  142527. _floor_long_mapping_44,
  142528. _mapres_template_44_stereo
  142529. };
  142530. /*** End of inlined file: setup_44.h ***/
  142531. /*** Start of inlined file: setup_44u.h ***/
  142532. /*** Start of inlined file: residue_44u.h ***/
  142533. /*** Start of inlined file: res_books_uncoupled.h ***/
  142534. static long _vq_quantlist__16u0__p1_0[] = {
  142535. 1,
  142536. 0,
  142537. 2,
  142538. };
  142539. static long _vq_lengthlist__16u0__p1_0[] = {
  142540. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142541. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142542. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142543. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142544. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142545. 12,
  142546. };
  142547. static float _vq_quantthresh__16u0__p1_0[] = {
  142548. -0.5, 0.5,
  142549. };
  142550. static long _vq_quantmap__16u0__p1_0[] = {
  142551. 1, 0, 2,
  142552. };
  142553. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142554. _vq_quantthresh__16u0__p1_0,
  142555. _vq_quantmap__16u0__p1_0,
  142556. 3,
  142557. 3
  142558. };
  142559. static static_codebook _16u0__p1_0 = {
  142560. 4, 81,
  142561. _vq_lengthlist__16u0__p1_0,
  142562. 1, -535822336, 1611661312, 2, 0,
  142563. _vq_quantlist__16u0__p1_0,
  142564. NULL,
  142565. &_vq_auxt__16u0__p1_0,
  142566. NULL,
  142567. 0
  142568. };
  142569. static long _vq_quantlist__16u0__p2_0[] = {
  142570. 1,
  142571. 0,
  142572. 2,
  142573. };
  142574. static long _vq_lengthlist__16u0__p2_0[] = {
  142575. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142576. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142577. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142578. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142579. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142580. 8,
  142581. };
  142582. static float _vq_quantthresh__16u0__p2_0[] = {
  142583. -0.5, 0.5,
  142584. };
  142585. static long _vq_quantmap__16u0__p2_0[] = {
  142586. 1, 0, 2,
  142587. };
  142588. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142589. _vq_quantthresh__16u0__p2_0,
  142590. _vq_quantmap__16u0__p2_0,
  142591. 3,
  142592. 3
  142593. };
  142594. static static_codebook _16u0__p2_0 = {
  142595. 4, 81,
  142596. _vq_lengthlist__16u0__p2_0,
  142597. 1, -535822336, 1611661312, 2, 0,
  142598. _vq_quantlist__16u0__p2_0,
  142599. NULL,
  142600. &_vq_auxt__16u0__p2_0,
  142601. NULL,
  142602. 0
  142603. };
  142604. static long _vq_quantlist__16u0__p3_0[] = {
  142605. 2,
  142606. 1,
  142607. 3,
  142608. 0,
  142609. 4,
  142610. };
  142611. static long _vq_lengthlist__16u0__p3_0[] = {
  142612. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142613. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142614. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142615. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142616. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142617. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142618. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142619. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142620. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142621. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142622. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142623. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142624. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142625. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142626. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142627. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142628. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142629. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142630. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142631. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142632. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142633. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142634. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142635. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142636. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142637. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142638. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142639. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142640. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142641. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142642. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142643. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142644. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142645. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142646. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142647. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142648. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142649. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142650. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142651. 18,
  142652. };
  142653. static float _vq_quantthresh__16u0__p3_0[] = {
  142654. -1.5, -0.5, 0.5, 1.5,
  142655. };
  142656. static long _vq_quantmap__16u0__p3_0[] = {
  142657. 3, 1, 0, 2, 4,
  142658. };
  142659. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142660. _vq_quantthresh__16u0__p3_0,
  142661. _vq_quantmap__16u0__p3_0,
  142662. 5,
  142663. 5
  142664. };
  142665. static static_codebook _16u0__p3_0 = {
  142666. 4, 625,
  142667. _vq_lengthlist__16u0__p3_0,
  142668. 1, -533725184, 1611661312, 3, 0,
  142669. _vq_quantlist__16u0__p3_0,
  142670. NULL,
  142671. &_vq_auxt__16u0__p3_0,
  142672. NULL,
  142673. 0
  142674. };
  142675. static long _vq_quantlist__16u0__p4_0[] = {
  142676. 2,
  142677. 1,
  142678. 3,
  142679. 0,
  142680. 4,
  142681. };
  142682. static long _vq_lengthlist__16u0__p4_0[] = {
  142683. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142684. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142685. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142686. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142687. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142688. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142689. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142690. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142691. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142692. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142693. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142694. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142695. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142696. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142697. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142698. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142699. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142700. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142701. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142702. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142703. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142704. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142705. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142706. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142707. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142708. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142709. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142710. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142711. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142712. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142713. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142714. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142715. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142716. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142717. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142718. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142719. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142720. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142721. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142722. 11,
  142723. };
  142724. static float _vq_quantthresh__16u0__p4_0[] = {
  142725. -1.5, -0.5, 0.5, 1.5,
  142726. };
  142727. static long _vq_quantmap__16u0__p4_0[] = {
  142728. 3, 1, 0, 2, 4,
  142729. };
  142730. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142731. _vq_quantthresh__16u0__p4_0,
  142732. _vq_quantmap__16u0__p4_0,
  142733. 5,
  142734. 5
  142735. };
  142736. static static_codebook _16u0__p4_0 = {
  142737. 4, 625,
  142738. _vq_lengthlist__16u0__p4_0,
  142739. 1, -533725184, 1611661312, 3, 0,
  142740. _vq_quantlist__16u0__p4_0,
  142741. NULL,
  142742. &_vq_auxt__16u0__p4_0,
  142743. NULL,
  142744. 0
  142745. };
  142746. static long _vq_quantlist__16u0__p5_0[] = {
  142747. 4,
  142748. 3,
  142749. 5,
  142750. 2,
  142751. 6,
  142752. 1,
  142753. 7,
  142754. 0,
  142755. 8,
  142756. };
  142757. static long _vq_lengthlist__16u0__p5_0[] = {
  142758. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142759. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142760. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142761. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142762. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142763. 12,
  142764. };
  142765. static float _vq_quantthresh__16u0__p5_0[] = {
  142766. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142767. };
  142768. static long _vq_quantmap__16u0__p5_0[] = {
  142769. 7, 5, 3, 1, 0, 2, 4, 6,
  142770. 8,
  142771. };
  142772. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142773. _vq_quantthresh__16u0__p5_0,
  142774. _vq_quantmap__16u0__p5_0,
  142775. 9,
  142776. 9
  142777. };
  142778. static static_codebook _16u0__p5_0 = {
  142779. 2, 81,
  142780. _vq_lengthlist__16u0__p5_0,
  142781. 1, -531628032, 1611661312, 4, 0,
  142782. _vq_quantlist__16u0__p5_0,
  142783. NULL,
  142784. &_vq_auxt__16u0__p5_0,
  142785. NULL,
  142786. 0
  142787. };
  142788. static long _vq_quantlist__16u0__p6_0[] = {
  142789. 6,
  142790. 5,
  142791. 7,
  142792. 4,
  142793. 8,
  142794. 3,
  142795. 9,
  142796. 2,
  142797. 10,
  142798. 1,
  142799. 11,
  142800. 0,
  142801. 12,
  142802. };
  142803. static long _vq_lengthlist__16u0__p6_0[] = {
  142804. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142805. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142806. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142807. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142808. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142809. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142810. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142811. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142812. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142813. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142814. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142815. };
  142816. static float _vq_quantthresh__16u0__p6_0[] = {
  142817. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142818. 12.5, 17.5, 22.5, 27.5,
  142819. };
  142820. static long _vq_quantmap__16u0__p6_0[] = {
  142821. 11, 9, 7, 5, 3, 1, 0, 2,
  142822. 4, 6, 8, 10, 12,
  142823. };
  142824. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142825. _vq_quantthresh__16u0__p6_0,
  142826. _vq_quantmap__16u0__p6_0,
  142827. 13,
  142828. 13
  142829. };
  142830. static static_codebook _16u0__p6_0 = {
  142831. 2, 169,
  142832. _vq_lengthlist__16u0__p6_0,
  142833. 1, -526516224, 1616117760, 4, 0,
  142834. _vq_quantlist__16u0__p6_0,
  142835. NULL,
  142836. &_vq_auxt__16u0__p6_0,
  142837. NULL,
  142838. 0
  142839. };
  142840. static long _vq_quantlist__16u0__p6_1[] = {
  142841. 2,
  142842. 1,
  142843. 3,
  142844. 0,
  142845. 4,
  142846. };
  142847. static long _vq_lengthlist__16u0__p6_1[] = {
  142848. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142849. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142850. };
  142851. static float _vq_quantthresh__16u0__p6_1[] = {
  142852. -1.5, -0.5, 0.5, 1.5,
  142853. };
  142854. static long _vq_quantmap__16u0__p6_1[] = {
  142855. 3, 1, 0, 2, 4,
  142856. };
  142857. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142858. _vq_quantthresh__16u0__p6_1,
  142859. _vq_quantmap__16u0__p6_1,
  142860. 5,
  142861. 5
  142862. };
  142863. static static_codebook _16u0__p6_1 = {
  142864. 2, 25,
  142865. _vq_lengthlist__16u0__p6_1,
  142866. 1, -533725184, 1611661312, 3, 0,
  142867. _vq_quantlist__16u0__p6_1,
  142868. NULL,
  142869. &_vq_auxt__16u0__p6_1,
  142870. NULL,
  142871. 0
  142872. };
  142873. static long _vq_quantlist__16u0__p7_0[] = {
  142874. 1,
  142875. 0,
  142876. 2,
  142877. };
  142878. static long _vq_lengthlist__16u0__p7_0[] = {
  142879. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142880. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142881. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142882. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142883. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142884. 7,
  142885. };
  142886. static float _vq_quantthresh__16u0__p7_0[] = {
  142887. -157.5, 157.5,
  142888. };
  142889. static long _vq_quantmap__16u0__p7_0[] = {
  142890. 1, 0, 2,
  142891. };
  142892. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142893. _vq_quantthresh__16u0__p7_0,
  142894. _vq_quantmap__16u0__p7_0,
  142895. 3,
  142896. 3
  142897. };
  142898. static static_codebook _16u0__p7_0 = {
  142899. 4, 81,
  142900. _vq_lengthlist__16u0__p7_0,
  142901. 1, -518803456, 1628680192, 2, 0,
  142902. _vq_quantlist__16u0__p7_0,
  142903. NULL,
  142904. &_vq_auxt__16u0__p7_0,
  142905. NULL,
  142906. 0
  142907. };
  142908. static long _vq_quantlist__16u0__p7_1[] = {
  142909. 7,
  142910. 6,
  142911. 8,
  142912. 5,
  142913. 9,
  142914. 4,
  142915. 10,
  142916. 3,
  142917. 11,
  142918. 2,
  142919. 12,
  142920. 1,
  142921. 13,
  142922. 0,
  142923. 14,
  142924. };
  142925. static long _vq_lengthlist__16u0__p7_1[] = {
  142926. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142927. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142928. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142929. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142930. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142931. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142940. 10,
  142941. };
  142942. static float _vq_quantthresh__16u0__p7_1[] = {
  142943. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142944. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142945. };
  142946. static long _vq_quantmap__16u0__p7_1[] = {
  142947. 13, 11, 9, 7, 5, 3, 1, 0,
  142948. 2, 4, 6, 8, 10, 12, 14,
  142949. };
  142950. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142951. _vq_quantthresh__16u0__p7_1,
  142952. _vq_quantmap__16u0__p7_1,
  142953. 15,
  142954. 15
  142955. };
  142956. static static_codebook _16u0__p7_1 = {
  142957. 2, 225,
  142958. _vq_lengthlist__16u0__p7_1,
  142959. 1, -520986624, 1620377600, 4, 0,
  142960. _vq_quantlist__16u0__p7_1,
  142961. NULL,
  142962. &_vq_auxt__16u0__p7_1,
  142963. NULL,
  142964. 0
  142965. };
  142966. static long _vq_quantlist__16u0__p7_2[] = {
  142967. 10,
  142968. 9,
  142969. 11,
  142970. 8,
  142971. 12,
  142972. 7,
  142973. 13,
  142974. 6,
  142975. 14,
  142976. 5,
  142977. 15,
  142978. 4,
  142979. 16,
  142980. 3,
  142981. 17,
  142982. 2,
  142983. 18,
  142984. 1,
  142985. 19,
  142986. 0,
  142987. 20,
  142988. };
  142989. static long _vq_lengthlist__16u0__p7_2[] = {
  142990. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142991. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142992. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142993. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142994. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142995. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142996. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142997. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142998. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142999. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143000. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143001. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143002. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143003. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143004. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143005. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143006. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143007. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143008. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143009. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143010. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143011. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143012. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143013. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143014. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143015. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143016. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143017. 10,10,12,11,10,11,11,11,10,
  143018. };
  143019. static float _vq_quantthresh__16u0__p7_2[] = {
  143020. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143021. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143022. 6.5, 7.5, 8.5, 9.5,
  143023. };
  143024. static long _vq_quantmap__16u0__p7_2[] = {
  143025. 19, 17, 15, 13, 11, 9, 7, 5,
  143026. 3, 1, 0, 2, 4, 6, 8, 10,
  143027. 12, 14, 16, 18, 20,
  143028. };
  143029. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143030. _vq_quantthresh__16u0__p7_2,
  143031. _vq_quantmap__16u0__p7_2,
  143032. 21,
  143033. 21
  143034. };
  143035. static static_codebook _16u0__p7_2 = {
  143036. 2, 441,
  143037. _vq_lengthlist__16u0__p7_2,
  143038. 1, -529268736, 1611661312, 5, 0,
  143039. _vq_quantlist__16u0__p7_2,
  143040. NULL,
  143041. &_vq_auxt__16u0__p7_2,
  143042. NULL,
  143043. 0
  143044. };
  143045. static long _huff_lengthlist__16u0__single[] = {
  143046. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143047. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143048. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143049. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143050. };
  143051. static static_codebook _huff_book__16u0__single = {
  143052. 2, 64,
  143053. _huff_lengthlist__16u0__single,
  143054. 0, 0, 0, 0, 0,
  143055. NULL,
  143056. NULL,
  143057. NULL,
  143058. NULL,
  143059. 0
  143060. };
  143061. static long _huff_lengthlist__16u1__long[] = {
  143062. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143063. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143064. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143065. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143066. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143067. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143068. 16,13,16,18,
  143069. };
  143070. static static_codebook _huff_book__16u1__long = {
  143071. 2, 100,
  143072. _huff_lengthlist__16u1__long,
  143073. 0, 0, 0, 0, 0,
  143074. NULL,
  143075. NULL,
  143076. NULL,
  143077. NULL,
  143078. 0
  143079. };
  143080. static long _vq_quantlist__16u1__p1_0[] = {
  143081. 1,
  143082. 0,
  143083. 2,
  143084. };
  143085. static long _vq_lengthlist__16u1__p1_0[] = {
  143086. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143087. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143088. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143089. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143090. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143091. 11,
  143092. };
  143093. static float _vq_quantthresh__16u1__p1_0[] = {
  143094. -0.5, 0.5,
  143095. };
  143096. static long _vq_quantmap__16u1__p1_0[] = {
  143097. 1, 0, 2,
  143098. };
  143099. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143100. _vq_quantthresh__16u1__p1_0,
  143101. _vq_quantmap__16u1__p1_0,
  143102. 3,
  143103. 3
  143104. };
  143105. static static_codebook _16u1__p1_0 = {
  143106. 4, 81,
  143107. _vq_lengthlist__16u1__p1_0,
  143108. 1, -535822336, 1611661312, 2, 0,
  143109. _vq_quantlist__16u1__p1_0,
  143110. NULL,
  143111. &_vq_auxt__16u1__p1_0,
  143112. NULL,
  143113. 0
  143114. };
  143115. static long _vq_quantlist__16u1__p2_0[] = {
  143116. 1,
  143117. 0,
  143118. 2,
  143119. };
  143120. static long _vq_lengthlist__16u1__p2_0[] = {
  143121. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143122. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143123. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143124. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143125. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143126. 8,
  143127. };
  143128. static float _vq_quantthresh__16u1__p2_0[] = {
  143129. -0.5, 0.5,
  143130. };
  143131. static long _vq_quantmap__16u1__p2_0[] = {
  143132. 1, 0, 2,
  143133. };
  143134. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143135. _vq_quantthresh__16u1__p2_0,
  143136. _vq_quantmap__16u1__p2_0,
  143137. 3,
  143138. 3
  143139. };
  143140. static static_codebook _16u1__p2_0 = {
  143141. 4, 81,
  143142. _vq_lengthlist__16u1__p2_0,
  143143. 1, -535822336, 1611661312, 2, 0,
  143144. _vq_quantlist__16u1__p2_0,
  143145. NULL,
  143146. &_vq_auxt__16u1__p2_0,
  143147. NULL,
  143148. 0
  143149. };
  143150. static long _vq_quantlist__16u1__p3_0[] = {
  143151. 2,
  143152. 1,
  143153. 3,
  143154. 0,
  143155. 4,
  143156. };
  143157. static long _vq_lengthlist__16u1__p3_0[] = {
  143158. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143159. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143160. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143161. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143162. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143163. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143164. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143165. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143166. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143167. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143168. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143169. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143170. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143171. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143172. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143173. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143174. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143175. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143176. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143177. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143178. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143179. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143180. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143181. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143182. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143183. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143184. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143185. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143186. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143187. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143188. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143189. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143190. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143191. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143192. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143193. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143194. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143195. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143196. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143197. 16,
  143198. };
  143199. static float _vq_quantthresh__16u1__p3_0[] = {
  143200. -1.5, -0.5, 0.5, 1.5,
  143201. };
  143202. static long _vq_quantmap__16u1__p3_0[] = {
  143203. 3, 1, 0, 2, 4,
  143204. };
  143205. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143206. _vq_quantthresh__16u1__p3_0,
  143207. _vq_quantmap__16u1__p3_0,
  143208. 5,
  143209. 5
  143210. };
  143211. static static_codebook _16u1__p3_0 = {
  143212. 4, 625,
  143213. _vq_lengthlist__16u1__p3_0,
  143214. 1, -533725184, 1611661312, 3, 0,
  143215. _vq_quantlist__16u1__p3_0,
  143216. NULL,
  143217. &_vq_auxt__16u1__p3_0,
  143218. NULL,
  143219. 0
  143220. };
  143221. static long _vq_quantlist__16u1__p4_0[] = {
  143222. 2,
  143223. 1,
  143224. 3,
  143225. 0,
  143226. 4,
  143227. };
  143228. static long _vq_lengthlist__16u1__p4_0[] = {
  143229. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143230. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143231. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143232. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143233. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143234. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143235. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143236. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143237. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143238. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143239. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143240. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143241. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143242. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143243. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143244. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143245. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143246. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143247. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143248. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143249. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143250. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143251. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143252. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143253. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143254. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143255. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143256. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143257. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143258. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143259. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143260. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143261. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143262. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143263. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143264. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143265. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143266. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143267. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143268. 11,
  143269. };
  143270. static float _vq_quantthresh__16u1__p4_0[] = {
  143271. -1.5, -0.5, 0.5, 1.5,
  143272. };
  143273. static long _vq_quantmap__16u1__p4_0[] = {
  143274. 3, 1, 0, 2, 4,
  143275. };
  143276. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143277. _vq_quantthresh__16u1__p4_0,
  143278. _vq_quantmap__16u1__p4_0,
  143279. 5,
  143280. 5
  143281. };
  143282. static static_codebook _16u1__p4_0 = {
  143283. 4, 625,
  143284. _vq_lengthlist__16u1__p4_0,
  143285. 1, -533725184, 1611661312, 3, 0,
  143286. _vq_quantlist__16u1__p4_0,
  143287. NULL,
  143288. &_vq_auxt__16u1__p4_0,
  143289. NULL,
  143290. 0
  143291. };
  143292. static long _vq_quantlist__16u1__p5_0[] = {
  143293. 4,
  143294. 3,
  143295. 5,
  143296. 2,
  143297. 6,
  143298. 1,
  143299. 7,
  143300. 0,
  143301. 8,
  143302. };
  143303. static long _vq_lengthlist__16u1__p5_0[] = {
  143304. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143305. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143306. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143307. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143308. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143309. 13,
  143310. };
  143311. static float _vq_quantthresh__16u1__p5_0[] = {
  143312. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143313. };
  143314. static long _vq_quantmap__16u1__p5_0[] = {
  143315. 7, 5, 3, 1, 0, 2, 4, 6,
  143316. 8,
  143317. };
  143318. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143319. _vq_quantthresh__16u1__p5_0,
  143320. _vq_quantmap__16u1__p5_0,
  143321. 9,
  143322. 9
  143323. };
  143324. static static_codebook _16u1__p5_0 = {
  143325. 2, 81,
  143326. _vq_lengthlist__16u1__p5_0,
  143327. 1, -531628032, 1611661312, 4, 0,
  143328. _vq_quantlist__16u1__p5_0,
  143329. NULL,
  143330. &_vq_auxt__16u1__p5_0,
  143331. NULL,
  143332. 0
  143333. };
  143334. static long _vq_quantlist__16u1__p6_0[] = {
  143335. 4,
  143336. 3,
  143337. 5,
  143338. 2,
  143339. 6,
  143340. 1,
  143341. 7,
  143342. 0,
  143343. 8,
  143344. };
  143345. static long _vq_lengthlist__16u1__p6_0[] = {
  143346. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143347. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143348. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143349. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143350. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143351. 11,
  143352. };
  143353. static float _vq_quantthresh__16u1__p6_0[] = {
  143354. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143355. };
  143356. static long _vq_quantmap__16u1__p6_0[] = {
  143357. 7, 5, 3, 1, 0, 2, 4, 6,
  143358. 8,
  143359. };
  143360. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143361. _vq_quantthresh__16u1__p6_0,
  143362. _vq_quantmap__16u1__p6_0,
  143363. 9,
  143364. 9
  143365. };
  143366. static static_codebook _16u1__p6_0 = {
  143367. 2, 81,
  143368. _vq_lengthlist__16u1__p6_0,
  143369. 1, -531628032, 1611661312, 4, 0,
  143370. _vq_quantlist__16u1__p6_0,
  143371. NULL,
  143372. &_vq_auxt__16u1__p6_0,
  143373. NULL,
  143374. 0
  143375. };
  143376. static long _vq_quantlist__16u1__p7_0[] = {
  143377. 1,
  143378. 0,
  143379. 2,
  143380. };
  143381. static long _vq_lengthlist__16u1__p7_0[] = {
  143382. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143383. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143384. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143385. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143386. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143387. 13,
  143388. };
  143389. static float _vq_quantthresh__16u1__p7_0[] = {
  143390. -5.5, 5.5,
  143391. };
  143392. static long _vq_quantmap__16u1__p7_0[] = {
  143393. 1, 0, 2,
  143394. };
  143395. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143396. _vq_quantthresh__16u1__p7_0,
  143397. _vq_quantmap__16u1__p7_0,
  143398. 3,
  143399. 3
  143400. };
  143401. static static_codebook _16u1__p7_0 = {
  143402. 4, 81,
  143403. _vq_lengthlist__16u1__p7_0,
  143404. 1, -529137664, 1618345984, 2, 0,
  143405. _vq_quantlist__16u1__p7_0,
  143406. NULL,
  143407. &_vq_auxt__16u1__p7_0,
  143408. NULL,
  143409. 0
  143410. };
  143411. static long _vq_quantlist__16u1__p7_1[] = {
  143412. 5,
  143413. 4,
  143414. 6,
  143415. 3,
  143416. 7,
  143417. 2,
  143418. 8,
  143419. 1,
  143420. 9,
  143421. 0,
  143422. 10,
  143423. };
  143424. static long _vq_lengthlist__16u1__p7_1[] = {
  143425. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143426. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143427. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143428. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143429. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143430. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143431. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143432. 8, 9, 9,10,10,10,10,10,10,
  143433. };
  143434. static float _vq_quantthresh__16u1__p7_1[] = {
  143435. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143436. 3.5, 4.5,
  143437. };
  143438. static long _vq_quantmap__16u1__p7_1[] = {
  143439. 9, 7, 5, 3, 1, 0, 2, 4,
  143440. 6, 8, 10,
  143441. };
  143442. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143443. _vq_quantthresh__16u1__p7_1,
  143444. _vq_quantmap__16u1__p7_1,
  143445. 11,
  143446. 11
  143447. };
  143448. static static_codebook _16u1__p7_1 = {
  143449. 2, 121,
  143450. _vq_lengthlist__16u1__p7_1,
  143451. 1, -531365888, 1611661312, 4, 0,
  143452. _vq_quantlist__16u1__p7_1,
  143453. NULL,
  143454. &_vq_auxt__16u1__p7_1,
  143455. NULL,
  143456. 0
  143457. };
  143458. static long _vq_quantlist__16u1__p8_0[] = {
  143459. 5,
  143460. 4,
  143461. 6,
  143462. 3,
  143463. 7,
  143464. 2,
  143465. 8,
  143466. 1,
  143467. 9,
  143468. 0,
  143469. 10,
  143470. };
  143471. static long _vq_lengthlist__16u1__p8_0[] = {
  143472. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143473. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143474. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143475. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143476. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143477. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143478. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143479. 13,14,14,15,15,16,16,15,16,
  143480. };
  143481. static float _vq_quantthresh__16u1__p8_0[] = {
  143482. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143483. 38.5, 49.5,
  143484. };
  143485. static long _vq_quantmap__16u1__p8_0[] = {
  143486. 9, 7, 5, 3, 1, 0, 2, 4,
  143487. 6, 8, 10,
  143488. };
  143489. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143490. _vq_quantthresh__16u1__p8_0,
  143491. _vq_quantmap__16u1__p8_0,
  143492. 11,
  143493. 11
  143494. };
  143495. static static_codebook _16u1__p8_0 = {
  143496. 2, 121,
  143497. _vq_lengthlist__16u1__p8_0,
  143498. 1, -524582912, 1618345984, 4, 0,
  143499. _vq_quantlist__16u1__p8_0,
  143500. NULL,
  143501. &_vq_auxt__16u1__p8_0,
  143502. NULL,
  143503. 0
  143504. };
  143505. static long _vq_quantlist__16u1__p8_1[] = {
  143506. 5,
  143507. 4,
  143508. 6,
  143509. 3,
  143510. 7,
  143511. 2,
  143512. 8,
  143513. 1,
  143514. 9,
  143515. 0,
  143516. 10,
  143517. };
  143518. static long _vq_lengthlist__16u1__p8_1[] = {
  143519. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143520. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143521. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143522. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143523. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143524. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143525. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143526. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143527. };
  143528. static float _vq_quantthresh__16u1__p8_1[] = {
  143529. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143530. 3.5, 4.5,
  143531. };
  143532. static long _vq_quantmap__16u1__p8_1[] = {
  143533. 9, 7, 5, 3, 1, 0, 2, 4,
  143534. 6, 8, 10,
  143535. };
  143536. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143537. _vq_quantthresh__16u1__p8_1,
  143538. _vq_quantmap__16u1__p8_1,
  143539. 11,
  143540. 11
  143541. };
  143542. static static_codebook _16u1__p8_1 = {
  143543. 2, 121,
  143544. _vq_lengthlist__16u1__p8_1,
  143545. 1, -531365888, 1611661312, 4, 0,
  143546. _vq_quantlist__16u1__p8_1,
  143547. NULL,
  143548. &_vq_auxt__16u1__p8_1,
  143549. NULL,
  143550. 0
  143551. };
  143552. static long _vq_quantlist__16u1__p9_0[] = {
  143553. 7,
  143554. 6,
  143555. 8,
  143556. 5,
  143557. 9,
  143558. 4,
  143559. 10,
  143560. 3,
  143561. 11,
  143562. 2,
  143563. 12,
  143564. 1,
  143565. 13,
  143566. 0,
  143567. 14,
  143568. };
  143569. static long _vq_lengthlist__16u1__p9_0[] = {
  143570. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143571. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143572. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143573. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143574. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143575. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143576. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143577. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143578. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143579. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143580. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143581. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143582. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143583. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143584. 8,
  143585. };
  143586. static float _vq_quantthresh__16u1__p9_0[] = {
  143587. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143588. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143589. };
  143590. static long _vq_quantmap__16u1__p9_0[] = {
  143591. 13, 11, 9, 7, 5, 3, 1, 0,
  143592. 2, 4, 6, 8, 10, 12, 14,
  143593. };
  143594. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143595. _vq_quantthresh__16u1__p9_0,
  143596. _vq_quantmap__16u1__p9_0,
  143597. 15,
  143598. 15
  143599. };
  143600. static static_codebook _16u1__p9_0 = {
  143601. 2, 225,
  143602. _vq_lengthlist__16u1__p9_0,
  143603. 1, -514071552, 1627381760, 4, 0,
  143604. _vq_quantlist__16u1__p9_0,
  143605. NULL,
  143606. &_vq_auxt__16u1__p9_0,
  143607. NULL,
  143608. 0
  143609. };
  143610. static long _vq_quantlist__16u1__p9_1[] = {
  143611. 7,
  143612. 6,
  143613. 8,
  143614. 5,
  143615. 9,
  143616. 4,
  143617. 10,
  143618. 3,
  143619. 11,
  143620. 2,
  143621. 12,
  143622. 1,
  143623. 13,
  143624. 0,
  143625. 14,
  143626. };
  143627. static long _vq_lengthlist__16u1__p9_1[] = {
  143628. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143629. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143630. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143631. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143632. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143633. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143634. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143635. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143636. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143637. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143638. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143639. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143640. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143641. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143642. 9,
  143643. };
  143644. static float _vq_quantthresh__16u1__p9_1[] = {
  143645. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143646. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143647. };
  143648. static long _vq_quantmap__16u1__p9_1[] = {
  143649. 13, 11, 9, 7, 5, 3, 1, 0,
  143650. 2, 4, 6, 8, 10, 12, 14,
  143651. };
  143652. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143653. _vq_quantthresh__16u1__p9_1,
  143654. _vq_quantmap__16u1__p9_1,
  143655. 15,
  143656. 15
  143657. };
  143658. static static_codebook _16u1__p9_1 = {
  143659. 2, 225,
  143660. _vq_lengthlist__16u1__p9_1,
  143661. 1, -522338304, 1620115456, 4, 0,
  143662. _vq_quantlist__16u1__p9_1,
  143663. NULL,
  143664. &_vq_auxt__16u1__p9_1,
  143665. NULL,
  143666. 0
  143667. };
  143668. static long _vq_quantlist__16u1__p9_2[] = {
  143669. 8,
  143670. 7,
  143671. 9,
  143672. 6,
  143673. 10,
  143674. 5,
  143675. 11,
  143676. 4,
  143677. 12,
  143678. 3,
  143679. 13,
  143680. 2,
  143681. 14,
  143682. 1,
  143683. 15,
  143684. 0,
  143685. 16,
  143686. };
  143687. static long _vq_lengthlist__16u1__p9_2[] = {
  143688. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143689. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143690. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143691. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143692. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143693. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143694. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143695. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143696. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143697. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143698. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143699. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143700. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143701. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143702. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143703. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143704. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143705. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143706. 10,
  143707. };
  143708. static float _vq_quantthresh__16u1__p9_2[] = {
  143709. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143710. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143711. };
  143712. static long _vq_quantmap__16u1__p9_2[] = {
  143713. 15, 13, 11, 9, 7, 5, 3, 1,
  143714. 0, 2, 4, 6, 8, 10, 12, 14,
  143715. 16,
  143716. };
  143717. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143718. _vq_quantthresh__16u1__p9_2,
  143719. _vq_quantmap__16u1__p9_2,
  143720. 17,
  143721. 17
  143722. };
  143723. static static_codebook _16u1__p9_2 = {
  143724. 2, 289,
  143725. _vq_lengthlist__16u1__p9_2,
  143726. 1, -529530880, 1611661312, 5, 0,
  143727. _vq_quantlist__16u1__p9_2,
  143728. NULL,
  143729. &_vq_auxt__16u1__p9_2,
  143730. NULL,
  143731. 0
  143732. };
  143733. static long _huff_lengthlist__16u1__short[] = {
  143734. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143735. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143736. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143737. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143738. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143739. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143740. 16,16,16,16,
  143741. };
  143742. static static_codebook _huff_book__16u1__short = {
  143743. 2, 100,
  143744. _huff_lengthlist__16u1__short,
  143745. 0, 0, 0, 0, 0,
  143746. NULL,
  143747. NULL,
  143748. NULL,
  143749. NULL,
  143750. 0
  143751. };
  143752. static long _huff_lengthlist__16u2__long[] = {
  143753. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143754. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143755. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143756. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143757. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143758. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143759. 13,14,18,18,
  143760. };
  143761. static static_codebook _huff_book__16u2__long = {
  143762. 2, 100,
  143763. _huff_lengthlist__16u2__long,
  143764. 0, 0, 0, 0, 0,
  143765. NULL,
  143766. NULL,
  143767. NULL,
  143768. NULL,
  143769. 0
  143770. };
  143771. static long _huff_lengthlist__16u2__short[] = {
  143772. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143773. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143774. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143775. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143776. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143777. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143778. 16,16,16,16,
  143779. };
  143780. static static_codebook _huff_book__16u2__short = {
  143781. 2, 100,
  143782. _huff_lengthlist__16u2__short,
  143783. 0, 0, 0, 0, 0,
  143784. NULL,
  143785. NULL,
  143786. NULL,
  143787. NULL,
  143788. 0
  143789. };
  143790. static long _vq_quantlist__16u2_p1_0[] = {
  143791. 1,
  143792. 0,
  143793. 2,
  143794. };
  143795. static long _vq_lengthlist__16u2_p1_0[] = {
  143796. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143797. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143798. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143799. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143800. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143801. 10,
  143802. };
  143803. static float _vq_quantthresh__16u2_p1_0[] = {
  143804. -0.5, 0.5,
  143805. };
  143806. static long _vq_quantmap__16u2_p1_0[] = {
  143807. 1, 0, 2,
  143808. };
  143809. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143810. _vq_quantthresh__16u2_p1_0,
  143811. _vq_quantmap__16u2_p1_0,
  143812. 3,
  143813. 3
  143814. };
  143815. static static_codebook _16u2_p1_0 = {
  143816. 4, 81,
  143817. _vq_lengthlist__16u2_p1_0,
  143818. 1, -535822336, 1611661312, 2, 0,
  143819. _vq_quantlist__16u2_p1_0,
  143820. NULL,
  143821. &_vq_auxt__16u2_p1_0,
  143822. NULL,
  143823. 0
  143824. };
  143825. static long _vq_quantlist__16u2_p2_0[] = {
  143826. 2,
  143827. 1,
  143828. 3,
  143829. 0,
  143830. 4,
  143831. };
  143832. static long _vq_lengthlist__16u2_p2_0[] = {
  143833. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143834. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143835. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143836. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143837. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143838. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143839. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143840. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143841. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143842. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143843. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143844. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143845. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143846. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143847. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143848. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143849. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143850. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143851. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143852. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143853. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143854. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143855. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143856. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143857. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143858. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143859. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143860. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143861. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143862. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143863. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143864. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143865. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143866. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143867. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143868. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143869. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143870. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143871. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143872. 13,
  143873. };
  143874. static float _vq_quantthresh__16u2_p2_0[] = {
  143875. -1.5, -0.5, 0.5, 1.5,
  143876. };
  143877. static long _vq_quantmap__16u2_p2_0[] = {
  143878. 3, 1, 0, 2, 4,
  143879. };
  143880. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143881. _vq_quantthresh__16u2_p2_0,
  143882. _vq_quantmap__16u2_p2_0,
  143883. 5,
  143884. 5
  143885. };
  143886. static static_codebook _16u2_p2_0 = {
  143887. 4, 625,
  143888. _vq_lengthlist__16u2_p2_0,
  143889. 1, -533725184, 1611661312, 3, 0,
  143890. _vq_quantlist__16u2_p2_0,
  143891. NULL,
  143892. &_vq_auxt__16u2_p2_0,
  143893. NULL,
  143894. 0
  143895. };
  143896. static long _vq_quantlist__16u2_p3_0[] = {
  143897. 4,
  143898. 3,
  143899. 5,
  143900. 2,
  143901. 6,
  143902. 1,
  143903. 7,
  143904. 0,
  143905. 8,
  143906. };
  143907. static long _vq_lengthlist__16u2_p3_0[] = {
  143908. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143909. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143910. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143911. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143912. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143913. 11,
  143914. };
  143915. static float _vq_quantthresh__16u2_p3_0[] = {
  143916. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143917. };
  143918. static long _vq_quantmap__16u2_p3_0[] = {
  143919. 7, 5, 3, 1, 0, 2, 4, 6,
  143920. 8,
  143921. };
  143922. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143923. _vq_quantthresh__16u2_p3_0,
  143924. _vq_quantmap__16u2_p3_0,
  143925. 9,
  143926. 9
  143927. };
  143928. static static_codebook _16u2_p3_0 = {
  143929. 2, 81,
  143930. _vq_lengthlist__16u2_p3_0,
  143931. 1, -531628032, 1611661312, 4, 0,
  143932. _vq_quantlist__16u2_p3_0,
  143933. NULL,
  143934. &_vq_auxt__16u2_p3_0,
  143935. NULL,
  143936. 0
  143937. };
  143938. static long _vq_quantlist__16u2_p4_0[] = {
  143939. 8,
  143940. 7,
  143941. 9,
  143942. 6,
  143943. 10,
  143944. 5,
  143945. 11,
  143946. 4,
  143947. 12,
  143948. 3,
  143949. 13,
  143950. 2,
  143951. 14,
  143952. 1,
  143953. 15,
  143954. 0,
  143955. 16,
  143956. };
  143957. static long _vq_lengthlist__16u2_p4_0[] = {
  143958. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143959. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143960. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143961. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143962. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143963. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143964. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143965. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143966. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143967. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143968. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143969. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143970. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143971. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143972. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143973. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143974. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143975. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143976. 14,
  143977. };
  143978. static float _vq_quantthresh__16u2_p4_0[] = {
  143979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143981. };
  143982. static long _vq_quantmap__16u2_p4_0[] = {
  143983. 15, 13, 11, 9, 7, 5, 3, 1,
  143984. 0, 2, 4, 6, 8, 10, 12, 14,
  143985. 16,
  143986. };
  143987. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143988. _vq_quantthresh__16u2_p4_0,
  143989. _vq_quantmap__16u2_p4_0,
  143990. 17,
  143991. 17
  143992. };
  143993. static static_codebook _16u2_p4_0 = {
  143994. 2, 289,
  143995. _vq_lengthlist__16u2_p4_0,
  143996. 1, -529530880, 1611661312, 5, 0,
  143997. _vq_quantlist__16u2_p4_0,
  143998. NULL,
  143999. &_vq_auxt__16u2_p4_0,
  144000. NULL,
  144001. 0
  144002. };
  144003. static long _vq_quantlist__16u2_p5_0[] = {
  144004. 1,
  144005. 0,
  144006. 2,
  144007. };
  144008. static long _vq_lengthlist__16u2_p5_0[] = {
  144009. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144010. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144011. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144012. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144013. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144014. 10,
  144015. };
  144016. static float _vq_quantthresh__16u2_p5_0[] = {
  144017. -5.5, 5.5,
  144018. };
  144019. static long _vq_quantmap__16u2_p5_0[] = {
  144020. 1, 0, 2,
  144021. };
  144022. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144023. _vq_quantthresh__16u2_p5_0,
  144024. _vq_quantmap__16u2_p5_0,
  144025. 3,
  144026. 3
  144027. };
  144028. static static_codebook _16u2_p5_0 = {
  144029. 4, 81,
  144030. _vq_lengthlist__16u2_p5_0,
  144031. 1, -529137664, 1618345984, 2, 0,
  144032. _vq_quantlist__16u2_p5_0,
  144033. NULL,
  144034. &_vq_auxt__16u2_p5_0,
  144035. NULL,
  144036. 0
  144037. };
  144038. static long _vq_quantlist__16u2_p5_1[] = {
  144039. 5,
  144040. 4,
  144041. 6,
  144042. 3,
  144043. 7,
  144044. 2,
  144045. 8,
  144046. 1,
  144047. 9,
  144048. 0,
  144049. 10,
  144050. };
  144051. static long _vq_lengthlist__16u2_p5_1[] = {
  144052. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144053. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144054. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144055. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144056. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144057. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144058. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144059. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144060. };
  144061. static float _vq_quantthresh__16u2_p5_1[] = {
  144062. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144063. 3.5, 4.5,
  144064. };
  144065. static long _vq_quantmap__16u2_p5_1[] = {
  144066. 9, 7, 5, 3, 1, 0, 2, 4,
  144067. 6, 8, 10,
  144068. };
  144069. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144070. _vq_quantthresh__16u2_p5_1,
  144071. _vq_quantmap__16u2_p5_1,
  144072. 11,
  144073. 11
  144074. };
  144075. static static_codebook _16u2_p5_1 = {
  144076. 2, 121,
  144077. _vq_lengthlist__16u2_p5_1,
  144078. 1, -531365888, 1611661312, 4, 0,
  144079. _vq_quantlist__16u2_p5_1,
  144080. NULL,
  144081. &_vq_auxt__16u2_p5_1,
  144082. NULL,
  144083. 0
  144084. };
  144085. static long _vq_quantlist__16u2_p6_0[] = {
  144086. 6,
  144087. 5,
  144088. 7,
  144089. 4,
  144090. 8,
  144091. 3,
  144092. 9,
  144093. 2,
  144094. 10,
  144095. 1,
  144096. 11,
  144097. 0,
  144098. 12,
  144099. };
  144100. static long _vq_lengthlist__16u2_p6_0[] = {
  144101. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144102. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144103. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144104. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144105. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144106. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144107. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144108. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144109. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144110. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144111. 12,13,13,14,14,14,14,15,15,
  144112. };
  144113. static float _vq_quantthresh__16u2_p6_0[] = {
  144114. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144115. 12.5, 17.5, 22.5, 27.5,
  144116. };
  144117. static long _vq_quantmap__16u2_p6_0[] = {
  144118. 11, 9, 7, 5, 3, 1, 0, 2,
  144119. 4, 6, 8, 10, 12,
  144120. };
  144121. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144122. _vq_quantthresh__16u2_p6_0,
  144123. _vq_quantmap__16u2_p6_0,
  144124. 13,
  144125. 13
  144126. };
  144127. static static_codebook _16u2_p6_0 = {
  144128. 2, 169,
  144129. _vq_lengthlist__16u2_p6_0,
  144130. 1, -526516224, 1616117760, 4, 0,
  144131. _vq_quantlist__16u2_p6_0,
  144132. NULL,
  144133. &_vq_auxt__16u2_p6_0,
  144134. NULL,
  144135. 0
  144136. };
  144137. static long _vq_quantlist__16u2_p6_1[] = {
  144138. 2,
  144139. 1,
  144140. 3,
  144141. 0,
  144142. 4,
  144143. };
  144144. static long _vq_lengthlist__16u2_p6_1[] = {
  144145. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144146. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144147. };
  144148. static float _vq_quantthresh__16u2_p6_1[] = {
  144149. -1.5, -0.5, 0.5, 1.5,
  144150. };
  144151. static long _vq_quantmap__16u2_p6_1[] = {
  144152. 3, 1, 0, 2, 4,
  144153. };
  144154. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144155. _vq_quantthresh__16u2_p6_1,
  144156. _vq_quantmap__16u2_p6_1,
  144157. 5,
  144158. 5
  144159. };
  144160. static static_codebook _16u2_p6_1 = {
  144161. 2, 25,
  144162. _vq_lengthlist__16u2_p6_1,
  144163. 1, -533725184, 1611661312, 3, 0,
  144164. _vq_quantlist__16u2_p6_1,
  144165. NULL,
  144166. &_vq_auxt__16u2_p6_1,
  144167. NULL,
  144168. 0
  144169. };
  144170. static long _vq_quantlist__16u2_p7_0[] = {
  144171. 6,
  144172. 5,
  144173. 7,
  144174. 4,
  144175. 8,
  144176. 3,
  144177. 9,
  144178. 2,
  144179. 10,
  144180. 1,
  144181. 11,
  144182. 0,
  144183. 12,
  144184. };
  144185. static long _vq_lengthlist__16u2_p7_0[] = {
  144186. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144187. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144188. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144189. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144190. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144191. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144192. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144193. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144194. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144195. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144196. 12,13,13,13,14,14,14,15,14,
  144197. };
  144198. static float _vq_quantthresh__16u2_p7_0[] = {
  144199. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144200. 27.5, 38.5, 49.5, 60.5,
  144201. };
  144202. static long _vq_quantmap__16u2_p7_0[] = {
  144203. 11, 9, 7, 5, 3, 1, 0, 2,
  144204. 4, 6, 8, 10, 12,
  144205. };
  144206. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144207. _vq_quantthresh__16u2_p7_0,
  144208. _vq_quantmap__16u2_p7_0,
  144209. 13,
  144210. 13
  144211. };
  144212. static static_codebook _16u2_p7_0 = {
  144213. 2, 169,
  144214. _vq_lengthlist__16u2_p7_0,
  144215. 1, -523206656, 1618345984, 4, 0,
  144216. _vq_quantlist__16u2_p7_0,
  144217. NULL,
  144218. &_vq_auxt__16u2_p7_0,
  144219. NULL,
  144220. 0
  144221. };
  144222. static long _vq_quantlist__16u2_p7_1[] = {
  144223. 5,
  144224. 4,
  144225. 6,
  144226. 3,
  144227. 7,
  144228. 2,
  144229. 8,
  144230. 1,
  144231. 9,
  144232. 0,
  144233. 10,
  144234. };
  144235. static long _vq_lengthlist__16u2_p7_1[] = {
  144236. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144237. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144238. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144239. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144240. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144241. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144242. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144243. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144244. };
  144245. static float _vq_quantthresh__16u2_p7_1[] = {
  144246. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144247. 3.5, 4.5,
  144248. };
  144249. static long _vq_quantmap__16u2_p7_1[] = {
  144250. 9, 7, 5, 3, 1, 0, 2, 4,
  144251. 6, 8, 10,
  144252. };
  144253. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144254. _vq_quantthresh__16u2_p7_1,
  144255. _vq_quantmap__16u2_p7_1,
  144256. 11,
  144257. 11
  144258. };
  144259. static static_codebook _16u2_p7_1 = {
  144260. 2, 121,
  144261. _vq_lengthlist__16u2_p7_1,
  144262. 1, -531365888, 1611661312, 4, 0,
  144263. _vq_quantlist__16u2_p7_1,
  144264. NULL,
  144265. &_vq_auxt__16u2_p7_1,
  144266. NULL,
  144267. 0
  144268. };
  144269. static long _vq_quantlist__16u2_p8_0[] = {
  144270. 7,
  144271. 6,
  144272. 8,
  144273. 5,
  144274. 9,
  144275. 4,
  144276. 10,
  144277. 3,
  144278. 11,
  144279. 2,
  144280. 12,
  144281. 1,
  144282. 13,
  144283. 0,
  144284. 14,
  144285. };
  144286. static long _vq_lengthlist__16u2_p8_0[] = {
  144287. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144288. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144289. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144290. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144291. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144292. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144293. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144294. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144295. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144296. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144297. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144298. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144299. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144300. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144301. 14,
  144302. };
  144303. static float _vq_quantthresh__16u2_p8_0[] = {
  144304. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144305. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144306. };
  144307. static long _vq_quantmap__16u2_p8_0[] = {
  144308. 13, 11, 9, 7, 5, 3, 1, 0,
  144309. 2, 4, 6, 8, 10, 12, 14,
  144310. };
  144311. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144312. _vq_quantthresh__16u2_p8_0,
  144313. _vq_quantmap__16u2_p8_0,
  144314. 15,
  144315. 15
  144316. };
  144317. static static_codebook _16u2_p8_0 = {
  144318. 2, 225,
  144319. _vq_lengthlist__16u2_p8_0,
  144320. 1, -520986624, 1620377600, 4, 0,
  144321. _vq_quantlist__16u2_p8_0,
  144322. NULL,
  144323. &_vq_auxt__16u2_p8_0,
  144324. NULL,
  144325. 0
  144326. };
  144327. static long _vq_quantlist__16u2_p8_1[] = {
  144328. 10,
  144329. 9,
  144330. 11,
  144331. 8,
  144332. 12,
  144333. 7,
  144334. 13,
  144335. 6,
  144336. 14,
  144337. 5,
  144338. 15,
  144339. 4,
  144340. 16,
  144341. 3,
  144342. 17,
  144343. 2,
  144344. 18,
  144345. 1,
  144346. 19,
  144347. 0,
  144348. 20,
  144349. };
  144350. static long _vq_lengthlist__16u2_p8_1[] = {
  144351. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144352. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144353. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144354. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144355. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144356. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144357. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144358. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144359. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144360. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144361. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144362. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144363. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144364. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144365. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144366. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144367. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144368. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144369. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144370. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144371. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144372. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144373. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144374. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144376. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144377. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144378. 11,11,10,11,11,11,10,11,11,
  144379. };
  144380. static float _vq_quantthresh__16u2_p8_1[] = {
  144381. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144382. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144383. 6.5, 7.5, 8.5, 9.5,
  144384. };
  144385. static long _vq_quantmap__16u2_p8_1[] = {
  144386. 19, 17, 15, 13, 11, 9, 7, 5,
  144387. 3, 1, 0, 2, 4, 6, 8, 10,
  144388. 12, 14, 16, 18, 20,
  144389. };
  144390. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144391. _vq_quantthresh__16u2_p8_1,
  144392. _vq_quantmap__16u2_p8_1,
  144393. 21,
  144394. 21
  144395. };
  144396. static static_codebook _16u2_p8_1 = {
  144397. 2, 441,
  144398. _vq_lengthlist__16u2_p8_1,
  144399. 1, -529268736, 1611661312, 5, 0,
  144400. _vq_quantlist__16u2_p8_1,
  144401. NULL,
  144402. &_vq_auxt__16u2_p8_1,
  144403. NULL,
  144404. 0
  144405. };
  144406. static long _vq_quantlist__16u2_p9_0[] = {
  144407. 5586,
  144408. 4655,
  144409. 6517,
  144410. 3724,
  144411. 7448,
  144412. 2793,
  144413. 8379,
  144414. 1862,
  144415. 9310,
  144416. 931,
  144417. 10241,
  144418. 0,
  144419. 11172,
  144420. 5521,
  144421. 5651,
  144422. };
  144423. static long _vq_lengthlist__16u2_p9_0[] = {
  144424. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144425. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144426. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144427. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144428. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144431. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144432. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144433. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144434. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144435. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144436. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144437. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144438. 5,
  144439. };
  144440. static float _vq_quantthresh__16u2_p9_0[] = {
  144441. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144442. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144443. };
  144444. static long _vq_quantmap__16u2_p9_0[] = {
  144445. 11, 9, 7, 5, 3, 1, 13, 0,
  144446. 14, 2, 4, 6, 8, 10, 12,
  144447. };
  144448. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144449. _vq_quantthresh__16u2_p9_0,
  144450. _vq_quantmap__16u2_p9_0,
  144451. 15,
  144452. 15
  144453. };
  144454. static static_codebook _16u2_p9_0 = {
  144455. 2, 225,
  144456. _vq_lengthlist__16u2_p9_0,
  144457. 1, -510275072, 1611661312, 14, 0,
  144458. _vq_quantlist__16u2_p9_0,
  144459. NULL,
  144460. &_vq_auxt__16u2_p9_0,
  144461. NULL,
  144462. 0
  144463. };
  144464. static long _vq_quantlist__16u2_p9_1[] = {
  144465. 392,
  144466. 343,
  144467. 441,
  144468. 294,
  144469. 490,
  144470. 245,
  144471. 539,
  144472. 196,
  144473. 588,
  144474. 147,
  144475. 637,
  144476. 98,
  144477. 686,
  144478. 49,
  144479. 735,
  144480. 0,
  144481. 784,
  144482. 388,
  144483. 396,
  144484. };
  144485. static long _vq_lengthlist__16u2_p9_1[] = {
  144486. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144487. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144488. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144489. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144490. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144491. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144492. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144493. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144494. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144495. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144496. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144497. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144498. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144499. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144500. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144506. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144507. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144508. 11,11,11,11,11,11,11, 5, 4,
  144509. };
  144510. static float _vq_quantthresh__16u2_p9_1[] = {
  144511. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144512. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144513. 318.5, 367.5,
  144514. };
  144515. static long _vq_quantmap__16u2_p9_1[] = {
  144516. 15, 13, 11, 9, 7, 5, 3, 1,
  144517. 17, 0, 18, 2, 4, 6, 8, 10,
  144518. 12, 14, 16,
  144519. };
  144520. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144521. _vq_quantthresh__16u2_p9_1,
  144522. _vq_quantmap__16u2_p9_1,
  144523. 19,
  144524. 19
  144525. };
  144526. static static_codebook _16u2_p9_1 = {
  144527. 2, 361,
  144528. _vq_lengthlist__16u2_p9_1,
  144529. 1, -518488064, 1611661312, 10, 0,
  144530. _vq_quantlist__16u2_p9_1,
  144531. NULL,
  144532. &_vq_auxt__16u2_p9_1,
  144533. NULL,
  144534. 0
  144535. };
  144536. static long _vq_quantlist__16u2_p9_2[] = {
  144537. 24,
  144538. 23,
  144539. 25,
  144540. 22,
  144541. 26,
  144542. 21,
  144543. 27,
  144544. 20,
  144545. 28,
  144546. 19,
  144547. 29,
  144548. 18,
  144549. 30,
  144550. 17,
  144551. 31,
  144552. 16,
  144553. 32,
  144554. 15,
  144555. 33,
  144556. 14,
  144557. 34,
  144558. 13,
  144559. 35,
  144560. 12,
  144561. 36,
  144562. 11,
  144563. 37,
  144564. 10,
  144565. 38,
  144566. 9,
  144567. 39,
  144568. 8,
  144569. 40,
  144570. 7,
  144571. 41,
  144572. 6,
  144573. 42,
  144574. 5,
  144575. 43,
  144576. 4,
  144577. 44,
  144578. 3,
  144579. 45,
  144580. 2,
  144581. 46,
  144582. 1,
  144583. 47,
  144584. 0,
  144585. 48,
  144586. };
  144587. static long _vq_lengthlist__16u2_p9_2[] = {
  144588. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144589. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144590. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144591. 11,
  144592. };
  144593. static float _vq_quantthresh__16u2_p9_2[] = {
  144594. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144595. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144598. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144599. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144600. };
  144601. static long _vq_quantmap__16u2_p9_2[] = {
  144602. 47, 45, 43, 41, 39, 37, 35, 33,
  144603. 31, 29, 27, 25, 23, 21, 19, 17,
  144604. 15, 13, 11, 9, 7, 5, 3, 1,
  144605. 0, 2, 4, 6, 8, 10, 12, 14,
  144606. 16, 18, 20, 22, 24, 26, 28, 30,
  144607. 32, 34, 36, 38, 40, 42, 44, 46,
  144608. 48,
  144609. };
  144610. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144611. _vq_quantthresh__16u2_p9_2,
  144612. _vq_quantmap__16u2_p9_2,
  144613. 49,
  144614. 49
  144615. };
  144616. static static_codebook _16u2_p9_2 = {
  144617. 1, 49,
  144618. _vq_lengthlist__16u2_p9_2,
  144619. 1, -526909440, 1611661312, 6, 0,
  144620. _vq_quantlist__16u2_p9_2,
  144621. NULL,
  144622. &_vq_auxt__16u2_p9_2,
  144623. NULL,
  144624. 0
  144625. };
  144626. static long _vq_quantlist__8u0__p1_0[] = {
  144627. 1,
  144628. 0,
  144629. 2,
  144630. };
  144631. static long _vq_lengthlist__8u0__p1_0[] = {
  144632. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144633. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144634. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144635. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144636. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144637. 11,
  144638. };
  144639. static float _vq_quantthresh__8u0__p1_0[] = {
  144640. -0.5, 0.5,
  144641. };
  144642. static long _vq_quantmap__8u0__p1_0[] = {
  144643. 1, 0, 2,
  144644. };
  144645. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144646. _vq_quantthresh__8u0__p1_0,
  144647. _vq_quantmap__8u0__p1_0,
  144648. 3,
  144649. 3
  144650. };
  144651. static static_codebook _8u0__p1_0 = {
  144652. 4, 81,
  144653. _vq_lengthlist__8u0__p1_0,
  144654. 1, -535822336, 1611661312, 2, 0,
  144655. _vq_quantlist__8u0__p1_0,
  144656. NULL,
  144657. &_vq_auxt__8u0__p1_0,
  144658. NULL,
  144659. 0
  144660. };
  144661. static long _vq_quantlist__8u0__p2_0[] = {
  144662. 1,
  144663. 0,
  144664. 2,
  144665. };
  144666. static long _vq_lengthlist__8u0__p2_0[] = {
  144667. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144668. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144669. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144670. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144671. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144672. 8,
  144673. };
  144674. static float _vq_quantthresh__8u0__p2_0[] = {
  144675. -0.5, 0.5,
  144676. };
  144677. static long _vq_quantmap__8u0__p2_0[] = {
  144678. 1, 0, 2,
  144679. };
  144680. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144681. _vq_quantthresh__8u0__p2_0,
  144682. _vq_quantmap__8u0__p2_0,
  144683. 3,
  144684. 3
  144685. };
  144686. static static_codebook _8u0__p2_0 = {
  144687. 4, 81,
  144688. _vq_lengthlist__8u0__p2_0,
  144689. 1, -535822336, 1611661312, 2, 0,
  144690. _vq_quantlist__8u0__p2_0,
  144691. NULL,
  144692. &_vq_auxt__8u0__p2_0,
  144693. NULL,
  144694. 0
  144695. };
  144696. static long _vq_quantlist__8u0__p3_0[] = {
  144697. 2,
  144698. 1,
  144699. 3,
  144700. 0,
  144701. 4,
  144702. };
  144703. static long _vq_lengthlist__8u0__p3_0[] = {
  144704. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144705. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144706. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144707. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144708. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144709. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144710. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144711. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144712. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144713. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144714. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144715. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144716. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144717. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144718. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144719. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144720. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144721. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144722. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144723. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144724. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144725. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144726. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144727. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144728. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144729. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144730. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144731. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144732. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144733. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144734. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144735. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144736. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144737. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144738. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144739. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144740. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144741. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144742. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144743. 16,
  144744. };
  144745. static float _vq_quantthresh__8u0__p3_0[] = {
  144746. -1.5, -0.5, 0.5, 1.5,
  144747. };
  144748. static long _vq_quantmap__8u0__p3_0[] = {
  144749. 3, 1, 0, 2, 4,
  144750. };
  144751. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144752. _vq_quantthresh__8u0__p3_0,
  144753. _vq_quantmap__8u0__p3_0,
  144754. 5,
  144755. 5
  144756. };
  144757. static static_codebook _8u0__p3_0 = {
  144758. 4, 625,
  144759. _vq_lengthlist__8u0__p3_0,
  144760. 1, -533725184, 1611661312, 3, 0,
  144761. _vq_quantlist__8u0__p3_0,
  144762. NULL,
  144763. &_vq_auxt__8u0__p3_0,
  144764. NULL,
  144765. 0
  144766. };
  144767. static long _vq_quantlist__8u0__p4_0[] = {
  144768. 2,
  144769. 1,
  144770. 3,
  144771. 0,
  144772. 4,
  144773. };
  144774. static long _vq_lengthlist__8u0__p4_0[] = {
  144775. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144776. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144777. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144778. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144779. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144780. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144781. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144782. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144783. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144784. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144785. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144786. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144787. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144788. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144789. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144790. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144791. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144792. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144793. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144794. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144795. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144796. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144797. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144798. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144799. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144800. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144801. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144802. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144803. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144804. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144805. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144806. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144807. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144808. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144809. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144810. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144811. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144812. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144813. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144814. 12,
  144815. };
  144816. static float _vq_quantthresh__8u0__p4_0[] = {
  144817. -1.5, -0.5, 0.5, 1.5,
  144818. };
  144819. static long _vq_quantmap__8u0__p4_0[] = {
  144820. 3, 1, 0, 2, 4,
  144821. };
  144822. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144823. _vq_quantthresh__8u0__p4_0,
  144824. _vq_quantmap__8u0__p4_0,
  144825. 5,
  144826. 5
  144827. };
  144828. static static_codebook _8u0__p4_0 = {
  144829. 4, 625,
  144830. _vq_lengthlist__8u0__p4_0,
  144831. 1, -533725184, 1611661312, 3, 0,
  144832. _vq_quantlist__8u0__p4_0,
  144833. NULL,
  144834. &_vq_auxt__8u0__p4_0,
  144835. NULL,
  144836. 0
  144837. };
  144838. static long _vq_quantlist__8u0__p5_0[] = {
  144839. 4,
  144840. 3,
  144841. 5,
  144842. 2,
  144843. 6,
  144844. 1,
  144845. 7,
  144846. 0,
  144847. 8,
  144848. };
  144849. static long _vq_lengthlist__8u0__p5_0[] = {
  144850. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144851. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144852. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144853. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144854. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144855. 12,
  144856. };
  144857. static float _vq_quantthresh__8u0__p5_0[] = {
  144858. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144859. };
  144860. static long _vq_quantmap__8u0__p5_0[] = {
  144861. 7, 5, 3, 1, 0, 2, 4, 6,
  144862. 8,
  144863. };
  144864. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144865. _vq_quantthresh__8u0__p5_0,
  144866. _vq_quantmap__8u0__p5_0,
  144867. 9,
  144868. 9
  144869. };
  144870. static static_codebook _8u0__p5_0 = {
  144871. 2, 81,
  144872. _vq_lengthlist__8u0__p5_0,
  144873. 1, -531628032, 1611661312, 4, 0,
  144874. _vq_quantlist__8u0__p5_0,
  144875. NULL,
  144876. &_vq_auxt__8u0__p5_0,
  144877. NULL,
  144878. 0
  144879. };
  144880. static long _vq_quantlist__8u0__p6_0[] = {
  144881. 6,
  144882. 5,
  144883. 7,
  144884. 4,
  144885. 8,
  144886. 3,
  144887. 9,
  144888. 2,
  144889. 10,
  144890. 1,
  144891. 11,
  144892. 0,
  144893. 12,
  144894. };
  144895. static long _vq_lengthlist__8u0__p6_0[] = {
  144896. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144897. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144898. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144899. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144900. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144901. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144902. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144903. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144904. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144905. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144906. 16, 0,15, 0,17, 0, 0, 0, 0,
  144907. };
  144908. static float _vq_quantthresh__8u0__p6_0[] = {
  144909. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144910. 12.5, 17.5, 22.5, 27.5,
  144911. };
  144912. static long _vq_quantmap__8u0__p6_0[] = {
  144913. 11, 9, 7, 5, 3, 1, 0, 2,
  144914. 4, 6, 8, 10, 12,
  144915. };
  144916. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144917. _vq_quantthresh__8u0__p6_0,
  144918. _vq_quantmap__8u0__p6_0,
  144919. 13,
  144920. 13
  144921. };
  144922. static static_codebook _8u0__p6_0 = {
  144923. 2, 169,
  144924. _vq_lengthlist__8u0__p6_0,
  144925. 1, -526516224, 1616117760, 4, 0,
  144926. _vq_quantlist__8u0__p6_0,
  144927. NULL,
  144928. &_vq_auxt__8u0__p6_0,
  144929. NULL,
  144930. 0
  144931. };
  144932. static long _vq_quantlist__8u0__p6_1[] = {
  144933. 2,
  144934. 1,
  144935. 3,
  144936. 0,
  144937. 4,
  144938. };
  144939. static long _vq_lengthlist__8u0__p6_1[] = {
  144940. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144941. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144942. };
  144943. static float _vq_quantthresh__8u0__p6_1[] = {
  144944. -1.5, -0.5, 0.5, 1.5,
  144945. };
  144946. static long _vq_quantmap__8u0__p6_1[] = {
  144947. 3, 1, 0, 2, 4,
  144948. };
  144949. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144950. _vq_quantthresh__8u0__p6_1,
  144951. _vq_quantmap__8u0__p6_1,
  144952. 5,
  144953. 5
  144954. };
  144955. static static_codebook _8u0__p6_1 = {
  144956. 2, 25,
  144957. _vq_lengthlist__8u0__p6_1,
  144958. 1, -533725184, 1611661312, 3, 0,
  144959. _vq_quantlist__8u0__p6_1,
  144960. NULL,
  144961. &_vq_auxt__8u0__p6_1,
  144962. NULL,
  144963. 0
  144964. };
  144965. static long _vq_quantlist__8u0__p7_0[] = {
  144966. 1,
  144967. 0,
  144968. 2,
  144969. };
  144970. static long _vq_lengthlist__8u0__p7_0[] = {
  144971. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144972. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144973. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144974. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144975. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144976. 7,
  144977. };
  144978. static float _vq_quantthresh__8u0__p7_0[] = {
  144979. -157.5, 157.5,
  144980. };
  144981. static long _vq_quantmap__8u0__p7_0[] = {
  144982. 1, 0, 2,
  144983. };
  144984. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144985. _vq_quantthresh__8u0__p7_0,
  144986. _vq_quantmap__8u0__p7_0,
  144987. 3,
  144988. 3
  144989. };
  144990. static static_codebook _8u0__p7_0 = {
  144991. 4, 81,
  144992. _vq_lengthlist__8u0__p7_0,
  144993. 1, -518803456, 1628680192, 2, 0,
  144994. _vq_quantlist__8u0__p7_0,
  144995. NULL,
  144996. &_vq_auxt__8u0__p7_0,
  144997. NULL,
  144998. 0
  144999. };
  145000. static long _vq_quantlist__8u0__p7_1[] = {
  145001. 7,
  145002. 6,
  145003. 8,
  145004. 5,
  145005. 9,
  145006. 4,
  145007. 10,
  145008. 3,
  145009. 11,
  145010. 2,
  145011. 12,
  145012. 1,
  145013. 13,
  145014. 0,
  145015. 14,
  145016. };
  145017. static long _vq_lengthlist__8u0__p7_1[] = {
  145018. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145019. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145020. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145021. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145022. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145023. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145030. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145032. 10,
  145033. };
  145034. static float _vq_quantthresh__8u0__p7_1[] = {
  145035. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145036. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145037. };
  145038. static long _vq_quantmap__8u0__p7_1[] = {
  145039. 13, 11, 9, 7, 5, 3, 1, 0,
  145040. 2, 4, 6, 8, 10, 12, 14,
  145041. };
  145042. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145043. _vq_quantthresh__8u0__p7_1,
  145044. _vq_quantmap__8u0__p7_1,
  145045. 15,
  145046. 15
  145047. };
  145048. static static_codebook _8u0__p7_1 = {
  145049. 2, 225,
  145050. _vq_lengthlist__8u0__p7_1,
  145051. 1, -520986624, 1620377600, 4, 0,
  145052. _vq_quantlist__8u0__p7_1,
  145053. NULL,
  145054. &_vq_auxt__8u0__p7_1,
  145055. NULL,
  145056. 0
  145057. };
  145058. static long _vq_quantlist__8u0__p7_2[] = {
  145059. 10,
  145060. 9,
  145061. 11,
  145062. 8,
  145063. 12,
  145064. 7,
  145065. 13,
  145066. 6,
  145067. 14,
  145068. 5,
  145069. 15,
  145070. 4,
  145071. 16,
  145072. 3,
  145073. 17,
  145074. 2,
  145075. 18,
  145076. 1,
  145077. 19,
  145078. 0,
  145079. 20,
  145080. };
  145081. static long _vq_lengthlist__8u0__p7_2[] = {
  145082. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145083. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145084. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145085. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145086. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145087. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145088. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145089. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145090. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145091. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145092. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145093. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145094. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145095. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145096. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145097. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145098. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145099. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145100. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145101. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145102. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145103. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145104. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145105. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145106. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145107. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145108. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145109. 11,12,11,11,11,10,10,11,11,
  145110. };
  145111. static float _vq_quantthresh__8u0__p7_2[] = {
  145112. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145113. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145114. 6.5, 7.5, 8.5, 9.5,
  145115. };
  145116. static long _vq_quantmap__8u0__p7_2[] = {
  145117. 19, 17, 15, 13, 11, 9, 7, 5,
  145118. 3, 1, 0, 2, 4, 6, 8, 10,
  145119. 12, 14, 16, 18, 20,
  145120. };
  145121. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145122. _vq_quantthresh__8u0__p7_2,
  145123. _vq_quantmap__8u0__p7_2,
  145124. 21,
  145125. 21
  145126. };
  145127. static static_codebook _8u0__p7_2 = {
  145128. 2, 441,
  145129. _vq_lengthlist__8u0__p7_2,
  145130. 1, -529268736, 1611661312, 5, 0,
  145131. _vq_quantlist__8u0__p7_2,
  145132. NULL,
  145133. &_vq_auxt__8u0__p7_2,
  145134. NULL,
  145135. 0
  145136. };
  145137. static long _huff_lengthlist__8u0__single[] = {
  145138. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145139. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145140. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145141. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145142. };
  145143. static static_codebook _huff_book__8u0__single = {
  145144. 2, 64,
  145145. _huff_lengthlist__8u0__single,
  145146. 0, 0, 0, 0, 0,
  145147. NULL,
  145148. NULL,
  145149. NULL,
  145150. NULL,
  145151. 0
  145152. };
  145153. static long _vq_quantlist__8u1__p1_0[] = {
  145154. 1,
  145155. 0,
  145156. 2,
  145157. };
  145158. static long _vq_lengthlist__8u1__p1_0[] = {
  145159. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145160. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145161. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145162. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145163. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145164. 10,
  145165. };
  145166. static float _vq_quantthresh__8u1__p1_0[] = {
  145167. -0.5, 0.5,
  145168. };
  145169. static long _vq_quantmap__8u1__p1_0[] = {
  145170. 1, 0, 2,
  145171. };
  145172. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145173. _vq_quantthresh__8u1__p1_0,
  145174. _vq_quantmap__8u1__p1_0,
  145175. 3,
  145176. 3
  145177. };
  145178. static static_codebook _8u1__p1_0 = {
  145179. 4, 81,
  145180. _vq_lengthlist__8u1__p1_0,
  145181. 1, -535822336, 1611661312, 2, 0,
  145182. _vq_quantlist__8u1__p1_0,
  145183. NULL,
  145184. &_vq_auxt__8u1__p1_0,
  145185. NULL,
  145186. 0
  145187. };
  145188. static long _vq_quantlist__8u1__p2_0[] = {
  145189. 1,
  145190. 0,
  145191. 2,
  145192. };
  145193. static long _vq_lengthlist__8u1__p2_0[] = {
  145194. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145195. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145196. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145197. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145198. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145199. 7,
  145200. };
  145201. static float _vq_quantthresh__8u1__p2_0[] = {
  145202. -0.5, 0.5,
  145203. };
  145204. static long _vq_quantmap__8u1__p2_0[] = {
  145205. 1, 0, 2,
  145206. };
  145207. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145208. _vq_quantthresh__8u1__p2_0,
  145209. _vq_quantmap__8u1__p2_0,
  145210. 3,
  145211. 3
  145212. };
  145213. static static_codebook _8u1__p2_0 = {
  145214. 4, 81,
  145215. _vq_lengthlist__8u1__p2_0,
  145216. 1, -535822336, 1611661312, 2, 0,
  145217. _vq_quantlist__8u1__p2_0,
  145218. NULL,
  145219. &_vq_auxt__8u1__p2_0,
  145220. NULL,
  145221. 0
  145222. };
  145223. static long _vq_quantlist__8u1__p3_0[] = {
  145224. 2,
  145225. 1,
  145226. 3,
  145227. 0,
  145228. 4,
  145229. };
  145230. static long _vq_lengthlist__8u1__p3_0[] = {
  145231. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145232. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145233. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145234. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145235. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145236. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145237. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145238. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145239. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145240. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145241. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145242. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145243. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145244. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145245. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145246. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145247. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145248. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145249. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145250. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145251. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145252. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145253. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145254. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145255. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145256. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145257. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145258. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145259. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145260. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145261. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145262. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145263. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145264. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145265. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145266. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145267. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145268. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145269. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145270. 16,
  145271. };
  145272. static float _vq_quantthresh__8u1__p3_0[] = {
  145273. -1.5, -0.5, 0.5, 1.5,
  145274. };
  145275. static long _vq_quantmap__8u1__p3_0[] = {
  145276. 3, 1, 0, 2, 4,
  145277. };
  145278. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145279. _vq_quantthresh__8u1__p3_0,
  145280. _vq_quantmap__8u1__p3_0,
  145281. 5,
  145282. 5
  145283. };
  145284. static static_codebook _8u1__p3_0 = {
  145285. 4, 625,
  145286. _vq_lengthlist__8u1__p3_0,
  145287. 1, -533725184, 1611661312, 3, 0,
  145288. _vq_quantlist__8u1__p3_0,
  145289. NULL,
  145290. &_vq_auxt__8u1__p3_0,
  145291. NULL,
  145292. 0
  145293. };
  145294. static long _vq_quantlist__8u1__p4_0[] = {
  145295. 2,
  145296. 1,
  145297. 3,
  145298. 0,
  145299. 4,
  145300. };
  145301. static long _vq_lengthlist__8u1__p4_0[] = {
  145302. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145303. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145304. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145305. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145306. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145307. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145308. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145309. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145310. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145311. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145312. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145313. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145314. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145315. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145316. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145317. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145318. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145319. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145320. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145321. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145322. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145323. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145324. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145325. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145326. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145327. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145328. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145329. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145330. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145331. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145332. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145333. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145334. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145335. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145336. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145337. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145338. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145339. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145340. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145341. 10,
  145342. };
  145343. static float _vq_quantthresh__8u1__p4_0[] = {
  145344. -1.5, -0.5, 0.5, 1.5,
  145345. };
  145346. static long _vq_quantmap__8u1__p4_0[] = {
  145347. 3, 1, 0, 2, 4,
  145348. };
  145349. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145350. _vq_quantthresh__8u1__p4_0,
  145351. _vq_quantmap__8u1__p4_0,
  145352. 5,
  145353. 5
  145354. };
  145355. static static_codebook _8u1__p4_0 = {
  145356. 4, 625,
  145357. _vq_lengthlist__8u1__p4_0,
  145358. 1, -533725184, 1611661312, 3, 0,
  145359. _vq_quantlist__8u1__p4_0,
  145360. NULL,
  145361. &_vq_auxt__8u1__p4_0,
  145362. NULL,
  145363. 0
  145364. };
  145365. static long _vq_quantlist__8u1__p5_0[] = {
  145366. 4,
  145367. 3,
  145368. 5,
  145369. 2,
  145370. 6,
  145371. 1,
  145372. 7,
  145373. 0,
  145374. 8,
  145375. };
  145376. static long _vq_lengthlist__8u1__p5_0[] = {
  145377. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145378. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145379. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145380. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145381. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145382. 13,
  145383. };
  145384. static float _vq_quantthresh__8u1__p5_0[] = {
  145385. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145386. };
  145387. static long _vq_quantmap__8u1__p5_0[] = {
  145388. 7, 5, 3, 1, 0, 2, 4, 6,
  145389. 8,
  145390. };
  145391. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145392. _vq_quantthresh__8u1__p5_0,
  145393. _vq_quantmap__8u1__p5_0,
  145394. 9,
  145395. 9
  145396. };
  145397. static static_codebook _8u1__p5_0 = {
  145398. 2, 81,
  145399. _vq_lengthlist__8u1__p5_0,
  145400. 1, -531628032, 1611661312, 4, 0,
  145401. _vq_quantlist__8u1__p5_0,
  145402. NULL,
  145403. &_vq_auxt__8u1__p5_0,
  145404. NULL,
  145405. 0
  145406. };
  145407. static long _vq_quantlist__8u1__p6_0[] = {
  145408. 4,
  145409. 3,
  145410. 5,
  145411. 2,
  145412. 6,
  145413. 1,
  145414. 7,
  145415. 0,
  145416. 8,
  145417. };
  145418. static long _vq_lengthlist__8u1__p6_0[] = {
  145419. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145420. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145421. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145422. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145423. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145424. 10,
  145425. };
  145426. static float _vq_quantthresh__8u1__p6_0[] = {
  145427. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145428. };
  145429. static long _vq_quantmap__8u1__p6_0[] = {
  145430. 7, 5, 3, 1, 0, 2, 4, 6,
  145431. 8,
  145432. };
  145433. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145434. _vq_quantthresh__8u1__p6_0,
  145435. _vq_quantmap__8u1__p6_0,
  145436. 9,
  145437. 9
  145438. };
  145439. static static_codebook _8u1__p6_0 = {
  145440. 2, 81,
  145441. _vq_lengthlist__8u1__p6_0,
  145442. 1, -531628032, 1611661312, 4, 0,
  145443. _vq_quantlist__8u1__p6_0,
  145444. NULL,
  145445. &_vq_auxt__8u1__p6_0,
  145446. NULL,
  145447. 0
  145448. };
  145449. static long _vq_quantlist__8u1__p7_0[] = {
  145450. 1,
  145451. 0,
  145452. 2,
  145453. };
  145454. static long _vq_lengthlist__8u1__p7_0[] = {
  145455. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145456. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145457. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145458. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145459. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145460. 11,
  145461. };
  145462. static float _vq_quantthresh__8u1__p7_0[] = {
  145463. -5.5, 5.5,
  145464. };
  145465. static long _vq_quantmap__8u1__p7_0[] = {
  145466. 1, 0, 2,
  145467. };
  145468. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145469. _vq_quantthresh__8u1__p7_0,
  145470. _vq_quantmap__8u1__p7_0,
  145471. 3,
  145472. 3
  145473. };
  145474. static static_codebook _8u1__p7_0 = {
  145475. 4, 81,
  145476. _vq_lengthlist__8u1__p7_0,
  145477. 1, -529137664, 1618345984, 2, 0,
  145478. _vq_quantlist__8u1__p7_0,
  145479. NULL,
  145480. &_vq_auxt__8u1__p7_0,
  145481. NULL,
  145482. 0
  145483. };
  145484. static long _vq_quantlist__8u1__p7_1[] = {
  145485. 5,
  145486. 4,
  145487. 6,
  145488. 3,
  145489. 7,
  145490. 2,
  145491. 8,
  145492. 1,
  145493. 9,
  145494. 0,
  145495. 10,
  145496. };
  145497. static long _vq_lengthlist__8u1__p7_1[] = {
  145498. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145499. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145500. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145501. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145502. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145503. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145504. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145505. 9, 9, 9, 9, 9,10,10,10,10,
  145506. };
  145507. static float _vq_quantthresh__8u1__p7_1[] = {
  145508. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145509. 3.5, 4.5,
  145510. };
  145511. static long _vq_quantmap__8u1__p7_1[] = {
  145512. 9, 7, 5, 3, 1, 0, 2, 4,
  145513. 6, 8, 10,
  145514. };
  145515. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145516. _vq_quantthresh__8u1__p7_1,
  145517. _vq_quantmap__8u1__p7_1,
  145518. 11,
  145519. 11
  145520. };
  145521. static static_codebook _8u1__p7_1 = {
  145522. 2, 121,
  145523. _vq_lengthlist__8u1__p7_1,
  145524. 1, -531365888, 1611661312, 4, 0,
  145525. _vq_quantlist__8u1__p7_1,
  145526. NULL,
  145527. &_vq_auxt__8u1__p7_1,
  145528. NULL,
  145529. 0
  145530. };
  145531. static long _vq_quantlist__8u1__p8_0[] = {
  145532. 5,
  145533. 4,
  145534. 6,
  145535. 3,
  145536. 7,
  145537. 2,
  145538. 8,
  145539. 1,
  145540. 9,
  145541. 0,
  145542. 10,
  145543. };
  145544. static long _vq_lengthlist__8u1__p8_0[] = {
  145545. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145546. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145547. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145548. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145549. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145550. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145551. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145552. 12,13,13,14,14,15,15,15,15,
  145553. };
  145554. static float _vq_quantthresh__8u1__p8_0[] = {
  145555. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145556. 38.5, 49.5,
  145557. };
  145558. static long _vq_quantmap__8u1__p8_0[] = {
  145559. 9, 7, 5, 3, 1, 0, 2, 4,
  145560. 6, 8, 10,
  145561. };
  145562. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145563. _vq_quantthresh__8u1__p8_0,
  145564. _vq_quantmap__8u1__p8_0,
  145565. 11,
  145566. 11
  145567. };
  145568. static static_codebook _8u1__p8_0 = {
  145569. 2, 121,
  145570. _vq_lengthlist__8u1__p8_0,
  145571. 1, -524582912, 1618345984, 4, 0,
  145572. _vq_quantlist__8u1__p8_0,
  145573. NULL,
  145574. &_vq_auxt__8u1__p8_0,
  145575. NULL,
  145576. 0
  145577. };
  145578. static long _vq_quantlist__8u1__p8_1[] = {
  145579. 5,
  145580. 4,
  145581. 6,
  145582. 3,
  145583. 7,
  145584. 2,
  145585. 8,
  145586. 1,
  145587. 9,
  145588. 0,
  145589. 10,
  145590. };
  145591. static long _vq_lengthlist__8u1__p8_1[] = {
  145592. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145593. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145594. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145595. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145596. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145597. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145598. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145599. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145600. };
  145601. static float _vq_quantthresh__8u1__p8_1[] = {
  145602. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145603. 3.5, 4.5,
  145604. };
  145605. static long _vq_quantmap__8u1__p8_1[] = {
  145606. 9, 7, 5, 3, 1, 0, 2, 4,
  145607. 6, 8, 10,
  145608. };
  145609. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145610. _vq_quantthresh__8u1__p8_1,
  145611. _vq_quantmap__8u1__p8_1,
  145612. 11,
  145613. 11
  145614. };
  145615. static static_codebook _8u1__p8_1 = {
  145616. 2, 121,
  145617. _vq_lengthlist__8u1__p8_1,
  145618. 1, -531365888, 1611661312, 4, 0,
  145619. _vq_quantlist__8u1__p8_1,
  145620. NULL,
  145621. &_vq_auxt__8u1__p8_1,
  145622. NULL,
  145623. 0
  145624. };
  145625. static long _vq_quantlist__8u1__p9_0[] = {
  145626. 7,
  145627. 6,
  145628. 8,
  145629. 5,
  145630. 9,
  145631. 4,
  145632. 10,
  145633. 3,
  145634. 11,
  145635. 2,
  145636. 12,
  145637. 1,
  145638. 13,
  145639. 0,
  145640. 14,
  145641. };
  145642. static long _vq_lengthlist__8u1__p9_0[] = {
  145643. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145644. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145645. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145655. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145656. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145657. 10,
  145658. };
  145659. static float _vq_quantthresh__8u1__p9_0[] = {
  145660. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145661. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145662. };
  145663. static long _vq_quantmap__8u1__p9_0[] = {
  145664. 13, 11, 9, 7, 5, 3, 1, 0,
  145665. 2, 4, 6, 8, 10, 12, 14,
  145666. };
  145667. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145668. _vq_quantthresh__8u1__p9_0,
  145669. _vq_quantmap__8u1__p9_0,
  145670. 15,
  145671. 15
  145672. };
  145673. static static_codebook _8u1__p9_0 = {
  145674. 2, 225,
  145675. _vq_lengthlist__8u1__p9_0,
  145676. 1, -514071552, 1627381760, 4, 0,
  145677. _vq_quantlist__8u1__p9_0,
  145678. NULL,
  145679. &_vq_auxt__8u1__p9_0,
  145680. NULL,
  145681. 0
  145682. };
  145683. static long _vq_quantlist__8u1__p9_1[] = {
  145684. 7,
  145685. 6,
  145686. 8,
  145687. 5,
  145688. 9,
  145689. 4,
  145690. 10,
  145691. 3,
  145692. 11,
  145693. 2,
  145694. 12,
  145695. 1,
  145696. 13,
  145697. 0,
  145698. 14,
  145699. };
  145700. static long _vq_lengthlist__8u1__p9_1[] = {
  145701. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145702. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145703. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145704. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145705. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145706. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145707. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145708. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145709. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145710. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145711. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145712. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145713. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145714. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145715. 13,
  145716. };
  145717. static float _vq_quantthresh__8u1__p9_1[] = {
  145718. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145719. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145720. };
  145721. static long _vq_quantmap__8u1__p9_1[] = {
  145722. 13, 11, 9, 7, 5, 3, 1, 0,
  145723. 2, 4, 6, 8, 10, 12, 14,
  145724. };
  145725. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145726. _vq_quantthresh__8u1__p9_1,
  145727. _vq_quantmap__8u1__p9_1,
  145728. 15,
  145729. 15
  145730. };
  145731. static static_codebook _8u1__p9_1 = {
  145732. 2, 225,
  145733. _vq_lengthlist__8u1__p9_1,
  145734. 1, -522338304, 1620115456, 4, 0,
  145735. _vq_quantlist__8u1__p9_1,
  145736. NULL,
  145737. &_vq_auxt__8u1__p9_1,
  145738. NULL,
  145739. 0
  145740. };
  145741. static long _vq_quantlist__8u1__p9_2[] = {
  145742. 8,
  145743. 7,
  145744. 9,
  145745. 6,
  145746. 10,
  145747. 5,
  145748. 11,
  145749. 4,
  145750. 12,
  145751. 3,
  145752. 13,
  145753. 2,
  145754. 14,
  145755. 1,
  145756. 15,
  145757. 0,
  145758. 16,
  145759. };
  145760. static long _vq_lengthlist__8u1__p9_2[] = {
  145761. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145762. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145763. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145764. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145765. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145766. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145767. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145768. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145769. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145770. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145771. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145772. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145773. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145774. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145776. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145777. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145778. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145779. 10,
  145780. };
  145781. static float _vq_quantthresh__8u1__p9_2[] = {
  145782. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145783. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145784. };
  145785. static long _vq_quantmap__8u1__p9_2[] = {
  145786. 15, 13, 11, 9, 7, 5, 3, 1,
  145787. 0, 2, 4, 6, 8, 10, 12, 14,
  145788. 16,
  145789. };
  145790. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145791. _vq_quantthresh__8u1__p9_2,
  145792. _vq_quantmap__8u1__p9_2,
  145793. 17,
  145794. 17
  145795. };
  145796. static static_codebook _8u1__p9_2 = {
  145797. 2, 289,
  145798. _vq_lengthlist__8u1__p9_2,
  145799. 1, -529530880, 1611661312, 5, 0,
  145800. _vq_quantlist__8u1__p9_2,
  145801. NULL,
  145802. &_vq_auxt__8u1__p9_2,
  145803. NULL,
  145804. 0
  145805. };
  145806. static long _huff_lengthlist__8u1__single[] = {
  145807. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145808. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145809. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145810. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145811. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145812. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145813. 13, 8, 8,15,
  145814. };
  145815. static static_codebook _huff_book__8u1__single = {
  145816. 2, 100,
  145817. _huff_lengthlist__8u1__single,
  145818. 0, 0, 0, 0, 0,
  145819. NULL,
  145820. NULL,
  145821. NULL,
  145822. NULL,
  145823. 0
  145824. };
  145825. static long _huff_lengthlist__44u0__long[] = {
  145826. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145827. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145828. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145829. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145830. };
  145831. static static_codebook _huff_book__44u0__long = {
  145832. 2, 64,
  145833. _huff_lengthlist__44u0__long,
  145834. 0, 0, 0, 0, 0,
  145835. NULL,
  145836. NULL,
  145837. NULL,
  145838. NULL,
  145839. 0
  145840. };
  145841. static long _vq_quantlist__44u0__p1_0[] = {
  145842. 1,
  145843. 0,
  145844. 2,
  145845. };
  145846. static long _vq_lengthlist__44u0__p1_0[] = {
  145847. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145848. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145849. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145850. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145851. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145852. 13,
  145853. };
  145854. static float _vq_quantthresh__44u0__p1_0[] = {
  145855. -0.5, 0.5,
  145856. };
  145857. static long _vq_quantmap__44u0__p1_0[] = {
  145858. 1, 0, 2,
  145859. };
  145860. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145861. _vq_quantthresh__44u0__p1_0,
  145862. _vq_quantmap__44u0__p1_0,
  145863. 3,
  145864. 3
  145865. };
  145866. static static_codebook _44u0__p1_0 = {
  145867. 4, 81,
  145868. _vq_lengthlist__44u0__p1_0,
  145869. 1, -535822336, 1611661312, 2, 0,
  145870. _vq_quantlist__44u0__p1_0,
  145871. NULL,
  145872. &_vq_auxt__44u0__p1_0,
  145873. NULL,
  145874. 0
  145875. };
  145876. static long _vq_quantlist__44u0__p2_0[] = {
  145877. 1,
  145878. 0,
  145879. 2,
  145880. };
  145881. static long _vq_lengthlist__44u0__p2_0[] = {
  145882. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145883. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145884. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145885. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145886. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145887. 9,
  145888. };
  145889. static float _vq_quantthresh__44u0__p2_0[] = {
  145890. -0.5, 0.5,
  145891. };
  145892. static long _vq_quantmap__44u0__p2_0[] = {
  145893. 1, 0, 2,
  145894. };
  145895. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145896. _vq_quantthresh__44u0__p2_0,
  145897. _vq_quantmap__44u0__p2_0,
  145898. 3,
  145899. 3
  145900. };
  145901. static static_codebook _44u0__p2_0 = {
  145902. 4, 81,
  145903. _vq_lengthlist__44u0__p2_0,
  145904. 1, -535822336, 1611661312, 2, 0,
  145905. _vq_quantlist__44u0__p2_0,
  145906. NULL,
  145907. &_vq_auxt__44u0__p2_0,
  145908. NULL,
  145909. 0
  145910. };
  145911. static long _vq_quantlist__44u0__p3_0[] = {
  145912. 2,
  145913. 1,
  145914. 3,
  145915. 0,
  145916. 4,
  145917. };
  145918. static long _vq_lengthlist__44u0__p3_0[] = {
  145919. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145920. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145921. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145922. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145923. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145924. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145925. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145926. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145927. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145928. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145929. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145930. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145931. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145932. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145933. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145934. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145935. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145936. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145937. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145938. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145939. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145940. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145941. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145942. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145943. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145944. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145945. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145946. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145947. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145948. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145949. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145950. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145951. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145952. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145953. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145954. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145955. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145956. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145957. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145958. 19,
  145959. };
  145960. static float _vq_quantthresh__44u0__p3_0[] = {
  145961. -1.5, -0.5, 0.5, 1.5,
  145962. };
  145963. static long _vq_quantmap__44u0__p3_0[] = {
  145964. 3, 1, 0, 2, 4,
  145965. };
  145966. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145967. _vq_quantthresh__44u0__p3_0,
  145968. _vq_quantmap__44u0__p3_0,
  145969. 5,
  145970. 5
  145971. };
  145972. static static_codebook _44u0__p3_0 = {
  145973. 4, 625,
  145974. _vq_lengthlist__44u0__p3_0,
  145975. 1, -533725184, 1611661312, 3, 0,
  145976. _vq_quantlist__44u0__p3_0,
  145977. NULL,
  145978. &_vq_auxt__44u0__p3_0,
  145979. NULL,
  145980. 0
  145981. };
  145982. static long _vq_quantlist__44u0__p4_0[] = {
  145983. 2,
  145984. 1,
  145985. 3,
  145986. 0,
  145987. 4,
  145988. };
  145989. static long _vq_lengthlist__44u0__p4_0[] = {
  145990. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145991. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145992. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145993. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145994. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145995. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145996. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145997. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145998. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145999. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146000. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146001. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146002. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146003. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146004. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146005. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146006. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146007. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146008. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146009. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146010. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146011. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146012. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146013. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146014. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146015. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146016. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146017. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146018. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146019. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146020. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146021. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146022. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146023. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146024. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146025. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146026. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146027. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146028. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146029. 12,
  146030. };
  146031. static float _vq_quantthresh__44u0__p4_0[] = {
  146032. -1.5, -0.5, 0.5, 1.5,
  146033. };
  146034. static long _vq_quantmap__44u0__p4_0[] = {
  146035. 3, 1, 0, 2, 4,
  146036. };
  146037. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146038. _vq_quantthresh__44u0__p4_0,
  146039. _vq_quantmap__44u0__p4_0,
  146040. 5,
  146041. 5
  146042. };
  146043. static static_codebook _44u0__p4_0 = {
  146044. 4, 625,
  146045. _vq_lengthlist__44u0__p4_0,
  146046. 1, -533725184, 1611661312, 3, 0,
  146047. _vq_quantlist__44u0__p4_0,
  146048. NULL,
  146049. &_vq_auxt__44u0__p4_0,
  146050. NULL,
  146051. 0
  146052. };
  146053. static long _vq_quantlist__44u0__p5_0[] = {
  146054. 4,
  146055. 3,
  146056. 5,
  146057. 2,
  146058. 6,
  146059. 1,
  146060. 7,
  146061. 0,
  146062. 8,
  146063. };
  146064. static long _vq_lengthlist__44u0__p5_0[] = {
  146065. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146066. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146067. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146068. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146069. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146070. 12,
  146071. };
  146072. static float _vq_quantthresh__44u0__p5_0[] = {
  146073. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146074. };
  146075. static long _vq_quantmap__44u0__p5_0[] = {
  146076. 7, 5, 3, 1, 0, 2, 4, 6,
  146077. 8,
  146078. };
  146079. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146080. _vq_quantthresh__44u0__p5_0,
  146081. _vq_quantmap__44u0__p5_0,
  146082. 9,
  146083. 9
  146084. };
  146085. static static_codebook _44u0__p5_0 = {
  146086. 2, 81,
  146087. _vq_lengthlist__44u0__p5_0,
  146088. 1, -531628032, 1611661312, 4, 0,
  146089. _vq_quantlist__44u0__p5_0,
  146090. NULL,
  146091. &_vq_auxt__44u0__p5_0,
  146092. NULL,
  146093. 0
  146094. };
  146095. static long _vq_quantlist__44u0__p6_0[] = {
  146096. 6,
  146097. 5,
  146098. 7,
  146099. 4,
  146100. 8,
  146101. 3,
  146102. 9,
  146103. 2,
  146104. 10,
  146105. 1,
  146106. 11,
  146107. 0,
  146108. 12,
  146109. };
  146110. static long _vq_lengthlist__44u0__p6_0[] = {
  146111. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146112. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146113. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146114. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146115. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146116. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146117. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146118. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146119. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146120. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146121. 15,17,16,17,18,17,17,18, 0,
  146122. };
  146123. static float _vq_quantthresh__44u0__p6_0[] = {
  146124. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146125. 12.5, 17.5, 22.5, 27.5,
  146126. };
  146127. static long _vq_quantmap__44u0__p6_0[] = {
  146128. 11, 9, 7, 5, 3, 1, 0, 2,
  146129. 4, 6, 8, 10, 12,
  146130. };
  146131. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146132. _vq_quantthresh__44u0__p6_0,
  146133. _vq_quantmap__44u0__p6_0,
  146134. 13,
  146135. 13
  146136. };
  146137. static static_codebook _44u0__p6_0 = {
  146138. 2, 169,
  146139. _vq_lengthlist__44u0__p6_0,
  146140. 1, -526516224, 1616117760, 4, 0,
  146141. _vq_quantlist__44u0__p6_0,
  146142. NULL,
  146143. &_vq_auxt__44u0__p6_0,
  146144. NULL,
  146145. 0
  146146. };
  146147. static long _vq_quantlist__44u0__p6_1[] = {
  146148. 2,
  146149. 1,
  146150. 3,
  146151. 0,
  146152. 4,
  146153. };
  146154. static long _vq_lengthlist__44u0__p6_1[] = {
  146155. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146156. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146157. };
  146158. static float _vq_quantthresh__44u0__p6_1[] = {
  146159. -1.5, -0.5, 0.5, 1.5,
  146160. };
  146161. static long _vq_quantmap__44u0__p6_1[] = {
  146162. 3, 1, 0, 2, 4,
  146163. };
  146164. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146165. _vq_quantthresh__44u0__p6_1,
  146166. _vq_quantmap__44u0__p6_1,
  146167. 5,
  146168. 5
  146169. };
  146170. static static_codebook _44u0__p6_1 = {
  146171. 2, 25,
  146172. _vq_lengthlist__44u0__p6_1,
  146173. 1, -533725184, 1611661312, 3, 0,
  146174. _vq_quantlist__44u0__p6_1,
  146175. NULL,
  146176. &_vq_auxt__44u0__p6_1,
  146177. NULL,
  146178. 0
  146179. };
  146180. static long _vq_quantlist__44u0__p7_0[] = {
  146181. 2,
  146182. 1,
  146183. 3,
  146184. 0,
  146185. 4,
  146186. };
  146187. static long _vq_lengthlist__44u0__p7_0[] = {
  146188. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146191. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146192. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146193. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146194. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146195. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146196. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146197. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146198. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146199. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146200. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146201. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146202. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146203. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146204. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146205. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146206. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146207. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146208. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146209. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146210. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146211. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146212. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146213. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146214. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146215. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146216. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146217. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146218. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146219. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146220. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146221. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146222. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146223. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146224. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146225. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146226. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146227. 10,
  146228. };
  146229. static float _vq_quantthresh__44u0__p7_0[] = {
  146230. -253.5, -84.5, 84.5, 253.5,
  146231. };
  146232. static long _vq_quantmap__44u0__p7_0[] = {
  146233. 3, 1, 0, 2, 4,
  146234. };
  146235. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146236. _vq_quantthresh__44u0__p7_0,
  146237. _vq_quantmap__44u0__p7_0,
  146238. 5,
  146239. 5
  146240. };
  146241. static static_codebook _44u0__p7_0 = {
  146242. 4, 625,
  146243. _vq_lengthlist__44u0__p7_0,
  146244. 1, -518709248, 1626677248, 3, 0,
  146245. _vq_quantlist__44u0__p7_0,
  146246. NULL,
  146247. &_vq_auxt__44u0__p7_0,
  146248. NULL,
  146249. 0
  146250. };
  146251. static long _vq_quantlist__44u0__p7_1[] = {
  146252. 6,
  146253. 5,
  146254. 7,
  146255. 4,
  146256. 8,
  146257. 3,
  146258. 9,
  146259. 2,
  146260. 10,
  146261. 1,
  146262. 11,
  146263. 0,
  146264. 12,
  146265. };
  146266. static long _vq_lengthlist__44u0__p7_1[] = {
  146267. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146268. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146269. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146270. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146271. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146272. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146273. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146274. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146275. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146276. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146277. 15,15,15,15,15,15,15,15,15,
  146278. };
  146279. static float _vq_quantthresh__44u0__p7_1[] = {
  146280. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146281. 32.5, 45.5, 58.5, 71.5,
  146282. };
  146283. static long _vq_quantmap__44u0__p7_1[] = {
  146284. 11, 9, 7, 5, 3, 1, 0, 2,
  146285. 4, 6, 8, 10, 12,
  146286. };
  146287. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146288. _vq_quantthresh__44u0__p7_1,
  146289. _vq_quantmap__44u0__p7_1,
  146290. 13,
  146291. 13
  146292. };
  146293. static static_codebook _44u0__p7_1 = {
  146294. 2, 169,
  146295. _vq_lengthlist__44u0__p7_1,
  146296. 1, -523010048, 1618608128, 4, 0,
  146297. _vq_quantlist__44u0__p7_1,
  146298. NULL,
  146299. &_vq_auxt__44u0__p7_1,
  146300. NULL,
  146301. 0
  146302. };
  146303. static long _vq_quantlist__44u0__p7_2[] = {
  146304. 6,
  146305. 5,
  146306. 7,
  146307. 4,
  146308. 8,
  146309. 3,
  146310. 9,
  146311. 2,
  146312. 10,
  146313. 1,
  146314. 11,
  146315. 0,
  146316. 12,
  146317. };
  146318. static long _vq_lengthlist__44u0__p7_2[] = {
  146319. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146320. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146321. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146322. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146323. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146324. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146325. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146326. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146327. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146328. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146329. 9, 9, 9,10, 9, 9,10,10, 9,
  146330. };
  146331. static float _vq_quantthresh__44u0__p7_2[] = {
  146332. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146333. 2.5, 3.5, 4.5, 5.5,
  146334. };
  146335. static long _vq_quantmap__44u0__p7_2[] = {
  146336. 11, 9, 7, 5, 3, 1, 0, 2,
  146337. 4, 6, 8, 10, 12,
  146338. };
  146339. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146340. _vq_quantthresh__44u0__p7_2,
  146341. _vq_quantmap__44u0__p7_2,
  146342. 13,
  146343. 13
  146344. };
  146345. static static_codebook _44u0__p7_2 = {
  146346. 2, 169,
  146347. _vq_lengthlist__44u0__p7_2,
  146348. 1, -531103744, 1611661312, 4, 0,
  146349. _vq_quantlist__44u0__p7_2,
  146350. NULL,
  146351. &_vq_auxt__44u0__p7_2,
  146352. NULL,
  146353. 0
  146354. };
  146355. static long _huff_lengthlist__44u0__short[] = {
  146356. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146357. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146358. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146359. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146360. };
  146361. static static_codebook _huff_book__44u0__short = {
  146362. 2, 64,
  146363. _huff_lengthlist__44u0__short,
  146364. 0, 0, 0, 0, 0,
  146365. NULL,
  146366. NULL,
  146367. NULL,
  146368. NULL,
  146369. 0
  146370. };
  146371. static long _huff_lengthlist__44u1__long[] = {
  146372. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146373. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146374. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146375. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146376. };
  146377. static static_codebook _huff_book__44u1__long = {
  146378. 2, 64,
  146379. _huff_lengthlist__44u1__long,
  146380. 0, 0, 0, 0, 0,
  146381. NULL,
  146382. NULL,
  146383. NULL,
  146384. NULL,
  146385. 0
  146386. };
  146387. static long _vq_quantlist__44u1__p1_0[] = {
  146388. 1,
  146389. 0,
  146390. 2,
  146391. };
  146392. static long _vq_lengthlist__44u1__p1_0[] = {
  146393. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146394. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146395. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146396. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146397. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146398. 13,
  146399. };
  146400. static float _vq_quantthresh__44u1__p1_0[] = {
  146401. -0.5, 0.5,
  146402. };
  146403. static long _vq_quantmap__44u1__p1_0[] = {
  146404. 1, 0, 2,
  146405. };
  146406. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146407. _vq_quantthresh__44u1__p1_0,
  146408. _vq_quantmap__44u1__p1_0,
  146409. 3,
  146410. 3
  146411. };
  146412. static static_codebook _44u1__p1_0 = {
  146413. 4, 81,
  146414. _vq_lengthlist__44u1__p1_0,
  146415. 1, -535822336, 1611661312, 2, 0,
  146416. _vq_quantlist__44u1__p1_0,
  146417. NULL,
  146418. &_vq_auxt__44u1__p1_0,
  146419. NULL,
  146420. 0
  146421. };
  146422. static long _vq_quantlist__44u1__p2_0[] = {
  146423. 1,
  146424. 0,
  146425. 2,
  146426. };
  146427. static long _vq_lengthlist__44u1__p2_0[] = {
  146428. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146429. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146430. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146431. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146432. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146433. 9,
  146434. };
  146435. static float _vq_quantthresh__44u1__p2_0[] = {
  146436. -0.5, 0.5,
  146437. };
  146438. static long _vq_quantmap__44u1__p2_0[] = {
  146439. 1, 0, 2,
  146440. };
  146441. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146442. _vq_quantthresh__44u1__p2_0,
  146443. _vq_quantmap__44u1__p2_0,
  146444. 3,
  146445. 3
  146446. };
  146447. static static_codebook _44u1__p2_0 = {
  146448. 4, 81,
  146449. _vq_lengthlist__44u1__p2_0,
  146450. 1, -535822336, 1611661312, 2, 0,
  146451. _vq_quantlist__44u1__p2_0,
  146452. NULL,
  146453. &_vq_auxt__44u1__p2_0,
  146454. NULL,
  146455. 0
  146456. };
  146457. static long _vq_quantlist__44u1__p3_0[] = {
  146458. 2,
  146459. 1,
  146460. 3,
  146461. 0,
  146462. 4,
  146463. };
  146464. static long _vq_lengthlist__44u1__p3_0[] = {
  146465. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146466. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146467. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146468. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146469. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146470. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146471. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146472. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146473. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146474. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146475. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146476. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146477. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146478. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146479. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146480. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146481. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146482. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146483. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146484. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146485. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146486. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146487. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146488. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146489. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146490. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146491. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146492. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146493. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146494. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146495. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146496. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146497. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146498. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146499. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146500. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146501. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146502. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146503. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146504. 19,
  146505. };
  146506. static float _vq_quantthresh__44u1__p3_0[] = {
  146507. -1.5, -0.5, 0.5, 1.5,
  146508. };
  146509. static long _vq_quantmap__44u1__p3_0[] = {
  146510. 3, 1, 0, 2, 4,
  146511. };
  146512. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146513. _vq_quantthresh__44u1__p3_0,
  146514. _vq_quantmap__44u1__p3_0,
  146515. 5,
  146516. 5
  146517. };
  146518. static static_codebook _44u1__p3_0 = {
  146519. 4, 625,
  146520. _vq_lengthlist__44u1__p3_0,
  146521. 1, -533725184, 1611661312, 3, 0,
  146522. _vq_quantlist__44u1__p3_0,
  146523. NULL,
  146524. &_vq_auxt__44u1__p3_0,
  146525. NULL,
  146526. 0
  146527. };
  146528. static long _vq_quantlist__44u1__p4_0[] = {
  146529. 2,
  146530. 1,
  146531. 3,
  146532. 0,
  146533. 4,
  146534. };
  146535. static long _vq_lengthlist__44u1__p4_0[] = {
  146536. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146537. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146538. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146539. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146540. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146541. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146542. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146543. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146544. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146545. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146546. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146547. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146548. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146549. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146550. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146551. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146552. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146553. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146554. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146555. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146556. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146557. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146558. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146559. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146560. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146561. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146562. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146563. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146564. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146565. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146566. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146567. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146568. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146569. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146570. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146571. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146572. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146573. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146574. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146575. 12,
  146576. };
  146577. static float _vq_quantthresh__44u1__p4_0[] = {
  146578. -1.5, -0.5, 0.5, 1.5,
  146579. };
  146580. static long _vq_quantmap__44u1__p4_0[] = {
  146581. 3, 1, 0, 2, 4,
  146582. };
  146583. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146584. _vq_quantthresh__44u1__p4_0,
  146585. _vq_quantmap__44u1__p4_0,
  146586. 5,
  146587. 5
  146588. };
  146589. static static_codebook _44u1__p4_0 = {
  146590. 4, 625,
  146591. _vq_lengthlist__44u1__p4_0,
  146592. 1, -533725184, 1611661312, 3, 0,
  146593. _vq_quantlist__44u1__p4_0,
  146594. NULL,
  146595. &_vq_auxt__44u1__p4_0,
  146596. NULL,
  146597. 0
  146598. };
  146599. static long _vq_quantlist__44u1__p5_0[] = {
  146600. 4,
  146601. 3,
  146602. 5,
  146603. 2,
  146604. 6,
  146605. 1,
  146606. 7,
  146607. 0,
  146608. 8,
  146609. };
  146610. static long _vq_lengthlist__44u1__p5_0[] = {
  146611. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146612. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146613. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146614. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146615. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146616. 12,
  146617. };
  146618. static float _vq_quantthresh__44u1__p5_0[] = {
  146619. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146620. };
  146621. static long _vq_quantmap__44u1__p5_0[] = {
  146622. 7, 5, 3, 1, 0, 2, 4, 6,
  146623. 8,
  146624. };
  146625. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146626. _vq_quantthresh__44u1__p5_0,
  146627. _vq_quantmap__44u1__p5_0,
  146628. 9,
  146629. 9
  146630. };
  146631. static static_codebook _44u1__p5_0 = {
  146632. 2, 81,
  146633. _vq_lengthlist__44u1__p5_0,
  146634. 1, -531628032, 1611661312, 4, 0,
  146635. _vq_quantlist__44u1__p5_0,
  146636. NULL,
  146637. &_vq_auxt__44u1__p5_0,
  146638. NULL,
  146639. 0
  146640. };
  146641. static long _vq_quantlist__44u1__p6_0[] = {
  146642. 6,
  146643. 5,
  146644. 7,
  146645. 4,
  146646. 8,
  146647. 3,
  146648. 9,
  146649. 2,
  146650. 10,
  146651. 1,
  146652. 11,
  146653. 0,
  146654. 12,
  146655. };
  146656. static long _vq_lengthlist__44u1__p6_0[] = {
  146657. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146658. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146659. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146660. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146661. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146662. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146663. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146664. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146665. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146666. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146667. 15,17,16,17,18,17,17,18, 0,
  146668. };
  146669. static float _vq_quantthresh__44u1__p6_0[] = {
  146670. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146671. 12.5, 17.5, 22.5, 27.5,
  146672. };
  146673. static long _vq_quantmap__44u1__p6_0[] = {
  146674. 11, 9, 7, 5, 3, 1, 0, 2,
  146675. 4, 6, 8, 10, 12,
  146676. };
  146677. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146678. _vq_quantthresh__44u1__p6_0,
  146679. _vq_quantmap__44u1__p6_0,
  146680. 13,
  146681. 13
  146682. };
  146683. static static_codebook _44u1__p6_0 = {
  146684. 2, 169,
  146685. _vq_lengthlist__44u1__p6_0,
  146686. 1, -526516224, 1616117760, 4, 0,
  146687. _vq_quantlist__44u1__p6_0,
  146688. NULL,
  146689. &_vq_auxt__44u1__p6_0,
  146690. NULL,
  146691. 0
  146692. };
  146693. static long _vq_quantlist__44u1__p6_1[] = {
  146694. 2,
  146695. 1,
  146696. 3,
  146697. 0,
  146698. 4,
  146699. };
  146700. static long _vq_lengthlist__44u1__p6_1[] = {
  146701. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146702. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146703. };
  146704. static float _vq_quantthresh__44u1__p6_1[] = {
  146705. -1.5, -0.5, 0.5, 1.5,
  146706. };
  146707. static long _vq_quantmap__44u1__p6_1[] = {
  146708. 3, 1, 0, 2, 4,
  146709. };
  146710. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146711. _vq_quantthresh__44u1__p6_1,
  146712. _vq_quantmap__44u1__p6_1,
  146713. 5,
  146714. 5
  146715. };
  146716. static static_codebook _44u1__p6_1 = {
  146717. 2, 25,
  146718. _vq_lengthlist__44u1__p6_1,
  146719. 1, -533725184, 1611661312, 3, 0,
  146720. _vq_quantlist__44u1__p6_1,
  146721. NULL,
  146722. &_vq_auxt__44u1__p6_1,
  146723. NULL,
  146724. 0
  146725. };
  146726. static long _vq_quantlist__44u1__p7_0[] = {
  146727. 3,
  146728. 2,
  146729. 4,
  146730. 1,
  146731. 5,
  146732. 0,
  146733. 6,
  146734. };
  146735. static long _vq_lengthlist__44u1__p7_0[] = {
  146736. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146737. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146738. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146739. 8,
  146740. };
  146741. static float _vq_quantthresh__44u1__p7_0[] = {
  146742. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146743. };
  146744. static long _vq_quantmap__44u1__p7_0[] = {
  146745. 5, 3, 1, 0, 2, 4, 6,
  146746. };
  146747. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146748. _vq_quantthresh__44u1__p7_0,
  146749. _vq_quantmap__44u1__p7_0,
  146750. 7,
  146751. 7
  146752. };
  146753. static static_codebook _44u1__p7_0 = {
  146754. 2, 49,
  146755. _vq_lengthlist__44u1__p7_0,
  146756. 1, -518017024, 1626677248, 3, 0,
  146757. _vq_quantlist__44u1__p7_0,
  146758. NULL,
  146759. &_vq_auxt__44u1__p7_0,
  146760. NULL,
  146761. 0
  146762. };
  146763. static long _vq_quantlist__44u1__p7_1[] = {
  146764. 6,
  146765. 5,
  146766. 7,
  146767. 4,
  146768. 8,
  146769. 3,
  146770. 9,
  146771. 2,
  146772. 10,
  146773. 1,
  146774. 11,
  146775. 0,
  146776. 12,
  146777. };
  146778. static long _vq_lengthlist__44u1__p7_1[] = {
  146779. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146780. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146781. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146782. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146783. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146784. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146785. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146786. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146787. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146788. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146789. 15,15,15,15,15,15,15,15,15,
  146790. };
  146791. static float _vq_quantthresh__44u1__p7_1[] = {
  146792. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146793. 32.5, 45.5, 58.5, 71.5,
  146794. };
  146795. static long _vq_quantmap__44u1__p7_1[] = {
  146796. 11, 9, 7, 5, 3, 1, 0, 2,
  146797. 4, 6, 8, 10, 12,
  146798. };
  146799. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146800. _vq_quantthresh__44u1__p7_1,
  146801. _vq_quantmap__44u1__p7_1,
  146802. 13,
  146803. 13
  146804. };
  146805. static static_codebook _44u1__p7_1 = {
  146806. 2, 169,
  146807. _vq_lengthlist__44u1__p7_1,
  146808. 1, -523010048, 1618608128, 4, 0,
  146809. _vq_quantlist__44u1__p7_1,
  146810. NULL,
  146811. &_vq_auxt__44u1__p7_1,
  146812. NULL,
  146813. 0
  146814. };
  146815. static long _vq_quantlist__44u1__p7_2[] = {
  146816. 6,
  146817. 5,
  146818. 7,
  146819. 4,
  146820. 8,
  146821. 3,
  146822. 9,
  146823. 2,
  146824. 10,
  146825. 1,
  146826. 11,
  146827. 0,
  146828. 12,
  146829. };
  146830. static long _vq_lengthlist__44u1__p7_2[] = {
  146831. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146832. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146833. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146834. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146835. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146836. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146837. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146838. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146839. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146840. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146841. 9, 9, 9,10, 9, 9,10,10, 9,
  146842. };
  146843. static float _vq_quantthresh__44u1__p7_2[] = {
  146844. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146845. 2.5, 3.5, 4.5, 5.5,
  146846. };
  146847. static long _vq_quantmap__44u1__p7_2[] = {
  146848. 11, 9, 7, 5, 3, 1, 0, 2,
  146849. 4, 6, 8, 10, 12,
  146850. };
  146851. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146852. _vq_quantthresh__44u1__p7_2,
  146853. _vq_quantmap__44u1__p7_2,
  146854. 13,
  146855. 13
  146856. };
  146857. static static_codebook _44u1__p7_2 = {
  146858. 2, 169,
  146859. _vq_lengthlist__44u1__p7_2,
  146860. 1, -531103744, 1611661312, 4, 0,
  146861. _vq_quantlist__44u1__p7_2,
  146862. NULL,
  146863. &_vq_auxt__44u1__p7_2,
  146864. NULL,
  146865. 0
  146866. };
  146867. static long _huff_lengthlist__44u1__short[] = {
  146868. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146869. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146870. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146871. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146872. };
  146873. static static_codebook _huff_book__44u1__short = {
  146874. 2, 64,
  146875. _huff_lengthlist__44u1__short,
  146876. 0, 0, 0, 0, 0,
  146877. NULL,
  146878. NULL,
  146879. NULL,
  146880. NULL,
  146881. 0
  146882. };
  146883. static long _huff_lengthlist__44u2__long[] = {
  146884. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146885. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146886. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146887. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146888. };
  146889. static static_codebook _huff_book__44u2__long = {
  146890. 2, 64,
  146891. _huff_lengthlist__44u2__long,
  146892. 0, 0, 0, 0, 0,
  146893. NULL,
  146894. NULL,
  146895. NULL,
  146896. NULL,
  146897. 0
  146898. };
  146899. static long _vq_quantlist__44u2__p1_0[] = {
  146900. 1,
  146901. 0,
  146902. 2,
  146903. };
  146904. static long _vq_lengthlist__44u2__p1_0[] = {
  146905. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146906. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146907. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146908. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146909. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146910. 13,
  146911. };
  146912. static float _vq_quantthresh__44u2__p1_0[] = {
  146913. -0.5, 0.5,
  146914. };
  146915. static long _vq_quantmap__44u2__p1_0[] = {
  146916. 1, 0, 2,
  146917. };
  146918. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146919. _vq_quantthresh__44u2__p1_0,
  146920. _vq_quantmap__44u2__p1_0,
  146921. 3,
  146922. 3
  146923. };
  146924. static static_codebook _44u2__p1_0 = {
  146925. 4, 81,
  146926. _vq_lengthlist__44u2__p1_0,
  146927. 1, -535822336, 1611661312, 2, 0,
  146928. _vq_quantlist__44u2__p1_0,
  146929. NULL,
  146930. &_vq_auxt__44u2__p1_0,
  146931. NULL,
  146932. 0
  146933. };
  146934. static long _vq_quantlist__44u2__p2_0[] = {
  146935. 1,
  146936. 0,
  146937. 2,
  146938. };
  146939. static long _vq_lengthlist__44u2__p2_0[] = {
  146940. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146941. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146942. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146943. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146944. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146945. 9,
  146946. };
  146947. static float _vq_quantthresh__44u2__p2_0[] = {
  146948. -0.5, 0.5,
  146949. };
  146950. static long _vq_quantmap__44u2__p2_0[] = {
  146951. 1, 0, 2,
  146952. };
  146953. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146954. _vq_quantthresh__44u2__p2_0,
  146955. _vq_quantmap__44u2__p2_0,
  146956. 3,
  146957. 3
  146958. };
  146959. static static_codebook _44u2__p2_0 = {
  146960. 4, 81,
  146961. _vq_lengthlist__44u2__p2_0,
  146962. 1, -535822336, 1611661312, 2, 0,
  146963. _vq_quantlist__44u2__p2_0,
  146964. NULL,
  146965. &_vq_auxt__44u2__p2_0,
  146966. NULL,
  146967. 0
  146968. };
  146969. static long _vq_quantlist__44u2__p3_0[] = {
  146970. 2,
  146971. 1,
  146972. 3,
  146973. 0,
  146974. 4,
  146975. };
  146976. static long _vq_lengthlist__44u2__p3_0[] = {
  146977. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146978. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146979. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146980. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146981. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146982. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146983. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146984. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146985. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146986. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146987. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146988. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146989. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146990. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146991. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146992. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146993. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146994. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146995. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146996. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146997. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146998. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146999. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147000. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147001. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147002. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147003. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147004. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147005. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147006. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147007. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147008. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147009. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147010. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147011. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147012. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147013. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147014. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147015. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147016. 0,
  147017. };
  147018. static float _vq_quantthresh__44u2__p3_0[] = {
  147019. -1.5, -0.5, 0.5, 1.5,
  147020. };
  147021. static long _vq_quantmap__44u2__p3_0[] = {
  147022. 3, 1, 0, 2, 4,
  147023. };
  147024. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147025. _vq_quantthresh__44u2__p3_0,
  147026. _vq_quantmap__44u2__p3_0,
  147027. 5,
  147028. 5
  147029. };
  147030. static static_codebook _44u2__p3_0 = {
  147031. 4, 625,
  147032. _vq_lengthlist__44u2__p3_0,
  147033. 1, -533725184, 1611661312, 3, 0,
  147034. _vq_quantlist__44u2__p3_0,
  147035. NULL,
  147036. &_vq_auxt__44u2__p3_0,
  147037. NULL,
  147038. 0
  147039. };
  147040. static long _vq_quantlist__44u2__p4_0[] = {
  147041. 2,
  147042. 1,
  147043. 3,
  147044. 0,
  147045. 4,
  147046. };
  147047. static long _vq_lengthlist__44u2__p4_0[] = {
  147048. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147049. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147050. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147051. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147052. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147053. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147054. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147055. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147056. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147057. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147058. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147059. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147060. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147061. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147062. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147063. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147064. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147065. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147066. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147067. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147068. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147069. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147070. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147071. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147072. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147073. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147074. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147075. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147076. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147077. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147078. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147079. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147080. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147081. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147082. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147083. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147084. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147085. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147086. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147087. 13,
  147088. };
  147089. static float _vq_quantthresh__44u2__p4_0[] = {
  147090. -1.5, -0.5, 0.5, 1.5,
  147091. };
  147092. static long _vq_quantmap__44u2__p4_0[] = {
  147093. 3, 1, 0, 2, 4,
  147094. };
  147095. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147096. _vq_quantthresh__44u2__p4_0,
  147097. _vq_quantmap__44u2__p4_0,
  147098. 5,
  147099. 5
  147100. };
  147101. static static_codebook _44u2__p4_0 = {
  147102. 4, 625,
  147103. _vq_lengthlist__44u2__p4_0,
  147104. 1, -533725184, 1611661312, 3, 0,
  147105. _vq_quantlist__44u2__p4_0,
  147106. NULL,
  147107. &_vq_auxt__44u2__p4_0,
  147108. NULL,
  147109. 0
  147110. };
  147111. static long _vq_quantlist__44u2__p5_0[] = {
  147112. 4,
  147113. 3,
  147114. 5,
  147115. 2,
  147116. 6,
  147117. 1,
  147118. 7,
  147119. 0,
  147120. 8,
  147121. };
  147122. static long _vq_lengthlist__44u2__p5_0[] = {
  147123. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147124. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147125. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147126. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147127. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147128. 13,
  147129. };
  147130. static float _vq_quantthresh__44u2__p5_0[] = {
  147131. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147132. };
  147133. static long _vq_quantmap__44u2__p5_0[] = {
  147134. 7, 5, 3, 1, 0, 2, 4, 6,
  147135. 8,
  147136. };
  147137. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147138. _vq_quantthresh__44u2__p5_0,
  147139. _vq_quantmap__44u2__p5_0,
  147140. 9,
  147141. 9
  147142. };
  147143. static static_codebook _44u2__p5_0 = {
  147144. 2, 81,
  147145. _vq_lengthlist__44u2__p5_0,
  147146. 1, -531628032, 1611661312, 4, 0,
  147147. _vq_quantlist__44u2__p5_0,
  147148. NULL,
  147149. &_vq_auxt__44u2__p5_0,
  147150. NULL,
  147151. 0
  147152. };
  147153. static long _vq_quantlist__44u2__p6_0[] = {
  147154. 6,
  147155. 5,
  147156. 7,
  147157. 4,
  147158. 8,
  147159. 3,
  147160. 9,
  147161. 2,
  147162. 10,
  147163. 1,
  147164. 11,
  147165. 0,
  147166. 12,
  147167. };
  147168. static long _vq_lengthlist__44u2__p6_0[] = {
  147169. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147170. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147171. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147172. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147173. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147174. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147175. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147176. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147177. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147178. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147179. 15,17,17,16,18,17,18, 0, 0,
  147180. };
  147181. static float _vq_quantthresh__44u2__p6_0[] = {
  147182. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147183. 12.5, 17.5, 22.5, 27.5,
  147184. };
  147185. static long _vq_quantmap__44u2__p6_0[] = {
  147186. 11, 9, 7, 5, 3, 1, 0, 2,
  147187. 4, 6, 8, 10, 12,
  147188. };
  147189. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147190. _vq_quantthresh__44u2__p6_0,
  147191. _vq_quantmap__44u2__p6_0,
  147192. 13,
  147193. 13
  147194. };
  147195. static static_codebook _44u2__p6_0 = {
  147196. 2, 169,
  147197. _vq_lengthlist__44u2__p6_0,
  147198. 1, -526516224, 1616117760, 4, 0,
  147199. _vq_quantlist__44u2__p6_0,
  147200. NULL,
  147201. &_vq_auxt__44u2__p6_0,
  147202. NULL,
  147203. 0
  147204. };
  147205. static long _vq_quantlist__44u2__p6_1[] = {
  147206. 2,
  147207. 1,
  147208. 3,
  147209. 0,
  147210. 4,
  147211. };
  147212. static long _vq_lengthlist__44u2__p6_1[] = {
  147213. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147214. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147215. };
  147216. static float _vq_quantthresh__44u2__p6_1[] = {
  147217. -1.5, -0.5, 0.5, 1.5,
  147218. };
  147219. static long _vq_quantmap__44u2__p6_1[] = {
  147220. 3, 1, 0, 2, 4,
  147221. };
  147222. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147223. _vq_quantthresh__44u2__p6_1,
  147224. _vq_quantmap__44u2__p6_1,
  147225. 5,
  147226. 5
  147227. };
  147228. static static_codebook _44u2__p6_1 = {
  147229. 2, 25,
  147230. _vq_lengthlist__44u2__p6_1,
  147231. 1, -533725184, 1611661312, 3, 0,
  147232. _vq_quantlist__44u2__p6_1,
  147233. NULL,
  147234. &_vq_auxt__44u2__p6_1,
  147235. NULL,
  147236. 0
  147237. };
  147238. static long _vq_quantlist__44u2__p7_0[] = {
  147239. 4,
  147240. 3,
  147241. 5,
  147242. 2,
  147243. 6,
  147244. 1,
  147245. 7,
  147246. 0,
  147247. 8,
  147248. };
  147249. static long _vq_lengthlist__44u2__p7_0[] = {
  147250. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147251. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147255. 11,
  147256. };
  147257. static float _vq_quantthresh__44u2__p7_0[] = {
  147258. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147259. };
  147260. static long _vq_quantmap__44u2__p7_0[] = {
  147261. 7, 5, 3, 1, 0, 2, 4, 6,
  147262. 8,
  147263. };
  147264. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147265. _vq_quantthresh__44u2__p7_0,
  147266. _vq_quantmap__44u2__p7_0,
  147267. 9,
  147268. 9
  147269. };
  147270. static static_codebook _44u2__p7_0 = {
  147271. 2, 81,
  147272. _vq_lengthlist__44u2__p7_0,
  147273. 1, -516612096, 1626677248, 4, 0,
  147274. _vq_quantlist__44u2__p7_0,
  147275. NULL,
  147276. &_vq_auxt__44u2__p7_0,
  147277. NULL,
  147278. 0
  147279. };
  147280. static long _vq_quantlist__44u2__p7_1[] = {
  147281. 6,
  147282. 5,
  147283. 7,
  147284. 4,
  147285. 8,
  147286. 3,
  147287. 9,
  147288. 2,
  147289. 10,
  147290. 1,
  147291. 11,
  147292. 0,
  147293. 12,
  147294. };
  147295. static long _vq_lengthlist__44u2__p7_1[] = {
  147296. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147297. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147298. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147299. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147300. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147301. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147302. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147303. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147304. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147305. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147306. 14,14,14,17,15,17,17,17,17,
  147307. };
  147308. static float _vq_quantthresh__44u2__p7_1[] = {
  147309. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147310. 32.5, 45.5, 58.5, 71.5,
  147311. };
  147312. static long _vq_quantmap__44u2__p7_1[] = {
  147313. 11, 9, 7, 5, 3, 1, 0, 2,
  147314. 4, 6, 8, 10, 12,
  147315. };
  147316. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147317. _vq_quantthresh__44u2__p7_1,
  147318. _vq_quantmap__44u2__p7_1,
  147319. 13,
  147320. 13
  147321. };
  147322. static static_codebook _44u2__p7_1 = {
  147323. 2, 169,
  147324. _vq_lengthlist__44u2__p7_1,
  147325. 1, -523010048, 1618608128, 4, 0,
  147326. _vq_quantlist__44u2__p7_1,
  147327. NULL,
  147328. &_vq_auxt__44u2__p7_1,
  147329. NULL,
  147330. 0
  147331. };
  147332. static long _vq_quantlist__44u2__p7_2[] = {
  147333. 6,
  147334. 5,
  147335. 7,
  147336. 4,
  147337. 8,
  147338. 3,
  147339. 9,
  147340. 2,
  147341. 10,
  147342. 1,
  147343. 11,
  147344. 0,
  147345. 12,
  147346. };
  147347. static long _vq_lengthlist__44u2__p7_2[] = {
  147348. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147349. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147350. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147351. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147352. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147353. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147354. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147355. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147356. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147357. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147358. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147359. };
  147360. static float _vq_quantthresh__44u2__p7_2[] = {
  147361. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147362. 2.5, 3.5, 4.5, 5.5,
  147363. };
  147364. static long _vq_quantmap__44u2__p7_2[] = {
  147365. 11, 9, 7, 5, 3, 1, 0, 2,
  147366. 4, 6, 8, 10, 12,
  147367. };
  147368. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147369. _vq_quantthresh__44u2__p7_2,
  147370. _vq_quantmap__44u2__p7_2,
  147371. 13,
  147372. 13
  147373. };
  147374. static static_codebook _44u2__p7_2 = {
  147375. 2, 169,
  147376. _vq_lengthlist__44u2__p7_2,
  147377. 1, -531103744, 1611661312, 4, 0,
  147378. _vq_quantlist__44u2__p7_2,
  147379. NULL,
  147380. &_vq_auxt__44u2__p7_2,
  147381. NULL,
  147382. 0
  147383. };
  147384. static long _huff_lengthlist__44u2__short[] = {
  147385. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147386. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147387. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147388. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147389. };
  147390. static static_codebook _huff_book__44u2__short = {
  147391. 2, 64,
  147392. _huff_lengthlist__44u2__short,
  147393. 0, 0, 0, 0, 0,
  147394. NULL,
  147395. NULL,
  147396. NULL,
  147397. NULL,
  147398. 0
  147399. };
  147400. static long _huff_lengthlist__44u3__long[] = {
  147401. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147402. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147403. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147404. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147405. };
  147406. static static_codebook _huff_book__44u3__long = {
  147407. 2, 64,
  147408. _huff_lengthlist__44u3__long,
  147409. 0, 0, 0, 0, 0,
  147410. NULL,
  147411. NULL,
  147412. NULL,
  147413. NULL,
  147414. 0
  147415. };
  147416. static long _vq_quantlist__44u3__p1_0[] = {
  147417. 1,
  147418. 0,
  147419. 2,
  147420. };
  147421. static long _vq_lengthlist__44u3__p1_0[] = {
  147422. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147423. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147424. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147425. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147426. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147427. 13,
  147428. };
  147429. static float _vq_quantthresh__44u3__p1_0[] = {
  147430. -0.5, 0.5,
  147431. };
  147432. static long _vq_quantmap__44u3__p1_0[] = {
  147433. 1, 0, 2,
  147434. };
  147435. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147436. _vq_quantthresh__44u3__p1_0,
  147437. _vq_quantmap__44u3__p1_0,
  147438. 3,
  147439. 3
  147440. };
  147441. static static_codebook _44u3__p1_0 = {
  147442. 4, 81,
  147443. _vq_lengthlist__44u3__p1_0,
  147444. 1, -535822336, 1611661312, 2, 0,
  147445. _vq_quantlist__44u3__p1_0,
  147446. NULL,
  147447. &_vq_auxt__44u3__p1_0,
  147448. NULL,
  147449. 0
  147450. };
  147451. static long _vq_quantlist__44u3__p2_0[] = {
  147452. 1,
  147453. 0,
  147454. 2,
  147455. };
  147456. static long _vq_lengthlist__44u3__p2_0[] = {
  147457. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147458. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147459. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147460. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147461. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147462. 9,
  147463. };
  147464. static float _vq_quantthresh__44u3__p2_0[] = {
  147465. -0.5, 0.5,
  147466. };
  147467. static long _vq_quantmap__44u3__p2_0[] = {
  147468. 1, 0, 2,
  147469. };
  147470. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147471. _vq_quantthresh__44u3__p2_0,
  147472. _vq_quantmap__44u3__p2_0,
  147473. 3,
  147474. 3
  147475. };
  147476. static static_codebook _44u3__p2_0 = {
  147477. 4, 81,
  147478. _vq_lengthlist__44u3__p2_0,
  147479. 1, -535822336, 1611661312, 2, 0,
  147480. _vq_quantlist__44u3__p2_0,
  147481. NULL,
  147482. &_vq_auxt__44u3__p2_0,
  147483. NULL,
  147484. 0
  147485. };
  147486. static long _vq_quantlist__44u3__p3_0[] = {
  147487. 2,
  147488. 1,
  147489. 3,
  147490. 0,
  147491. 4,
  147492. };
  147493. static long _vq_lengthlist__44u3__p3_0[] = {
  147494. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147495. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147496. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147497. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147498. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147499. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147500. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147501. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147502. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147503. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147504. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147505. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147506. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147507. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147508. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147509. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147510. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147511. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147512. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147513. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147514. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147515. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147516. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147517. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147518. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147519. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147520. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147521. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147522. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147523. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147524. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147525. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147526. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147527. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147528. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147529. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147530. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147531. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147532. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147533. 0,
  147534. };
  147535. static float _vq_quantthresh__44u3__p3_0[] = {
  147536. -1.5, -0.5, 0.5, 1.5,
  147537. };
  147538. static long _vq_quantmap__44u3__p3_0[] = {
  147539. 3, 1, 0, 2, 4,
  147540. };
  147541. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147542. _vq_quantthresh__44u3__p3_0,
  147543. _vq_quantmap__44u3__p3_0,
  147544. 5,
  147545. 5
  147546. };
  147547. static static_codebook _44u3__p3_0 = {
  147548. 4, 625,
  147549. _vq_lengthlist__44u3__p3_0,
  147550. 1, -533725184, 1611661312, 3, 0,
  147551. _vq_quantlist__44u3__p3_0,
  147552. NULL,
  147553. &_vq_auxt__44u3__p3_0,
  147554. NULL,
  147555. 0
  147556. };
  147557. static long _vq_quantlist__44u3__p4_0[] = {
  147558. 2,
  147559. 1,
  147560. 3,
  147561. 0,
  147562. 4,
  147563. };
  147564. static long _vq_lengthlist__44u3__p4_0[] = {
  147565. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147566. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147567. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147568. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147569. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147570. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147571. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147572. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147573. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147574. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147575. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147576. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147577. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147578. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147579. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147580. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147581. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147582. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147583. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147584. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147585. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147586. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147587. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147588. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147589. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147590. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147591. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147592. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147593. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147594. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147595. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147596. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147597. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147598. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147599. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147600. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147601. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147602. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147603. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147604. 13,
  147605. };
  147606. static float _vq_quantthresh__44u3__p4_0[] = {
  147607. -1.5, -0.5, 0.5, 1.5,
  147608. };
  147609. static long _vq_quantmap__44u3__p4_0[] = {
  147610. 3, 1, 0, 2, 4,
  147611. };
  147612. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147613. _vq_quantthresh__44u3__p4_0,
  147614. _vq_quantmap__44u3__p4_0,
  147615. 5,
  147616. 5
  147617. };
  147618. static static_codebook _44u3__p4_0 = {
  147619. 4, 625,
  147620. _vq_lengthlist__44u3__p4_0,
  147621. 1, -533725184, 1611661312, 3, 0,
  147622. _vq_quantlist__44u3__p4_0,
  147623. NULL,
  147624. &_vq_auxt__44u3__p4_0,
  147625. NULL,
  147626. 0
  147627. };
  147628. static long _vq_quantlist__44u3__p5_0[] = {
  147629. 4,
  147630. 3,
  147631. 5,
  147632. 2,
  147633. 6,
  147634. 1,
  147635. 7,
  147636. 0,
  147637. 8,
  147638. };
  147639. static long _vq_lengthlist__44u3__p5_0[] = {
  147640. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147641. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147642. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147643. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147644. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147645. 12,
  147646. };
  147647. static float _vq_quantthresh__44u3__p5_0[] = {
  147648. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147649. };
  147650. static long _vq_quantmap__44u3__p5_0[] = {
  147651. 7, 5, 3, 1, 0, 2, 4, 6,
  147652. 8,
  147653. };
  147654. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147655. _vq_quantthresh__44u3__p5_0,
  147656. _vq_quantmap__44u3__p5_0,
  147657. 9,
  147658. 9
  147659. };
  147660. static static_codebook _44u3__p5_0 = {
  147661. 2, 81,
  147662. _vq_lengthlist__44u3__p5_0,
  147663. 1, -531628032, 1611661312, 4, 0,
  147664. _vq_quantlist__44u3__p5_0,
  147665. NULL,
  147666. &_vq_auxt__44u3__p5_0,
  147667. NULL,
  147668. 0
  147669. };
  147670. static long _vq_quantlist__44u3__p6_0[] = {
  147671. 6,
  147672. 5,
  147673. 7,
  147674. 4,
  147675. 8,
  147676. 3,
  147677. 9,
  147678. 2,
  147679. 10,
  147680. 1,
  147681. 11,
  147682. 0,
  147683. 12,
  147684. };
  147685. static long _vq_lengthlist__44u3__p6_0[] = {
  147686. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147687. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147688. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147689. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147690. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147691. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147692. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147693. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147694. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147695. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147696. 15,16,16,16,17,18,16,20,18,
  147697. };
  147698. static float _vq_quantthresh__44u3__p6_0[] = {
  147699. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147700. 12.5, 17.5, 22.5, 27.5,
  147701. };
  147702. static long _vq_quantmap__44u3__p6_0[] = {
  147703. 11, 9, 7, 5, 3, 1, 0, 2,
  147704. 4, 6, 8, 10, 12,
  147705. };
  147706. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147707. _vq_quantthresh__44u3__p6_0,
  147708. _vq_quantmap__44u3__p6_0,
  147709. 13,
  147710. 13
  147711. };
  147712. static static_codebook _44u3__p6_0 = {
  147713. 2, 169,
  147714. _vq_lengthlist__44u3__p6_0,
  147715. 1, -526516224, 1616117760, 4, 0,
  147716. _vq_quantlist__44u3__p6_0,
  147717. NULL,
  147718. &_vq_auxt__44u3__p6_0,
  147719. NULL,
  147720. 0
  147721. };
  147722. static long _vq_quantlist__44u3__p6_1[] = {
  147723. 2,
  147724. 1,
  147725. 3,
  147726. 0,
  147727. 4,
  147728. };
  147729. static long _vq_lengthlist__44u3__p6_1[] = {
  147730. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147731. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147732. };
  147733. static float _vq_quantthresh__44u3__p6_1[] = {
  147734. -1.5, -0.5, 0.5, 1.5,
  147735. };
  147736. static long _vq_quantmap__44u3__p6_1[] = {
  147737. 3, 1, 0, 2, 4,
  147738. };
  147739. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147740. _vq_quantthresh__44u3__p6_1,
  147741. _vq_quantmap__44u3__p6_1,
  147742. 5,
  147743. 5
  147744. };
  147745. static static_codebook _44u3__p6_1 = {
  147746. 2, 25,
  147747. _vq_lengthlist__44u3__p6_1,
  147748. 1, -533725184, 1611661312, 3, 0,
  147749. _vq_quantlist__44u3__p6_1,
  147750. NULL,
  147751. &_vq_auxt__44u3__p6_1,
  147752. NULL,
  147753. 0
  147754. };
  147755. static long _vq_quantlist__44u3__p7_0[] = {
  147756. 4,
  147757. 3,
  147758. 5,
  147759. 2,
  147760. 6,
  147761. 1,
  147762. 7,
  147763. 0,
  147764. 8,
  147765. };
  147766. static long _vq_lengthlist__44u3__p7_0[] = {
  147767. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147768. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147769. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147770. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147771. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147772. 9,
  147773. };
  147774. static float _vq_quantthresh__44u3__p7_0[] = {
  147775. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147776. };
  147777. static long _vq_quantmap__44u3__p7_0[] = {
  147778. 7, 5, 3, 1, 0, 2, 4, 6,
  147779. 8,
  147780. };
  147781. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147782. _vq_quantthresh__44u3__p7_0,
  147783. _vq_quantmap__44u3__p7_0,
  147784. 9,
  147785. 9
  147786. };
  147787. static static_codebook _44u3__p7_0 = {
  147788. 2, 81,
  147789. _vq_lengthlist__44u3__p7_0,
  147790. 1, -515907584, 1627381760, 4, 0,
  147791. _vq_quantlist__44u3__p7_0,
  147792. NULL,
  147793. &_vq_auxt__44u3__p7_0,
  147794. NULL,
  147795. 0
  147796. };
  147797. static long _vq_quantlist__44u3__p7_1[] = {
  147798. 7,
  147799. 6,
  147800. 8,
  147801. 5,
  147802. 9,
  147803. 4,
  147804. 10,
  147805. 3,
  147806. 11,
  147807. 2,
  147808. 12,
  147809. 1,
  147810. 13,
  147811. 0,
  147812. 14,
  147813. };
  147814. static long _vq_lengthlist__44u3__p7_1[] = {
  147815. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147816. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147817. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147818. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147819. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147820. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147821. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147822. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147823. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147824. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147825. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147826. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147827. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147828. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147829. 17,
  147830. };
  147831. static float _vq_quantthresh__44u3__p7_1[] = {
  147832. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147833. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147834. };
  147835. static long _vq_quantmap__44u3__p7_1[] = {
  147836. 13, 11, 9, 7, 5, 3, 1, 0,
  147837. 2, 4, 6, 8, 10, 12, 14,
  147838. };
  147839. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147840. _vq_quantthresh__44u3__p7_1,
  147841. _vq_quantmap__44u3__p7_1,
  147842. 15,
  147843. 15
  147844. };
  147845. static static_codebook _44u3__p7_1 = {
  147846. 2, 225,
  147847. _vq_lengthlist__44u3__p7_1,
  147848. 1, -522338304, 1620115456, 4, 0,
  147849. _vq_quantlist__44u3__p7_1,
  147850. NULL,
  147851. &_vq_auxt__44u3__p7_1,
  147852. NULL,
  147853. 0
  147854. };
  147855. static long _vq_quantlist__44u3__p7_2[] = {
  147856. 8,
  147857. 7,
  147858. 9,
  147859. 6,
  147860. 10,
  147861. 5,
  147862. 11,
  147863. 4,
  147864. 12,
  147865. 3,
  147866. 13,
  147867. 2,
  147868. 14,
  147869. 1,
  147870. 15,
  147871. 0,
  147872. 16,
  147873. };
  147874. static long _vq_lengthlist__44u3__p7_2[] = {
  147875. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147876. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147877. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147878. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147879. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147880. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147881. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147882. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147883. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147884. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147885. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147886. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147887. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147888. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147889. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147890. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147892. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147893. 11,
  147894. };
  147895. static float _vq_quantthresh__44u3__p7_2[] = {
  147896. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147897. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147898. };
  147899. static long _vq_quantmap__44u3__p7_2[] = {
  147900. 15, 13, 11, 9, 7, 5, 3, 1,
  147901. 0, 2, 4, 6, 8, 10, 12, 14,
  147902. 16,
  147903. };
  147904. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147905. _vq_quantthresh__44u3__p7_2,
  147906. _vq_quantmap__44u3__p7_2,
  147907. 17,
  147908. 17
  147909. };
  147910. static static_codebook _44u3__p7_2 = {
  147911. 2, 289,
  147912. _vq_lengthlist__44u3__p7_2,
  147913. 1, -529530880, 1611661312, 5, 0,
  147914. _vq_quantlist__44u3__p7_2,
  147915. NULL,
  147916. &_vq_auxt__44u3__p7_2,
  147917. NULL,
  147918. 0
  147919. };
  147920. static long _huff_lengthlist__44u3__short[] = {
  147921. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147922. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147923. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147924. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147925. };
  147926. static static_codebook _huff_book__44u3__short = {
  147927. 2, 64,
  147928. _huff_lengthlist__44u3__short,
  147929. 0, 0, 0, 0, 0,
  147930. NULL,
  147931. NULL,
  147932. NULL,
  147933. NULL,
  147934. 0
  147935. };
  147936. static long _huff_lengthlist__44u4__long[] = {
  147937. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147938. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147939. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147940. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147941. };
  147942. static static_codebook _huff_book__44u4__long = {
  147943. 2, 64,
  147944. _huff_lengthlist__44u4__long,
  147945. 0, 0, 0, 0, 0,
  147946. NULL,
  147947. NULL,
  147948. NULL,
  147949. NULL,
  147950. 0
  147951. };
  147952. static long _vq_quantlist__44u4__p1_0[] = {
  147953. 1,
  147954. 0,
  147955. 2,
  147956. };
  147957. static long _vq_lengthlist__44u4__p1_0[] = {
  147958. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147959. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147960. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147961. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147962. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147963. 13,
  147964. };
  147965. static float _vq_quantthresh__44u4__p1_0[] = {
  147966. -0.5, 0.5,
  147967. };
  147968. static long _vq_quantmap__44u4__p1_0[] = {
  147969. 1, 0, 2,
  147970. };
  147971. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147972. _vq_quantthresh__44u4__p1_0,
  147973. _vq_quantmap__44u4__p1_0,
  147974. 3,
  147975. 3
  147976. };
  147977. static static_codebook _44u4__p1_0 = {
  147978. 4, 81,
  147979. _vq_lengthlist__44u4__p1_0,
  147980. 1, -535822336, 1611661312, 2, 0,
  147981. _vq_quantlist__44u4__p1_0,
  147982. NULL,
  147983. &_vq_auxt__44u4__p1_0,
  147984. NULL,
  147985. 0
  147986. };
  147987. static long _vq_quantlist__44u4__p2_0[] = {
  147988. 1,
  147989. 0,
  147990. 2,
  147991. };
  147992. static long _vq_lengthlist__44u4__p2_0[] = {
  147993. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147994. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147995. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147996. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147997. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147998. 9,
  147999. };
  148000. static float _vq_quantthresh__44u4__p2_0[] = {
  148001. -0.5, 0.5,
  148002. };
  148003. static long _vq_quantmap__44u4__p2_0[] = {
  148004. 1, 0, 2,
  148005. };
  148006. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148007. _vq_quantthresh__44u4__p2_0,
  148008. _vq_quantmap__44u4__p2_0,
  148009. 3,
  148010. 3
  148011. };
  148012. static static_codebook _44u4__p2_0 = {
  148013. 4, 81,
  148014. _vq_lengthlist__44u4__p2_0,
  148015. 1, -535822336, 1611661312, 2, 0,
  148016. _vq_quantlist__44u4__p2_0,
  148017. NULL,
  148018. &_vq_auxt__44u4__p2_0,
  148019. NULL,
  148020. 0
  148021. };
  148022. static long _vq_quantlist__44u4__p3_0[] = {
  148023. 2,
  148024. 1,
  148025. 3,
  148026. 0,
  148027. 4,
  148028. };
  148029. static long _vq_lengthlist__44u4__p3_0[] = {
  148030. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148031. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148032. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148033. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148034. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148035. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148036. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148037. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148038. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148039. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148040. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148041. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148042. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148043. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148044. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148045. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148046. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148047. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148048. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148049. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148050. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148051. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148052. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148053. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148054. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148055. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148056. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148057. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148058. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148059. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148060. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148061. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148062. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148063. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148064. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148065. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148066. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148067. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148068. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148069. 0,
  148070. };
  148071. static float _vq_quantthresh__44u4__p3_0[] = {
  148072. -1.5, -0.5, 0.5, 1.5,
  148073. };
  148074. static long _vq_quantmap__44u4__p3_0[] = {
  148075. 3, 1, 0, 2, 4,
  148076. };
  148077. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148078. _vq_quantthresh__44u4__p3_0,
  148079. _vq_quantmap__44u4__p3_0,
  148080. 5,
  148081. 5
  148082. };
  148083. static static_codebook _44u4__p3_0 = {
  148084. 4, 625,
  148085. _vq_lengthlist__44u4__p3_0,
  148086. 1, -533725184, 1611661312, 3, 0,
  148087. _vq_quantlist__44u4__p3_0,
  148088. NULL,
  148089. &_vq_auxt__44u4__p3_0,
  148090. NULL,
  148091. 0
  148092. };
  148093. static long _vq_quantlist__44u4__p4_0[] = {
  148094. 2,
  148095. 1,
  148096. 3,
  148097. 0,
  148098. 4,
  148099. };
  148100. static long _vq_lengthlist__44u4__p4_0[] = {
  148101. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148102. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148103. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148104. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148105. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148106. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148107. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148108. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148109. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148110. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148111. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148112. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148113. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148114. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148115. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148116. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148117. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148118. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148119. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148120. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148121. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148122. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148123. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148124. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148125. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148126. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148127. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148128. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148129. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148130. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148131. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148132. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148133. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148134. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148135. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148136. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148137. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148138. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148139. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148140. 13,
  148141. };
  148142. static float _vq_quantthresh__44u4__p4_0[] = {
  148143. -1.5, -0.5, 0.5, 1.5,
  148144. };
  148145. static long _vq_quantmap__44u4__p4_0[] = {
  148146. 3, 1, 0, 2, 4,
  148147. };
  148148. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148149. _vq_quantthresh__44u4__p4_0,
  148150. _vq_quantmap__44u4__p4_0,
  148151. 5,
  148152. 5
  148153. };
  148154. static static_codebook _44u4__p4_0 = {
  148155. 4, 625,
  148156. _vq_lengthlist__44u4__p4_0,
  148157. 1, -533725184, 1611661312, 3, 0,
  148158. _vq_quantlist__44u4__p4_0,
  148159. NULL,
  148160. &_vq_auxt__44u4__p4_0,
  148161. NULL,
  148162. 0
  148163. };
  148164. static long _vq_quantlist__44u4__p5_0[] = {
  148165. 4,
  148166. 3,
  148167. 5,
  148168. 2,
  148169. 6,
  148170. 1,
  148171. 7,
  148172. 0,
  148173. 8,
  148174. };
  148175. static long _vq_lengthlist__44u4__p5_0[] = {
  148176. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148177. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148178. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148179. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148180. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148181. 12,
  148182. };
  148183. static float _vq_quantthresh__44u4__p5_0[] = {
  148184. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148185. };
  148186. static long _vq_quantmap__44u4__p5_0[] = {
  148187. 7, 5, 3, 1, 0, 2, 4, 6,
  148188. 8,
  148189. };
  148190. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148191. _vq_quantthresh__44u4__p5_0,
  148192. _vq_quantmap__44u4__p5_0,
  148193. 9,
  148194. 9
  148195. };
  148196. static static_codebook _44u4__p5_0 = {
  148197. 2, 81,
  148198. _vq_lengthlist__44u4__p5_0,
  148199. 1, -531628032, 1611661312, 4, 0,
  148200. _vq_quantlist__44u4__p5_0,
  148201. NULL,
  148202. &_vq_auxt__44u4__p5_0,
  148203. NULL,
  148204. 0
  148205. };
  148206. static long _vq_quantlist__44u4__p6_0[] = {
  148207. 6,
  148208. 5,
  148209. 7,
  148210. 4,
  148211. 8,
  148212. 3,
  148213. 9,
  148214. 2,
  148215. 10,
  148216. 1,
  148217. 11,
  148218. 0,
  148219. 12,
  148220. };
  148221. static long _vq_lengthlist__44u4__p6_0[] = {
  148222. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148223. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148224. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148225. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148226. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148227. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148228. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148229. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148230. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148231. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148232. 16,16,16,17,17,18,17,20,21,
  148233. };
  148234. static float _vq_quantthresh__44u4__p6_0[] = {
  148235. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148236. 12.5, 17.5, 22.5, 27.5,
  148237. };
  148238. static long _vq_quantmap__44u4__p6_0[] = {
  148239. 11, 9, 7, 5, 3, 1, 0, 2,
  148240. 4, 6, 8, 10, 12,
  148241. };
  148242. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148243. _vq_quantthresh__44u4__p6_0,
  148244. _vq_quantmap__44u4__p6_0,
  148245. 13,
  148246. 13
  148247. };
  148248. static static_codebook _44u4__p6_0 = {
  148249. 2, 169,
  148250. _vq_lengthlist__44u4__p6_0,
  148251. 1, -526516224, 1616117760, 4, 0,
  148252. _vq_quantlist__44u4__p6_0,
  148253. NULL,
  148254. &_vq_auxt__44u4__p6_0,
  148255. NULL,
  148256. 0
  148257. };
  148258. static long _vq_quantlist__44u4__p6_1[] = {
  148259. 2,
  148260. 1,
  148261. 3,
  148262. 0,
  148263. 4,
  148264. };
  148265. static long _vq_lengthlist__44u4__p6_1[] = {
  148266. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148267. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148268. };
  148269. static float _vq_quantthresh__44u4__p6_1[] = {
  148270. -1.5, -0.5, 0.5, 1.5,
  148271. };
  148272. static long _vq_quantmap__44u4__p6_1[] = {
  148273. 3, 1, 0, 2, 4,
  148274. };
  148275. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148276. _vq_quantthresh__44u4__p6_1,
  148277. _vq_quantmap__44u4__p6_1,
  148278. 5,
  148279. 5
  148280. };
  148281. static static_codebook _44u4__p6_1 = {
  148282. 2, 25,
  148283. _vq_lengthlist__44u4__p6_1,
  148284. 1, -533725184, 1611661312, 3, 0,
  148285. _vq_quantlist__44u4__p6_1,
  148286. NULL,
  148287. &_vq_auxt__44u4__p6_1,
  148288. NULL,
  148289. 0
  148290. };
  148291. static long _vq_quantlist__44u4__p7_0[] = {
  148292. 6,
  148293. 5,
  148294. 7,
  148295. 4,
  148296. 8,
  148297. 3,
  148298. 9,
  148299. 2,
  148300. 10,
  148301. 1,
  148302. 11,
  148303. 0,
  148304. 12,
  148305. };
  148306. static long _vq_lengthlist__44u4__p7_0[] = {
  148307. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148308. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148309. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148310. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148311. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148312. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148317. 11,11,11,11,11,11,11,11,11,
  148318. };
  148319. static float _vq_quantthresh__44u4__p7_0[] = {
  148320. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148321. 637.5, 892.5, 1147.5, 1402.5,
  148322. };
  148323. static long _vq_quantmap__44u4__p7_0[] = {
  148324. 11, 9, 7, 5, 3, 1, 0, 2,
  148325. 4, 6, 8, 10, 12,
  148326. };
  148327. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148328. _vq_quantthresh__44u4__p7_0,
  148329. _vq_quantmap__44u4__p7_0,
  148330. 13,
  148331. 13
  148332. };
  148333. static static_codebook _44u4__p7_0 = {
  148334. 2, 169,
  148335. _vq_lengthlist__44u4__p7_0,
  148336. 1, -514332672, 1627381760, 4, 0,
  148337. _vq_quantlist__44u4__p7_0,
  148338. NULL,
  148339. &_vq_auxt__44u4__p7_0,
  148340. NULL,
  148341. 0
  148342. };
  148343. static long _vq_quantlist__44u4__p7_1[] = {
  148344. 7,
  148345. 6,
  148346. 8,
  148347. 5,
  148348. 9,
  148349. 4,
  148350. 10,
  148351. 3,
  148352. 11,
  148353. 2,
  148354. 12,
  148355. 1,
  148356. 13,
  148357. 0,
  148358. 14,
  148359. };
  148360. static long _vq_lengthlist__44u4__p7_1[] = {
  148361. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148362. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148363. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148364. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148365. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148366. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148367. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148368. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148369. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148370. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148371. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148372. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148373. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148374. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148375. 16,
  148376. };
  148377. static float _vq_quantthresh__44u4__p7_1[] = {
  148378. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148379. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148380. };
  148381. static long _vq_quantmap__44u4__p7_1[] = {
  148382. 13, 11, 9, 7, 5, 3, 1, 0,
  148383. 2, 4, 6, 8, 10, 12, 14,
  148384. };
  148385. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148386. _vq_quantthresh__44u4__p7_1,
  148387. _vq_quantmap__44u4__p7_1,
  148388. 15,
  148389. 15
  148390. };
  148391. static static_codebook _44u4__p7_1 = {
  148392. 2, 225,
  148393. _vq_lengthlist__44u4__p7_1,
  148394. 1, -522338304, 1620115456, 4, 0,
  148395. _vq_quantlist__44u4__p7_1,
  148396. NULL,
  148397. &_vq_auxt__44u4__p7_1,
  148398. NULL,
  148399. 0
  148400. };
  148401. static long _vq_quantlist__44u4__p7_2[] = {
  148402. 8,
  148403. 7,
  148404. 9,
  148405. 6,
  148406. 10,
  148407. 5,
  148408. 11,
  148409. 4,
  148410. 12,
  148411. 3,
  148412. 13,
  148413. 2,
  148414. 14,
  148415. 1,
  148416. 15,
  148417. 0,
  148418. 16,
  148419. };
  148420. static long _vq_lengthlist__44u4__p7_2[] = {
  148421. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148422. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148423. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148424. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148425. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148426. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148427. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148428. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148429. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148430. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148431. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148432. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148433. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148434. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148435. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148436. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148437. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148438. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148439. 10,
  148440. };
  148441. static float _vq_quantthresh__44u4__p7_2[] = {
  148442. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148443. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148444. };
  148445. static long _vq_quantmap__44u4__p7_2[] = {
  148446. 15, 13, 11, 9, 7, 5, 3, 1,
  148447. 0, 2, 4, 6, 8, 10, 12, 14,
  148448. 16,
  148449. };
  148450. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148451. _vq_quantthresh__44u4__p7_2,
  148452. _vq_quantmap__44u4__p7_2,
  148453. 17,
  148454. 17
  148455. };
  148456. static static_codebook _44u4__p7_2 = {
  148457. 2, 289,
  148458. _vq_lengthlist__44u4__p7_2,
  148459. 1, -529530880, 1611661312, 5, 0,
  148460. _vq_quantlist__44u4__p7_2,
  148461. NULL,
  148462. &_vq_auxt__44u4__p7_2,
  148463. NULL,
  148464. 0
  148465. };
  148466. static long _huff_lengthlist__44u4__short[] = {
  148467. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148468. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148469. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148470. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148471. };
  148472. static static_codebook _huff_book__44u4__short = {
  148473. 2, 64,
  148474. _huff_lengthlist__44u4__short,
  148475. 0, 0, 0, 0, 0,
  148476. NULL,
  148477. NULL,
  148478. NULL,
  148479. NULL,
  148480. 0
  148481. };
  148482. static long _huff_lengthlist__44u5__long[] = {
  148483. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148484. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148485. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148486. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148487. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148488. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148489. 14, 8, 7, 8,
  148490. };
  148491. static static_codebook _huff_book__44u5__long = {
  148492. 2, 100,
  148493. _huff_lengthlist__44u5__long,
  148494. 0, 0, 0, 0, 0,
  148495. NULL,
  148496. NULL,
  148497. NULL,
  148498. NULL,
  148499. 0
  148500. };
  148501. static long _vq_quantlist__44u5__p1_0[] = {
  148502. 1,
  148503. 0,
  148504. 2,
  148505. };
  148506. static long _vq_lengthlist__44u5__p1_0[] = {
  148507. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148508. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148509. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148510. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148511. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148512. 12,
  148513. };
  148514. static float _vq_quantthresh__44u5__p1_0[] = {
  148515. -0.5, 0.5,
  148516. };
  148517. static long _vq_quantmap__44u5__p1_0[] = {
  148518. 1, 0, 2,
  148519. };
  148520. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148521. _vq_quantthresh__44u5__p1_0,
  148522. _vq_quantmap__44u5__p1_0,
  148523. 3,
  148524. 3
  148525. };
  148526. static static_codebook _44u5__p1_0 = {
  148527. 4, 81,
  148528. _vq_lengthlist__44u5__p1_0,
  148529. 1, -535822336, 1611661312, 2, 0,
  148530. _vq_quantlist__44u5__p1_0,
  148531. NULL,
  148532. &_vq_auxt__44u5__p1_0,
  148533. NULL,
  148534. 0
  148535. };
  148536. static long _vq_quantlist__44u5__p2_0[] = {
  148537. 1,
  148538. 0,
  148539. 2,
  148540. };
  148541. static long _vq_lengthlist__44u5__p2_0[] = {
  148542. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148543. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148544. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148545. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148546. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148547. 9,
  148548. };
  148549. static float _vq_quantthresh__44u5__p2_0[] = {
  148550. -0.5, 0.5,
  148551. };
  148552. static long _vq_quantmap__44u5__p2_0[] = {
  148553. 1, 0, 2,
  148554. };
  148555. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148556. _vq_quantthresh__44u5__p2_0,
  148557. _vq_quantmap__44u5__p2_0,
  148558. 3,
  148559. 3
  148560. };
  148561. static static_codebook _44u5__p2_0 = {
  148562. 4, 81,
  148563. _vq_lengthlist__44u5__p2_0,
  148564. 1, -535822336, 1611661312, 2, 0,
  148565. _vq_quantlist__44u5__p2_0,
  148566. NULL,
  148567. &_vq_auxt__44u5__p2_0,
  148568. NULL,
  148569. 0
  148570. };
  148571. static long _vq_quantlist__44u5__p3_0[] = {
  148572. 2,
  148573. 1,
  148574. 3,
  148575. 0,
  148576. 4,
  148577. };
  148578. static long _vq_lengthlist__44u5__p3_0[] = {
  148579. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148580. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148581. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148582. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148583. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148584. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148585. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148586. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148587. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148588. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148589. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148590. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148591. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148592. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148593. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148594. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148595. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148596. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148597. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148598. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148599. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148600. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148601. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148602. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148603. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148604. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148605. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148606. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148607. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148608. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148609. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148610. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148611. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148612. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148613. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148614. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148615. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148616. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148617. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148618. 0,
  148619. };
  148620. static float _vq_quantthresh__44u5__p3_0[] = {
  148621. -1.5, -0.5, 0.5, 1.5,
  148622. };
  148623. static long _vq_quantmap__44u5__p3_0[] = {
  148624. 3, 1, 0, 2, 4,
  148625. };
  148626. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148627. _vq_quantthresh__44u5__p3_0,
  148628. _vq_quantmap__44u5__p3_0,
  148629. 5,
  148630. 5
  148631. };
  148632. static static_codebook _44u5__p3_0 = {
  148633. 4, 625,
  148634. _vq_lengthlist__44u5__p3_0,
  148635. 1, -533725184, 1611661312, 3, 0,
  148636. _vq_quantlist__44u5__p3_0,
  148637. NULL,
  148638. &_vq_auxt__44u5__p3_0,
  148639. NULL,
  148640. 0
  148641. };
  148642. static long _vq_quantlist__44u5__p4_0[] = {
  148643. 2,
  148644. 1,
  148645. 3,
  148646. 0,
  148647. 4,
  148648. };
  148649. static long _vq_lengthlist__44u5__p4_0[] = {
  148650. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148651. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148652. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148653. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148654. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148655. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148656. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148657. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148658. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148659. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148660. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148661. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148662. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148663. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148664. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148665. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148666. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148667. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148668. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148669. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148670. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148671. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148672. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148673. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148674. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148675. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148676. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148677. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148678. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148679. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148680. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148681. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148682. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148683. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148684. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148685. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148686. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148687. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148688. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148689. 12,
  148690. };
  148691. static float _vq_quantthresh__44u5__p4_0[] = {
  148692. -1.5, -0.5, 0.5, 1.5,
  148693. };
  148694. static long _vq_quantmap__44u5__p4_0[] = {
  148695. 3, 1, 0, 2, 4,
  148696. };
  148697. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148698. _vq_quantthresh__44u5__p4_0,
  148699. _vq_quantmap__44u5__p4_0,
  148700. 5,
  148701. 5
  148702. };
  148703. static static_codebook _44u5__p4_0 = {
  148704. 4, 625,
  148705. _vq_lengthlist__44u5__p4_0,
  148706. 1, -533725184, 1611661312, 3, 0,
  148707. _vq_quantlist__44u5__p4_0,
  148708. NULL,
  148709. &_vq_auxt__44u5__p4_0,
  148710. NULL,
  148711. 0
  148712. };
  148713. static long _vq_quantlist__44u5__p5_0[] = {
  148714. 4,
  148715. 3,
  148716. 5,
  148717. 2,
  148718. 6,
  148719. 1,
  148720. 7,
  148721. 0,
  148722. 8,
  148723. };
  148724. static long _vq_lengthlist__44u5__p5_0[] = {
  148725. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148726. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148727. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148728. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148729. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148730. 14,
  148731. };
  148732. static float _vq_quantthresh__44u5__p5_0[] = {
  148733. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148734. };
  148735. static long _vq_quantmap__44u5__p5_0[] = {
  148736. 7, 5, 3, 1, 0, 2, 4, 6,
  148737. 8,
  148738. };
  148739. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148740. _vq_quantthresh__44u5__p5_0,
  148741. _vq_quantmap__44u5__p5_0,
  148742. 9,
  148743. 9
  148744. };
  148745. static static_codebook _44u5__p5_0 = {
  148746. 2, 81,
  148747. _vq_lengthlist__44u5__p5_0,
  148748. 1, -531628032, 1611661312, 4, 0,
  148749. _vq_quantlist__44u5__p5_0,
  148750. NULL,
  148751. &_vq_auxt__44u5__p5_0,
  148752. NULL,
  148753. 0
  148754. };
  148755. static long _vq_quantlist__44u5__p6_0[] = {
  148756. 4,
  148757. 3,
  148758. 5,
  148759. 2,
  148760. 6,
  148761. 1,
  148762. 7,
  148763. 0,
  148764. 8,
  148765. };
  148766. static long _vq_lengthlist__44u5__p6_0[] = {
  148767. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148768. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148769. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148770. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148771. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148772. 11,
  148773. };
  148774. static float _vq_quantthresh__44u5__p6_0[] = {
  148775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148776. };
  148777. static long _vq_quantmap__44u5__p6_0[] = {
  148778. 7, 5, 3, 1, 0, 2, 4, 6,
  148779. 8,
  148780. };
  148781. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148782. _vq_quantthresh__44u5__p6_0,
  148783. _vq_quantmap__44u5__p6_0,
  148784. 9,
  148785. 9
  148786. };
  148787. static static_codebook _44u5__p6_0 = {
  148788. 2, 81,
  148789. _vq_lengthlist__44u5__p6_0,
  148790. 1, -531628032, 1611661312, 4, 0,
  148791. _vq_quantlist__44u5__p6_0,
  148792. NULL,
  148793. &_vq_auxt__44u5__p6_0,
  148794. NULL,
  148795. 0
  148796. };
  148797. static long _vq_quantlist__44u5__p7_0[] = {
  148798. 1,
  148799. 0,
  148800. 2,
  148801. };
  148802. static long _vq_lengthlist__44u5__p7_0[] = {
  148803. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148804. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148805. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148806. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148807. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148808. 12,
  148809. };
  148810. static float _vq_quantthresh__44u5__p7_0[] = {
  148811. -5.5, 5.5,
  148812. };
  148813. static long _vq_quantmap__44u5__p7_0[] = {
  148814. 1, 0, 2,
  148815. };
  148816. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148817. _vq_quantthresh__44u5__p7_0,
  148818. _vq_quantmap__44u5__p7_0,
  148819. 3,
  148820. 3
  148821. };
  148822. static static_codebook _44u5__p7_0 = {
  148823. 4, 81,
  148824. _vq_lengthlist__44u5__p7_0,
  148825. 1, -529137664, 1618345984, 2, 0,
  148826. _vq_quantlist__44u5__p7_0,
  148827. NULL,
  148828. &_vq_auxt__44u5__p7_0,
  148829. NULL,
  148830. 0
  148831. };
  148832. static long _vq_quantlist__44u5__p7_1[] = {
  148833. 5,
  148834. 4,
  148835. 6,
  148836. 3,
  148837. 7,
  148838. 2,
  148839. 8,
  148840. 1,
  148841. 9,
  148842. 0,
  148843. 10,
  148844. };
  148845. static long _vq_lengthlist__44u5__p7_1[] = {
  148846. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148847. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148848. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148849. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148850. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148851. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148852. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148853. 9, 9, 9, 9, 9,10,10,10,10,
  148854. };
  148855. static float _vq_quantthresh__44u5__p7_1[] = {
  148856. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148857. 3.5, 4.5,
  148858. };
  148859. static long _vq_quantmap__44u5__p7_1[] = {
  148860. 9, 7, 5, 3, 1, 0, 2, 4,
  148861. 6, 8, 10,
  148862. };
  148863. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148864. _vq_quantthresh__44u5__p7_1,
  148865. _vq_quantmap__44u5__p7_1,
  148866. 11,
  148867. 11
  148868. };
  148869. static static_codebook _44u5__p7_1 = {
  148870. 2, 121,
  148871. _vq_lengthlist__44u5__p7_1,
  148872. 1, -531365888, 1611661312, 4, 0,
  148873. _vq_quantlist__44u5__p7_1,
  148874. NULL,
  148875. &_vq_auxt__44u5__p7_1,
  148876. NULL,
  148877. 0
  148878. };
  148879. static long _vq_quantlist__44u5__p8_0[] = {
  148880. 5,
  148881. 4,
  148882. 6,
  148883. 3,
  148884. 7,
  148885. 2,
  148886. 8,
  148887. 1,
  148888. 9,
  148889. 0,
  148890. 10,
  148891. };
  148892. static long _vq_lengthlist__44u5__p8_0[] = {
  148893. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148894. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148895. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148896. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148897. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148898. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148899. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148900. 12,13,13,14,14,14,14,15,15,
  148901. };
  148902. static float _vq_quantthresh__44u5__p8_0[] = {
  148903. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148904. 38.5, 49.5,
  148905. };
  148906. static long _vq_quantmap__44u5__p8_0[] = {
  148907. 9, 7, 5, 3, 1, 0, 2, 4,
  148908. 6, 8, 10,
  148909. };
  148910. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148911. _vq_quantthresh__44u5__p8_0,
  148912. _vq_quantmap__44u5__p8_0,
  148913. 11,
  148914. 11
  148915. };
  148916. static static_codebook _44u5__p8_0 = {
  148917. 2, 121,
  148918. _vq_lengthlist__44u5__p8_0,
  148919. 1, -524582912, 1618345984, 4, 0,
  148920. _vq_quantlist__44u5__p8_0,
  148921. NULL,
  148922. &_vq_auxt__44u5__p8_0,
  148923. NULL,
  148924. 0
  148925. };
  148926. static long _vq_quantlist__44u5__p8_1[] = {
  148927. 5,
  148928. 4,
  148929. 6,
  148930. 3,
  148931. 7,
  148932. 2,
  148933. 8,
  148934. 1,
  148935. 9,
  148936. 0,
  148937. 10,
  148938. };
  148939. static long _vq_lengthlist__44u5__p8_1[] = {
  148940. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148941. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148942. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148943. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148944. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148945. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148946. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148947. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148948. };
  148949. static float _vq_quantthresh__44u5__p8_1[] = {
  148950. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148951. 3.5, 4.5,
  148952. };
  148953. static long _vq_quantmap__44u5__p8_1[] = {
  148954. 9, 7, 5, 3, 1, 0, 2, 4,
  148955. 6, 8, 10,
  148956. };
  148957. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148958. _vq_quantthresh__44u5__p8_1,
  148959. _vq_quantmap__44u5__p8_1,
  148960. 11,
  148961. 11
  148962. };
  148963. static static_codebook _44u5__p8_1 = {
  148964. 2, 121,
  148965. _vq_lengthlist__44u5__p8_1,
  148966. 1, -531365888, 1611661312, 4, 0,
  148967. _vq_quantlist__44u5__p8_1,
  148968. NULL,
  148969. &_vq_auxt__44u5__p8_1,
  148970. NULL,
  148971. 0
  148972. };
  148973. static long _vq_quantlist__44u5__p9_0[] = {
  148974. 6,
  148975. 5,
  148976. 7,
  148977. 4,
  148978. 8,
  148979. 3,
  148980. 9,
  148981. 2,
  148982. 10,
  148983. 1,
  148984. 11,
  148985. 0,
  148986. 12,
  148987. };
  148988. static long _vq_lengthlist__44u5__p9_0[] = {
  148989. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148990. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148991. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148992. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148993. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148994. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148995. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148996. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148997. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148998. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148999. 12,12,12,12,12,12,12,12,12,
  149000. };
  149001. static float _vq_quantthresh__44u5__p9_0[] = {
  149002. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149003. 637.5, 892.5, 1147.5, 1402.5,
  149004. };
  149005. static long _vq_quantmap__44u5__p9_0[] = {
  149006. 11, 9, 7, 5, 3, 1, 0, 2,
  149007. 4, 6, 8, 10, 12,
  149008. };
  149009. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149010. _vq_quantthresh__44u5__p9_0,
  149011. _vq_quantmap__44u5__p9_0,
  149012. 13,
  149013. 13
  149014. };
  149015. static static_codebook _44u5__p9_0 = {
  149016. 2, 169,
  149017. _vq_lengthlist__44u5__p9_0,
  149018. 1, -514332672, 1627381760, 4, 0,
  149019. _vq_quantlist__44u5__p9_0,
  149020. NULL,
  149021. &_vq_auxt__44u5__p9_0,
  149022. NULL,
  149023. 0
  149024. };
  149025. static long _vq_quantlist__44u5__p9_1[] = {
  149026. 7,
  149027. 6,
  149028. 8,
  149029. 5,
  149030. 9,
  149031. 4,
  149032. 10,
  149033. 3,
  149034. 11,
  149035. 2,
  149036. 12,
  149037. 1,
  149038. 13,
  149039. 0,
  149040. 14,
  149041. };
  149042. static long _vq_lengthlist__44u5__p9_1[] = {
  149043. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149044. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149045. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149046. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149047. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149048. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149049. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149050. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149051. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149052. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149053. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149054. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149055. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149056. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149057. 14,
  149058. };
  149059. static float _vq_quantthresh__44u5__p9_1[] = {
  149060. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149061. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149062. };
  149063. static long _vq_quantmap__44u5__p9_1[] = {
  149064. 13, 11, 9, 7, 5, 3, 1, 0,
  149065. 2, 4, 6, 8, 10, 12, 14,
  149066. };
  149067. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149068. _vq_quantthresh__44u5__p9_1,
  149069. _vq_quantmap__44u5__p9_1,
  149070. 15,
  149071. 15
  149072. };
  149073. static static_codebook _44u5__p9_1 = {
  149074. 2, 225,
  149075. _vq_lengthlist__44u5__p9_1,
  149076. 1, -522338304, 1620115456, 4, 0,
  149077. _vq_quantlist__44u5__p9_1,
  149078. NULL,
  149079. &_vq_auxt__44u5__p9_1,
  149080. NULL,
  149081. 0
  149082. };
  149083. static long _vq_quantlist__44u5__p9_2[] = {
  149084. 8,
  149085. 7,
  149086. 9,
  149087. 6,
  149088. 10,
  149089. 5,
  149090. 11,
  149091. 4,
  149092. 12,
  149093. 3,
  149094. 13,
  149095. 2,
  149096. 14,
  149097. 1,
  149098. 15,
  149099. 0,
  149100. 16,
  149101. };
  149102. static long _vq_lengthlist__44u5__p9_2[] = {
  149103. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149104. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149105. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149106. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149107. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149108. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149109. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149110. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149111. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149112. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149113. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149114. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149115. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149116. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149117. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149118. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149119. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149120. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149121. 10,
  149122. };
  149123. static float _vq_quantthresh__44u5__p9_2[] = {
  149124. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149125. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149126. };
  149127. static long _vq_quantmap__44u5__p9_2[] = {
  149128. 15, 13, 11, 9, 7, 5, 3, 1,
  149129. 0, 2, 4, 6, 8, 10, 12, 14,
  149130. 16,
  149131. };
  149132. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149133. _vq_quantthresh__44u5__p9_2,
  149134. _vq_quantmap__44u5__p9_2,
  149135. 17,
  149136. 17
  149137. };
  149138. static static_codebook _44u5__p9_2 = {
  149139. 2, 289,
  149140. _vq_lengthlist__44u5__p9_2,
  149141. 1, -529530880, 1611661312, 5, 0,
  149142. _vq_quantlist__44u5__p9_2,
  149143. NULL,
  149144. &_vq_auxt__44u5__p9_2,
  149145. NULL,
  149146. 0
  149147. };
  149148. static long _huff_lengthlist__44u5__short[] = {
  149149. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149150. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149151. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149152. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149153. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149154. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149155. 6, 8,15,17,
  149156. };
  149157. static static_codebook _huff_book__44u5__short = {
  149158. 2, 100,
  149159. _huff_lengthlist__44u5__short,
  149160. 0, 0, 0, 0, 0,
  149161. NULL,
  149162. NULL,
  149163. NULL,
  149164. NULL,
  149165. 0
  149166. };
  149167. static long _huff_lengthlist__44u6__long[] = {
  149168. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149169. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149170. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149171. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149172. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149173. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149174. 13, 8, 7, 7,
  149175. };
  149176. static static_codebook _huff_book__44u6__long = {
  149177. 2, 100,
  149178. _huff_lengthlist__44u6__long,
  149179. 0, 0, 0, 0, 0,
  149180. NULL,
  149181. NULL,
  149182. NULL,
  149183. NULL,
  149184. 0
  149185. };
  149186. static long _vq_quantlist__44u6__p1_0[] = {
  149187. 1,
  149188. 0,
  149189. 2,
  149190. };
  149191. static long _vq_lengthlist__44u6__p1_0[] = {
  149192. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149193. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149194. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149195. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149196. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149197. 12,
  149198. };
  149199. static float _vq_quantthresh__44u6__p1_0[] = {
  149200. -0.5, 0.5,
  149201. };
  149202. static long _vq_quantmap__44u6__p1_0[] = {
  149203. 1, 0, 2,
  149204. };
  149205. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149206. _vq_quantthresh__44u6__p1_0,
  149207. _vq_quantmap__44u6__p1_0,
  149208. 3,
  149209. 3
  149210. };
  149211. static static_codebook _44u6__p1_0 = {
  149212. 4, 81,
  149213. _vq_lengthlist__44u6__p1_0,
  149214. 1, -535822336, 1611661312, 2, 0,
  149215. _vq_quantlist__44u6__p1_0,
  149216. NULL,
  149217. &_vq_auxt__44u6__p1_0,
  149218. NULL,
  149219. 0
  149220. };
  149221. static long _vq_quantlist__44u6__p2_0[] = {
  149222. 1,
  149223. 0,
  149224. 2,
  149225. };
  149226. static long _vq_lengthlist__44u6__p2_0[] = {
  149227. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149228. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149229. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149230. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149231. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149232. 9,
  149233. };
  149234. static float _vq_quantthresh__44u6__p2_0[] = {
  149235. -0.5, 0.5,
  149236. };
  149237. static long _vq_quantmap__44u6__p2_0[] = {
  149238. 1, 0, 2,
  149239. };
  149240. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149241. _vq_quantthresh__44u6__p2_0,
  149242. _vq_quantmap__44u6__p2_0,
  149243. 3,
  149244. 3
  149245. };
  149246. static static_codebook _44u6__p2_0 = {
  149247. 4, 81,
  149248. _vq_lengthlist__44u6__p2_0,
  149249. 1, -535822336, 1611661312, 2, 0,
  149250. _vq_quantlist__44u6__p2_0,
  149251. NULL,
  149252. &_vq_auxt__44u6__p2_0,
  149253. NULL,
  149254. 0
  149255. };
  149256. static long _vq_quantlist__44u6__p3_0[] = {
  149257. 2,
  149258. 1,
  149259. 3,
  149260. 0,
  149261. 4,
  149262. };
  149263. static long _vq_lengthlist__44u6__p3_0[] = {
  149264. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149265. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149266. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149267. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149268. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149269. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149270. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149271. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149272. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149273. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149274. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149275. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149276. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149277. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149278. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149279. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149280. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149281. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149282. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149283. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149284. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149285. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149286. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149287. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149288. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149289. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149290. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149291. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149292. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149293. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149294. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149295. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149296. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149297. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149298. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149299. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149300. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149301. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149302. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149303. 19,
  149304. };
  149305. static float _vq_quantthresh__44u6__p3_0[] = {
  149306. -1.5, -0.5, 0.5, 1.5,
  149307. };
  149308. static long _vq_quantmap__44u6__p3_0[] = {
  149309. 3, 1, 0, 2, 4,
  149310. };
  149311. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149312. _vq_quantthresh__44u6__p3_0,
  149313. _vq_quantmap__44u6__p3_0,
  149314. 5,
  149315. 5
  149316. };
  149317. static static_codebook _44u6__p3_0 = {
  149318. 4, 625,
  149319. _vq_lengthlist__44u6__p3_0,
  149320. 1, -533725184, 1611661312, 3, 0,
  149321. _vq_quantlist__44u6__p3_0,
  149322. NULL,
  149323. &_vq_auxt__44u6__p3_0,
  149324. NULL,
  149325. 0
  149326. };
  149327. static long _vq_quantlist__44u6__p4_0[] = {
  149328. 2,
  149329. 1,
  149330. 3,
  149331. 0,
  149332. 4,
  149333. };
  149334. static long _vq_lengthlist__44u6__p4_0[] = {
  149335. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149336. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149337. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149338. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149339. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149340. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149341. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149342. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149343. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149344. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149345. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149346. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149347. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149348. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149349. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149350. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149351. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149352. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149353. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149354. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149355. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149356. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149357. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149358. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149359. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149360. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149361. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149362. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149363. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149364. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149365. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149366. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149367. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149368. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149369. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149370. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149371. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149372. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149373. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149374. 13,
  149375. };
  149376. static float _vq_quantthresh__44u6__p4_0[] = {
  149377. -1.5, -0.5, 0.5, 1.5,
  149378. };
  149379. static long _vq_quantmap__44u6__p4_0[] = {
  149380. 3, 1, 0, 2, 4,
  149381. };
  149382. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149383. _vq_quantthresh__44u6__p4_0,
  149384. _vq_quantmap__44u6__p4_0,
  149385. 5,
  149386. 5
  149387. };
  149388. static static_codebook _44u6__p4_0 = {
  149389. 4, 625,
  149390. _vq_lengthlist__44u6__p4_0,
  149391. 1, -533725184, 1611661312, 3, 0,
  149392. _vq_quantlist__44u6__p4_0,
  149393. NULL,
  149394. &_vq_auxt__44u6__p4_0,
  149395. NULL,
  149396. 0
  149397. };
  149398. static long _vq_quantlist__44u6__p5_0[] = {
  149399. 4,
  149400. 3,
  149401. 5,
  149402. 2,
  149403. 6,
  149404. 1,
  149405. 7,
  149406. 0,
  149407. 8,
  149408. };
  149409. static long _vq_lengthlist__44u6__p5_0[] = {
  149410. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149411. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149412. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149413. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149414. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149415. 14,
  149416. };
  149417. static float _vq_quantthresh__44u6__p5_0[] = {
  149418. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149419. };
  149420. static long _vq_quantmap__44u6__p5_0[] = {
  149421. 7, 5, 3, 1, 0, 2, 4, 6,
  149422. 8,
  149423. };
  149424. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149425. _vq_quantthresh__44u6__p5_0,
  149426. _vq_quantmap__44u6__p5_0,
  149427. 9,
  149428. 9
  149429. };
  149430. static static_codebook _44u6__p5_0 = {
  149431. 2, 81,
  149432. _vq_lengthlist__44u6__p5_0,
  149433. 1, -531628032, 1611661312, 4, 0,
  149434. _vq_quantlist__44u6__p5_0,
  149435. NULL,
  149436. &_vq_auxt__44u6__p5_0,
  149437. NULL,
  149438. 0
  149439. };
  149440. static long _vq_quantlist__44u6__p6_0[] = {
  149441. 4,
  149442. 3,
  149443. 5,
  149444. 2,
  149445. 6,
  149446. 1,
  149447. 7,
  149448. 0,
  149449. 8,
  149450. };
  149451. static long _vq_lengthlist__44u6__p6_0[] = {
  149452. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149453. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149454. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149455. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149456. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149457. 12,
  149458. };
  149459. static float _vq_quantthresh__44u6__p6_0[] = {
  149460. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149461. };
  149462. static long _vq_quantmap__44u6__p6_0[] = {
  149463. 7, 5, 3, 1, 0, 2, 4, 6,
  149464. 8,
  149465. };
  149466. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149467. _vq_quantthresh__44u6__p6_0,
  149468. _vq_quantmap__44u6__p6_0,
  149469. 9,
  149470. 9
  149471. };
  149472. static static_codebook _44u6__p6_0 = {
  149473. 2, 81,
  149474. _vq_lengthlist__44u6__p6_0,
  149475. 1, -531628032, 1611661312, 4, 0,
  149476. _vq_quantlist__44u6__p6_0,
  149477. NULL,
  149478. &_vq_auxt__44u6__p6_0,
  149479. NULL,
  149480. 0
  149481. };
  149482. static long _vq_quantlist__44u6__p7_0[] = {
  149483. 1,
  149484. 0,
  149485. 2,
  149486. };
  149487. static long _vq_lengthlist__44u6__p7_0[] = {
  149488. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149489. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149490. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149491. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149492. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149493. 10,
  149494. };
  149495. static float _vq_quantthresh__44u6__p7_0[] = {
  149496. -5.5, 5.5,
  149497. };
  149498. static long _vq_quantmap__44u6__p7_0[] = {
  149499. 1, 0, 2,
  149500. };
  149501. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149502. _vq_quantthresh__44u6__p7_0,
  149503. _vq_quantmap__44u6__p7_0,
  149504. 3,
  149505. 3
  149506. };
  149507. static static_codebook _44u6__p7_0 = {
  149508. 4, 81,
  149509. _vq_lengthlist__44u6__p7_0,
  149510. 1, -529137664, 1618345984, 2, 0,
  149511. _vq_quantlist__44u6__p7_0,
  149512. NULL,
  149513. &_vq_auxt__44u6__p7_0,
  149514. NULL,
  149515. 0
  149516. };
  149517. static long _vq_quantlist__44u6__p7_1[] = {
  149518. 5,
  149519. 4,
  149520. 6,
  149521. 3,
  149522. 7,
  149523. 2,
  149524. 8,
  149525. 1,
  149526. 9,
  149527. 0,
  149528. 10,
  149529. };
  149530. static long _vq_lengthlist__44u6__p7_1[] = {
  149531. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149532. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149533. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149534. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149535. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149536. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149537. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149538. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149539. };
  149540. static float _vq_quantthresh__44u6__p7_1[] = {
  149541. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149542. 3.5, 4.5,
  149543. };
  149544. static long _vq_quantmap__44u6__p7_1[] = {
  149545. 9, 7, 5, 3, 1, 0, 2, 4,
  149546. 6, 8, 10,
  149547. };
  149548. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149549. _vq_quantthresh__44u6__p7_1,
  149550. _vq_quantmap__44u6__p7_1,
  149551. 11,
  149552. 11
  149553. };
  149554. static static_codebook _44u6__p7_1 = {
  149555. 2, 121,
  149556. _vq_lengthlist__44u6__p7_1,
  149557. 1, -531365888, 1611661312, 4, 0,
  149558. _vq_quantlist__44u6__p7_1,
  149559. NULL,
  149560. &_vq_auxt__44u6__p7_1,
  149561. NULL,
  149562. 0
  149563. };
  149564. static long _vq_quantlist__44u6__p8_0[] = {
  149565. 5,
  149566. 4,
  149567. 6,
  149568. 3,
  149569. 7,
  149570. 2,
  149571. 8,
  149572. 1,
  149573. 9,
  149574. 0,
  149575. 10,
  149576. };
  149577. static long _vq_lengthlist__44u6__p8_0[] = {
  149578. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149579. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149580. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149581. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149582. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149583. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149584. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149585. 12,13,13,14,14,14,15,15,15,
  149586. };
  149587. static float _vq_quantthresh__44u6__p8_0[] = {
  149588. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149589. 38.5, 49.5,
  149590. };
  149591. static long _vq_quantmap__44u6__p8_0[] = {
  149592. 9, 7, 5, 3, 1, 0, 2, 4,
  149593. 6, 8, 10,
  149594. };
  149595. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149596. _vq_quantthresh__44u6__p8_0,
  149597. _vq_quantmap__44u6__p8_0,
  149598. 11,
  149599. 11
  149600. };
  149601. static static_codebook _44u6__p8_0 = {
  149602. 2, 121,
  149603. _vq_lengthlist__44u6__p8_0,
  149604. 1, -524582912, 1618345984, 4, 0,
  149605. _vq_quantlist__44u6__p8_0,
  149606. NULL,
  149607. &_vq_auxt__44u6__p8_0,
  149608. NULL,
  149609. 0
  149610. };
  149611. static long _vq_quantlist__44u6__p8_1[] = {
  149612. 5,
  149613. 4,
  149614. 6,
  149615. 3,
  149616. 7,
  149617. 2,
  149618. 8,
  149619. 1,
  149620. 9,
  149621. 0,
  149622. 10,
  149623. };
  149624. static long _vq_lengthlist__44u6__p8_1[] = {
  149625. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149626. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149627. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149628. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149629. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149630. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149631. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149632. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149633. };
  149634. static float _vq_quantthresh__44u6__p8_1[] = {
  149635. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149636. 3.5, 4.5,
  149637. };
  149638. static long _vq_quantmap__44u6__p8_1[] = {
  149639. 9, 7, 5, 3, 1, 0, 2, 4,
  149640. 6, 8, 10,
  149641. };
  149642. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149643. _vq_quantthresh__44u6__p8_1,
  149644. _vq_quantmap__44u6__p8_1,
  149645. 11,
  149646. 11
  149647. };
  149648. static static_codebook _44u6__p8_1 = {
  149649. 2, 121,
  149650. _vq_lengthlist__44u6__p8_1,
  149651. 1, -531365888, 1611661312, 4, 0,
  149652. _vq_quantlist__44u6__p8_1,
  149653. NULL,
  149654. &_vq_auxt__44u6__p8_1,
  149655. NULL,
  149656. 0
  149657. };
  149658. static long _vq_quantlist__44u6__p9_0[] = {
  149659. 7,
  149660. 6,
  149661. 8,
  149662. 5,
  149663. 9,
  149664. 4,
  149665. 10,
  149666. 3,
  149667. 11,
  149668. 2,
  149669. 12,
  149670. 1,
  149671. 13,
  149672. 0,
  149673. 14,
  149674. };
  149675. static long _vq_lengthlist__44u6__p9_0[] = {
  149676. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149677. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149678. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149679. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149680. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149681. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149682. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149683. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149684. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149685. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149686. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149687. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149688. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149689. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149690. 14,
  149691. };
  149692. static float _vq_quantthresh__44u6__p9_0[] = {
  149693. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149694. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149695. };
  149696. static long _vq_quantmap__44u6__p9_0[] = {
  149697. 13, 11, 9, 7, 5, 3, 1, 0,
  149698. 2, 4, 6, 8, 10, 12, 14,
  149699. };
  149700. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149701. _vq_quantthresh__44u6__p9_0,
  149702. _vq_quantmap__44u6__p9_0,
  149703. 15,
  149704. 15
  149705. };
  149706. static static_codebook _44u6__p9_0 = {
  149707. 2, 225,
  149708. _vq_lengthlist__44u6__p9_0,
  149709. 1, -514071552, 1627381760, 4, 0,
  149710. _vq_quantlist__44u6__p9_0,
  149711. NULL,
  149712. &_vq_auxt__44u6__p9_0,
  149713. NULL,
  149714. 0
  149715. };
  149716. static long _vq_quantlist__44u6__p9_1[] = {
  149717. 7,
  149718. 6,
  149719. 8,
  149720. 5,
  149721. 9,
  149722. 4,
  149723. 10,
  149724. 3,
  149725. 11,
  149726. 2,
  149727. 12,
  149728. 1,
  149729. 13,
  149730. 0,
  149731. 14,
  149732. };
  149733. static long _vq_lengthlist__44u6__p9_1[] = {
  149734. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149735. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149736. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149737. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149738. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149739. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149740. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149741. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149742. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149743. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149744. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149745. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149746. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149747. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149748. 13,
  149749. };
  149750. static float _vq_quantthresh__44u6__p9_1[] = {
  149751. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149752. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149753. };
  149754. static long _vq_quantmap__44u6__p9_1[] = {
  149755. 13, 11, 9, 7, 5, 3, 1, 0,
  149756. 2, 4, 6, 8, 10, 12, 14,
  149757. };
  149758. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149759. _vq_quantthresh__44u6__p9_1,
  149760. _vq_quantmap__44u6__p9_1,
  149761. 15,
  149762. 15
  149763. };
  149764. static static_codebook _44u6__p9_1 = {
  149765. 2, 225,
  149766. _vq_lengthlist__44u6__p9_1,
  149767. 1, -522338304, 1620115456, 4, 0,
  149768. _vq_quantlist__44u6__p9_1,
  149769. NULL,
  149770. &_vq_auxt__44u6__p9_1,
  149771. NULL,
  149772. 0
  149773. };
  149774. static long _vq_quantlist__44u6__p9_2[] = {
  149775. 8,
  149776. 7,
  149777. 9,
  149778. 6,
  149779. 10,
  149780. 5,
  149781. 11,
  149782. 4,
  149783. 12,
  149784. 3,
  149785. 13,
  149786. 2,
  149787. 14,
  149788. 1,
  149789. 15,
  149790. 0,
  149791. 16,
  149792. };
  149793. static long _vq_lengthlist__44u6__p9_2[] = {
  149794. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149795. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149796. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149797. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149798. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149799. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149800. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149801. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149802. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149803. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149804. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149805. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149806. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149807. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149808. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149809. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149810. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149811. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149812. 10,
  149813. };
  149814. static float _vq_quantthresh__44u6__p9_2[] = {
  149815. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149816. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149817. };
  149818. static long _vq_quantmap__44u6__p9_2[] = {
  149819. 15, 13, 11, 9, 7, 5, 3, 1,
  149820. 0, 2, 4, 6, 8, 10, 12, 14,
  149821. 16,
  149822. };
  149823. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149824. _vq_quantthresh__44u6__p9_2,
  149825. _vq_quantmap__44u6__p9_2,
  149826. 17,
  149827. 17
  149828. };
  149829. static static_codebook _44u6__p9_2 = {
  149830. 2, 289,
  149831. _vq_lengthlist__44u6__p9_2,
  149832. 1, -529530880, 1611661312, 5, 0,
  149833. _vq_quantlist__44u6__p9_2,
  149834. NULL,
  149835. &_vq_auxt__44u6__p9_2,
  149836. NULL,
  149837. 0
  149838. };
  149839. static long _huff_lengthlist__44u6__short[] = {
  149840. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149841. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149842. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149843. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149844. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149845. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149846. 7, 6, 9,16,
  149847. };
  149848. static static_codebook _huff_book__44u6__short = {
  149849. 2, 100,
  149850. _huff_lengthlist__44u6__short,
  149851. 0, 0, 0, 0, 0,
  149852. NULL,
  149853. NULL,
  149854. NULL,
  149855. NULL,
  149856. 0
  149857. };
  149858. static long _huff_lengthlist__44u7__long[] = {
  149859. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149860. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149861. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149862. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149863. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149864. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149865. 12, 8, 6, 7,
  149866. };
  149867. static static_codebook _huff_book__44u7__long = {
  149868. 2, 100,
  149869. _huff_lengthlist__44u7__long,
  149870. 0, 0, 0, 0, 0,
  149871. NULL,
  149872. NULL,
  149873. NULL,
  149874. NULL,
  149875. 0
  149876. };
  149877. static long _vq_quantlist__44u7__p1_0[] = {
  149878. 1,
  149879. 0,
  149880. 2,
  149881. };
  149882. static long _vq_lengthlist__44u7__p1_0[] = {
  149883. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149884. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149885. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149886. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149887. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149888. 12,
  149889. };
  149890. static float _vq_quantthresh__44u7__p1_0[] = {
  149891. -0.5, 0.5,
  149892. };
  149893. static long _vq_quantmap__44u7__p1_0[] = {
  149894. 1, 0, 2,
  149895. };
  149896. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149897. _vq_quantthresh__44u7__p1_0,
  149898. _vq_quantmap__44u7__p1_0,
  149899. 3,
  149900. 3
  149901. };
  149902. static static_codebook _44u7__p1_0 = {
  149903. 4, 81,
  149904. _vq_lengthlist__44u7__p1_0,
  149905. 1, -535822336, 1611661312, 2, 0,
  149906. _vq_quantlist__44u7__p1_0,
  149907. NULL,
  149908. &_vq_auxt__44u7__p1_0,
  149909. NULL,
  149910. 0
  149911. };
  149912. static long _vq_quantlist__44u7__p2_0[] = {
  149913. 1,
  149914. 0,
  149915. 2,
  149916. };
  149917. static long _vq_lengthlist__44u7__p2_0[] = {
  149918. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149919. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149920. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149921. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149922. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149923. 9,
  149924. };
  149925. static float _vq_quantthresh__44u7__p2_0[] = {
  149926. -0.5, 0.5,
  149927. };
  149928. static long _vq_quantmap__44u7__p2_0[] = {
  149929. 1, 0, 2,
  149930. };
  149931. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149932. _vq_quantthresh__44u7__p2_0,
  149933. _vq_quantmap__44u7__p2_0,
  149934. 3,
  149935. 3
  149936. };
  149937. static static_codebook _44u7__p2_0 = {
  149938. 4, 81,
  149939. _vq_lengthlist__44u7__p2_0,
  149940. 1, -535822336, 1611661312, 2, 0,
  149941. _vq_quantlist__44u7__p2_0,
  149942. NULL,
  149943. &_vq_auxt__44u7__p2_0,
  149944. NULL,
  149945. 0
  149946. };
  149947. static long _vq_quantlist__44u7__p3_0[] = {
  149948. 2,
  149949. 1,
  149950. 3,
  149951. 0,
  149952. 4,
  149953. };
  149954. static long _vq_lengthlist__44u7__p3_0[] = {
  149955. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149956. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149957. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149958. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149959. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149960. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149961. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149962. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149963. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149964. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149965. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149966. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149967. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149968. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149969. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149970. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149971. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149972. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149973. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149974. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149975. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149976. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149977. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149978. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149979. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149980. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149981. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149982. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149983. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149984. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149985. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149986. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149987. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149988. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149989. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149990. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149991. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149992. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149993. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149994. 0,
  149995. };
  149996. static float _vq_quantthresh__44u7__p3_0[] = {
  149997. -1.5, -0.5, 0.5, 1.5,
  149998. };
  149999. static long _vq_quantmap__44u7__p3_0[] = {
  150000. 3, 1, 0, 2, 4,
  150001. };
  150002. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150003. _vq_quantthresh__44u7__p3_0,
  150004. _vq_quantmap__44u7__p3_0,
  150005. 5,
  150006. 5
  150007. };
  150008. static static_codebook _44u7__p3_0 = {
  150009. 4, 625,
  150010. _vq_lengthlist__44u7__p3_0,
  150011. 1, -533725184, 1611661312, 3, 0,
  150012. _vq_quantlist__44u7__p3_0,
  150013. NULL,
  150014. &_vq_auxt__44u7__p3_0,
  150015. NULL,
  150016. 0
  150017. };
  150018. static long _vq_quantlist__44u7__p4_0[] = {
  150019. 2,
  150020. 1,
  150021. 3,
  150022. 0,
  150023. 4,
  150024. };
  150025. static long _vq_lengthlist__44u7__p4_0[] = {
  150026. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150027. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150028. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150029. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150030. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150031. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150032. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150033. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150034. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150035. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150036. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150037. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150038. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150039. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150040. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150041. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150042. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150043. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150044. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150045. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150046. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150047. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150048. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150049. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150050. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150051. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150052. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150053. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150054. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150055. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150056. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150057. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150058. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150059. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150060. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150061. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150062. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150063. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150064. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150065. 14,
  150066. };
  150067. static float _vq_quantthresh__44u7__p4_0[] = {
  150068. -1.5, -0.5, 0.5, 1.5,
  150069. };
  150070. static long _vq_quantmap__44u7__p4_0[] = {
  150071. 3, 1, 0, 2, 4,
  150072. };
  150073. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150074. _vq_quantthresh__44u7__p4_0,
  150075. _vq_quantmap__44u7__p4_0,
  150076. 5,
  150077. 5
  150078. };
  150079. static static_codebook _44u7__p4_0 = {
  150080. 4, 625,
  150081. _vq_lengthlist__44u7__p4_0,
  150082. 1, -533725184, 1611661312, 3, 0,
  150083. _vq_quantlist__44u7__p4_0,
  150084. NULL,
  150085. &_vq_auxt__44u7__p4_0,
  150086. NULL,
  150087. 0
  150088. };
  150089. static long _vq_quantlist__44u7__p5_0[] = {
  150090. 4,
  150091. 3,
  150092. 5,
  150093. 2,
  150094. 6,
  150095. 1,
  150096. 7,
  150097. 0,
  150098. 8,
  150099. };
  150100. static long _vq_lengthlist__44u7__p5_0[] = {
  150101. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150102. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150103. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150104. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150105. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150106. 14,
  150107. };
  150108. static float _vq_quantthresh__44u7__p5_0[] = {
  150109. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150110. };
  150111. static long _vq_quantmap__44u7__p5_0[] = {
  150112. 7, 5, 3, 1, 0, 2, 4, 6,
  150113. 8,
  150114. };
  150115. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150116. _vq_quantthresh__44u7__p5_0,
  150117. _vq_quantmap__44u7__p5_0,
  150118. 9,
  150119. 9
  150120. };
  150121. static static_codebook _44u7__p5_0 = {
  150122. 2, 81,
  150123. _vq_lengthlist__44u7__p5_0,
  150124. 1, -531628032, 1611661312, 4, 0,
  150125. _vq_quantlist__44u7__p5_0,
  150126. NULL,
  150127. &_vq_auxt__44u7__p5_0,
  150128. NULL,
  150129. 0
  150130. };
  150131. static long _vq_quantlist__44u7__p6_0[] = {
  150132. 4,
  150133. 3,
  150134. 5,
  150135. 2,
  150136. 6,
  150137. 1,
  150138. 7,
  150139. 0,
  150140. 8,
  150141. };
  150142. static long _vq_lengthlist__44u7__p6_0[] = {
  150143. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150144. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150145. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150146. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150147. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150148. 12,
  150149. };
  150150. static float _vq_quantthresh__44u7__p6_0[] = {
  150151. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150152. };
  150153. static long _vq_quantmap__44u7__p6_0[] = {
  150154. 7, 5, 3, 1, 0, 2, 4, 6,
  150155. 8,
  150156. };
  150157. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150158. _vq_quantthresh__44u7__p6_0,
  150159. _vq_quantmap__44u7__p6_0,
  150160. 9,
  150161. 9
  150162. };
  150163. static static_codebook _44u7__p6_0 = {
  150164. 2, 81,
  150165. _vq_lengthlist__44u7__p6_0,
  150166. 1, -531628032, 1611661312, 4, 0,
  150167. _vq_quantlist__44u7__p6_0,
  150168. NULL,
  150169. &_vq_auxt__44u7__p6_0,
  150170. NULL,
  150171. 0
  150172. };
  150173. static long _vq_quantlist__44u7__p7_0[] = {
  150174. 1,
  150175. 0,
  150176. 2,
  150177. };
  150178. static long _vq_lengthlist__44u7__p7_0[] = {
  150179. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150180. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150181. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150182. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150183. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150184. 10,
  150185. };
  150186. static float _vq_quantthresh__44u7__p7_0[] = {
  150187. -5.5, 5.5,
  150188. };
  150189. static long _vq_quantmap__44u7__p7_0[] = {
  150190. 1, 0, 2,
  150191. };
  150192. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150193. _vq_quantthresh__44u7__p7_0,
  150194. _vq_quantmap__44u7__p7_0,
  150195. 3,
  150196. 3
  150197. };
  150198. static static_codebook _44u7__p7_0 = {
  150199. 4, 81,
  150200. _vq_lengthlist__44u7__p7_0,
  150201. 1, -529137664, 1618345984, 2, 0,
  150202. _vq_quantlist__44u7__p7_0,
  150203. NULL,
  150204. &_vq_auxt__44u7__p7_0,
  150205. NULL,
  150206. 0
  150207. };
  150208. static long _vq_quantlist__44u7__p7_1[] = {
  150209. 5,
  150210. 4,
  150211. 6,
  150212. 3,
  150213. 7,
  150214. 2,
  150215. 8,
  150216. 1,
  150217. 9,
  150218. 0,
  150219. 10,
  150220. };
  150221. static long _vq_lengthlist__44u7__p7_1[] = {
  150222. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150223. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150224. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150225. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150226. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150227. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150228. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150229. 8, 9, 9, 9, 9, 9,10,10,10,
  150230. };
  150231. static float _vq_quantthresh__44u7__p7_1[] = {
  150232. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150233. 3.5, 4.5,
  150234. };
  150235. static long _vq_quantmap__44u7__p7_1[] = {
  150236. 9, 7, 5, 3, 1, 0, 2, 4,
  150237. 6, 8, 10,
  150238. };
  150239. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150240. _vq_quantthresh__44u7__p7_1,
  150241. _vq_quantmap__44u7__p7_1,
  150242. 11,
  150243. 11
  150244. };
  150245. static static_codebook _44u7__p7_1 = {
  150246. 2, 121,
  150247. _vq_lengthlist__44u7__p7_1,
  150248. 1, -531365888, 1611661312, 4, 0,
  150249. _vq_quantlist__44u7__p7_1,
  150250. NULL,
  150251. &_vq_auxt__44u7__p7_1,
  150252. NULL,
  150253. 0
  150254. };
  150255. static long _vq_quantlist__44u7__p8_0[] = {
  150256. 5,
  150257. 4,
  150258. 6,
  150259. 3,
  150260. 7,
  150261. 2,
  150262. 8,
  150263. 1,
  150264. 9,
  150265. 0,
  150266. 10,
  150267. };
  150268. static long _vq_lengthlist__44u7__p8_0[] = {
  150269. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150270. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150271. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150272. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150273. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150274. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150275. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150276. 12,13,13,14,14,15,15,15,16,
  150277. };
  150278. static float _vq_quantthresh__44u7__p8_0[] = {
  150279. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150280. 38.5, 49.5,
  150281. };
  150282. static long _vq_quantmap__44u7__p8_0[] = {
  150283. 9, 7, 5, 3, 1, 0, 2, 4,
  150284. 6, 8, 10,
  150285. };
  150286. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150287. _vq_quantthresh__44u7__p8_0,
  150288. _vq_quantmap__44u7__p8_0,
  150289. 11,
  150290. 11
  150291. };
  150292. static static_codebook _44u7__p8_0 = {
  150293. 2, 121,
  150294. _vq_lengthlist__44u7__p8_0,
  150295. 1, -524582912, 1618345984, 4, 0,
  150296. _vq_quantlist__44u7__p8_0,
  150297. NULL,
  150298. &_vq_auxt__44u7__p8_0,
  150299. NULL,
  150300. 0
  150301. };
  150302. static long _vq_quantlist__44u7__p8_1[] = {
  150303. 5,
  150304. 4,
  150305. 6,
  150306. 3,
  150307. 7,
  150308. 2,
  150309. 8,
  150310. 1,
  150311. 9,
  150312. 0,
  150313. 10,
  150314. };
  150315. static long _vq_lengthlist__44u7__p8_1[] = {
  150316. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150317. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150318. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150319. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150320. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150321. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150322. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150323. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150324. };
  150325. static float _vq_quantthresh__44u7__p8_1[] = {
  150326. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150327. 3.5, 4.5,
  150328. };
  150329. static long _vq_quantmap__44u7__p8_1[] = {
  150330. 9, 7, 5, 3, 1, 0, 2, 4,
  150331. 6, 8, 10,
  150332. };
  150333. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150334. _vq_quantthresh__44u7__p8_1,
  150335. _vq_quantmap__44u7__p8_1,
  150336. 11,
  150337. 11
  150338. };
  150339. static static_codebook _44u7__p8_1 = {
  150340. 2, 121,
  150341. _vq_lengthlist__44u7__p8_1,
  150342. 1, -531365888, 1611661312, 4, 0,
  150343. _vq_quantlist__44u7__p8_1,
  150344. NULL,
  150345. &_vq_auxt__44u7__p8_1,
  150346. NULL,
  150347. 0
  150348. };
  150349. static long _vq_quantlist__44u7__p9_0[] = {
  150350. 5,
  150351. 4,
  150352. 6,
  150353. 3,
  150354. 7,
  150355. 2,
  150356. 8,
  150357. 1,
  150358. 9,
  150359. 0,
  150360. 10,
  150361. };
  150362. static long _vq_lengthlist__44u7__p9_0[] = {
  150363. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150364. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150365. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150366. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150367. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150368. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150369. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150370. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150371. };
  150372. static float _vq_quantthresh__44u7__p9_0[] = {
  150373. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150374. 2229.5, 2866.5,
  150375. };
  150376. static long _vq_quantmap__44u7__p9_0[] = {
  150377. 9, 7, 5, 3, 1, 0, 2, 4,
  150378. 6, 8, 10,
  150379. };
  150380. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150381. _vq_quantthresh__44u7__p9_0,
  150382. _vq_quantmap__44u7__p9_0,
  150383. 11,
  150384. 11
  150385. };
  150386. static static_codebook _44u7__p9_0 = {
  150387. 2, 121,
  150388. _vq_lengthlist__44u7__p9_0,
  150389. 1, -512171520, 1630791680, 4, 0,
  150390. _vq_quantlist__44u7__p9_0,
  150391. NULL,
  150392. &_vq_auxt__44u7__p9_0,
  150393. NULL,
  150394. 0
  150395. };
  150396. static long _vq_quantlist__44u7__p9_1[] = {
  150397. 6,
  150398. 5,
  150399. 7,
  150400. 4,
  150401. 8,
  150402. 3,
  150403. 9,
  150404. 2,
  150405. 10,
  150406. 1,
  150407. 11,
  150408. 0,
  150409. 12,
  150410. };
  150411. static long _vq_lengthlist__44u7__p9_1[] = {
  150412. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150413. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150414. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150415. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150416. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150417. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150418. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150419. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150420. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150421. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150422. 15,15,15,15,17,17,16,17,16,
  150423. };
  150424. static float _vq_quantthresh__44u7__p9_1[] = {
  150425. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150426. 122.5, 171.5, 220.5, 269.5,
  150427. };
  150428. static long _vq_quantmap__44u7__p9_1[] = {
  150429. 11, 9, 7, 5, 3, 1, 0, 2,
  150430. 4, 6, 8, 10, 12,
  150431. };
  150432. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150433. _vq_quantthresh__44u7__p9_1,
  150434. _vq_quantmap__44u7__p9_1,
  150435. 13,
  150436. 13
  150437. };
  150438. static static_codebook _44u7__p9_1 = {
  150439. 2, 169,
  150440. _vq_lengthlist__44u7__p9_1,
  150441. 1, -518889472, 1622704128, 4, 0,
  150442. _vq_quantlist__44u7__p9_1,
  150443. NULL,
  150444. &_vq_auxt__44u7__p9_1,
  150445. NULL,
  150446. 0
  150447. };
  150448. static long _vq_quantlist__44u7__p9_2[] = {
  150449. 24,
  150450. 23,
  150451. 25,
  150452. 22,
  150453. 26,
  150454. 21,
  150455. 27,
  150456. 20,
  150457. 28,
  150458. 19,
  150459. 29,
  150460. 18,
  150461. 30,
  150462. 17,
  150463. 31,
  150464. 16,
  150465. 32,
  150466. 15,
  150467. 33,
  150468. 14,
  150469. 34,
  150470. 13,
  150471. 35,
  150472. 12,
  150473. 36,
  150474. 11,
  150475. 37,
  150476. 10,
  150477. 38,
  150478. 9,
  150479. 39,
  150480. 8,
  150481. 40,
  150482. 7,
  150483. 41,
  150484. 6,
  150485. 42,
  150486. 5,
  150487. 43,
  150488. 4,
  150489. 44,
  150490. 3,
  150491. 45,
  150492. 2,
  150493. 46,
  150494. 1,
  150495. 47,
  150496. 0,
  150497. 48,
  150498. };
  150499. static long _vq_lengthlist__44u7__p9_2[] = {
  150500. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150501. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150502. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150503. 8,
  150504. };
  150505. static float _vq_quantthresh__44u7__p9_2[] = {
  150506. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150507. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150508. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150509. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150510. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150511. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150512. };
  150513. static long _vq_quantmap__44u7__p9_2[] = {
  150514. 47, 45, 43, 41, 39, 37, 35, 33,
  150515. 31, 29, 27, 25, 23, 21, 19, 17,
  150516. 15, 13, 11, 9, 7, 5, 3, 1,
  150517. 0, 2, 4, 6, 8, 10, 12, 14,
  150518. 16, 18, 20, 22, 24, 26, 28, 30,
  150519. 32, 34, 36, 38, 40, 42, 44, 46,
  150520. 48,
  150521. };
  150522. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150523. _vq_quantthresh__44u7__p9_2,
  150524. _vq_quantmap__44u7__p9_2,
  150525. 49,
  150526. 49
  150527. };
  150528. static static_codebook _44u7__p9_2 = {
  150529. 1, 49,
  150530. _vq_lengthlist__44u7__p9_2,
  150531. 1, -526909440, 1611661312, 6, 0,
  150532. _vq_quantlist__44u7__p9_2,
  150533. NULL,
  150534. &_vq_auxt__44u7__p9_2,
  150535. NULL,
  150536. 0
  150537. };
  150538. static long _huff_lengthlist__44u7__short[] = {
  150539. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150540. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150541. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150542. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150543. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150544. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150545. 6, 8, 5, 9,
  150546. };
  150547. static static_codebook _huff_book__44u7__short = {
  150548. 2, 100,
  150549. _huff_lengthlist__44u7__short,
  150550. 0, 0, 0, 0, 0,
  150551. NULL,
  150552. NULL,
  150553. NULL,
  150554. NULL,
  150555. 0
  150556. };
  150557. static long _huff_lengthlist__44u8__long[] = {
  150558. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150559. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150560. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150561. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150562. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150563. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150564. 10, 8, 8, 9,
  150565. };
  150566. static static_codebook _huff_book__44u8__long = {
  150567. 2, 100,
  150568. _huff_lengthlist__44u8__long,
  150569. 0, 0, 0, 0, 0,
  150570. NULL,
  150571. NULL,
  150572. NULL,
  150573. NULL,
  150574. 0
  150575. };
  150576. static long _huff_lengthlist__44u8__short[] = {
  150577. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150578. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150579. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150580. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150581. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150582. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150583. 10,10,15,17,
  150584. };
  150585. static static_codebook _huff_book__44u8__short = {
  150586. 2, 100,
  150587. _huff_lengthlist__44u8__short,
  150588. 0, 0, 0, 0, 0,
  150589. NULL,
  150590. NULL,
  150591. NULL,
  150592. NULL,
  150593. 0
  150594. };
  150595. static long _vq_quantlist__44u8_p1_0[] = {
  150596. 1,
  150597. 0,
  150598. 2,
  150599. };
  150600. static long _vq_lengthlist__44u8_p1_0[] = {
  150601. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150602. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150603. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150604. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150605. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150606. 10,
  150607. };
  150608. static float _vq_quantthresh__44u8_p1_0[] = {
  150609. -0.5, 0.5,
  150610. };
  150611. static long _vq_quantmap__44u8_p1_0[] = {
  150612. 1, 0, 2,
  150613. };
  150614. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150615. _vq_quantthresh__44u8_p1_0,
  150616. _vq_quantmap__44u8_p1_0,
  150617. 3,
  150618. 3
  150619. };
  150620. static static_codebook _44u8_p1_0 = {
  150621. 4, 81,
  150622. _vq_lengthlist__44u8_p1_0,
  150623. 1, -535822336, 1611661312, 2, 0,
  150624. _vq_quantlist__44u8_p1_0,
  150625. NULL,
  150626. &_vq_auxt__44u8_p1_0,
  150627. NULL,
  150628. 0
  150629. };
  150630. static long _vq_quantlist__44u8_p2_0[] = {
  150631. 2,
  150632. 1,
  150633. 3,
  150634. 0,
  150635. 4,
  150636. };
  150637. static long _vq_lengthlist__44u8_p2_0[] = {
  150638. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150639. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150640. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150641. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150642. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150643. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150644. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150645. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150646. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150647. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150648. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150649. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150650. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150651. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150652. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150653. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150654. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150655. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150656. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150657. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150658. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150659. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150660. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150661. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150662. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150663. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150664. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150665. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150666. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150667. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150668. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150669. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150670. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150671. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150672. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150673. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150674. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150675. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150676. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150677. 14,
  150678. };
  150679. static float _vq_quantthresh__44u8_p2_0[] = {
  150680. -1.5, -0.5, 0.5, 1.5,
  150681. };
  150682. static long _vq_quantmap__44u8_p2_0[] = {
  150683. 3, 1, 0, 2, 4,
  150684. };
  150685. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150686. _vq_quantthresh__44u8_p2_0,
  150687. _vq_quantmap__44u8_p2_0,
  150688. 5,
  150689. 5
  150690. };
  150691. static static_codebook _44u8_p2_0 = {
  150692. 4, 625,
  150693. _vq_lengthlist__44u8_p2_0,
  150694. 1, -533725184, 1611661312, 3, 0,
  150695. _vq_quantlist__44u8_p2_0,
  150696. NULL,
  150697. &_vq_auxt__44u8_p2_0,
  150698. NULL,
  150699. 0
  150700. };
  150701. static long _vq_quantlist__44u8_p3_0[] = {
  150702. 4,
  150703. 3,
  150704. 5,
  150705. 2,
  150706. 6,
  150707. 1,
  150708. 7,
  150709. 0,
  150710. 8,
  150711. };
  150712. static long _vq_lengthlist__44u8_p3_0[] = {
  150713. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150714. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150715. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150716. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150717. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150718. 12,
  150719. };
  150720. static float _vq_quantthresh__44u8_p3_0[] = {
  150721. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150722. };
  150723. static long _vq_quantmap__44u8_p3_0[] = {
  150724. 7, 5, 3, 1, 0, 2, 4, 6,
  150725. 8,
  150726. };
  150727. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150728. _vq_quantthresh__44u8_p3_0,
  150729. _vq_quantmap__44u8_p3_0,
  150730. 9,
  150731. 9
  150732. };
  150733. static static_codebook _44u8_p3_0 = {
  150734. 2, 81,
  150735. _vq_lengthlist__44u8_p3_0,
  150736. 1, -531628032, 1611661312, 4, 0,
  150737. _vq_quantlist__44u8_p3_0,
  150738. NULL,
  150739. &_vq_auxt__44u8_p3_0,
  150740. NULL,
  150741. 0
  150742. };
  150743. static long _vq_quantlist__44u8_p4_0[] = {
  150744. 8,
  150745. 7,
  150746. 9,
  150747. 6,
  150748. 10,
  150749. 5,
  150750. 11,
  150751. 4,
  150752. 12,
  150753. 3,
  150754. 13,
  150755. 2,
  150756. 14,
  150757. 1,
  150758. 15,
  150759. 0,
  150760. 16,
  150761. };
  150762. static long _vq_lengthlist__44u8_p4_0[] = {
  150763. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150764. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150765. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150766. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150767. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150768. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150769. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150770. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150771. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150772. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150773. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150774. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150775. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150776. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150777. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150778. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150779. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150780. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150781. 14,
  150782. };
  150783. static float _vq_quantthresh__44u8_p4_0[] = {
  150784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150786. };
  150787. static long _vq_quantmap__44u8_p4_0[] = {
  150788. 15, 13, 11, 9, 7, 5, 3, 1,
  150789. 0, 2, 4, 6, 8, 10, 12, 14,
  150790. 16,
  150791. };
  150792. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150793. _vq_quantthresh__44u8_p4_0,
  150794. _vq_quantmap__44u8_p4_0,
  150795. 17,
  150796. 17
  150797. };
  150798. static static_codebook _44u8_p4_0 = {
  150799. 2, 289,
  150800. _vq_lengthlist__44u8_p4_0,
  150801. 1, -529530880, 1611661312, 5, 0,
  150802. _vq_quantlist__44u8_p4_0,
  150803. NULL,
  150804. &_vq_auxt__44u8_p4_0,
  150805. NULL,
  150806. 0
  150807. };
  150808. static long _vq_quantlist__44u8_p5_0[] = {
  150809. 1,
  150810. 0,
  150811. 2,
  150812. };
  150813. static long _vq_lengthlist__44u8_p5_0[] = {
  150814. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150815. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150816. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150817. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150818. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150819. 10,
  150820. };
  150821. static float _vq_quantthresh__44u8_p5_0[] = {
  150822. -5.5, 5.5,
  150823. };
  150824. static long _vq_quantmap__44u8_p5_0[] = {
  150825. 1, 0, 2,
  150826. };
  150827. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150828. _vq_quantthresh__44u8_p5_0,
  150829. _vq_quantmap__44u8_p5_0,
  150830. 3,
  150831. 3
  150832. };
  150833. static static_codebook _44u8_p5_0 = {
  150834. 4, 81,
  150835. _vq_lengthlist__44u8_p5_0,
  150836. 1, -529137664, 1618345984, 2, 0,
  150837. _vq_quantlist__44u8_p5_0,
  150838. NULL,
  150839. &_vq_auxt__44u8_p5_0,
  150840. NULL,
  150841. 0
  150842. };
  150843. static long _vq_quantlist__44u8_p5_1[] = {
  150844. 5,
  150845. 4,
  150846. 6,
  150847. 3,
  150848. 7,
  150849. 2,
  150850. 8,
  150851. 1,
  150852. 9,
  150853. 0,
  150854. 10,
  150855. };
  150856. static long _vq_lengthlist__44u8_p5_1[] = {
  150857. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150858. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150859. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150860. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150861. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150862. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150863. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150864. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150865. };
  150866. static float _vq_quantthresh__44u8_p5_1[] = {
  150867. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150868. 3.5, 4.5,
  150869. };
  150870. static long _vq_quantmap__44u8_p5_1[] = {
  150871. 9, 7, 5, 3, 1, 0, 2, 4,
  150872. 6, 8, 10,
  150873. };
  150874. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150875. _vq_quantthresh__44u8_p5_1,
  150876. _vq_quantmap__44u8_p5_1,
  150877. 11,
  150878. 11
  150879. };
  150880. static static_codebook _44u8_p5_1 = {
  150881. 2, 121,
  150882. _vq_lengthlist__44u8_p5_1,
  150883. 1, -531365888, 1611661312, 4, 0,
  150884. _vq_quantlist__44u8_p5_1,
  150885. NULL,
  150886. &_vq_auxt__44u8_p5_1,
  150887. NULL,
  150888. 0
  150889. };
  150890. static long _vq_quantlist__44u8_p6_0[] = {
  150891. 6,
  150892. 5,
  150893. 7,
  150894. 4,
  150895. 8,
  150896. 3,
  150897. 9,
  150898. 2,
  150899. 10,
  150900. 1,
  150901. 11,
  150902. 0,
  150903. 12,
  150904. };
  150905. static long _vq_lengthlist__44u8_p6_0[] = {
  150906. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150907. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150908. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150909. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150910. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150911. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150912. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150913. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150914. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150915. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150916. 11,11,11,11,11,12,11,12,12,
  150917. };
  150918. static float _vq_quantthresh__44u8_p6_0[] = {
  150919. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150920. 12.5, 17.5, 22.5, 27.5,
  150921. };
  150922. static long _vq_quantmap__44u8_p6_0[] = {
  150923. 11, 9, 7, 5, 3, 1, 0, 2,
  150924. 4, 6, 8, 10, 12,
  150925. };
  150926. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150927. _vq_quantthresh__44u8_p6_0,
  150928. _vq_quantmap__44u8_p6_0,
  150929. 13,
  150930. 13
  150931. };
  150932. static static_codebook _44u8_p6_0 = {
  150933. 2, 169,
  150934. _vq_lengthlist__44u8_p6_0,
  150935. 1, -526516224, 1616117760, 4, 0,
  150936. _vq_quantlist__44u8_p6_0,
  150937. NULL,
  150938. &_vq_auxt__44u8_p6_0,
  150939. NULL,
  150940. 0
  150941. };
  150942. static long _vq_quantlist__44u8_p6_1[] = {
  150943. 2,
  150944. 1,
  150945. 3,
  150946. 0,
  150947. 4,
  150948. };
  150949. static long _vq_lengthlist__44u8_p6_1[] = {
  150950. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150951. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150952. };
  150953. static float _vq_quantthresh__44u8_p6_1[] = {
  150954. -1.5, -0.5, 0.5, 1.5,
  150955. };
  150956. static long _vq_quantmap__44u8_p6_1[] = {
  150957. 3, 1, 0, 2, 4,
  150958. };
  150959. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150960. _vq_quantthresh__44u8_p6_1,
  150961. _vq_quantmap__44u8_p6_1,
  150962. 5,
  150963. 5
  150964. };
  150965. static static_codebook _44u8_p6_1 = {
  150966. 2, 25,
  150967. _vq_lengthlist__44u8_p6_1,
  150968. 1, -533725184, 1611661312, 3, 0,
  150969. _vq_quantlist__44u8_p6_1,
  150970. NULL,
  150971. &_vq_auxt__44u8_p6_1,
  150972. NULL,
  150973. 0
  150974. };
  150975. static long _vq_quantlist__44u8_p7_0[] = {
  150976. 6,
  150977. 5,
  150978. 7,
  150979. 4,
  150980. 8,
  150981. 3,
  150982. 9,
  150983. 2,
  150984. 10,
  150985. 1,
  150986. 11,
  150987. 0,
  150988. 12,
  150989. };
  150990. static long _vq_lengthlist__44u8_p7_0[] = {
  150991. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150992. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150993. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150994. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150995. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150996. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150997. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150998. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150999. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151000. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151001. 13,13,14,14,14,15,15,15,16,
  151002. };
  151003. static float _vq_quantthresh__44u8_p7_0[] = {
  151004. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151005. 27.5, 38.5, 49.5, 60.5,
  151006. };
  151007. static long _vq_quantmap__44u8_p7_0[] = {
  151008. 11, 9, 7, 5, 3, 1, 0, 2,
  151009. 4, 6, 8, 10, 12,
  151010. };
  151011. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151012. _vq_quantthresh__44u8_p7_0,
  151013. _vq_quantmap__44u8_p7_0,
  151014. 13,
  151015. 13
  151016. };
  151017. static static_codebook _44u8_p7_0 = {
  151018. 2, 169,
  151019. _vq_lengthlist__44u8_p7_0,
  151020. 1, -523206656, 1618345984, 4, 0,
  151021. _vq_quantlist__44u8_p7_0,
  151022. NULL,
  151023. &_vq_auxt__44u8_p7_0,
  151024. NULL,
  151025. 0
  151026. };
  151027. static long _vq_quantlist__44u8_p7_1[] = {
  151028. 5,
  151029. 4,
  151030. 6,
  151031. 3,
  151032. 7,
  151033. 2,
  151034. 8,
  151035. 1,
  151036. 9,
  151037. 0,
  151038. 10,
  151039. };
  151040. static long _vq_lengthlist__44u8_p7_1[] = {
  151041. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151042. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151043. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151044. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151045. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151046. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151047. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151048. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151049. };
  151050. static float _vq_quantthresh__44u8_p7_1[] = {
  151051. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151052. 3.5, 4.5,
  151053. };
  151054. static long _vq_quantmap__44u8_p7_1[] = {
  151055. 9, 7, 5, 3, 1, 0, 2, 4,
  151056. 6, 8, 10,
  151057. };
  151058. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151059. _vq_quantthresh__44u8_p7_1,
  151060. _vq_quantmap__44u8_p7_1,
  151061. 11,
  151062. 11
  151063. };
  151064. static static_codebook _44u8_p7_1 = {
  151065. 2, 121,
  151066. _vq_lengthlist__44u8_p7_1,
  151067. 1, -531365888, 1611661312, 4, 0,
  151068. _vq_quantlist__44u8_p7_1,
  151069. NULL,
  151070. &_vq_auxt__44u8_p7_1,
  151071. NULL,
  151072. 0
  151073. };
  151074. static long _vq_quantlist__44u8_p8_0[] = {
  151075. 7,
  151076. 6,
  151077. 8,
  151078. 5,
  151079. 9,
  151080. 4,
  151081. 10,
  151082. 3,
  151083. 11,
  151084. 2,
  151085. 12,
  151086. 1,
  151087. 13,
  151088. 0,
  151089. 14,
  151090. };
  151091. static long _vq_lengthlist__44u8_p8_0[] = {
  151092. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151093. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151094. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151095. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151096. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151097. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151098. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151099. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151100. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151101. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151102. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151103. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151104. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151105. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151106. 17,
  151107. };
  151108. static float _vq_quantthresh__44u8_p8_0[] = {
  151109. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151110. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151111. };
  151112. static long _vq_quantmap__44u8_p8_0[] = {
  151113. 13, 11, 9, 7, 5, 3, 1, 0,
  151114. 2, 4, 6, 8, 10, 12, 14,
  151115. };
  151116. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151117. _vq_quantthresh__44u8_p8_0,
  151118. _vq_quantmap__44u8_p8_0,
  151119. 15,
  151120. 15
  151121. };
  151122. static static_codebook _44u8_p8_0 = {
  151123. 2, 225,
  151124. _vq_lengthlist__44u8_p8_0,
  151125. 1, -520986624, 1620377600, 4, 0,
  151126. _vq_quantlist__44u8_p8_0,
  151127. NULL,
  151128. &_vq_auxt__44u8_p8_0,
  151129. NULL,
  151130. 0
  151131. };
  151132. static long _vq_quantlist__44u8_p8_1[] = {
  151133. 10,
  151134. 9,
  151135. 11,
  151136. 8,
  151137. 12,
  151138. 7,
  151139. 13,
  151140. 6,
  151141. 14,
  151142. 5,
  151143. 15,
  151144. 4,
  151145. 16,
  151146. 3,
  151147. 17,
  151148. 2,
  151149. 18,
  151150. 1,
  151151. 19,
  151152. 0,
  151153. 20,
  151154. };
  151155. static long _vq_lengthlist__44u8_p8_1[] = {
  151156. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151157. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151159. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151160. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151161. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151164. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151165. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151166. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151167. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151168. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151169. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151170. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151171. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151172. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151173. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151174. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151175. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151176. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151177. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151178. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151179. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151180. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151181. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151182. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151183. 10,10,10,10,10,10,10,10,10,
  151184. };
  151185. static float _vq_quantthresh__44u8_p8_1[] = {
  151186. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151187. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151188. 6.5, 7.5, 8.5, 9.5,
  151189. };
  151190. static long _vq_quantmap__44u8_p8_1[] = {
  151191. 19, 17, 15, 13, 11, 9, 7, 5,
  151192. 3, 1, 0, 2, 4, 6, 8, 10,
  151193. 12, 14, 16, 18, 20,
  151194. };
  151195. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151196. _vq_quantthresh__44u8_p8_1,
  151197. _vq_quantmap__44u8_p8_1,
  151198. 21,
  151199. 21
  151200. };
  151201. static static_codebook _44u8_p8_1 = {
  151202. 2, 441,
  151203. _vq_lengthlist__44u8_p8_1,
  151204. 1, -529268736, 1611661312, 5, 0,
  151205. _vq_quantlist__44u8_p8_1,
  151206. NULL,
  151207. &_vq_auxt__44u8_p8_1,
  151208. NULL,
  151209. 0
  151210. };
  151211. static long _vq_quantlist__44u8_p9_0[] = {
  151212. 4,
  151213. 3,
  151214. 5,
  151215. 2,
  151216. 6,
  151217. 1,
  151218. 7,
  151219. 0,
  151220. 8,
  151221. };
  151222. static long _vq_lengthlist__44u8_p9_0[] = {
  151223. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151224. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151225. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151227. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151228. 8,
  151229. };
  151230. static float _vq_quantthresh__44u8_p9_0[] = {
  151231. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151232. };
  151233. static long _vq_quantmap__44u8_p9_0[] = {
  151234. 7, 5, 3, 1, 0, 2, 4, 6,
  151235. 8,
  151236. };
  151237. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151238. _vq_quantthresh__44u8_p9_0,
  151239. _vq_quantmap__44u8_p9_0,
  151240. 9,
  151241. 9
  151242. };
  151243. static static_codebook _44u8_p9_0 = {
  151244. 2, 81,
  151245. _vq_lengthlist__44u8_p9_0,
  151246. 1, -511895552, 1631393792, 4, 0,
  151247. _vq_quantlist__44u8_p9_0,
  151248. NULL,
  151249. &_vq_auxt__44u8_p9_0,
  151250. NULL,
  151251. 0
  151252. };
  151253. static long _vq_quantlist__44u8_p9_1[] = {
  151254. 9,
  151255. 8,
  151256. 10,
  151257. 7,
  151258. 11,
  151259. 6,
  151260. 12,
  151261. 5,
  151262. 13,
  151263. 4,
  151264. 14,
  151265. 3,
  151266. 15,
  151267. 2,
  151268. 16,
  151269. 1,
  151270. 17,
  151271. 0,
  151272. 18,
  151273. };
  151274. static long _vq_lengthlist__44u8_p9_1[] = {
  151275. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151276. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151277. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151278. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151279. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151280. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151281. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151282. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151283. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151284. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151285. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151286. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151287. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151288. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151289. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151290. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151291. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151292. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151293. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151294. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151295. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151296. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151297. 16,15,16,16,16,16,16,16,16,
  151298. };
  151299. static float _vq_quantthresh__44u8_p9_1[] = {
  151300. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151301. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151302. 367.5, 416.5,
  151303. };
  151304. static long _vq_quantmap__44u8_p9_1[] = {
  151305. 17, 15, 13, 11, 9, 7, 5, 3,
  151306. 1, 0, 2, 4, 6, 8, 10, 12,
  151307. 14, 16, 18,
  151308. };
  151309. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151310. _vq_quantthresh__44u8_p9_1,
  151311. _vq_quantmap__44u8_p9_1,
  151312. 19,
  151313. 19
  151314. };
  151315. static static_codebook _44u8_p9_1 = {
  151316. 2, 361,
  151317. _vq_lengthlist__44u8_p9_1,
  151318. 1, -518287360, 1622704128, 5, 0,
  151319. _vq_quantlist__44u8_p9_1,
  151320. NULL,
  151321. &_vq_auxt__44u8_p9_1,
  151322. NULL,
  151323. 0
  151324. };
  151325. static long _vq_quantlist__44u8_p9_2[] = {
  151326. 24,
  151327. 23,
  151328. 25,
  151329. 22,
  151330. 26,
  151331. 21,
  151332. 27,
  151333. 20,
  151334. 28,
  151335. 19,
  151336. 29,
  151337. 18,
  151338. 30,
  151339. 17,
  151340. 31,
  151341. 16,
  151342. 32,
  151343. 15,
  151344. 33,
  151345. 14,
  151346. 34,
  151347. 13,
  151348. 35,
  151349. 12,
  151350. 36,
  151351. 11,
  151352. 37,
  151353. 10,
  151354. 38,
  151355. 9,
  151356. 39,
  151357. 8,
  151358. 40,
  151359. 7,
  151360. 41,
  151361. 6,
  151362. 42,
  151363. 5,
  151364. 43,
  151365. 4,
  151366. 44,
  151367. 3,
  151368. 45,
  151369. 2,
  151370. 46,
  151371. 1,
  151372. 47,
  151373. 0,
  151374. 48,
  151375. };
  151376. static long _vq_lengthlist__44u8_p9_2[] = {
  151377. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151378. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151379. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151380. 7,
  151381. };
  151382. static float _vq_quantthresh__44u8_p9_2[] = {
  151383. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151384. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151385. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151386. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151387. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151388. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151389. };
  151390. static long _vq_quantmap__44u8_p9_2[] = {
  151391. 47, 45, 43, 41, 39, 37, 35, 33,
  151392. 31, 29, 27, 25, 23, 21, 19, 17,
  151393. 15, 13, 11, 9, 7, 5, 3, 1,
  151394. 0, 2, 4, 6, 8, 10, 12, 14,
  151395. 16, 18, 20, 22, 24, 26, 28, 30,
  151396. 32, 34, 36, 38, 40, 42, 44, 46,
  151397. 48,
  151398. };
  151399. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151400. _vq_quantthresh__44u8_p9_2,
  151401. _vq_quantmap__44u8_p9_2,
  151402. 49,
  151403. 49
  151404. };
  151405. static static_codebook _44u8_p9_2 = {
  151406. 1, 49,
  151407. _vq_lengthlist__44u8_p9_2,
  151408. 1, -526909440, 1611661312, 6, 0,
  151409. _vq_quantlist__44u8_p9_2,
  151410. NULL,
  151411. &_vq_auxt__44u8_p9_2,
  151412. NULL,
  151413. 0
  151414. };
  151415. static long _huff_lengthlist__44u9__long[] = {
  151416. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151417. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151418. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151419. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151420. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151421. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151422. 10, 8, 8, 9,
  151423. };
  151424. static static_codebook _huff_book__44u9__long = {
  151425. 2, 100,
  151426. _huff_lengthlist__44u9__long,
  151427. 0, 0, 0, 0, 0,
  151428. NULL,
  151429. NULL,
  151430. NULL,
  151431. NULL,
  151432. 0
  151433. };
  151434. static long _huff_lengthlist__44u9__short[] = {
  151435. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151436. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151437. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151438. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151439. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151440. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151441. 9, 9,12,15,
  151442. };
  151443. static static_codebook _huff_book__44u9__short = {
  151444. 2, 100,
  151445. _huff_lengthlist__44u9__short,
  151446. 0, 0, 0, 0, 0,
  151447. NULL,
  151448. NULL,
  151449. NULL,
  151450. NULL,
  151451. 0
  151452. };
  151453. static long _vq_quantlist__44u9_p1_0[] = {
  151454. 1,
  151455. 0,
  151456. 2,
  151457. };
  151458. static long _vq_lengthlist__44u9_p1_0[] = {
  151459. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151460. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151461. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151462. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151463. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151464. 10,
  151465. };
  151466. static float _vq_quantthresh__44u9_p1_0[] = {
  151467. -0.5, 0.5,
  151468. };
  151469. static long _vq_quantmap__44u9_p1_0[] = {
  151470. 1, 0, 2,
  151471. };
  151472. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151473. _vq_quantthresh__44u9_p1_0,
  151474. _vq_quantmap__44u9_p1_0,
  151475. 3,
  151476. 3
  151477. };
  151478. static static_codebook _44u9_p1_0 = {
  151479. 4, 81,
  151480. _vq_lengthlist__44u9_p1_0,
  151481. 1, -535822336, 1611661312, 2, 0,
  151482. _vq_quantlist__44u9_p1_0,
  151483. NULL,
  151484. &_vq_auxt__44u9_p1_0,
  151485. NULL,
  151486. 0
  151487. };
  151488. static long _vq_quantlist__44u9_p2_0[] = {
  151489. 2,
  151490. 1,
  151491. 3,
  151492. 0,
  151493. 4,
  151494. };
  151495. static long _vq_lengthlist__44u9_p2_0[] = {
  151496. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151497. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151498. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151499. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151500. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151501. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151502. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151503. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151504. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151505. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151506. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151507. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151508. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151509. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151510. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151511. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151512. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151513. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151514. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151515. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151516. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151517. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151518. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151519. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151520. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151521. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151522. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151523. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151524. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151525. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151526. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151527. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151528. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151529. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151530. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151531. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151532. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151533. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151534. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151535. 14,
  151536. };
  151537. static float _vq_quantthresh__44u9_p2_0[] = {
  151538. -1.5, -0.5, 0.5, 1.5,
  151539. };
  151540. static long _vq_quantmap__44u9_p2_0[] = {
  151541. 3, 1, 0, 2, 4,
  151542. };
  151543. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151544. _vq_quantthresh__44u9_p2_0,
  151545. _vq_quantmap__44u9_p2_0,
  151546. 5,
  151547. 5
  151548. };
  151549. static static_codebook _44u9_p2_0 = {
  151550. 4, 625,
  151551. _vq_lengthlist__44u9_p2_0,
  151552. 1, -533725184, 1611661312, 3, 0,
  151553. _vq_quantlist__44u9_p2_0,
  151554. NULL,
  151555. &_vq_auxt__44u9_p2_0,
  151556. NULL,
  151557. 0
  151558. };
  151559. static long _vq_quantlist__44u9_p3_0[] = {
  151560. 4,
  151561. 3,
  151562. 5,
  151563. 2,
  151564. 6,
  151565. 1,
  151566. 7,
  151567. 0,
  151568. 8,
  151569. };
  151570. static long _vq_lengthlist__44u9_p3_0[] = {
  151571. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151572. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151573. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151574. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151575. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151576. 11,
  151577. };
  151578. static float _vq_quantthresh__44u9_p3_0[] = {
  151579. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151580. };
  151581. static long _vq_quantmap__44u9_p3_0[] = {
  151582. 7, 5, 3, 1, 0, 2, 4, 6,
  151583. 8,
  151584. };
  151585. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151586. _vq_quantthresh__44u9_p3_0,
  151587. _vq_quantmap__44u9_p3_0,
  151588. 9,
  151589. 9
  151590. };
  151591. static static_codebook _44u9_p3_0 = {
  151592. 2, 81,
  151593. _vq_lengthlist__44u9_p3_0,
  151594. 1, -531628032, 1611661312, 4, 0,
  151595. _vq_quantlist__44u9_p3_0,
  151596. NULL,
  151597. &_vq_auxt__44u9_p3_0,
  151598. NULL,
  151599. 0
  151600. };
  151601. static long _vq_quantlist__44u9_p4_0[] = {
  151602. 8,
  151603. 7,
  151604. 9,
  151605. 6,
  151606. 10,
  151607. 5,
  151608. 11,
  151609. 4,
  151610. 12,
  151611. 3,
  151612. 13,
  151613. 2,
  151614. 14,
  151615. 1,
  151616. 15,
  151617. 0,
  151618. 16,
  151619. };
  151620. static long _vq_lengthlist__44u9_p4_0[] = {
  151621. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151622. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151623. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151624. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151625. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151626. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151627. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151628. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151629. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151630. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151631. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151632. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151633. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151634. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151635. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151636. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151637. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151638. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151639. 14,
  151640. };
  151641. static float _vq_quantthresh__44u9_p4_0[] = {
  151642. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151643. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151644. };
  151645. static long _vq_quantmap__44u9_p4_0[] = {
  151646. 15, 13, 11, 9, 7, 5, 3, 1,
  151647. 0, 2, 4, 6, 8, 10, 12, 14,
  151648. 16,
  151649. };
  151650. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151651. _vq_quantthresh__44u9_p4_0,
  151652. _vq_quantmap__44u9_p4_0,
  151653. 17,
  151654. 17
  151655. };
  151656. static static_codebook _44u9_p4_0 = {
  151657. 2, 289,
  151658. _vq_lengthlist__44u9_p4_0,
  151659. 1, -529530880, 1611661312, 5, 0,
  151660. _vq_quantlist__44u9_p4_0,
  151661. NULL,
  151662. &_vq_auxt__44u9_p4_0,
  151663. NULL,
  151664. 0
  151665. };
  151666. static long _vq_quantlist__44u9_p5_0[] = {
  151667. 1,
  151668. 0,
  151669. 2,
  151670. };
  151671. static long _vq_lengthlist__44u9_p5_0[] = {
  151672. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151673. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151674. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151675. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151676. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151677. 10,
  151678. };
  151679. static float _vq_quantthresh__44u9_p5_0[] = {
  151680. -5.5, 5.5,
  151681. };
  151682. static long _vq_quantmap__44u9_p5_0[] = {
  151683. 1, 0, 2,
  151684. };
  151685. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151686. _vq_quantthresh__44u9_p5_0,
  151687. _vq_quantmap__44u9_p5_0,
  151688. 3,
  151689. 3
  151690. };
  151691. static static_codebook _44u9_p5_0 = {
  151692. 4, 81,
  151693. _vq_lengthlist__44u9_p5_0,
  151694. 1, -529137664, 1618345984, 2, 0,
  151695. _vq_quantlist__44u9_p5_0,
  151696. NULL,
  151697. &_vq_auxt__44u9_p5_0,
  151698. NULL,
  151699. 0
  151700. };
  151701. static long _vq_quantlist__44u9_p5_1[] = {
  151702. 5,
  151703. 4,
  151704. 6,
  151705. 3,
  151706. 7,
  151707. 2,
  151708. 8,
  151709. 1,
  151710. 9,
  151711. 0,
  151712. 10,
  151713. };
  151714. static long _vq_lengthlist__44u9_p5_1[] = {
  151715. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151716. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151717. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151718. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151719. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151720. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151721. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151722. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151723. };
  151724. static float _vq_quantthresh__44u9_p5_1[] = {
  151725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151726. 3.5, 4.5,
  151727. };
  151728. static long _vq_quantmap__44u9_p5_1[] = {
  151729. 9, 7, 5, 3, 1, 0, 2, 4,
  151730. 6, 8, 10,
  151731. };
  151732. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151733. _vq_quantthresh__44u9_p5_1,
  151734. _vq_quantmap__44u9_p5_1,
  151735. 11,
  151736. 11
  151737. };
  151738. static static_codebook _44u9_p5_1 = {
  151739. 2, 121,
  151740. _vq_lengthlist__44u9_p5_1,
  151741. 1, -531365888, 1611661312, 4, 0,
  151742. _vq_quantlist__44u9_p5_1,
  151743. NULL,
  151744. &_vq_auxt__44u9_p5_1,
  151745. NULL,
  151746. 0
  151747. };
  151748. static long _vq_quantlist__44u9_p6_0[] = {
  151749. 6,
  151750. 5,
  151751. 7,
  151752. 4,
  151753. 8,
  151754. 3,
  151755. 9,
  151756. 2,
  151757. 10,
  151758. 1,
  151759. 11,
  151760. 0,
  151761. 12,
  151762. };
  151763. static long _vq_lengthlist__44u9_p6_0[] = {
  151764. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151765. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151766. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151767. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151768. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151769. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151770. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151771. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151772. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151773. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151774. 10,11,11,11,11,12,11,12,12,
  151775. };
  151776. static float _vq_quantthresh__44u9_p6_0[] = {
  151777. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151778. 12.5, 17.5, 22.5, 27.5,
  151779. };
  151780. static long _vq_quantmap__44u9_p6_0[] = {
  151781. 11, 9, 7, 5, 3, 1, 0, 2,
  151782. 4, 6, 8, 10, 12,
  151783. };
  151784. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151785. _vq_quantthresh__44u9_p6_0,
  151786. _vq_quantmap__44u9_p6_0,
  151787. 13,
  151788. 13
  151789. };
  151790. static static_codebook _44u9_p6_0 = {
  151791. 2, 169,
  151792. _vq_lengthlist__44u9_p6_0,
  151793. 1, -526516224, 1616117760, 4, 0,
  151794. _vq_quantlist__44u9_p6_0,
  151795. NULL,
  151796. &_vq_auxt__44u9_p6_0,
  151797. NULL,
  151798. 0
  151799. };
  151800. static long _vq_quantlist__44u9_p6_1[] = {
  151801. 2,
  151802. 1,
  151803. 3,
  151804. 0,
  151805. 4,
  151806. };
  151807. static long _vq_lengthlist__44u9_p6_1[] = {
  151808. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151809. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151810. };
  151811. static float _vq_quantthresh__44u9_p6_1[] = {
  151812. -1.5, -0.5, 0.5, 1.5,
  151813. };
  151814. static long _vq_quantmap__44u9_p6_1[] = {
  151815. 3, 1, 0, 2, 4,
  151816. };
  151817. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151818. _vq_quantthresh__44u9_p6_1,
  151819. _vq_quantmap__44u9_p6_1,
  151820. 5,
  151821. 5
  151822. };
  151823. static static_codebook _44u9_p6_1 = {
  151824. 2, 25,
  151825. _vq_lengthlist__44u9_p6_1,
  151826. 1, -533725184, 1611661312, 3, 0,
  151827. _vq_quantlist__44u9_p6_1,
  151828. NULL,
  151829. &_vq_auxt__44u9_p6_1,
  151830. NULL,
  151831. 0
  151832. };
  151833. static long _vq_quantlist__44u9_p7_0[] = {
  151834. 6,
  151835. 5,
  151836. 7,
  151837. 4,
  151838. 8,
  151839. 3,
  151840. 9,
  151841. 2,
  151842. 10,
  151843. 1,
  151844. 11,
  151845. 0,
  151846. 12,
  151847. };
  151848. static long _vq_lengthlist__44u9_p7_0[] = {
  151849. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151850. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151851. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151852. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151853. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151854. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151855. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151856. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151857. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151858. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151859. 12,13,13,14,14,14,15,15,15,
  151860. };
  151861. static float _vq_quantthresh__44u9_p7_0[] = {
  151862. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151863. 27.5, 38.5, 49.5, 60.5,
  151864. };
  151865. static long _vq_quantmap__44u9_p7_0[] = {
  151866. 11, 9, 7, 5, 3, 1, 0, 2,
  151867. 4, 6, 8, 10, 12,
  151868. };
  151869. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151870. _vq_quantthresh__44u9_p7_0,
  151871. _vq_quantmap__44u9_p7_0,
  151872. 13,
  151873. 13
  151874. };
  151875. static static_codebook _44u9_p7_0 = {
  151876. 2, 169,
  151877. _vq_lengthlist__44u9_p7_0,
  151878. 1, -523206656, 1618345984, 4, 0,
  151879. _vq_quantlist__44u9_p7_0,
  151880. NULL,
  151881. &_vq_auxt__44u9_p7_0,
  151882. NULL,
  151883. 0
  151884. };
  151885. static long _vq_quantlist__44u9_p7_1[] = {
  151886. 5,
  151887. 4,
  151888. 6,
  151889. 3,
  151890. 7,
  151891. 2,
  151892. 8,
  151893. 1,
  151894. 9,
  151895. 0,
  151896. 10,
  151897. };
  151898. static long _vq_lengthlist__44u9_p7_1[] = {
  151899. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151900. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151901. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151902. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151903. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151904. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151905. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151906. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151907. };
  151908. static float _vq_quantthresh__44u9_p7_1[] = {
  151909. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151910. 3.5, 4.5,
  151911. };
  151912. static long _vq_quantmap__44u9_p7_1[] = {
  151913. 9, 7, 5, 3, 1, 0, 2, 4,
  151914. 6, 8, 10,
  151915. };
  151916. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151917. _vq_quantthresh__44u9_p7_1,
  151918. _vq_quantmap__44u9_p7_1,
  151919. 11,
  151920. 11
  151921. };
  151922. static static_codebook _44u9_p7_1 = {
  151923. 2, 121,
  151924. _vq_lengthlist__44u9_p7_1,
  151925. 1, -531365888, 1611661312, 4, 0,
  151926. _vq_quantlist__44u9_p7_1,
  151927. NULL,
  151928. &_vq_auxt__44u9_p7_1,
  151929. NULL,
  151930. 0
  151931. };
  151932. static long _vq_quantlist__44u9_p8_0[] = {
  151933. 7,
  151934. 6,
  151935. 8,
  151936. 5,
  151937. 9,
  151938. 4,
  151939. 10,
  151940. 3,
  151941. 11,
  151942. 2,
  151943. 12,
  151944. 1,
  151945. 13,
  151946. 0,
  151947. 14,
  151948. };
  151949. static long _vq_lengthlist__44u9_p8_0[] = {
  151950. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151951. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151952. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151953. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151954. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151955. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151956. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151957. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151958. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151959. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151960. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151961. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151962. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151963. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151964. 15,
  151965. };
  151966. static float _vq_quantthresh__44u9_p8_0[] = {
  151967. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151968. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151969. };
  151970. static long _vq_quantmap__44u9_p8_0[] = {
  151971. 13, 11, 9, 7, 5, 3, 1, 0,
  151972. 2, 4, 6, 8, 10, 12, 14,
  151973. };
  151974. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151975. _vq_quantthresh__44u9_p8_0,
  151976. _vq_quantmap__44u9_p8_0,
  151977. 15,
  151978. 15
  151979. };
  151980. static static_codebook _44u9_p8_0 = {
  151981. 2, 225,
  151982. _vq_lengthlist__44u9_p8_0,
  151983. 1, -520986624, 1620377600, 4, 0,
  151984. _vq_quantlist__44u9_p8_0,
  151985. NULL,
  151986. &_vq_auxt__44u9_p8_0,
  151987. NULL,
  151988. 0
  151989. };
  151990. static long _vq_quantlist__44u9_p8_1[] = {
  151991. 10,
  151992. 9,
  151993. 11,
  151994. 8,
  151995. 12,
  151996. 7,
  151997. 13,
  151998. 6,
  151999. 14,
  152000. 5,
  152001. 15,
  152002. 4,
  152003. 16,
  152004. 3,
  152005. 17,
  152006. 2,
  152007. 18,
  152008. 1,
  152009. 19,
  152010. 0,
  152011. 20,
  152012. };
  152013. static long _vq_lengthlist__44u9_p8_1[] = {
  152014. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152015. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152017. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152018. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152019. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152020. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152021. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152022. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152023. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152024. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152025. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152026. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152027. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152028. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152029. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152030. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152031. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152032. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152033. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152035. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152036. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152037. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152038. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152039. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152040. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152041. 10,10,10,10,10,10,10,10,10,
  152042. };
  152043. static float _vq_quantthresh__44u9_p8_1[] = {
  152044. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152045. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152046. 6.5, 7.5, 8.5, 9.5,
  152047. };
  152048. static long _vq_quantmap__44u9_p8_1[] = {
  152049. 19, 17, 15, 13, 11, 9, 7, 5,
  152050. 3, 1, 0, 2, 4, 6, 8, 10,
  152051. 12, 14, 16, 18, 20,
  152052. };
  152053. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152054. _vq_quantthresh__44u9_p8_1,
  152055. _vq_quantmap__44u9_p8_1,
  152056. 21,
  152057. 21
  152058. };
  152059. static static_codebook _44u9_p8_1 = {
  152060. 2, 441,
  152061. _vq_lengthlist__44u9_p8_1,
  152062. 1, -529268736, 1611661312, 5, 0,
  152063. _vq_quantlist__44u9_p8_1,
  152064. NULL,
  152065. &_vq_auxt__44u9_p8_1,
  152066. NULL,
  152067. 0
  152068. };
  152069. static long _vq_quantlist__44u9_p9_0[] = {
  152070. 7,
  152071. 6,
  152072. 8,
  152073. 5,
  152074. 9,
  152075. 4,
  152076. 10,
  152077. 3,
  152078. 11,
  152079. 2,
  152080. 12,
  152081. 1,
  152082. 13,
  152083. 0,
  152084. 14,
  152085. };
  152086. static long _vq_lengthlist__44u9_p9_0[] = {
  152087. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152088. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152089. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152099. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152100. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152101. 10,
  152102. };
  152103. static float _vq_quantthresh__44u9_p9_0[] = {
  152104. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152105. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152106. };
  152107. static long _vq_quantmap__44u9_p9_0[] = {
  152108. 13, 11, 9, 7, 5, 3, 1, 0,
  152109. 2, 4, 6, 8, 10, 12, 14,
  152110. };
  152111. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152112. _vq_quantthresh__44u9_p9_0,
  152113. _vq_quantmap__44u9_p9_0,
  152114. 15,
  152115. 15
  152116. };
  152117. static static_codebook _44u9_p9_0 = {
  152118. 2, 225,
  152119. _vq_lengthlist__44u9_p9_0,
  152120. 1, -510036736, 1631393792, 4, 0,
  152121. _vq_quantlist__44u9_p9_0,
  152122. NULL,
  152123. &_vq_auxt__44u9_p9_0,
  152124. NULL,
  152125. 0
  152126. };
  152127. static long _vq_quantlist__44u9_p9_1[] = {
  152128. 9,
  152129. 8,
  152130. 10,
  152131. 7,
  152132. 11,
  152133. 6,
  152134. 12,
  152135. 5,
  152136. 13,
  152137. 4,
  152138. 14,
  152139. 3,
  152140. 15,
  152141. 2,
  152142. 16,
  152143. 1,
  152144. 17,
  152145. 0,
  152146. 18,
  152147. };
  152148. static long _vq_lengthlist__44u9_p9_1[] = {
  152149. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152150. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152151. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152152. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152153. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152154. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152155. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152156. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152157. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152158. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152159. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152160. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152161. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152162. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152163. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152164. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152165. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152166. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152167. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152168. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152169. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152170. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152171. 17,17,15,17,15,17,16,16,17,
  152172. };
  152173. static float _vq_quantthresh__44u9_p9_1[] = {
  152174. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152175. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152176. 367.5, 416.5,
  152177. };
  152178. static long _vq_quantmap__44u9_p9_1[] = {
  152179. 17, 15, 13, 11, 9, 7, 5, 3,
  152180. 1, 0, 2, 4, 6, 8, 10, 12,
  152181. 14, 16, 18,
  152182. };
  152183. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152184. _vq_quantthresh__44u9_p9_1,
  152185. _vq_quantmap__44u9_p9_1,
  152186. 19,
  152187. 19
  152188. };
  152189. static static_codebook _44u9_p9_1 = {
  152190. 2, 361,
  152191. _vq_lengthlist__44u9_p9_1,
  152192. 1, -518287360, 1622704128, 5, 0,
  152193. _vq_quantlist__44u9_p9_1,
  152194. NULL,
  152195. &_vq_auxt__44u9_p9_1,
  152196. NULL,
  152197. 0
  152198. };
  152199. static long _vq_quantlist__44u9_p9_2[] = {
  152200. 24,
  152201. 23,
  152202. 25,
  152203. 22,
  152204. 26,
  152205. 21,
  152206. 27,
  152207. 20,
  152208. 28,
  152209. 19,
  152210. 29,
  152211. 18,
  152212. 30,
  152213. 17,
  152214. 31,
  152215. 16,
  152216. 32,
  152217. 15,
  152218. 33,
  152219. 14,
  152220. 34,
  152221. 13,
  152222. 35,
  152223. 12,
  152224. 36,
  152225. 11,
  152226. 37,
  152227. 10,
  152228. 38,
  152229. 9,
  152230. 39,
  152231. 8,
  152232. 40,
  152233. 7,
  152234. 41,
  152235. 6,
  152236. 42,
  152237. 5,
  152238. 43,
  152239. 4,
  152240. 44,
  152241. 3,
  152242. 45,
  152243. 2,
  152244. 46,
  152245. 1,
  152246. 47,
  152247. 0,
  152248. 48,
  152249. };
  152250. static long _vq_lengthlist__44u9_p9_2[] = {
  152251. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152252. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152253. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152254. 7,
  152255. };
  152256. static float _vq_quantthresh__44u9_p9_2[] = {
  152257. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152258. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152259. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152260. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152261. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152262. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152263. };
  152264. static long _vq_quantmap__44u9_p9_2[] = {
  152265. 47, 45, 43, 41, 39, 37, 35, 33,
  152266. 31, 29, 27, 25, 23, 21, 19, 17,
  152267. 15, 13, 11, 9, 7, 5, 3, 1,
  152268. 0, 2, 4, 6, 8, 10, 12, 14,
  152269. 16, 18, 20, 22, 24, 26, 28, 30,
  152270. 32, 34, 36, 38, 40, 42, 44, 46,
  152271. 48,
  152272. };
  152273. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152274. _vq_quantthresh__44u9_p9_2,
  152275. _vq_quantmap__44u9_p9_2,
  152276. 49,
  152277. 49
  152278. };
  152279. static static_codebook _44u9_p9_2 = {
  152280. 1, 49,
  152281. _vq_lengthlist__44u9_p9_2,
  152282. 1, -526909440, 1611661312, 6, 0,
  152283. _vq_quantlist__44u9_p9_2,
  152284. NULL,
  152285. &_vq_auxt__44u9_p9_2,
  152286. NULL,
  152287. 0
  152288. };
  152289. static long _huff_lengthlist__44un1__long[] = {
  152290. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152291. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152292. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152293. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152294. };
  152295. static static_codebook _huff_book__44un1__long = {
  152296. 2, 64,
  152297. _huff_lengthlist__44un1__long,
  152298. 0, 0, 0, 0, 0,
  152299. NULL,
  152300. NULL,
  152301. NULL,
  152302. NULL,
  152303. 0
  152304. };
  152305. static long _vq_quantlist__44un1__p1_0[] = {
  152306. 1,
  152307. 0,
  152308. 2,
  152309. };
  152310. static long _vq_lengthlist__44un1__p1_0[] = {
  152311. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152312. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152313. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152314. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152315. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152316. 12,
  152317. };
  152318. static float _vq_quantthresh__44un1__p1_0[] = {
  152319. -0.5, 0.5,
  152320. };
  152321. static long _vq_quantmap__44un1__p1_0[] = {
  152322. 1, 0, 2,
  152323. };
  152324. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152325. _vq_quantthresh__44un1__p1_0,
  152326. _vq_quantmap__44un1__p1_0,
  152327. 3,
  152328. 3
  152329. };
  152330. static static_codebook _44un1__p1_0 = {
  152331. 4, 81,
  152332. _vq_lengthlist__44un1__p1_0,
  152333. 1, -535822336, 1611661312, 2, 0,
  152334. _vq_quantlist__44un1__p1_0,
  152335. NULL,
  152336. &_vq_auxt__44un1__p1_0,
  152337. NULL,
  152338. 0
  152339. };
  152340. static long _vq_quantlist__44un1__p2_0[] = {
  152341. 1,
  152342. 0,
  152343. 2,
  152344. };
  152345. static long _vq_lengthlist__44un1__p2_0[] = {
  152346. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152347. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152348. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152349. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152350. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152351. 8,
  152352. };
  152353. static float _vq_quantthresh__44un1__p2_0[] = {
  152354. -0.5, 0.5,
  152355. };
  152356. static long _vq_quantmap__44un1__p2_0[] = {
  152357. 1, 0, 2,
  152358. };
  152359. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152360. _vq_quantthresh__44un1__p2_0,
  152361. _vq_quantmap__44un1__p2_0,
  152362. 3,
  152363. 3
  152364. };
  152365. static static_codebook _44un1__p2_0 = {
  152366. 4, 81,
  152367. _vq_lengthlist__44un1__p2_0,
  152368. 1, -535822336, 1611661312, 2, 0,
  152369. _vq_quantlist__44un1__p2_0,
  152370. NULL,
  152371. &_vq_auxt__44un1__p2_0,
  152372. NULL,
  152373. 0
  152374. };
  152375. static long _vq_quantlist__44un1__p3_0[] = {
  152376. 2,
  152377. 1,
  152378. 3,
  152379. 0,
  152380. 4,
  152381. };
  152382. static long _vq_lengthlist__44un1__p3_0[] = {
  152383. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152384. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152385. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152386. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152387. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152388. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152389. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152390. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152391. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152392. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152393. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152394. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152395. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152396. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152397. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152398. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152399. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152400. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152401. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152402. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152403. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152404. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152405. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152406. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152407. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152408. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152409. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152410. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152411. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152412. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152413. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152414. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152415. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152416. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152417. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152418. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152419. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152420. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152421. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152422. 17,
  152423. };
  152424. static float _vq_quantthresh__44un1__p3_0[] = {
  152425. -1.5, -0.5, 0.5, 1.5,
  152426. };
  152427. static long _vq_quantmap__44un1__p3_0[] = {
  152428. 3, 1, 0, 2, 4,
  152429. };
  152430. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152431. _vq_quantthresh__44un1__p3_0,
  152432. _vq_quantmap__44un1__p3_0,
  152433. 5,
  152434. 5
  152435. };
  152436. static static_codebook _44un1__p3_0 = {
  152437. 4, 625,
  152438. _vq_lengthlist__44un1__p3_0,
  152439. 1, -533725184, 1611661312, 3, 0,
  152440. _vq_quantlist__44un1__p3_0,
  152441. NULL,
  152442. &_vq_auxt__44un1__p3_0,
  152443. NULL,
  152444. 0
  152445. };
  152446. static long _vq_quantlist__44un1__p4_0[] = {
  152447. 2,
  152448. 1,
  152449. 3,
  152450. 0,
  152451. 4,
  152452. };
  152453. static long _vq_lengthlist__44un1__p4_0[] = {
  152454. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152455. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152456. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152457. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152458. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152459. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152460. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152461. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152462. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152463. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152464. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152465. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152466. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152467. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152468. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152469. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152470. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152471. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152472. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152473. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152474. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152475. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152476. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152477. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152478. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152479. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152480. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152481. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152482. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152483. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152484. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152485. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152486. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152487. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152488. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152489. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152490. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152491. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152492. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152493. 12,
  152494. };
  152495. static float _vq_quantthresh__44un1__p4_0[] = {
  152496. -1.5, -0.5, 0.5, 1.5,
  152497. };
  152498. static long _vq_quantmap__44un1__p4_0[] = {
  152499. 3, 1, 0, 2, 4,
  152500. };
  152501. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152502. _vq_quantthresh__44un1__p4_0,
  152503. _vq_quantmap__44un1__p4_0,
  152504. 5,
  152505. 5
  152506. };
  152507. static static_codebook _44un1__p4_0 = {
  152508. 4, 625,
  152509. _vq_lengthlist__44un1__p4_0,
  152510. 1, -533725184, 1611661312, 3, 0,
  152511. _vq_quantlist__44un1__p4_0,
  152512. NULL,
  152513. &_vq_auxt__44un1__p4_0,
  152514. NULL,
  152515. 0
  152516. };
  152517. static long _vq_quantlist__44un1__p5_0[] = {
  152518. 4,
  152519. 3,
  152520. 5,
  152521. 2,
  152522. 6,
  152523. 1,
  152524. 7,
  152525. 0,
  152526. 8,
  152527. };
  152528. static long _vq_lengthlist__44un1__p5_0[] = {
  152529. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152530. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152531. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152532. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152533. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152534. 12,
  152535. };
  152536. static float _vq_quantthresh__44un1__p5_0[] = {
  152537. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152538. };
  152539. static long _vq_quantmap__44un1__p5_0[] = {
  152540. 7, 5, 3, 1, 0, 2, 4, 6,
  152541. 8,
  152542. };
  152543. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152544. _vq_quantthresh__44un1__p5_0,
  152545. _vq_quantmap__44un1__p5_0,
  152546. 9,
  152547. 9
  152548. };
  152549. static static_codebook _44un1__p5_0 = {
  152550. 2, 81,
  152551. _vq_lengthlist__44un1__p5_0,
  152552. 1, -531628032, 1611661312, 4, 0,
  152553. _vq_quantlist__44un1__p5_0,
  152554. NULL,
  152555. &_vq_auxt__44un1__p5_0,
  152556. NULL,
  152557. 0
  152558. };
  152559. static long _vq_quantlist__44un1__p6_0[] = {
  152560. 6,
  152561. 5,
  152562. 7,
  152563. 4,
  152564. 8,
  152565. 3,
  152566. 9,
  152567. 2,
  152568. 10,
  152569. 1,
  152570. 11,
  152571. 0,
  152572. 12,
  152573. };
  152574. static long _vq_lengthlist__44un1__p6_0[] = {
  152575. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152576. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152577. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152578. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152579. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152580. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152581. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152582. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152583. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152584. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152585. 16, 0,15,18,18, 0,16, 0, 0,
  152586. };
  152587. static float _vq_quantthresh__44un1__p6_0[] = {
  152588. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152589. 12.5, 17.5, 22.5, 27.5,
  152590. };
  152591. static long _vq_quantmap__44un1__p6_0[] = {
  152592. 11, 9, 7, 5, 3, 1, 0, 2,
  152593. 4, 6, 8, 10, 12,
  152594. };
  152595. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152596. _vq_quantthresh__44un1__p6_0,
  152597. _vq_quantmap__44un1__p6_0,
  152598. 13,
  152599. 13
  152600. };
  152601. static static_codebook _44un1__p6_0 = {
  152602. 2, 169,
  152603. _vq_lengthlist__44un1__p6_0,
  152604. 1, -526516224, 1616117760, 4, 0,
  152605. _vq_quantlist__44un1__p6_0,
  152606. NULL,
  152607. &_vq_auxt__44un1__p6_0,
  152608. NULL,
  152609. 0
  152610. };
  152611. static long _vq_quantlist__44un1__p6_1[] = {
  152612. 2,
  152613. 1,
  152614. 3,
  152615. 0,
  152616. 4,
  152617. };
  152618. static long _vq_lengthlist__44un1__p6_1[] = {
  152619. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152620. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152621. };
  152622. static float _vq_quantthresh__44un1__p6_1[] = {
  152623. -1.5, -0.5, 0.5, 1.5,
  152624. };
  152625. static long _vq_quantmap__44un1__p6_1[] = {
  152626. 3, 1, 0, 2, 4,
  152627. };
  152628. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152629. _vq_quantthresh__44un1__p6_1,
  152630. _vq_quantmap__44un1__p6_1,
  152631. 5,
  152632. 5
  152633. };
  152634. static static_codebook _44un1__p6_1 = {
  152635. 2, 25,
  152636. _vq_lengthlist__44un1__p6_1,
  152637. 1, -533725184, 1611661312, 3, 0,
  152638. _vq_quantlist__44un1__p6_1,
  152639. NULL,
  152640. &_vq_auxt__44un1__p6_1,
  152641. NULL,
  152642. 0
  152643. };
  152644. static long _vq_quantlist__44un1__p7_0[] = {
  152645. 2,
  152646. 1,
  152647. 3,
  152648. 0,
  152649. 4,
  152650. };
  152651. static long _vq_lengthlist__44un1__p7_0[] = {
  152652. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152653. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152655. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152659. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152667. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152669. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152670. 11,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152691. 10,
  152692. };
  152693. static float _vq_quantthresh__44un1__p7_0[] = {
  152694. -253.5, -84.5, 84.5, 253.5,
  152695. };
  152696. static long _vq_quantmap__44un1__p7_0[] = {
  152697. 3, 1, 0, 2, 4,
  152698. };
  152699. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152700. _vq_quantthresh__44un1__p7_0,
  152701. _vq_quantmap__44un1__p7_0,
  152702. 5,
  152703. 5
  152704. };
  152705. static static_codebook _44un1__p7_0 = {
  152706. 4, 625,
  152707. _vq_lengthlist__44un1__p7_0,
  152708. 1, -518709248, 1626677248, 3, 0,
  152709. _vq_quantlist__44un1__p7_0,
  152710. NULL,
  152711. &_vq_auxt__44un1__p7_0,
  152712. NULL,
  152713. 0
  152714. };
  152715. static long _vq_quantlist__44un1__p7_1[] = {
  152716. 6,
  152717. 5,
  152718. 7,
  152719. 4,
  152720. 8,
  152721. 3,
  152722. 9,
  152723. 2,
  152724. 10,
  152725. 1,
  152726. 11,
  152727. 0,
  152728. 12,
  152729. };
  152730. static long _vq_lengthlist__44un1__p7_1[] = {
  152731. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152732. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152733. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152734. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152735. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152736. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152737. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152738. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152739. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152740. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152741. 12,13,13,12,13,13,14,14,14,
  152742. };
  152743. static float _vq_quantthresh__44un1__p7_1[] = {
  152744. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152745. 32.5, 45.5, 58.5, 71.5,
  152746. };
  152747. static long _vq_quantmap__44un1__p7_1[] = {
  152748. 11, 9, 7, 5, 3, 1, 0, 2,
  152749. 4, 6, 8, 10, 12,
  152750. };
  152751. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152752. _vq_quantthresh__44un1__p7_1,
  152753. _vq_quantmap__44un1__p7_1,
  152754. 13,
  152755. 13
  152756. };
  152757. static static_codebook _44un1__p7_1 = {
  152758. 2, 169,
  152759. _vq_lengthlist__44un1__p7_1,
  152760. 1, -523010048, 1618608128, 4, 0,
  152761. _vq_quantlist__44un1__p7_1,
  152762. NULL,
  152763. &_vq_auxt__44un1__p7_1,
  152764. NULL,
  152765. 0
  152766. };
  152767. static long _vq_quantlist__44un1__p7_2[] = {
  152768. 6,
  152769. 5,
  152770. 7,
  152771. 4,
  152772. 8,
  152773. 3,
  152774. 9,
  152775. 2,
  152776. 10,
  152777. 1,
  152778. 11,
  152779. 0,
  152780. 12,
  152781. };
  152782. static long _vq_lengthlist__44un1__p7_2[] = {
  152783. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152784. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152785. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152786. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152787. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152788. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152789. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152790. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152791. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152792. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152793. 9, 9, 9,10,10,10,10,10,10,
  152794. };
  152795. static float _vq_quantthresh__44un1__p7_2[] = {
  152796. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152797. 2.5, 3.5, 4.5, 5.5,
  152798. };
  152799. static long _vq_quantmap__44un1__p7_2[] = {
  152800. 11, 9, 7, 5, 3, 1, 0, 2,
  152801. 4, 6, 8, 10, 12,
  152802. };
  152803. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152804. _vq_quantthresh__44un1__p7_2,
  152805. _vq_quantmap__44un1__p7_2,
  152806. 13,
  152807. 13
  152808. };
  152809. static static_codebook _44un1__p7_2 = {
  152810. 2, 169,
  152811. _vq_lengthlist__44un1__p7_2,
  152812. 1, -531103744, 1611661312, 4, 0,
  152813. _vq_quantlist__44un1__p7_2,
  152814. NULL,
  152815. &_vq_auxt__44un1__p7_2,
  152816. NULL,
  152817. 0
  152818. };
  152819. static long _huff_lengthlist__44un1__short[] = {
  152820. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152821. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152822. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152823. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152824. };
  152825. static static_codebook _huff_book__44un1__short = {
  152826. 2, 64,
  152827. _huff_lengthlist__44un1__short,
  152828. 0, 0, 0, 0, 0,
  152829. NULL,
  152830. NULL,
  152831. NULL,
  152832. NULL,
  152833. 0
  152834. };
  152835. /*** End of inlined file: res_books_uncoupled.h ***/
  152836. /***** residue backends *********************************************/
  152837. static vorbis_info_residue0 _residue_44_low_un={
  152838. 0,-1, -1, 8,-1,
  152839. {0},
  152840. {-1},
  152841. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152842. { -1, 25, -1, 45, -1, -1, -1}
  152843. };
  152844. static vorbis_info_residue0 _residue_44_mid_un={
  152845. 0,-1, -1, 10,-1,
  152846. /* 0 1 2 3 4 5 6 7 8 9 */
  152847. {0},
  152848. {-1},
  152849. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152850. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152851. };
  152852. static vorbis_info_residue0 _residue_44_hi_un={
  152853. 0,-1, -1, 10,-1,
  152854. /* 0 1 2 3 4 5 6 7 8 9 */
  152855. {0},
  152856. {-1},
  152857. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152858. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152859. };
  152860. /* mapping conventions:
  152861. only one submap (this would change for efficient 5.1 support for example)*/
  152862. /* Four psychoacoustic profiles are used, one for each blocktype */
  152863. static vorbis_info_mapping0 _map_nominal_u[2]={
  152864. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152865. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152866. };
  152867. static static_bookblock _resbook_44u_n1={
  152868. {
  152869. {0},
  152870. {0,0,&_44un1__p1_0},
  152871. {0,0,&_44un1__p2_0},
  152872. {0,0,&_44un1__p3_0},
  152873. {0,0,&_44un1__p4_0},
  152874. {0,0,&_44un1__p5_0},
  152875. {&_44un1__p6_0,&_44un1__p6_1},
  152876. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152877. }
  152878. };
  152879. static static_bookblock _resbook_44u_0={
  152880. {
  152881. {0},
  152882. {0,0,&_44u0__p1_0},
  152883. {0,0,&_44u0__p2_0},
  152884. {0,0,&_44u0__p3_0},
  152885. {0,0,&_44u0__p4_0},
  152886. {0,0,&_44u0__p5_0},
  152887. {&_44u0__p6_0,&_44u0__p6_1},
  152888. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152889. }
  152890. };
  152891. static static_bookblock _resbook_44u_1={
  152892. {
  152893. {0},
  152894. {0,0,&_44u1__p1_0},
  152895. {0,0,&_44u1__p2_0},
  152896. {0,0,&_44u1__p3_0},
  152897. {0,0,&_44u1__p4_0},
  152898. {0,0,&_44u1__p5_0},
  152899. {&_44u1__p6_0,&_44u1__p6_1},
  152900. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152901. }
  152902. };
  152903. static static_bookblock _resbook_44u_2={
  152904. {
  152905. {0},
  152906. {0,0,&_44u2__p1_0},
  152907. {0,0,&_44u2__p2_0},
  152908. {0,0,&_44u2__p3_0},
  152909. {0,0,&_44u2__p4_0},
  152910. {0,0,&_44u2__p5_0},
  152911. {&_44u2__p6_0,&_44u2__p6_1},
  152912. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152913. }
  152914. };
  152915. static static_bookblock _resbook_44u_3={
  152916. {
  152917. {0},
  152918. {0,0,&_44u3__p1_0},
  152919. {0,0,&_44u3__p2_0},
  152920. {0,0,&_44u3__p3_0},
  152921. {0,0,&_44u3__p4_0},
  152922. {0,0,&_44u3__p5_0},
  152923. {&_44u3__p6_0,&_44u3__p6_1},
  152924. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152925. }
  152926. };
  152927. static static_bookblock _resbook_44u_4={
  152928. {
  152929. {0},
  152930. {0,0,&_44u4__p1_0},
  152931. {0,0,&_44u4__p2_0},
  152932. {0,0,&_44u4__p3_0},
  152933. {0,0,&_44u4__p4_0},
  152934. {0,0,&_44u4__p5_0},
  152935. {&_44u4__p6_0,&_44u4__p6_1},
  152936. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152937. }
  152938. };
  152939. static static_bookblock _resbook_44u_5={
  152940. {
  152941. {0},
  152942. {0,0,&_44u5__p1_0},
  152943. {0,0,&_44u5__p2_0},
  152944. {0,0,&_44u5__p3_0},
  152945. {0,0,&_44u5__p4_0},
  152946. {0,0,&_44u5__p5_0},
  152947. {0,0,&_44u5__p6_0},
  152948. {&_44u5__p7_0,&_44u5__p7_1},
  152949. {&_44u5__p8_0,&_44u5__p8_1},
  152950. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152951. }
  152952. };
  152953. static static_bookblock _resbook_44u_6={
  152954. {
  152955. {0},
  152956. {0,0,&_44u6__p1_0},
  152957. {0,0,&_44u6__p2_0},
  152958. {0,0,&_44u6__p3_0},
  152959. {0,0,&_44u6__p4_0},
  152960. {0,0,&_44u6__p5_0},
  152961. {0,0,&_44u6__p6_0},
  152962. {&_44u6__p7_0,&_44u6__p7_1},
  152963. {&_44u6__p8_0,&_44u6__p8_1},
  152964. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152965. }
  152966. };
  152967. static static_bookblock _resbook_44u_7={
  152968. {
  152969. {0},
  152970. {0,0,&_44u7__p1_0},
  152971. {0,0,&_44u7__p2_0},
  152972. {0,0,&_44u7__p3_0},
  152973. {0,0,&_44u7__p4_0},
  152974. {0,0,&_44u7__p5_0},
  152975. {0,0,&_44u7__p6_0},
  152976. {&_44u7__p7_0,&_44u7__p7_1},
  152977. {&_44u7__p8_0,&_44u7__p8_1},
  152978. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152979. }
  152980. };
  152981. static static_bookblock _resbook_44u_8={
  152982. {
  152983. {0},
  152984. {0,0,&_44u8_p1_0},
  152985. {0,0,&_44u8_p2_0},
  152986. {0,0,&_44u8_p3_0},
  152987. {0,0,&_44u8_p4_0},
  152988. {&_44u8_p5_0,&_44u8_p5_1},
  152989. {&_44u8_p6_0,&_44u8_p6_1},
  152990. {&_44u8_p7_0,&_44u8_p7_1},
  152991. {&_44u8_p8_0,&_44u8_p8_1},
  152992. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152993. }
  152994. };
  152995. static static_bookblock _resbook_44u_9={
  152996. {
  152997. {0},
  152998. {0,0,&_44u9_p1_0},
  152999. {0,0,&_44u9_p2_0},
  153000. {0,0,&_44u9_p3_0},
  153001. {0,0,&_44u9_p4_0},
  153002. {&_44u9_p5_0,&_44u9_p5_1},
  153003. {&_44u9_p6_0,&_44u9_p6_1},
  153004. {&_44u9_p7_0,&_44u9_p7_1},
  153005. {&_44u9_p8_0,&_44u9_p8_1},
  153006. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153007. }
  153008. };
  153009. static vorbis_residue_template _res_44u_n1[]={
  153010. {1,0, &_residue_44_low_un,
  153011. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153012. &_resbook_44u_n1,&_resbook_44u_n1},
  153013. {1,0, &_residue_44_low_un,
  153014. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153015. &_resbook_44u_n1,&_resbook_44u_n1}
  153016. };
  153017. static vorbis_residue_template _res_44u_0[]={
  153018. {1,0, &_residue_44_low_un,
  153019. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153020. &_resbook_44u_0,&_resbook_44u_0},
  153021. {1,0, &_residue_44_low_un,
  153022. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153023. &_resbook_44u_0,&_resbook_44u_0}
  153024. };
  153025. static vorbis_residue_template _res_44u_1[]={
  153026. {1,0, &_residue_44_low_un,
  153027. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153028. &_resbook_44u_1,&_resbook_44u_1},
  153029. {1,0, &_residue_44_low_un,
  153030. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153031. &_resbook_44u_1,&_resbook_44u_1}
  153032. };
  153033. static vorbis_residue_template _res_44u_2[]={
  153034. {1,0, &_residue_44_low_un,
  153035. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153036. &_resbook_44u_2,&_resbook_44u_2},
  153037. {1,0, &_residue_44_low_un,
  153038. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153039. &_resbook_44u_2,&_resbook_44u_2}
  153040. };
  153041. static vorbis_residue_template _res_44u_3[]={
  153042. {1,0, &_residue_44_low_un,
  153043. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153044. &_resbook_44u_3,&_resbook_44u_3},
  153045. {1,0, &_residue_44_low_un,
  153046. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153047. &_resbook_44u_3,&_resbook_44u_3}
  153048. };
  153049. static vorbis_residue_template _res_44u_4[]={
  153050. {1,0, &_residue_44_low_un,
  153051. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153052. &_resbook_44u_4,&_resbook_44u_4},
  153053. {1,0, &_residue_44_low_un,
  153054. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153055. &_resbook_44u_4,&_resbook_44u_4}
  153056. };
  153057. static vorbis_residue_template _res_44u_5[]={
  153058. {1,0, &_residue_44_mid_un,
  153059. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153060. &_resbook_44u_5,&_resbook_44u_5},
  153061. {1,0, &_residue_44_mid_un,
  153062. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153063. &_resbook_44u_5,&_resbook_44u_5}
  153064. };
  153065. static vorbis_residue_template _res_44u_6[]={
  153066. {1,0, &_residue_44_mid_un,
  153067. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153068. &_resbook_44u_6,&_resbook_44u_6},
  153069. {1,0, &_residue_44_mid_un,
  153070. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153071. &_resbook_44u_6,&_resbook_44u_6}
  153072. };
  153073. static vorbis_residue_template _res_44u_7[]={
  153074. {1,0, &_residue_44_mid_un,
  153075. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153076. &_resbook_44u_7,&_resbook_44u_7},
  153077. {1,0, &_residue_44_mid_un,
  153078. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153079. &_resbook_44u_7,&_resbook_44u_7}
  153080. };
  153081. static vorbis_residue_template _res_44u_8[]={
  153082. {1,0, &_residue_44_hi_un,
  153083. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153084. &_resbook_44u_8,&_resbook_44u_8},
  153085. {1,0, &_residue_44_hi_un,
  153086. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153087. &_resbook_44u_8,&_resbook_44u_8}
  153088. };
  153089. static vorbis_residue_template _res_44u_9[]={
  153090. {1,0, &_residue_44_hi_un,
  153091. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153092. &_resbook_44u_9,&_resbook_44u_9},
  153093. {1,0, &_residue_44_hi_un,
  153094. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153095. &_resbook_44u_9,&_resbook_44u_9}
  153096. };
  153097. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153098. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153099. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153100. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153101. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153102. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153103. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153104. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153105. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153106. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153107. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153108. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153109. };
  153110. /*** End of inlined file: residue_44u.h ***/
  153111. static double rate_mapping_44_un[12]={
  153112. 32000.,48000.,60000.,70000.,80000.,86000.,
  153113. 96000.,110000.,120000.,140000.,160000.,240001.
  153114. };
  153115. ve_setup_data_template ve_setup_44_uncoupled={
  153116. 11,
  153117. rate_mapping_44_un,
  153118. quality_mapping_44,
  153119. -1,
  153120. 40000,
  153121. 50000,
  153122. blocksize_short_44,
  153123. blocksize_long_44,
  153124. _psy_tone_masteratt_44,
  153125. _psy_tone_0dB,
  153126. _psy_tone_suppress,
  153127. _vp_tonemask_adj_otherblock,
  153128. _vp_tonemask_adj_longblock,
  153129. _vp_tonemask_adj_otherblock,
  153130. _psy_noiseguards_44,
  153131. _psy_noisebias_impulse,
  153132. _psy_noisebias_padding,
  153133. _psy_noisebias_trans,
  153134. _psy_noisebias_long,
  153135. _psy_noise_suppress,
  153136. _psy_compand_44,
  153137. _psy_compand_short_mapping,
  153138. _psy_compand_long_mapping,
  153139. {_noise_start_short_44,_noise_start_long_44},
  153140. {_noise_part_short_44,_noise_part_long_44},
  153141. _noise_thresh_44,
  153142. _psy_ath_floater,
  153143. _psy_ath_abs,
  153144. _psy_lowpass_44,
  153145. _psy_global_44,
  153146. _global_mapping_44,
  153147. NULL,
  153148. _floor_books,
  153149. _floor,
  153150. _floor_short_mapping_44,
  153151. _floor_long_mapping_44,
  153152. _mapres_template_44_uncoupled
  153153. };
  153154. /*** End of inlined file: setup_44u.h ***/
  153155. /*** Start of inlined file: setup_32.h ***/
  153156. static double rate_mapping_32[12]={
  153157. 18000.,28000.,35000.,45000.,56000.,60000.,
  153158. 75000.,90000.,100000.,115000.,150000.,190000.,
  153159. };
  153160. static double rate_mapping_32_un[12]={
  153161. 30000.,42000.,52000.,64000.,72000.,78000.,
  153162. 86000.,92000.,110000.,120000.,140000.,190000.,
  153163. };
  153164. static double _psy_lowpass_32[12]={
  153165. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153166. };
  153167. ve_setup_data_template ve_setup_32_stereo={
  153168. 11,
  153169. rate_mapping_32,
  153170. quality_mapping_44,
  153171. 2,
  153172. 26000,
  153173. 40000,
  153174. blocksize_short_44,
  153175. blocksize_long_44,
  153176. _psy_tone_masteratt_44,
  153177. _psy_tone_0dB,
  153178. _psy_tone_suppress,
  153179. _vp_tonemask_adj_otherblock,
  153180. _vp_tonemask_adj_longblock,
  153181. _vp_tonemask_adj_otherblock,
  153182. _psy_noiseguards_44,
  153183. _psy_noisebias_impulse,
  153184. _psy_noisebias_padding,
  153185. _psy_noisebias_trans,
  153186. _psy_noisebias_long,
  153187. _psy_noise_suppress,
  153188. _psy_compand_44,
  153189. _psy_compand_short_mapping,
  153190. _psy_compand_long_mapping,
  153191. {_noise_start_short_44,_noise_start_long_44},
  153192. {_noise_part_short_44,_noise_part_long_44},
  153193. _noise_thresh_44,
  153194. _psy_ath_floater,
  153195. _psy_ath_abs,
  153196. _psy_lowpass_32,
  153197. _psy_global_44,
  153198. _global_mapping_44,
  153199. _psy_stereo_modes_44,
  153200. _floor_books,
  153201. _floor,
  153202. _floor_short_mapping_44,
  153203. _floor_long_mapping_44,
  153204. _mapres_template_44_stereo
  153205. };
  153206. ve_setup_data_template ve_setup_32_uncoupled={
  153207. 11,
  153208. rate_mapping_32_un,
  153209. quality_mapping_44,
  153210. -1,
  153211. 26000,
  153212. 40000,
  153213. blocksize_short_44,
  153214. blocksize_long_44,
  153215. _psy_tone_masteratt_44,
  153216. _psy_tone_0dB,
  153217. _psy_tone_suppress,
  153218. _vp_tonemask_adj_otherblock,
  153219. _vp_tonemask_adj_longblock,
  153220. _vp_tonemask_adj_otherblock,
  153221. _psy_noiseguards_44,
  153222. _psy_noisebias_impulse,
  153223. _psy_noisebias_padding,
  153224. _psy_noisebias_trans,
  153225. _psy_noisebias_long,
  153226. _psy_noise_suppress,
  153227. _psy_compand_44,
  153228. _psy_compand_short_mapping,
  153229. _psy_compand_long_mapping,
  153230. {_noise_start_short_44,_noise_start_long_44},
  153231. {_noise_part_short_44,_noise_part_long_44},
  153232. _noise_thresh_44,
  153233. _psy_ath_floater,
  153234. _psy_ath_abs,
  153235. _psy_lowpass_32,
  153236. _psy_global_44,
  153237. _global_mapping_44,
  153238. NULL,
  153239. _floor_books,
  153240. _floor,
  153241. _floor_short_mapping_44,
  153242. _floor_long_mapping_44,
  153243. _mapres_template_44_uncoupled
  153244. };
  153245. /*** End of inlined file: setup_32.h ***/
  153246. /*** Start of inlined file: setup_8.h ***/
  153247. /*** Start of inlined file: psych_8.h ***/
  153248. static att3 _psy_tone_masteratt_8[3]={
  153249. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153250. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153251. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153252. };
  153253. static vp_adjblock _vp_tonemask_adj_8[3]={
  153254. /* adjust for mode zero */
  153255. /* 63 125 250 500 1 2 4 8 16 */
  153256. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153257. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153258. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153259. };
  153260. static noise3 _psy_noisebias_8[3]={
  153261. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153262. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153263. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153264. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153265. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153266. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153267. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153268. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153269. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153270. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153271. };
  153272. /* stereo mode by base quality level */
  153273. static adj_stereo _psy_stereo_modes_8[3]={
  153274. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153275. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153276. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153277. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153278. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153279. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153280. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153281. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153282. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153283. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153284. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153285. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153286. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153287. };
  153288. static noiseguard _psy_noiseguards_8[2]={
  153289. {10,10,-1},
  153290. {10,10,-1},
  153291. };
  153292. static compandblock _psy_compand_8[2]={
  153293. {{
  153294. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153295. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153296. 12,12,13,13,14,14,15, 15, /* 23dB */
  153297. 16,16,17,17,17,18,18, 19, /* 31dB */
  153298. 19,19,20,21,22,23,24, 25, /* 39dB */
  153299. }},
  153300. {{
  153301. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153302. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153303. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153304. 9,10,11,12,13,14,15, 16, /* 31dB */
  153305. 17,18,19,20,21,22,23, 24, /* 39dB */
  153306. }},
  153307. };
  153308. static double _psy_lowpass_8[3]={3.,4.,4.};
  153309. static int _noise_start_8[2]={
  153310. 64,64,
  153311. };
  153312. static int _noise_part_8[2]={
  153313. 8,8,
  153314. };
  153315. static int _psy_ath_floater_8[3]={
  153316. -100,-100,-105,
  153317. };
  153318. static int _psy_ath_abs_8[3]={
  153319. -130,-130,-140,
  153320. };
  153321. /*** End of inlined file: psych_8.h ***/
  153322. /*** Start of inlined file: residue_8.h ***/
  153323. /***** residue backends *********************************************/
  153324. static static_bookblock _resbook_8s_0={
  153325. {
  153326. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153327. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153328. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153329. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153330. }
  153331. };
  153332. static static_bookblock _resbook_8s_1={
  153333. {
  153334. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153335. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153336. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153337. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153338. }
  153339. };
  153340. static vorbis_residue_template _res_8s_0[]={
  153341. {2,0, &_residue_44_mid,
  153342. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153343. &_resbook_8s_0,&_resbook_8s_0},
  153344. };
  153345. static vorbis_residue_template _res_8s_1[]={
  153346. {2,0, &_residue_44_mid,
  153347. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153348. &_resbook_8s_1,&_resbook_8s_1},
  153349. };
  153350. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153351. { _map_nominal, _res_8s_0 }, /* 0 */
  153352. { _map_nominal, _res_8s_1 }, /* 1 */
  153353. };
  153354. static static_bookblock _resbook_8u_0={
  153355. {
  153356. {0},
  153357. {0,0,&_8u0__p1_0},
  153358. {0,0,&_8u0__p2_0},
  153359. {0,0,&_8u0__p3_0},
  153360. {0,0,&_8u0__p4_0},
  153361. {0,0,&_8u0__p5_0},
  153362. {&_8u0__p6_0,&_8u0__p6_1},
  153363. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153364. }
  153365. };
  153366. static static_bookblock _resbook_8u_1={
  153367. {
  153368. {0},
  153369. {0,0,&_8u1__p1_0},
  153370. {0,0,&_8u1__p2_0},
  153371. {0,0,&_8u1__p3_0},
  153372. {0,0,&_8u1__p4_0},
  153373. {0,0,&_8u1__p5_0},
  153374. {0,0,&_8u1__p6_0},
  153375. {&_8u1__p7_0,&_8u1__p7_1},
  153376. {&_8u1__p8_0,&_8u1__p8_1},
  153377. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153378. }
  153379. };
  153380. static vorbis_residue_template _res_8u_0[]={
  153381. {1,0, &_residue_44_low_un,
  153382. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153383. &_resbook_8u_0,&_resbook_8u_0},
  153384. };
  153385. static vorbis_residue_template _res_8u_1[]={
  153386. {1,0, &_residue_44_mid_un,
  153387. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153388. &_resbook_8u_1,&_resbook_8u_1},
  153389. };
  153390. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153391. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153392. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153393. };
  153394. /*** End of inlined file: residue_8.h ***/
  153395. static int blocksize_8[2]={
  153396. 512,512
  153397. };
  153398. static int _floor_mapping_8[2]={
  153399. 6,6,
  153400. };
  153401. static double rate_mapping_8[3]={
  153402. 6000.,9000.,32000.,
  153403. };
  153404. static double rate_mapping_8_uncoupled[3]={
  153405. 8000.,14000.,42000.,
  153406. };
  153407. static double quality_mapping_8[3]={
  153408. -.1,.0,1.
  153409. };
  153410. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153411. static double _global_mapping_8[3]={ 1., 2., 3. };
  153412. ve_setup_data_template ve_setup_8_stereo={
  153413. 2,
  153414. rate_mapping_8,
  153415. quality_mapping_8,
  153416. 2,
  153417. 8000,
  153418. 9000,
  153419. blocksize_8,
  153420. blocksize_8,
  153421. _psy_tone_masteratt_8,
  153422. _psy_tone_0dB,
  153423. _psy_tone_suppress,
  153424. _vp_tonemask_adj_8,
  153425. NULL,
  153426. _vp_tonemask_adj_8,
  153427. _psy_noiseguards_8,
  153428. _psy_noisebias_8,
  153429. _psy_noisebias_8,
  153430. NULL,
  153431. NULL,
  153432. _psy_noise_suppress,
  153433. _psy_compand_8,
  153434. _psy_compand_8_mapping,
  153435. NULL,
  153436. {_noise_start_8,_noise_start_8},
  153437. {_noise_part_8,_noise_part_8},
  153438. _noise_thresh_5only,
  153439. _psy_ath_floater_8,
  153440. _psy_ath_abs_8,
  153441. _psy_lowpass_8,
  153442. _psy_global_44,
  153443. _global_mapping_8,
  153444. _psy_stereo_modes_8,
  153445. _floor_books,
  153446. _floor,
  153447. _floor_mapping_8,
  153448. NULL,
  153449. _mapres_template_8_stereo
  153450. };
  153451. ve_setup_data_template ve_setup_8_uncoupled={
  153452. 2,
  153453. rate_mapping_8_uncoupled,
  153454. quality_mapping_8,
  153455. -1,
  153456. 8000,
  153457. 9000,
  153458. blocksize_8,
  153459. blocksize_8,
  153460. _psy_tone_masteratt_8,
  153461. _psy_tone_0dB,
  153462. _psy_tone_suppress,
  153463. _vp_tonemask_adj_8,
  153464. NULL,
  153465. _vp_tonemask_adj_8,
  153466. _psy_noiseguards_8,
  153467. _psy_noisebias_8,
  153468. _psy_noisebias_8,
  153469. NULL,
  153470. NULL,
  153471. _psy_noise_suppress,
  153472. _psy_compand_8,
  153473. _psy_compand_8_mapping,
  153474. NULL,
  153475. {_noise_start_8,_noise_start_8},
  153476. {_noise_part_8,_noise_part_8},
  153477. _noise_thresh_5only,
  153478. _psy_ath_floater_8,
  153479. _psy_ath_abs_8,
  153480. _psy_lowpass_8,
  153481. _psy_global_44,
  153482. _global_mapping_8,
  153483. _psy_stereo_modes_8,
  153484. _floor_books,
  153485. _floor,
  153486. _floor_mapping_8,
  153487. NULL,
  153488. _mapres_template_8_uncoupled
  153489. };
  153490. /*** End of inlined file: setup_8.h ***/
  153491. /*** Start of inlined file: setup_11.h ***/
  153492. /*** Start of inlined file: psych_11.h ***/
  153493. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153494. static att3 _psy_tone_masteratt_11[3]={
  153495. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153496. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153497. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153498. };
  153499. static vp_adjblock _vp_tonemask_adj_11[3]={
  153500. /* adjust for mode zero */
  153501. /* 63 125 250 500 1 2 4 8 16 */
  153502. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153503. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153504. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153505. };
  153506. static noise3 _psy_noisebias_11[3]={
  153507. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153508. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153509. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153510. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153511. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153512. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153513. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153514. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153515. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153516. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153517. };
  153518. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153519. /*** End of inlined file: psych_11.h ***/
  153520. static int blocksize_11[2]={
  153521. 512,512
  153522. };
  153523. static int _floor_mapping_11[2]={
  153524. 6,6,
  153525. };
  153526. static double rate_mapping_11[3]={
  153527. 8000.,13000.,44000.,
  153528. };
  153529. static double rate_mapping_11_uncoupled[3]={
  153530. 12000.,20000.,50000.,
  153531. };
  153532. static double quality_mapping_11[3]={
  153533. -.1,.0,1.
  153534. };
  153535. ve_setup_data_template ve_setup_11_stereo={
  153536. 2,
  153537. rate_mapping_11,
  153538. quality_mapping_11,
  153539. 2,
  153540. 9000,
  153541. 15000,
  153542. blocksize_11,
  153543. blocksize_11,
  153544. _psy_tone_masteratt_11,
  153545. _psy_tone_0dB,
  153546. _psy_tone_suppress,
  153547. _vp_tonemask_adj_11,
  153548. NULL,
  153549. _vp_tonemask_adj_11,
  153550. _psy_noiseguards_8,
  153551. _psy_noisebias_11,
  153552. _psy_noisebias_11,
  153553. NULL,
  153554. NULL,
  153555. _psy_noise_suppress,
  153556. _psy_compand_8,
  153557. _psy_compand_8_mapping,
  153558. NULL,
  153559. {_noise_start_8,_noise_start_8},
  153560. {_noise_part_8,_noise_part_8},
  153561. _noise_thresh_11,
  153562. _psy_ath_floater_8,
  153563. _psy_ath_abs_8,
  153564. _psy_lowpass_11,
  153565. _psy_global_44,
  153566. _global_mapping_8,
  153567. _psy_stereo_modes_8,
  153568. _floor_books,
  153569. _floor,
  153570. _floor_mapping_11,
  153571. NULL,
  153572. _mapres_template_8_stereo
  153573. };
  153574. ve_setup_data_template ve_setup_11_uncoupled={
  153575. 2,
  153576. rate_mapping_11_uncoupled,
  153577. quality_mapping_11,
  153578. -1,
  153579. 9000,
  153580. 15000,
  153581. blocksize_11,
  153582. blocksize_11,
  153583. _psy_tone_masteratt_11,
  153584. _psy_tone_0dB,
  153585. _psy_tone_suppress,
  153586. _vp_tonemask_adj_11,
  153587. NULL,
  153588. _vp_tonemask_adj_11,
  153589. _psy_noiseguards_8,
  153590. _psy_noisebias_11,
  153591. _psy_noisebias_11,
  153592. NULL,
  153593. NULL,
  153594. _psy_noise_suppress,
  153595. _psy_compand_8,
  153596. _psy_compand_8_mapping,
  153597. NULL,
  153598. {_noise_start_8,_noise_start_8},
  153599. {_noise_part_8,_noise_part_8},
  153600. _noise_thresh_11,
  153601. _psy_ath_floater_8,
  153602. _psy_ath_abs_8,
  153603. _psy_lowpass_11,
  153604. _psy_global_44,
  153605. _global_mapping_8,
  153606. _psy_stereo_modes_8,
  153607. _floor_books,
  153608. _floor,
  153609. _floor_mapping_11,
  153610. NULL,
  153611. _mapres_template_8_uncoupled
  153612. };
  153613. /*** End of inlined file: setup_11.h ***/
  153614. /*** Start of inlined file: setup_16.h ***/
  153615. /*** Start of inlined file: psych_16.h ***/
  153616. /* stereo mode by base quality level */
  153617. static adj_stereo _psy_stereo_modes_16[4]={
  153618. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153619. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153620. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153621. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153622. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153623. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153624. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153625. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153626. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153627. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153628. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153629. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153630. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153631. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153632. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153633. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153634. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153635. };
  153636. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153637. static att3 _psy_tone_masteratt_16[4]={
  153638. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153639. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153640. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153641. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153642. };
  153643. static vp_adjblock _vp_tonemask_adj_16[4]={
  153644. /* adjust for mode zero */
  153645. /* 63 125 250 500 1 2 4 8 16 */
  153646. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153647. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153648. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153649. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153650. };
  153651. static noise3 _psy_noisebias_16_short[4]={
  153652. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153653. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153654. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153655. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153656. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153657. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153658. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153659. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153660. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153661. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153662. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153663. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153664. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153665. };
  153666. static noise3 _psy_noisebias_16_impulse[4]={
  153667. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153668. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153669. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153670. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153671. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153672. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153673. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153674. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153675. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153676. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153677. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153678. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153679. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153680. };
  153681. static noise3 _psy_noisebias_16[4]={
  153682. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153683. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153684. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153685. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153686. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153687. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153688. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153689. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153690. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153691. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153692. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153693. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153694. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153695. };
  153696. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153697. static int _noise_start_16[3]={ 256,256,9999 };
  153698. static int _noise_part_16[4]={ 8,8,8,8 };
  153699. static int _psy_ath_floater_16[4]={
  153700. -100,-100,-100,-105,
  153701. };
  153702. static int _psy_ath_abs_16[4]={
  153703. -130,-130,-130,-140,
  153704. };
  153705. /*** End of inlined file: psych_16.h ***/
  153706. /*** Start of inlined file: residue_16.h ***/
  153707. /***** residue backends *********************************************/
  153708. static static_bookblock _resbook_16s_0={
  153709. {
  153710. {0},
  153711. {0,0,&_16c0_s_p1_0},
  153712. {0,0,&_16c0_s_p2_0},
  153713. {0,0,&_16c0_s_p3_0},
  153714. {0,0,&_16c0_s_p4_0},
  153715. {0,0,&_16c0_s_p5_0},
  153716. {0,0,&_16c0_s_p6_0},
  153717. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153718. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153719. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153720. }
  153721. };
  153722. static static_bookblock _resbook_16s_1={
  153723. {
  153724. {0},
  153725. {0,0,&_16c1_s_p1_0},
  153726. {0,0,&_16c1_s_p2_0},
  153727. {0,0,&_16c1_s_p3_0},
  153728. {0,0,&_16c1_s_p4_0},
  153729. {0,0,&_16c1_s_p5_0},
  153730. {0,0,&_16c1_s_p6_0},
  153731. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153732. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153733. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153734. }
  153735. };
  153736. static static_bookblock _resbook_16s_2={
  153737. {
  153738. {0},
  153739. {0,0,&_16c2_s_p1_0},
  153740. {0,0,&_16c2_s_p2_0},
  153741. {0,0,&_16c2_s_p3_0},
  153742. {0,0,&_16c2_s_p4_0},
  153743. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153744. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153745. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153746. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153747. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153748. }
  153749. };
  153750. static vorbis_residue_template _res_16s_0[]={
  153751. {2,0, &_residue_44_mid,
  153752. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153753. &_resbook_16s_0,&_resbook_16s_0},
  153754. };
  153755. static vorbis_residue_template _res_16s_1[]={
  153756. {2,0, &_residue_44_mid,
  153757. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153758. &_resbook_16s_1,&_resbook_16s_1},
  153759. {2,0, &_residue_44_mid,
  153760. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153761. &_resbook_16s_1,&_resbook_16s_1}
  153762. };
  153763. static vorbis_residue_template _res_16s_2[]={
  153764. {2,0, &_residue_44_high,
  153765. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153766. &_resbook_16s_2,&_resbook_16s_2},
  153767. {2,0, &_residue_44_high,
  153768. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153769. &_resbook_16s_2,&_resbook_16s_2}
  153770. };
  153771. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153772. { _map_nominal, _res_16s_0 }, /* 0 */
  153773. { _map_nominal, _res_16s_1 }, /* 1 */
  153774. { _map_nominal, _res_16s_2 }, /* 2 */
  153775. };
  153776. static static_bookblock _resbook_16u_0={
  153777. {
  153778. {0},
  153779. {0,0,&_16u0__p1_0},
  153780. {0,0,&_16u0__p2_0},
  153781. {0,0,&_16u0__p3_0},
  153782. {0,0,&_16u0__p4_0},
  153783. {0,0,&_16u0__p5_0},
  153784. {&_16u0__p6_0,&_16u0__p6_1},
  153785. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153786. }
  153787. };
  153788. static static_bookblock _resbook_16u_1={
  153789. {
  153790. {0},
  153791. {0,0,&_16u1__p1_0},
  153792. {0,0,&_16u1__p2_0},
  153793. {0,0,&_16u1__p3_0},
  153794. {0,0,&_16u1__p4_0},
  153795. {0,0,&_16u1__p5_0},
  153796. {0,0,&_16u1__p6_0},
  153797. {&_16u1__p7_0,&_16u1__p7_1},
  153798. {&_16u1__p8_0,&_16u1__p8_1},
  153799. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153800. }
  153801. };
  153802. static static_bookblock _resbook_16u_2={
  153803. {
  153804. {0},
  153805. {0,0,&_16u2_p1_0},
  153806. {0,0,&_16u2_p2_0},
  153807. {0,0,&_16u2_p3_0},
  153808. {0,0,&_16u2_p4_0},
  153809. {&_16u2_p5_0,&_16u2_p5_1},
  153810. {&_16u2_p6_0,&_16u2_p6_1},
  153811. {&_16u2_p7_0,&_16u2_p7_1},
  153812. {&_16u2_p8_0,&_16u2_p8_1},
  153813. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153814. }
  153815. };
  153816. static vorbis_residue_template _res_16u_0[]={
  153817. {1,0, &_residue_44_low_un,
  153818. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153819. &_resbook_16u_0,&_resbook_16u_0},
  153820. };
  153821. static vorbis_residue_template _res_16u_1[]={
  153822. {1,0, &_residue_44_mid_un,
  153823. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153824. &_resbook_16u_1,&_resbook_16u_1},
  153825. {1,0, &_residue_44_mid_un,
  153826. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153827. &_resbook_16u_1,&_resbook_16u_1}
  153828. };
  153829. static vorbis_residue_template _res_16u_2[]={
  153830. {1,0, &_residue_44_hi_un,
  153831. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153832. &_resbook_16u_2,&_resbook_16u_2},
  153833. {1,0, &_residue_44_hi_un,
  153834. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153835. &_resbook_16u_2,&_resbook_16u_2}
  153836. };
  153837. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153838. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153839. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153840. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153841. };
  153842. /*** End of inlined file: residue_16.h ***/
  153843. static int blocksize_16_short[3]={
  153844. 1024,512,512
  153845. };
  153846. static int blocksize_16_long[3]={
  153847. 1024,1024,1024
  153848. };
  153849. static int _floor_mapping_16_short[3]={
  153850. 9,3,3
  153851. };
  153852. static int _floor_mapping_16[3]={
  153853. 9,9,9
  153854. };
  153855. static double rate_mapping_16[4]={
  153856. 12000.,20000.,44000.,86000.
  153857. };
  153858. static double rate_mapping_16_uncoupled[4]={
  153859. 16000.,28000.,64000.,100000.
  153860. };
  153861. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153862. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153863. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153864. ve_setup_data_template ve_setup_16_stereo={
  153865. 3,
  153866. rate_mapping_16,
  153867. quality_mapping_16,
  153868. 2,
  153869. 15000,
  153870. 19000,
  153871. blocksize_16_short,
  153872. blocksize_16_long,
  153873. _psy_tone_masteratt_16,
  153874. _psy_tone_0dB,
  153875. _psy_tone_suppress,
  153876. _vp_tonemask_adj_16,
  153877. _vp_tonemask_adj_16,
  153878. _vp_tonemask_adj_16,
  153879. _psy_noiseguards_8,
  153880. _psy_noisebias_16_impulse,
  153881. _psy_noisebias_16_short,
  153882. _psy_noisebias_16_short,
  153883. _psy_noisebias_16,
  153884. _psy_noise_suppress,
  153885. _psy_compand_8,
  153886. _psy_compand_16_mapping,
  153887. _psy_compand_16_mapping,
  153888. {_noise_start_16,_noise_start_16},
  153889. { _noise_part_16, _noise_part_16},
  153890. _noise_thresh_16,
  153891. _psy_ath_floater_16,
  153892. _psy_ath_abs_16,
  153893. _psy_lowpass_16,
  153894. _psy_global_44,
  153895. _global_mapping_16,
  153896. _psy_stereo_modes_16,
  153897. _floor_books,
  153898. _floor,
  153899. _floor_mapping_16_short,
  153900. _floor_mapping_16,
  153901. _mapres_template_16_stereo
  153902. };
  153903. ve_setup_data_template ve_setup_16_uncoupled={
  153904. 3,
  153905. rate_mapping_16_uncoupled,
  153906. quality_mapping_16,
  153907. -1,
  153908. 15000,
  153909. 19000,
  153910. blocksize_16_short,
  153911. blocksize_16_long,
  153912. _psy_tone_masteratt_16,
  153913. _psy_tone_0dB,
  153914. _psy_tone_suppress,
  153915. _vp_tonemask_adj_16,
  153916. _vp_tonemask_adj_16,
  153917. _vp_tonemask_adj_16,
  153918. _psy_noiseguards_8,
  153919. _psy_noisebias_16_impulse,
  153920. _psy_noisebias_16_short,
  153921. _psy_noisebias_16_short,
  153922. _psy_noisebias_16,
  153923. _psy_noise_suppress,
  153924. _psy_compand_8,
  153925. _psy_compand_16_mapping,
  153926. _psy_compand_16_mapping,
  153927. {_noise_start_16,_noise_start_16},
  153928. { _noise_part_16, _noise_part_16},
  153929. _noise_thresh_16,
  153930. _psy_ath_floater_16,
  153931. _psy_ath_abs_16,
  153932. _psy_lowpass_16,
  153933. _psy_global_44,
  153934. _global_mapping_16,
  153935. _psy_stereo_modes_16,
  153936. _floor_books,
  153937. _floor,
  153938. _floor_mapping_16_short,
  153939. _floor_mapping_16,
  153940. _mapres_template_16_uncoupled
  153941. };
  153942. /*** End of inlined file: setup_16.h ***/
  153943. /*** Start of inlined file: setup_22.h ***/
  153944. static double rate_mapping_22[4]={
  153945. 15000.,20000.,44000.,86000.
  153946. };
  153947. static double rate_mapping_22_uncoupled[4]={
  153948. 16000.,28000.,50000.,90000.
  153949. };
  153950. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153951. ve_setup_data_template ve_setup_22_stereo={
  153952. 3,
  153953. rate_mapping_22,
  153954. quality_mapping_16,
  153955. 2,
  153956. 19000,
  153957. 26000,
  153958. blocksize_16_short,
  153959. blocksize_16_long,
  153960. _psy_tone_masteratt_16,
  153961. _psy_tone_0dB,
  153962. _psy_tone_suppress,
  153963. _vp_tonemask_adj_16,
  153964. _vp_tonemask_adj_16,
  153965. _vp_tonemask_adj_16,
  153966. _psy_noiseguards_8,
  153967. _psy_noisebias_16_impulse,
  153968. _psy_noisebias_16_short,
  153969. _psy_noisebias_16_short,
  153970. _psy_noisebias_16,
  153971. _psy_noise_suppress,
  153972. _psy_compand_8,
  153973. _psy_compand_8_mapping,
  153974. _psy_compand_8_mapping,
  153975. {_noise_start_16,_noise_start_16},
  153976. { _noise_part_16, _noise_part_16},
  153977. _noise_thresh_16,
  153978. _psy_ath_floater_16,
  153979. _psy_ath_abs_16,
  153980. _psy_lowpass_22,
  153981. _psy_global_44,
  153982. _global_mapping_16,
  153983. _psy_stereo_modes_16,
  153984. _floor_books,
  153985. _floor,
  153986. _floor_mapping_16_short,
  153987. _floor_mapping_16,
  153988. _mapres_template_16_stereo
  153989. };
  153990. ve_setup_data_template ve_setup_22_uncoupled={
  153991. 3,
  153992. rate_mapping_22_uncoupled,
  153993. quality_mapping_16,
  153994. -1,
  153995. 19000,
  153996. 26000,
  153997. blocksize_16_short,
  153998. blocksize_16_long,
  153999. _psy_tone_masteratt_16,
  154000. _psy_tone_0dB,
  154001. _psy_tone_suppress,
  154002. _vp_tonemask_adj_16,
  154003. _vp_tonemask_adj_16,
  154004. _vp_tonemask_adj_16,
  154005. _psy_noiseguards_8,
  154006. _psy_noisebias_16_impulse,
  154007. _psy_noisebias_16_short,
  154008. _psy_noisebias_16_short,
  154009. _psy_noisebias_16,
  154010. _psy_noise_suppress,
  154011. _psy_compand_8,
  154012. _psy_compand_8_mapping,
  154013. _psy_compand_8_mapping,
  154014. {_noise_start_16,_noise_start_16},
  154015. { _noise_part_16, _noise_part_16},
  154016. _noise_thresh_16,
  154017. _psy_ath_floater_16,
  154018. _psy_ath_abs_16,
  154019. _psy_lowpass_22,
  154020. _psy_global_44,
  154021. _global_mapping_16,
  154022. _psy_stereo_modes_16,
  154023. _floor_books,
  154024. _floor,
  154025. _floor_mapping_16_short,
  154026. _floor_mapping_16,
  154027. _mapres_template_16_uncoupled
  154028. };
  154029. /*** End of inlined file: setup_22.h ***/
  154030. /*** Start of inlined file: setup_X.h ***/
  154031. static double rate_mapping_X[12]={
  154032. -1.,-1.,-1.,-1.,-1.,-1.,
  154033. -1.,-1.,-1.,-1.,-1.,-1.
  154034. };
  154035. ve_setup_data_template ve_setup_X_stereo={
  154036. 11,
  154037. rate_mapping_X,
  154038. quality_mapping_44,
  154039. 2,
  154040. 50000,
  154041. 200000,
  154042. blocksize_short_44,
  154043. blocksize_long_44,
  154044. _psy_tone_masteratt_44,
  154045. _psy_tone_0dB,
  154046. _psy_tone_suppress,
  154047. _vp_tonemask_adj_otherblock,
  154048. _vp_tonemask_adj_longblock,
  154049. _vp_tonemask_adj_otherblock,
  154050. _psy_noiseguards_44,
  154051. _psy_noisebias_impulse,
  154052. _psy_noisebias_padding,
  154053. _psy_noisebias_trans,
  154054. _psy_noisebias_long,
  154055. _psy_noise_suppress,
  154056. _psy_compand_44,
  154057. _psy_compand_short_mapping,
  154058. _psy_compand_long_mapping,
  154059. {_noise_start_short_44,_noise_start_long_44},
  154060. {_noise_part_short_44,_noise_part_long_44},
  154061. _noise_thresh_44,
  154062. _psy_ath_floater,
  154063. _psy_ath_abs,
  154064. _psy_lowpass_44,
  154065. _psy_global_44,
  154066. _global_mapping_44,
  154067. _psy_stereo_modes_44,
  154068. _floor_books,
  154069. _floor,
  154070. _floor_short_mapping_44,
  154071. _floor_long_mapping_44,
  154072. _mapres_template_44_stereo
  154073. };
  154074. ve_setup_data_template ve_setup_X_uncoupled={
  154075. 11,
  154076. rate_mapping_X,
  154077. quality_mapping_44,
  154078. -1,
  154079. 50000,
  154080. 200000,
  154081. blocksize_short_44,
  154082. blocksize_long_44,
  154083. _psy_tone_masteratt_44,
  154084. _psy_tone_0dB,
  154085. _psy_tone_suppress,
  154086. _vp_tonemask_adj_otherblock,
  154087. _vp_tonemask_adj_longblock,
  154088. _vp_tonemask_adj_otherblock,
  154089. _psy_noiseguards_44,
  154090. _psy_noisebias_impulse,
  154091. _psy_noisebias_padding,
  154092. _psy_noisebias_trans,
  154093. _psy_noisebias_long,
  154094. _psy_noise_suppress,
  154095. _psy_compand_44,
  154096. _psy_compand_short_mapping,
  154097. _psy_compand_long_mapping,
  154098. {_noise_start_short_44,_noise_start_long_44},
  154099. {_noise_part_short_44,_noise_part_long_44},
  154100. _noise_thresh_44,
  154101. _psy_ath_floater,
  154102. _psy_ath_abs,
  154103. _psy_lowpass_44,
  154104. _psy_global_44,
  154105. _global_mapping_44,
  154106. NULL,
  154107. _floor_books,
  154108. _floor,
  154109. _floor_short_mapping_44,
  154110. _floor_long_mapping_44,
  154111. _mapres_template_44_uncoupled
  154112. };
  154113. ve_setup_data_template ve_setup_XX_stereo={
  154114. 2,
  154115. rate_mapping_X,
  154116. quality_mapping_8,
  154117. 2,
  154118. 0,
  154119. 8000,
  154120. blocksize_8,
  154121. blocksize_8,
  154122. _psy_tone_masteratt_8,
  154123. _psy_tone_0dB,
  154124. _psy_tone_suppress,
  154125. _vp_tonemask_adj_8,
  154126. NULL,
  154127. _vp_tonemask_adj_8,
  154128. _psy_noiseguards_8,
  154129. _psy_noisebias_8,
  154130. _psy_noisebias_8,
  154131. NULL,
  154132. NULL,
  154133. _psy_noise_suppress,
  154134. _psy_compand_8,
  154135. _psy_compand_8_mapping,
  154136. NULL,
  154137. {_noise_start_8,_noise_start_8},
  154138. {_noise_part_8,_noise_part_8},
  154139. _noise_thresh_5only,
  154140. _psy_ath_floater_8,
  154141. _psy_ath_abs_8,
  154142. _psy_lowpass_8,
  154143. _psy_global_44,
  154144. _global_mapping_8,
  154145. _psy_stereo_modes_8,
  154146. _floor_books,
  154147. _floor,
  154148. _floor_mapping_8,
  154149. NULL,
  154150. _mapres_template_8_stereo
  154151. };
  154152. ve_setup_data_template ve_setup_XX_uncoupled={
  154153. 2,
  154154. rate_mapping_X,
  154155. quality_mapping_8,
  154156. -1,
  154157. 0,
  154158. 8000,
  154159. blocksize_8,
  154160. blocksize_8,
  154161. _psy_tone_masteratt_8,
  154162. _psy_tone_0dB,
  154163. _psy_tone_suppress,
  154164. _vp_tonemask_adj_8,
  154165. NULL,
  154166. _vp_tonemask_adj_8,
  154167. _psy_noiseguards_8,
  154168. _psy_noisebias_8,
  154169. _psy_noisebias_8,
  154170. NULL,
  154171. NULL,
  154172. _psy_noise_suppress,
  154173. _psy_compand_8,
  154174. _psy_compand_8_mapping,
  154175. NULL,
  154176. {_noise_start_8,_noise_start_8},
  154177. {_noise_part_8,_noise_part_8},
  154178. _noise_thresh_5only,
  154179. _psy_ath_floater_8,
  154180. _psy_ath_abs_8,
  154181. _psy_lowpass_8,
  154182. _psy_global_44,
  154183. _global_mapping_8,
  154184. _psy_stereo_modes_8,
  154185. _floor_books,
  154186. _floor,
  154187. _floor_mapping_8,
  154188. NULL,
  154189. _mapres_template_8_uncoupled
  154190. };
  154191. /*** End of inlined file: setup_X.h ***/
  154192. static ve_setup_data_template *setup_list[]={
  154193. &ve_setup_44_stereo,
  154194. &ve_setup_44_uncoupled,
  154195. &ve_setup_32_stereo,
  154196. &ve_setup_32_uncoupled,
  154197. &ve_setup_22_stereo,
  154198. &ve_setup_22_uncoupled,
  154199. &ve_setup_16_stereo,
  154200. &ve_setup_16_uncoupled,
  154201. &ve_setup_11_stereo,
  154202. &ve_setup_11_uncoupled,
  154203. &ve_setup_8_stereo,
  154204. &ve_setup_8_uncoupled,
  154205. &ve_setup_X_stereo,
  154206. &ve_setup_X_uncoupled,
  154207. &ve_setup_XX_stereo,
  154208. &ve_setup_XX_uncoupled,
  154209. 0
  154210. };
  154211. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154212. if(vi && vi->codec_setup){
  154213. vi->version=0;
  154214. vi->channels=ch;
  154215. vi->rate=rate;
  154216. return(0);
  154217. }
  154218. return(OV_EINVAL);
  154219. }
  154220. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154221. static_codebook ***books,
  154222. vorbis_info_floor1 *in,
  154223. int *x){
  154224. int i,k,is=s;
  154225. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154226. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154227. memcpy(f,in+x[is],sizeof(*f));
  154228. /* fill in the lowpass field, even if it's temporary */
  154229. f->n=ci->blocksizes[block]>>1;
  154230. /* books */
  154231. {
  154232. int partitions=f->partitions;
  154233. int maxclass=-1;
  154234. int maxbook=-1;
  154235. for(i=0;i<partitions;i++)
  154236. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154237. for(i=0;i<=maxclass;i++){
  154238. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154239. f->class_book[i]+=ci->books;
  154240. for(k=0;k<(1<<f->class_subs[i]);k++){
  154241. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154242. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154243. }
  154244. }
  154245. for(i=0;i<=maxbook;i++)
  154246. ci->book_param[ci->books++]=books[x[is]][i];
  154247. }
  154248. /* for now, we're only using floor 1 */
  154249. ci->floor_type[ci->floors]=1;
  154250. ci->floor_param[ci->floors]=f;
  154251. ci->floors++;
  154252. return;
  154253. }
  154254. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154255. vorbis_info_psy_global *in,
  154256. double *x){
  154257. int i,is=s;
  154258. double ds=s-is;
  154259. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154260. vorbis_info_psy_global *g=&ci->psy_g_param;
  154261. memcpy(g,in+(int)x[is],sizeof(*g));
  154262. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154263. is=(int)ds;
  154264. ds-=is;
  154265. if(ds==0 && is>0){
  154266. is--;
  154267. ds=1.;
  154268. }
  154269. /* interpolate the trigger threshholds */
  154270. for(i=0;i<4;i++){
  154271. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154272. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154273. }
  154274. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154275. return;
  154276. }
  154277. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154278. highlevel_encode_setup *hi,
  154279. adj_stereo *p){
  154280. float s=hi->stereo_point_setting;
  154281. int i,is=s;
  154282. double ds=s-is;
  154283. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154284. vorbis_info_psy_global *g=&ci->psy_g_param;
  154285. if(p){
  154286. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154287. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154288. if(hi->managed){
  154289. /* interpolate the kHz threshholds */
  154290. for(i=0;i<PACKETBLOBS;i++){
  154291. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154292. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154293. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154294. g->coupling_pkHz[i]=kHz;
  154295. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154296. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154297. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154298. }
  154299. }else{
  154300. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154301. for(i=0;i<PACKETBLOBS;i++){
  154302. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154303. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154304. g->coupling_pkHz[i]=kHz;
  154305. }
  154306. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154307. for(i=0;i<PACKETBLOBS;i++){
  154308. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154309. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154310. }
  154311. }
  154312. }else{
  154313. for(i=0;i<PACKETBLOBS;i++){
  154314. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154315. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154316. }
  154317. }
  154318. return;
  154319. }
  154320. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154321. int *nn_start,
  154322. int *nn_partition,
  154323. double *nn_thresh,
  154324. int block){
  154325. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154326. vorbis_info_psy *p=ci->psy_param[block];
  154327. highlevel_encode_setup *hi=&ci->hi;
  154328. int is=s;
  154329. if(block>=ci->psys)
  154330. ci->psys=block+1;
  154331. if(!p){
  154332. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154333. ci->psy_param[block]=p;
  154334. }
  154335. memcpy(p,&_psy_info_template,sizeof(*p));
  154336. p->blockflag=block>>1;
  154337. if(hi->noise_normalize_p){
  154338. p->normal_channel_p=1;
  154339. p->normal_point_p=1;
  154340. p->normal_start=nn_start[is];
  154341. p->normal_partition=nn_partition[is];
  154342. p->normal_thresh=nn_thresh[is];
  154343. }
  154344. return;
  154345. }
  154346. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154347. att3 *att,
  154348. int *max,
  154349. vp_adjblock *in){
  154350. int i,is=s;
  154351. double ds=s-is;
  154352. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154353. vorbis_info_psy *p=ci->psy_param[block];
  154354. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154355. filling the values in here */
  154356. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154357. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154358. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154359. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154360. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154361. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154362. for(i=0;i<P_BANDS;i++)
  154363. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154364. return;
  154365. }
  154366. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154367. compandblock *in, double *x){
  154368. int i,is=s;
  154369. double ds=s-is;
  154370. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154371. vorbis_info_psy *p=ci->psy_param[block];
  154372. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154373. is=(int)ds;
  154374. ds-=is;
  154375. if(ds==0 && is>0){
  154376. is--;
  154377. ds=1.;
  154378. }
  154379. /* interpolate the compander settings */
  154380. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154381. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154382. return;
  154383. }
  154384. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154385. int *suppress){
  154386. int is=s;
  154387. double ds=s-is;
  154388. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154389. vorbis_info_psy *p=ci->psy_param[block];
  154390. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154391. return;
  154392. }
  154393. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154394. int *suppress,
  154395. noise3 *in,
  154396. noiseguard *guard,
  154397. double userbias){
  154398. int i,is=s,j;
  154399. double ds=s-is;
  154400. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154401. vorbis_info_psy *p=ci->psy_param[block];
  154402. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154403. p->noisewindowlomin=guard[block].lo;
  154404. p->noisewindowhimin=guard[block].hi;
  154405. p->noisewindowfixed=guard[block].fixed;
  154406. for(j=0;j<P_NOISECURVES;j++)
  154407. for(i=0;i<P_BANDS;i++)
  154408. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154409. /* impulse blocks may take a user specified bias to boost the
  154410. nominal/high noise encoding depth */
  154411. for(j=0;j<P_NOISECURVES;j++){
  154412. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154413. for(i=0;i<P_BANDS;i++){
  154414. p->noiseoff[j][i]+=userbias;
  154415. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154416. }
  154417. }
  154418. return;
  154419. }
  154420. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154421. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154422. vorbis_info_psy *p=ci->psy_param[block];
  154423. p->ath_adjatt=ci->hi.ath_floating_dB;
  154424. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154425. return;
  154426. }
  154427. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154428. int i;
  154429. for(i=0;i<ci->books;i++)
  154430. if(ci->book_param[i]==book)return(i);
  154431. return(ci->books++);
  154432. }
  154433. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154434. int *shortb,int *longb){
  154435. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154436. int is=s;
  154437. int blockshort=shortb[is];
  154438. int blocklong=longb[is];
  154439. ci->blocksizes[0]=blockshort;
  154440. ci->blocksizes[1]=blocklong;
  154441. }
  154442. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154443. int number, int block,
  154444. vorbis_residue_template *res){
  154445. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154446. int i,n;
  154447. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154448. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154449. memcpy(r,res->res,sizeof(*r));
  154450. if(ci->residues<=number)ci->residues=number+1;
  154451. switch(ci->blocksizes[block]){
  154452. case 64:case 128:case 256:
  154453. r->grouping=16;
  154454. break;
  154455. default:
  154456. r->grouping=32;
  154457. break;
  154458. }
  154459. ci->residue_type[number]=res->res_type;
  154460. /* to be adjusted by lowpass/pointlimit later */
  154461. n=r->end=ci->blocksizes[block]>>1;
  154462. if(res->res_type==2)
  154463. n=r->end*=vi->channels;
  154464. /* fill in all the books */
  154465. {
  154466. int booklist=0,k;
  154467. if(ci->hi.managed){
  154468. for(i=0;i<r->partitions;i++)
  154469. for(k=0;k<3;k++)
  154470. if(res->books_base_managed->books[i][k])
  154471. r->secondstages[i]|=(1<<k);
  154472. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154473. ci->book_param[r->groupbook]=res->book_aux_managed;
  154474. for(i=0;i<r->partitions;i++){
  154475. for(k=0;k<3;k++){
  154476. if(res->books_base_managed->books[i][k]){
  154477. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154478. r->booklist[booklist++]=bookid;
  154479. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154480. }
  154481. }
  154482. }
  154483. }else{
  154484. for(i=0;i<r->partitions;i++)
  154485. for(k=0;k<3;k++)
  154486. if(res->books_base->books[i][k])
  154487. r->secondstages[i]|=(1<<k);
  154488. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154489. ci->book_param[r->groupbook]=res->book_aux;
  154490. for(i=0;i<r->partitions;i++){
  154491. for(k=0;k<3;k++){
  154492. if(res->books_base->books[i][k]){
  154493. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154494. r->booklist[booklist++]=bookid;
  154495. ci->book_param[bookid]=res->books_base->books[i][k];
  154496. }
  154497. }
  154498. }
  154499. }
  154500. }
  154501. /* lowpass setup/pointlimit */
  154502. {
  154503. double freq=ci->hi.lowpass_kHz*1000.;
  154504. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154505. double nyq=vi->rate/2.;
  154506. long blocksize=ci->blocksizes[block]>>1;
  154507. /* lowpass needs to be set in the floor and the residue. */
  154508. if(freq>nyq)freq=nyq;
  154509. /* in the floor, the granularity can be very fine; it doesn't alter
  154510. the encoding structure, only the samples used to fit the floor
  154511. approximation */
  154512. f->n=freq/nyq*blocksize;
  154513. /* this res may by limited by the maximum pointlimit of the mode,
  154514. not the lowpass. the floor is always lowpass limited. */
  154515. if(res->limit_type){
  154516. if(ci->hi.managed)
  154517. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154518. else
  154519. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154520. if(freq>nyq)freq=nyq;
  154521. }
  154522. /* in the residue, we're constrained, physically, by partition
  154523. boundaries. We still lowpass 'wherever', but we have to round up
  154524. here to next boundary, or the vorbis spec will round it *down* to
  154525. previous boundary in encode/decode */
  154526. if(ci->residue_type[block]==2)
  154527. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154528. r->grouping;
  154529. else
  154530. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154531. r->grouping;
  154532. }
  154533. }
  154534. /* we assume two maps in this encoder */
  154535. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154536. vorbis_mapping_template *maps){
  154537. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154538. int i,j,is=s,modes=2;
  154539. vorbis_info_mapping0 *map=maps[is].map;
  154540. vorbis_info_mode *mode=_mode_template;
  154541. vorbis_residue_template *res=maps[is].res;
  154542. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154543. for(i=0;i<modes;i++){
  154544. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154545. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154546. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154547. if(i>=ci->modes)ci->modes=i+1;
  154548. ci->map_type[i]=0;
  154549. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154550. if(i>=ci->maps)ci->maps=i+1;
  154551. for(j=0;j<map[i].submaps;j++)
  154552. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154553. ,res+map[i].residuesubmap[j]);
  154554. }
  154555. }
  154556. static double setting_to_approx_bitrate(vorbis_info *vi){
  154557. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154558. highlevel_encode_setup *hi=&ci->hi;
  154559. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154560. int is=hi->base_setting;
  154561. double ds=hi->base_setting-is;
  154562. int ch=vi->channels;
  154563. double *r=setup->rate_mapping;
  154564. if(r==NULL)
  154565. return(-1);
  154566. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154567. }
  154568. static void get_setup_template(vorbis_info *vi,
  154569. long ch,long srate,
  154570. double req,int q_or_bitrate){
  154571. int i=0,j;
  154572. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154573. highlevel_encode_setup *hi=&ci->hi;
  154574. if(q_or_bitrate)req/=ch;
  154575. while(setup_list[i]){
  154576. if(setup_list[i]->coupling_restriction==-1 ||
  154577. setup_list[i]->coupling_restriction==ch){
  154578. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154579. srate<=setup_list[i]->samplerate_max_restriction){
  154580. int mappings=setup_list[i]->mappings;
  154581. double *map=(q_or_bitrate?
  154582. setup_list[i]->rate_mapping:
  154583. setup_list[i]->quality_mapping);
  154584. /* the template matches. Does the requested quality mode
  154585. fall within this template's modes? */
  154586. if(req<map[0]){++i;continue;}
  154587. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154588. for(j=0;j<mappings;j++)
  154589. if(req>=map[j] && req<map[j+1])break;
  154590. /* an all-points match */
  154591. hi->setup=setup_list[i];
  154592. if(j==mappings)
  154593. hi->base_setting=j-.001;
  154594. else{
  154595. float low=map[j];
  154596. float high=map[j+1];
  154597. float del=(req-low)/(high-low);
  154598. hi->base_setting=j+del;
  154599. }
  154600. return;
  154601. }
  154602. }
  154603. i++;
  154604. }
  154605. hi->setup=NULL;
  154606. }
  154607. /* encoders will need to use vorbis_info_init beforehand and call
  154608. vorbis_info clear when all done */
  154609. /* two interfaces; this, more detailed one, and later a convenience
  154610. layer on top */
  154611. /* the final setup call */
  154612. int vorbis_encode_setup_init(vorbis_info *vi){
  154613. int i0=0,singleblock=0;
  154614. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154615. ve_setup_data_template *setup=NULL;
  154616. highlevel_encode_setup *hi=&ci->hi;
  154617. if(ci==NULL)return(OV_EINVAL);
  154618. if(!hi->impulse_block_p)i0=1;
  154619. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154620. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154621. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154622. /* again, bound this to avoid the app shooting itself int he foot
  154623. too badly */
  154624. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154625. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154626. /* get the appropriate setup template; matches the fetch in previous
  154627. stages */
  154628. setup=(ve_setup_data_template *)hi->setup;
  154629. if(setup==NULL)return(OV_EINVAL);
  154630. hi->set_in_stone=1;
  154631. /* choose block sizes from configured sizes as well as paying
  154632. attention to long_block_p and short_block_p. If the configured
  154633. short and long blocks are the same length, we set long_block_p
  154634. and unset short_block_p */
  154635. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154636. setup->blocksize_short,
  154637. setup->blocksize_long);
  154638. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154639. /* floor setup; choose proper floor params. Allocated on the floor
  154640. stack in order; if we alloc only long floor, it's 0 */
  154641. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154642. setup->floor_books,
  154643. setup->floor_params,
  154644. setup->floor_short_mapping);
  154645. if(!singleblock)
  154646. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154647. setup->floor_books,
  154648. setup->floor_params,
  154649. setup->floor_long_mapping);
  154650. /* setup of [mostly] short block detection and stereo*/
  154651. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154652. setup->global_params,
  154653. setup->global_mapping);
  154654. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154655. /* basic psych setup and noise normalization */
  154656. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154657. setup->psy_noise_normal_start[0],
  154658. setup->psy_noise_normal_partition[0],
  154659. setup->psy_noise_normal_thresh,
  154660. 0);
  154661. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154662. setup->psy_noise_normal_start[0],
  154663. setup->psy_noise_normal_partition[0],
  154664. setup->psy_noise_normal_thresh,
  154665. 1);
  154666. if(!singleblock){
  154667. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154668. setup->psy_noise_normal_start[1],
  154669. setup->psy_noise_normal_partition[1],
  154670. setup->psy_noise_normal_thresh,
  154671. 2);
  154672. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154673. setup->psy_noise_normal_start[1],
  154674. setup->psy_noise_normal_partition[1],
  154675. setup->psy_noise_normal_thresh,
  154676. 3);
  154677. }
  154678. /* tone masking setup */
  154679. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154680. setup->psy_tone_masteratt,
  154681. setup->psy_tone_0dB,
  154682. setup->psy_tone_adj_impulse);
  154683. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154684. setup->psy_tone_masteratt,
  154685. setup->psy_tone_0dB,
  154686. setup->psy_tone_adj_other);
  154687. if(!singleblock){
  154688. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154689. setup->psy_tone_masteratt,
  154690. setup->psy_tone_0dB,
  154691. setup->psy_tone_adj_other);
  154692. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154693. setup->psy_tone_masteratt,
  154694. setup->psy_tone_0dB,
  154695. setup->psy_tone_adj_long);
  154696. }
  154697. /* noise companding setup */
  154698. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154699. setup->psy_noise_compand,
  154700. setup->psy_noise_compand_short_mapping);
  154701. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154702. setup->psy_noise_compand,
  154703. setup->psy_noise_compand_short_mapping);
  154704. if(!singleblock){
  154705. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154706. setup->psy_noise_compand,
  154707. setup->psy_noise_compand_long_mapping);
  154708. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154709. setup->psy_noise_compand,
  154710. setup->psy_noise_compand_long_mapping);
  154711. }
  154712. /* peak guarding setup */
  154713. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154714. setup->psy_tone_dBsuppress);
  154715. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154716. setup->psy_tone_dBsuppress);
  154717. if(!singleblock){
  154718. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154719. setup->psy_tone_dBsuppress);
  154720. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154721. setup->psy_tone_dBsuppress);
  154722. }
  154723. /* noise bias setup */
  154724. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154725. setup->psy_noise_dBsuppress,
  154726. setup->psy_noise_bias_impulse,
  154727. setup->psy_noiseguards,
  154728. (i0==0?hi->impulse_noisetune:0.));
  154729. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154730. setup->psy_noise_dBsuppress,
  154731. setup->psy_noise_bias_padding,
  154732. setup->psy_noiseguards,0.);
  154733. if(!singleblock){
  154734. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154735. setup->psy_noise_dBsuppress,
  154736. setup->psy_noise_bias_trans,
  154737. setup->psy_noiseguards,0.);
  154738. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154739. setup->psy_noise_dBsuppress,
  154740. setup->psy_noise_bias_long,
  154741. setup->psy_noiseguards,0.);
  154742. }
  154743. vorbis_encode_ath_setup(vi,0);
  154744. vorbis_encode_ath_setup(vi,1);
  154745. if(!singleblock){
  154746. vorbis_encode_ath_setup(vi,2);
  154747. vorbis_encode_ath_setup(vi,3);
  154748. }
  154749. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154750. /* set bitrate readonlies and management */
  154751. if(hi->bitrate_av>0)
  154752. vi->bitrate_nominal=hi->bitrate_av;
  154753. else{
  154754. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154755. }
  154756. vi->bitrate_lower=hi->bitrate_min;
  154757. vi->bitrate_upper=hi->bitrate_max;
  154758. if(hi->bitrate_av)
  154759. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154760. else
  154761. vi->bitrate_window=0.;
  154762. if(hi->managed){
  154763. ci->bi.avg_rate=hi->bitrate_av;
  154764. ci->bi.min_rate=hi->bitrate_min;
  154765. ci->bi.max_rate=hi->bitrate_max;
  154766. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154767. ci->bi.reservoir_bias=
  154768. hi->bitrate_reservoir_bias;
  154769. ci->bi.slew_damp=hi->bitrate_av_damp;
  154770. }
  154771. return(0);
  154772. }
  154773. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154774. long channels,
  154775. long rate){
  154776. int ret=0,i,is;
  154777. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154778. highlevel_encode_setup *hi=&ci->hi;
  154779. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154780. double ds;
  154781. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154782. if(ret)return(ret);
  154783. is=hi->base_setting;
  154784. ds=hi->base_setting-is;
  154785. hi->short_setting=hi->base_setting;
  154786. hi->long_setting=hi->base_setting;
  154787. hi->managed=0;
  154788. hi->impulse_block_p=1;
  154789. hi->noise_normalize_p=1;
  154790. hi->stereo_point_setting=hi->base_setting;
  154791. hi->lowpass_kHz=
  154792. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154793. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154794. setup->psy_ath_float[is+1]*ds;
  154795. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154796. setup->psy_ath_abs[is+1]*ds;
  154797. hi->amplitude_track_dBpersec=-6.;
  154798. hi->trigger_setting=hi->base_setting;
  154799. for(i=0;i<4;i++){
  154800. hi->block[i].tone_mask_setting=hi->base_setting;
  154801. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154802. hi->block[i].noise_bias_setting=hi->base_setting;
  154803. hi->block[i].noise_compand_setting=hi->base_setting;
  154804. }
  154805. return(ret);
  154806. }
  154807. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154808. long channels,
  154809. long rate,
  154810. float quality){
  154811. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154812. highlevel_encode_setup *hi=&ci->hi;
  154813. quality+=.0000001;
  154814. if(quality>=1.)quality=.9999;
  154815. get_setup_template(vi,channels,rate,quality,0);
  154816. if(!hi->setup)return OV_EIMPL;
  154817. return vorbis_encode_setup_setting(vi,channels,rate);
  154818. }
  154819. int vorbis_encode_init_vbr(vorbis_info *vi,
  154820. long channels,
  154821. long rate,
  154822. float base_quality /* 0. to 1. */
  154823. ){
  154824. int ret=0;
  154825. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154826. if(ret){
  154827. vorbis_info_clear(vi);
  154828. return ret;
  154829. }
  154830. ret=vorbis_encode_setup_init(vi);
  154831. if(ret)
  154832. vorbis_info_clear(vi);
  154833. return(ret);
  154834. }
  154835. int vorbis_encode_setup_managed(vorbis_info *vi,
  154836. long channels,
  154837. long rate,
  154838. long max_bitrate,
  154839. long nominal_bitrate,
  154840. long min_bitrate){
  154841. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154842. highlevel_encode_setup *hi=&ci->hi;
  154843. double tnominal=nominal_bitrate;
  154844. int ret=0;
  154845. if(nominal_bitrate<=0.){
  154846. if(max_bitrate>0.){
  154847. if(min_bitrate>0.)
  154848. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154849. else
  154850. nominal_bitrate=max_bitrate*.875;
  154851. }else{
  154852. if(min_bitrate>0.){
  154853. nominal_bitrate=min_bitrate;
  154854. }else{
  154855. return(OV_EINVAL);
  154856. }
  154857. }
  154858. }
  154859. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154860. if(!hi->setup)return OV_EIMPL;
  154861. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154862. if(ret){
  154863. vorbis_info_clear(vi);
  154864. return ret;
  154865. }
  154866. /* initialize management with sane defaults */
  154867. hi->managed=1;
  154868. hi->bitrate_min=min_bitrate;
  154869. hi->bitrate_max=max_bitrate;
  154870. hi->bitrate_av=tnominal;
  154871. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154872. hi->bitrate_reservoir=nominal_bitrate*2;
  154873. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154874. return(ret);
  154875. }
  154876. int vorbis_encode_init(vorbis_info *vi,
  154877. long channels,
  154878. long rate,
  154879. long max_bitrate,
  154880. long nominal_bitrate,
  154881. long min_bitrate){
  154882. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154883. max_bitrate,
  154884. nominal_bitrate,
  154885. min_bitrate);
  154886. if(ret){
  154887. vorbis_info_clear(vi);
  154888. return(ret);
  154889. }
  154890. ret=vorbis_encode_setup_init(vi);
  154891. if(ret)
  154892. vorbis_info_clear(vi);
  154893. return(ret);
  154894. }
  154895. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154896. if(vi){
  154897. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154898. highlevel_encode_setup *hi=&ci->hi;
  154899. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154900. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154901. switch(number){
  154902. /* now deprecated *****************/
  154903. case OV_ECTL_RATEMANAGE_GET:
  154904. {
  154905. struct ovectl_ratemanage_arg *ai=
  154906. (struct ovectl_ratemanage_arg *)arg;
  154907. ai->management_active=hi->managed;
  154908. ai->bitrate_hard_window=ai->bitrate_av_window=
  154909. (double)hi->bitrate_reservoir/vi->rate;
  154910. ai->bitrate_av_window_center=1.;
  154911. ai->bitrate_hard_min=hi->bitrate_min;
  154912. ai->bitrate_hard_max=hi->bitrate_max;
  154913. ai->bitrate_av_lo=hi->bitrate_av;
  154914. ai->bitrate_av_hi=hi->bitrate_av;
  154915. }
  154916. return(0);
  154917. /* now deprecated *****************/
  154918. case OV_ECTL_RATEMANAGE_SET:
  154919. {
  154920. struct ovectl_ratemanage_arg *ai=
  154921. (struct ovectl_ratemanage_arg *)arg;
  154922. if(ai==NULL){
  154923. hi->managed=0;
  154924. }else{
  154925. hi->managed=ai->management_active;
  154926. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154927. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154928. }
  154929. }
  154930. return 0;
  154931. /* now deprecated *****************/
  154932. case OV_ECTL_RATEMANAGE_AVG:
  154933. {
  154934. struct ovectl_ratemanage_arg *ai=
  154935. (struct ovectl_ratemanage_arg *)arg;
  154936. if(ai==NULL){
  154937. hi->bitrate_av=0;
  154938. }else{
  154939. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154940. }
  154941. }
  154942. return(0);
  154943. /* now deprecated *****************/
  154944. case OV_ECTL_RATEMANAGE_HARD:
  154945. {
  154946. struct ovectl_ratemanage_arg *ai=
  154947. (struct ovectl_ratemanage_arg *)arg;
  154948. if(ai==NULL){
  154949. hi->bitrate_min=0;
  154950. hi->bitrate_max=0;
  154951. }else{
  154952. hi->bitrate_min=ai->bitrate_hard_min;
  154953. hi->bitrate_max=ai->bitrate_hard_max;
  154954. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154955. (hi->bitrate_max+hi->bitrate_min)*.5;
  154956. }
  154957. if(hi->bitrate_reservoir<128.)
  154958. hi->bitrate_reservoir=128.;
  154959. }
  154960. return(0);
  154961. /* replacement ratemanage interface */
  154962. case OV_ECTL_RATEMANAGE2_GET:
  154963. {
  154964. struct ovectl_ratemanage2_arg *ai=
  154965. (struct ovectl_ratemanage2_arg *)arg;
  154966. if(ai==NULL)return OV_EINVAL;
  154967. ai->management_active=hi->managed;
  154968. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154969. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154970. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154971. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154972. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154973. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154974. }
  154975. return (0);
  154976. case OV_ECTL_RATEMANAGE2_SET:
  154977. {
  154978. struct ovectl_ratemanage2_arg *ai=
  154979. (struct ovectl_ratemanage2_arg *)arg;
  154980. if(ai==NULL){
  154981. hi->managed=0;
  154982. }else{
  154983. /* sanity check; only catch invariant violations */
  154984. if(ai->bitrate_limit_min_kbps>0 &&
  154985. ai->bitrate_average_kbps>0 &&
  154986. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154987. return OV_EINVAL;
  154988. if(ai->bitrate_limit_max_kbps>0 &&
  154989. ai->bitrate_average_kbps>0 &&
  154990. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154991. return OV_EINVAL;
  154992. if(ai->bitrate_limit_min_kbps>0 &&
  154993. ai->bitrate_limit_max_kbps>0 &&
  154994. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154995. return OV_EINVAL;
  154996. if(ai->bitrate_average_damping <= 0.)
  154997. return OV_EINVAL;
  154998. if(ai->bitrate_limit_reservoir_bits < 0)
  154999. return OV_EINVAL;
  155000. if(ai->bitrate_limit_reservoir_bias < 0.)
  155001. return OV_EINVAL;
  155002. if(ai->bitrate_limit_reservoir_bias > 1.)
  155003. return OV_EINVAL;
  155004. hi->managed=ai->management_active;
  155005. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155006. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155007. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155008. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155009. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155010. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155011. }
  155012. }
  155013. return 0;
  155014. case OV_ECTL_LOWPASS_GET:
  155015. {
  155016. double *farg=(double *)arg;
  155017. *farg=hi->lowpass_kHz;
  155018. }
  155019. return(0);
  155020. case OV_ECTL_LOWPASS_SET:
  155021. {
  155022. double *farg=(double *)arg;
  155023. hi->lowpass_kHz=*farg;
  155024. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155025. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155026. }
  155027. return(0);
  155028. case OV_ECTL_IBLOCK_GET:
  155029. {
  155030. double *farg=(double *)arg;
  155031. *farg=hi->impulse_noisetune;
  155032. }
  155033. return(0);
  155034. case OV_ECTL_IBLOCK_SET:
  155035. {
  155036. double *farg=(double *)arg;
  155037. hi->impulse_noisetune=*farg;
  155038. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155039. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155040. }
  155041. return(0);
  155042. }
  155043. return(OV_EIMPL);
  155044. }
  155045. return(OV_EINVAL);
  155046. }
  155047. #endif
  155048. /*** End of inlined file: vorbisenc.c ***/
  155049. /*** Start of inlined file: vorbisfile.c ***/
  155050. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155051. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155052. // tasks..
  155053. #if JUCE_MSVC
  155054. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155055. #endif
  155056. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155057. #if JUCE_USE_OGGVORBIS
  155058. #include <stdlib.h>
  155059. #include <stdio.h>
  155060. #include <errno.h>
  155061. #include <string.h>
  155062. #include <math.h>
  155063. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155064. one logical bitstream arranged end to end (the only form of Ogg
  155065. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155066. multiplexing] is not allowed in Vorbis) */
  155067. /* A Vorbis file can be played beginning to end (streamed) without
  155068. worrying ahead of time about chaining (see decoder_example.c). If
  155069. we have the whole file, however, and want random access
  155070. (seeking/scrubbing) or desire to know the total length/time of a
  155071. file, we need to account for the possibility of chaining. */
  155072. /* We can handle things a number of ways; we can determine the entire
  155073. bitstream structure right off the bat, or find pieces on demand.
  155074. This example determines and caches structure for the entire
  155075. bitstream, but builds a virtual decoder on the fly when moving
  155076. between links in the chain. */
  155077. /* There are also different ways to implement seeking. Enough
  155078. information exists in an Ogg bitstream to seek to
  155079. sample-granularity positions in the output. Or, one can seek by
  155080. picking some portion of the stream roughly in the desired area if
  155081. we only want coarse navigation through the stream. */
  155082. /*************************************************************************
  155083. * Many, many internal helpers. The intention is not to be confusing;
  155084. * rampant duplication and monolithic function implementation would be
  155085. * harder to understand anyway. The high level functions are last. Begin
  155086. * grokking near the end of the file */
  155087. /* read a little more data from the file/pipe into the ogg_sync framer
  155088. */
  155089. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155090. over 8k gets what they deserve */
  155091. static long _get_data(OggVorbis_File *vf){
  155092. errno=0;
  155093. if(vf->datasource){
  155094. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155095. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155096. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155097. if(bytes==0 && errno)return(-1);
  155098. return(bytes);
  155099. }else
  155100. return(0);
  155101. }
  155102. /* save a tiny smidge of verbosity to make the code more readable */
  155103. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155104. if(vf->datasource){
  155105. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155106. vf->offset=offset;
  155107. ogg_sync_reset(&vf->oy);
  155108. }else{
  155109. /* shouldn't happen unless someone writes a broken callback */
  155110. return;
  155111. }
  155112. }
  155113. /* The read/seek functions track absolute position within the stream */
  155114. /* from the head of the stream, get the next page. boundary specifies
  155115. if the function is allowed to fetch more data from the stream (and
  155116. how much) or only use internally buffered data.
  155117. boundary: -1) unbounded search
  155118. 0) read no additional data; use cached only
  155119. n) search for a new page beginning for n bytes
  155120. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155121. n) found a page at absolute offset n */
  155122. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155123. ogg_int64_t boundary){
  155124. if(boundary>0)boundary+=vf->offset;
  155125. while(1){
  155126. long more;
  155127. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155128. more=ogg_sync_pageseek(&vf->oy,og);
  155129. if(more<0){
  155130. /* skipped n bytes */
  155131. vf->offset-=more;
  155132. }else{
  155133. if(more==0){
  155134. /* send more paramedics */
  155135. if(!boundary)return(OV_FALSE);
  155136. {
  155137. long ret=_get_data(vf);
  155138. if(ret==0)return(OV_EOF);
  155139. if(ret<0)return(OV_EREAD);
  155140. }
  155141. }else{
  155142. /* got a page. Return the offset at the page beginning,
  155143. advance the internal offset past the page end */
  155144. ogg_int64_t ret=vf->offset;
  155145. vf->offset+=more;
  155146. return(ret);
  155147. }
  155148. }
  155149. }
  155150. }
  155151. /* find the latest page beginning before the current stream cursor
  155152. position. Much dirtier than the above as Ogg doesn't have any
  155153. backward search linkage. no 'readp' as it will certainly have to
  155154. read. */
  155155. /* returns offset or OV_EREAD, OV_FAULT */
  155156. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155157. ogg_int64_t begin=vf->offset;
  155158. ogg_int64_t end=begin;
  155159. ogg_int64_t ret;
  155160. ogg_int64_t offset=-1;
  155161. while(offset==-1){
  155162. begin-=CHUNKSIZE;
  155163. if(begin<0)
  155164. begin=0;
  155165. _seek_helper(vf,begin);
  155166. while(vf->offset<end){
  155167. ret=_get_next_page(vf,og,end-vf->offset);
  155168. if(ret==OV_EREAD)return(OV_EREAD);
  155169. if(ret<0){
  155170. break;
  155171. }else{
  155172. offset=ret;
  155173. }
  155174. }
  155175. }
  155176. /* we have the offset. Actually snork and hold the page now */
  155177. _seek_helper(vf,offset);
  155178. ret=_get_next_page(vf,og,CHUNKSIZE);
  155179. if(ret<0)
  155180. /* this shouldn't be possible */
  155181. return(OV_EFAULT);
  155182. return(offset);
  155183. }
  155184. /* finds each bitstream link one at a time using a bisection search
  155185. (has to begin by knowing the offset of the lb's initial page).
  155186. Recurses for each link so it can alloc the link storage after
  155187. finding them all, then unroll and fill the cache at the same time */
  155188. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155189. ogg_int64_t begin,
  155190. ogg_int64_t searched,
  155191. ogg_int64_t end,
  155192. long currentno,
  155193. long m){
  155194. ogg_int64_t endsearched=end;
  155195. ogg_int64_t next=end;
  155196. ogg_page og;
  155197. ogg_int64_t ret;
  155198. /* the below guards against garbage seperating the last and
  155199. first pages of two links. */
  155200. while(searched<endsearched){
  155201. ogg_int64_t bisect;
  155202. if(endsearched-searched<CHUNKSIZE){
  155203. bisect=searched;
  155204. }else{
  155205. bisect=(searched+endsearched)/2;
  155206. }
  155207. _seek_helper(vf,bisect);
  155208. ret=_get_next_page(vf,&og,-1);
  155209. if(ret==OV_EREAD)return(OV_EREAD);
  155210. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155211. endsearched=bisect;
  155212. if(ret>=0)next=ret;
  155213. }else{
  155214. searched=ret+og.header_len+og.body_len;
  155215. }
  155216. }
  155217. _seek_helper(vf,next);
  155218. ret=_get_next_page(vf,&og,-1);
  155219. if(ret==OV_EREAD)return(OV_EREAD);
  155220. if(searched>=end || ret<0){
  155221. vf->links=m+1;
  155222. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155223. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155224. vf->offsets[m+1]=searched;
  155225. }else{
  155226. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155227. end,ogg_page_serialno(&og),m+1);
  155228. if(ret==OV_EREAD)return(OV_EREAD);
  155229. }
  155230. vf->offsets[m]=begin;
  155231. vf->serialnos[m]=currentno;
  155232. return(0);
  155233. }
  155234. /* uses the local ogg_stream storage in vf; this is important for
  155235. non-streaming input sources */
  155236. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155237. long *serialno,ogg_page *og_ptr){
  155238. ogg_page og;
  155239. ogg_packet op;
  155240. int i,ret;
  155241. if(!og_ptr){
  155242. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155243. if(llret==OV_EREAD)return(OV_EREAD);
  155244. if(llret<0)return OV_ENOTVORBIS;
  155245. og_ptr=&og;
  155246. }
  155247. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155248. if(serialno)*serialno=vf->os.serialno;
  155249. vf->ready_state=STREAMSET;
  155250. /* extract the initial header from the first page and verify that the
  155251. Ogg bitstream is in fact Vorbis data */
  155252. vorbis_info_init(vi);
  155253. vorbis_comment_init(vc);
  155254. i=0;
  155255. while(i<3){
  155256. ogg_stream_pagein(&vf->os,og_ptr);
  155257. while(i<3){
  155258. int result=ogg_stream_packetout(&vf->os,&op);
  155259. if(result==0)break;
  155260. if(result==-1){
  155261. ret=OV_EBADHEADER;
  155262. goto bail_header;
  155263. }
  155264. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155265. goto bail_header;
  155266. }
  155267. i++;
  155268. }
  155269. if(i<3)
  155270. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155271. ret=OV_EBADHEADER;
  155272. goto bail_header;
  155273. }
  155274. }
  155275. return 0;
  155276. bail_header:
  155277. vorbis_info_clear(vi);
  155278. vorbis_comment_clear(vc);
  155279. vf->ready_state=OPENED;
  155280. return ret;
  155281. }
  155282. /* last step of the OggVorbis_File initialization; get all the
  155283. vorbis_info structs and PCM positions. Only called by the seekable
  155284. initialization (local stream storage is hacked slightly; pay
  155285. attention to how that's done) */
  155286. /* this is void and does not propogate errors up because we want to be
  155287. able to open and use damaged bitstreams as well as we can. Just
  155288. watch out for missing information for links in the OggVorbis_File
  155289. struct */
  155290. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155291. ogg_page og;
  155292. int i;
  155293. ogg_int64_t ret;
  155294. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155295. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155296. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155297. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155298. for(i=0;i<vf->links;i++){
  155299. if(i==0){
  155300. /* we already grabbed the initial header earlier. Just set the offset */
  155301. vf->dataoffsets[i]=dataoffset;
  155302. _seek_helper(vf,dataoffset);
  155303. }else{
  155304. /* seek to the location of the initial header */
  155305. _seek_helper(vf,vf->offsets[i]);
  155306. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155307. vf->dataoffsets[i]=-1;
  155308. }else{
  155309. vf->dataoffsets[i]=vf->offset;
  155310. }
  155311. }
  155312. /* fetch beginning PCM offset */
  155313. if(vf->dataoffsets[i]!=-1){
  155314. ogg_int64_t accumulated=0;
  155315. long lastblock=-1;
  155316. int result;
  155317. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155318. while(1){
  155319. ogg_packet op;
  155320. ret=_get_next_page(vf,&og,-1);
  155321. if(ret<0)
  155322. /* this should not be possible unless the file is
  155323. truncated/mangled */
  155324. break;
  155325. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155326. break;
  155327. /* count blocksizes of all frames in the page */
  155328. ogg_stream_pagein(&vf->os,&og);
  155329. while((result=ogg_stream_packetout(&vf->os,&op))){
  155330. if(result>0){ /* ignore holes */
  155331. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155332. if(lastblock!=-1)
  155333. accumulated+=(lastblock+thisblock)>>2;
  155334. lastblock=thisblock;
  155335. }
  155336. }
  155337. if(ogg_page_granulepos(&og)!=-1){
  155338. /* pcm offset of last packet on the first audio page */
  155339. accumulated= ogg_page_granulepos(&og)-accumulated;
  155340. break;
  155341. }
  155342. }
  155343. /* less than zero? This is a stream with samples trimmed off
  155344. the beginning, a normal occurrence; set the offset to zero */
  155345. if(accumulated<0)accumulated=0;
  155346. vf->pcmlengths[i*2]=accumulated;
  155347. }
  155348. /* get the PCM length of this link. To do this,
  155349. get the last page of the stream */
  155350. {
  155351. ogg_int64_t end=vf->offsets[i+1];
  155352. _seek_helper(vf,end);
  155353. while(1){
  155354. ret=_get_prev_page(vf,&og);
  155355. if(ret<0){
  155356. /* this should not be possible */
  155357. vorbis_info_clear(vf->vi+i);
  155358. vorbis_comment_clear(vf->vc+i);
  155359. break;
  155360. }
  155361. if(ogg_page_granulepos(&og)!=-1){
  155362. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155363. break;
  155364. }
  155365. vf->offset=ret;
  155366. }
  155367. }
  155368. }
  155369. }
  155370. static int _make_decode_ready(OggVorbis_File *vf){
  155371. if(vf->ready_state>STREAMSET)return 0;
  155372. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155373. if(vf->seekable){
  155374. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155375. return OV_EBADLINK;
  155376. }else{
  155377. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155378. return OV_EBADLINK;
  155379. }
  155380. vorbis_block_init(&vf->vd,&vf->vb);
  155381. vf->ready_state=INITSET;
  155382. vf->bittrack=0.f;
  155383. vf->samptrack=0.f;
  155384. return 0;
  155385. }
  155386. static int _open_seekable2(OggVorbis_File *vf){
  155387. long serialno=vf->current_serialno;
  155388. ogg_int64_t dataoffset=vf->offset, end;
  155389. ogg_page og;
  155390. /* we're partially open and have a first link header state in
  155391. storage in vf */
  155392. /* we can seek, so set out learning all about this file */
  155393. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155394. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155395. /* We get the offset for the last page of the physical bitstream.
  155396. Most OggVorbis files will contain a single logical bitstream */
  155397. end=_get_prev_page(vf,&og);
  155398. if(end<0)return(end);
  155399. /* more than one logical bitstream? */
  155400. if(ogg_page_serialno(&og)!=serialno){
  155401. /* Chained bitstream. Bisect-search each logical bitstream
  155402. section. Do so based on serial number only */
  155403. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155404. }else{
  155405. /* Only one logical bitstream */
  155406. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155407. }
  155408. /* the initial header memory is referenced by vf after; don't free it */
  155409. _prefetch_all_headers(vf,dataoffset);
  155410. return(ov_raw_seek(vf,0));
  155411. }
  155412. /* clear out the current logical bitstream decoder */
  155413. static void _decode_clear(OggVorbis_File *vf){
  155414. vorbis_dsp_clear(&vf->vd);
  155415. vorbis_block_clear(&vf->vb);
  155416. vf->ready_state=OPENED;
  155417. }
  155418. /* fetch and process a packet. Handles the case where we're at a
  155419. bitstream boundary and dumps the decoding machine. If the decoding
  155420. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155421. date (seek and read both use this. seek uses a special hack with
  155422. readp).
  155423. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155424. 0) need more data (only if readp==0)
  155425. 1) got a packet
  155426. */
  155427. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155428. ogg_packet *op_in,
  155429. int readp,
  155430. int spanp){
  155431. ogg_page og;
  155432. /* handle one packet. Try to fetch it from current stream state */
  155433. /* extract packets from page */
  155434. while(1){
  155435. /* process a packet if we can. If the machine isn't loaded,
  155436. neither is a page */
  155437. if(vf->ready_state==INITSET){
  155438. while(1) {
  155439. ogg_packet op;
  155440. ogg_packet *op_ptr=(op_in?op_in:&op);
  155441. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155442. ogg_int64_t granulepos;
  155443. op_in=NULL;
  155444. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155445. if(result>0){
  155446. /* got a packet. process it */
  155447. granulepos=op_ptr->granulepos;
  155448. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155449. header handling. The
  155450. header packets aren't
  155451. audio, so if/when we
  155452. submit them,
  155453. vorbis_synthesis will
  155454. reject them */
  155455. /* suck in the synthesis data and track bitrate */
  155456. {
  155457. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155458. /* for proper use of libvorbis within libvorbisfile,
  155459. oldsamples will always be zero. */
  155460. if(oldsamples)return(OV_EFAULT);
  155461. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155462. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155463. vf->bittrack+=op_ptr->bytes*8;
  155464. }
  155465. /* update the pcm offset. */
  155466. if(granulepos!=-1 && !op_ptr->e_o_s){
  155467. int link=(vf->seekable?vf->current_link:0);
  155468. int i,samples;
  155469. /* this packet has a pcm_offset on it (the last packet
  155470. completed on a page carries the offset) After processing
  155471. (above), we know the pcm position of the *last* sample
  155472. ready to be returned. Find the offset of the *first*
  155473. As an aside, this trick is inaccurate if we begin
  155474. reading anew right at the last page; the end-of-stream
  155475. granulepos declares the last frame in the stream, and the
  155476. last packet of the last page may be a partial frame.
  155477. So, we need a previous granulepos from an in-sequence page
  155478. to have a reference point. Thus the !op_ptr->e_o_s clause
  155479. above */
  155480. if(vf->seekable && link>0)
  155481. granulepos-=vf->pcmlengths[link*2];
  155482. if(granulepos<0)granulepos=0; /* actually, this
  155483. shouldn't be possible
  155484. here unless the stream
  155485. is very broken */
  155486. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155487. granulepos-=samples;
  155488. for(i=0;i<link;i++)
  155489. granulepos+=vf->pcmlengths[i*2+1];
  155490. vf->pcm_offset=granulepos;
  155491. }
  155492. return(1);
  155493. }
  155494. }
  155495. else
  155496. break;
  155497. }
  155498. }
  155499. if(vf->ready_state>=OPENED){
  155500. ogg_int64_t ret;
  155501. if(!readp)return(0);
  155502. if((ret=_get_next_page(vf,&og,-1))<0){
  155503. return(OV_EOF); /* eof.
  155504. leave unitialized */
  155505. }
  155506. /* bitrate tracking; add the header's bytes here, the body bytes
  155507. are done by packet above */
  155508. vf->bittrack+=og.header_len*8;
  155509. /* has our decoding just traversed a bitstream boundary? */
  155510. if(vf->ready_state==INITSET){
  155511. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155512. if(!spanp)
  155513. return(OV_EOF);
  155514. _decode_clear(vf);
  155515. if(!vf->seekable){
  155516. vorbis_info_clear(vf->vi);
  155517. vorbis_comment_clear(vf->vc);
  155518. }
  155519. }
  155520. }
  155521. }
  155522. /* Do we need to load a new machine before submitting the page? */
  155523. /* This is different in the seekable and non-seekable cases.
  155524. In the seekable case, we already have all the header
  155525. information loaded and cached; we just initialize the machine
  155526. with it and continue on our merry way.
  155527. In the non-seekable (streaming) case, we'll only be at a
  155528. boundary if we just left the previous logical bitstream and
  155529. we're now nominally at the header of the next bitstream
  155530. */
  155531. if(vf->ready_state!=INITSET){
  155532. int link;
  155533. if(vf->ready_state<STREAMSET){
  155534. if(vf->seekable){
  155535. vf->current_serialno=ogg_page_serialno(&og);
  155536. /* match the serialno to bitstream section. We use this rather than
  155537. offset positions to avoid problems near logical bitstream
  155538. boundaries */
  155539. for(link=0;link<vf->links;link++)
  155540. if(vf->serialnos[link]==vf->current_serialno)break;
  155541. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155542. stream. error out,
  155543. leave machine
  155544. uninitialized */
  155545. vf->current_link=link;
  155546. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155547. vf->ready_state=STREAMSET;
  155548. }else{
  155549. /* we're streaming */
  155550. /* fetch the three header packets, build the info struct */
  155551. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155552. if(ret)return(ret);
  155553. vf->current_link++;
  155554. link=0;
  155555. }
  155556. }
  155557. {
  155558. int ret=_make_decode_ready(vf);
  155559. if(ret<0)return ret;
  155560. }
  155561. }
  155562. ogg_stream_pagein(&vf->os,&og);
  155563. }
  155564. }
  155565. /* if, eg, 64 bit stdio is configured by default, this will build with
  155566. fseek64 */
  155567. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155568. if(f==NULL)return(-1);
  155569. return fseek(f,off,whence);
  155570. }
  155571. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155572. long ibytes, ov_callbacks callbacks){
  155573. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155574. int ret;
  155575. memset(vf,0,sizeof(*vf));
  155576. vf->datasource=f;
  155577. vf->callbacks = callbacks;
  155578. /* init the framing state */
  155579. ogg_sync_init(&vf->oy);
  155580. /* perhaps some data was previously read into a buffer for testing
  155581. against other stream types. Allow initialization from this
  155582. previously read data (as we may be reading from a non-seekable
  155583. stream) */
  155584. if(initial){
  155585. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155586. memcpy(buffer,initial,ibytes);
  155587. ogg_sync_wrote(&vf->oy,ibytes);
  155588. }
  155589. /* can we seek? Stevens suggests the seek test was portable */
  155590. if(offsettest!=-1)vf->seekable=1;
  155591. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155592. entry for partial open */
  155593. vf->links=1;
  155594. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155595. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155596. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155597. /* Try to fetch the headers, maintaining all the storage */
  155598. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155599. vf->datasource=NULL;
  155600. ov_clear(vf);
  155601. }else
  155602. vf->ready_state=PARTOPEN;
  155603. return(ret);
  155604. }
  155605. static int _ov_open2(OggVorbis_File *vf){
  155606. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155607. vf->ready_state=OPENED;
  155608. if(vf->seekable){
  155609. int ret=_open_seekable2(vf);
  155610. if(ret){
  155611. vf->datasource=NULL;
  155612. ov_clear(vf);
  155613. }
  155614. return(ret);
  155615. }else
  155616. vf->ready_state=STREAMSET;
  155617. return 0;
  155618. }
  155619. /* clear out the OggVorbis_File struct */
  155620. int ov_clear(OggVorbis_File *vf){
  155621. if(vf){
  155622. vorbis_block_clear(&vf->vb);
  155623. vorbis_dsp_clear(&vf->vd);
  155624. ogg_stream_clear(&vf->os);
  155625. if(vf->vi && vf->links){
  155626. int i;
  155627. for(i=0;i<vf->links;i++){
  155628. vorbis_info_clear(vf->vi+i);
  155629. vorbis_comment_clear(vf->vc+i);
  155630. }
  155631. _ogg_free(vf->vi);
  155632. _ogg_free(vf->vc);
  155633. }
  155634. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155635. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155636. if(vf->serialnos)_ogg_free(vf->serialnos);
  155637. if(vf->offsets)_ogg_free(vf->offsets);
  155638. ogg_sync_clear(&vf->oy);
  155639. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155640. memset(vf,0,sizeof(*vf));
  155641. }
  155642. #ifdef DEBUG_LEAKS
  155643. _VDBG_dump();
  155644. #endif
  155645. return(0);
  155646. }
  155647. /* inspects the OggVorbis file and finds/documents all the logical
  155648. bitstreams contained in it. Tries to be tolerant of logical
  155649. bitstream sections that are truncated/woogie.
  155650. return: -1) error
  155651. 0) OK
  155652. */
  155653. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155654. ov_callbacks callbacks){
  155655. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155656. if(ret)return ret;
  155657. return _ov_open2(vf);
  155658. }
  155659. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155660. ov_callbacks callbacks = {
  155661. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155662. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155663. (int (*)(void *)) fclose,
  155664. (long (*)(void *)) ftell
  155665. };
  155666. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155667. }
  155668. /* cheap hack for game usage where downsampling is desirable; there's
  155669. no need for SRC as we can just do it cheaply in libvorbis. */
  155670. int ov_halfrate(OggVorbis_File *vf,int flag){
  155671. int i;
  155672. if(vf->vi==NULL)return OV_EINVAL;
  155673. if(!vf->seekable)return OV_EINVAL;
  155674. if(vf->ready_state>=STREAMSET)
  155675. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155676. will be able to swap this on the fly, but
  155677. for now dumping the decode machine is needed
  155678. to reinit the MDCT lookups. 1.1 libvorbis
  155679. is planned to be able to switch on the fly */
  155680. for(i=0;i<vf->links;i++){
  155681. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155682. ov_halfrate(vf,0);
  155683. return OV_EINVAL;
  155684. }
  155685. }
  155686. return 0;
  155687. }
  155688. int ov_halfrate_p(OggVorbis_File *vf){
  155689. if(vf->vi==NULL)return OV_EINVAL;
  155690. return vorbis_synthesis_halfrate_p(vf->vi);
  155691. }
  155692. /* Only partially open the vorbis file; test for Vorbisness, and load
  155693. the headers for the first chain. Do not seek (although test for
  155694. seekability). Use ov_test_open to finish opening the file, else
  155695. ov_clear to close/free it. Same return codes as open. */
  155696. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155697. ov_callbacks callbacks)
  155698. {
  155699. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155700. }
  155701. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155702. ov_callbacks callbacks = {
  155703. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155704. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155705. (int (*)(void *)) fclose,
  155706. (long (*)(void *)) ftell
  155707. };
  155708. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155709. }
  155710. int ov_test_open(OggVorbis_File *vf){
  155711. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155712. return _ov_open2(vf);
  155713. }
  155714. /* How many logical bitstreams in this physical bitstream? */
  155715. long ov_streams(OggVorbis_File *vf){
  155716. return vf->links;
  155717. }
  155718. /* Is the FILE * associated with vf seekable? */
  155719. long ov_seekable(OggVorbis_File *vf){
  155720. return vf->seekable;
  155721. }
  155722. /* returns the bitrate for a given logical bitstream or the entire
  155723. physical bitstream. If the file is open for random access, it will
  155724. find the *actual* average bitrate. If the file is streaming, it
  155725. returns the nominal bitrate (if set) else the average of the
  155726. upper/lower bounds (if set) else -1 (unset).
  155727. If you want the actual bitrate field settings, get them from the
  155728. vorbis_info structs */
  155729. long ov_bitrate(OggVorbis_File *vf,int i){
  155730. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155731. if(i>=vf->links)return(OV_EINVAL);
  155732. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155733. if(i<0){
  155734. ogg_int64_t bits=0;
  155735. int i;
  155736. float br;
  155737. for(i=0;i<vf->links;i++)
  155738. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155739. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155740. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155741. * so this is slightly transformed to make it work.
  155742. */
  155743. br = bits/ov_time_total(vf,-1);
  155744. return(rint(br));
  155745. }else{
  155746. if(vf->seekable){
  155747. /* return the actual bitrate */
  155748. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155749. }else{
  155750. /* return nominal if set */
  155751. if(vf->vi[i].bitrate_nominal>0){
  155752. return vf->vi[i].bitrate_nominal;
  155753. }else{
  155754. if(vf->vi[i].bitrate_upper>0){
  155755. if(vf->vi[i].bitrate_lower>0){
  155756. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155757. }else{
  155758. return vf->vi[i].bitrate_upper;
  155759. }
  155760. }
  155761. return(OV_FALSE);
  155762. }
  155763. }
  155764. }
  155765. }
  155766. /* returns the actual bitrate since last call. returns -1 if no
  155767. additional data to offer since last call (or at beginning of stream),
  155768. EINVAL if stream is only partially open
  155769. */
  155770. long ov_bitrate_instant(OggVorbis_File *vf){
  155771. int link=(vf->seekable?vf->current_link:0);
  155772. long ret;
  155773. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155774. if(vf->samptrack==0)return(OV_FALSE);
  155775. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155776. vf->bittrack=0.f;
  155777. vf->samptrack=0.f;
  155778. return(ret);
  155779. }
  155780. /* Guess */
  155781. long ov_serialnumber(OggVorbis_File *vf,int i){
  155782. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155783. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155784. if(i<0){
  155785. return(vf->current_serialno);
  155786. }else{
  155787. return(vf->serialnos[i]);
  155788. }
  155789. }
  155790. /* returns: total raw (compressed) length of content if i==-1
  155791. raw (compressed) length of that logical bitstream for i==0 to n
  155792. OV_EINVAL if the stream is not seekable (we can't know the length)
  155793. or if stream is only partially open
  155794. */
  155795. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155796. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155797. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155798. if(i<0){
  155799. ogg_int64_t acc=0;
  155800. int i;
  155801. for(i=0;i<vf->links;i++)
  155802. acc+=ov_raw_total(vf,i);
  155803. return(acc);
  155804. }else{
  155805. return(vf->offsets[i+1]-vf->offsets[i]);
  155806. }
  155807. }
  155808. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155809. (samples) of that logical bitstream for i==0 to n
  155810. OV_EINVAL if the stream is not seekable (we can't know the
  155811. length) or only partially open
  155812. */
  155813. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155814. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155815. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155816. if(i<0){
  155817. ogg_int64_t acc=0;
  155818. int i;
  155819. for(i=0;i<vf->links;i++)
  155820. acc+=ov_pcm_total(vf,i);
  155821. return(acc);
  155822. }else{
  155823. return(vf->pcmlengths[i*2+1]);
  155824. }
  155825. }
  155826. /* returns: total seconds of content if i==-1
  155827. seconds in that logical bitstream for i==0 to n
  155828. OV_EINVAL if the stream is not seekable (we can't know the
  155829. length) or only partially open
  155830. */
  155831. double ov_time_total(OggVorbis_File *vf,int i){
  155832. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155833. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155834. if(i<0){
  155835. double acc=0;
  155836. int i;
  155837. for(i=0;i<vf->links;i++)
  155838. acc+=ov_time_total(vf,i);
  155839. return(acc);
  155840. }else{
  155841. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155842. }
  155843. }
  155844. /* seek to an offset relative to the *compressed* data. This also
  155845. scans packets to update the PCM cursor. It will cross a logical
  155846. bitstream boundary, but only if it can't get any packets out of the
  155847. tail of the bitstream we seek to (so no surprises).
  155848. returns zero on success, nonzero on failure */
  155849. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155850. ogg_stream_state work_os;
  155851. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155852. if(!vf->seekable)
  155853. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155854. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155855. /* don't yet clear out decoding machine (if it's initialized), in
  155856. the case we're in the same link. Restart the decode lapping, and
  155857. let _fetch_and_process_packet deal with a potential bitstream
  155858. boundary */
  155859. vf->pcm_offset=-1;
  155860. ogg_stream_reset_serialno(&vf->os,
  155861. vf->current_serialno); /* must set serialno */
  155862. vorbis_synthesis_restart(&vf->vd);
  155863. _seek_helper(vf,pos);
  155864. /* we need to make sure the pcm_offset is set, but we don't want to
  155865. advance the raw cursor past good packets just to get to the first
  155866. with a granulepos. That's not equivalent behavior to beginning
  155867. decoding as immediately after the seek position as possible.
  155868. So, a hack. We use two stream states; a local scratch state and
  155869. the shared vf->os stream state. We use the local state to
  155870. scan, and the shared state as a buffer for later decode.
  155871. Unfortuantely, on the last page we still advance to last packet
  155872. because the granulepos on the last page is not necessarily on a
  155873. packet boundary, and we need to make sure the granpos is
  155874. correct.
  155875. */
  155876. {
  155877. ogg_page og;
  155878. ogg_packet op;
  155879. int lastblock=0;
  155880. int accblock=0;
  155881. int thisblock;
  155882. int eosflag;
  155883. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155884. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155885. return from not necessarily
  155886. starting from the beginning */
  155887. while(1){
  155888. if(vf->ready_state>=STREAMSET){
  155889. /* snarf/scan a packet if we can */
  155890. int result=ogg_stream_packetout(&work_os,&op);
  155891. if(result>0){
  155892. if(vf->vi[vf->current_link].codec_setup){
  155893. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155894. if(thisblock<0){
  155895. ogg_stream_packetout(&vf->os,NULL);
  155896. thisblock=0;
  155897. }else{
  155898. if(eosflag)
  155899. ogg_stream_packetout(&vf->os,NULL);
  155900. else
  155901. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155902. }
  155903. if(op.granulepos!=-1){
  155904. int i,link=vf->current_link;
  155905. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155906. if(granulepos<0)granulepos=0;
  155907. for(i=0;i<link;i++)
  155908. granulepos+=vf->pcmlengths[i*2+1];
  155909. vf->pcm_offset=granulepos-accblock;
  155910. break;
  155911. }
  155912. lastblock=thisblock;
  155913. continue;
  155914. }else
  155915. ogg_stream_packetout(&vf->os,NULL);
  155916. }
  155917. }
  155918. if(!lastblock){
  155919. if(_get_next_page(vf,&og,-1)<0){
  155920. vf->pcm_offset=ov_pcm_total(vf,-1);
  155921. break;
  155922. }
  155923. }else{
  155924. /* huh? Bogus stream with packets but no granulepos */
  155925. vf->pcm_offset=-1;
  155926. break;
  155927. }
  155928. /* has our decoding just traversed a bitstream boundary? */
  155929. if(vf->ready_state>=STREAMSET)
  155930. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155931. _decode_clear(vf); /* clear out stream state */
  155932. ogg_stream_clear(&work_os);
  155933. }
  155934. if(vf->ready_state<STREAMSET){
  155935. int link;
  155936. vf->current_serialno=ogg_page_serialno(&og);
  155937. for(link=0;link<vf->links;link++)
  155938. if(vf->serialnos[link]==vf->current_serialno)break;
  155939. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155940. error out, leave
  155941. machine uninitialized */
  155942. vf->current_link=link;
  155943. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155944. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155945. vf->ready_state=STREAMSET;
  155946. }
  155947. ogg_stream_pagein(&vf->os,&og);
  155948. ogg_stream_pagein(&work_os,&og);
  155949. eosflag=ogg_page_eos(&og);
  155950. }
  155951. }
  155952. ogg_stream_clear(&work_os);
  155953. vf->bittrack=0.f;
  155954. vf->samptrack=0.f;
  155955. return(0);
  155956. seek_error:
  155957. /* dump the machine so we're in a known state */
  155958. vf->pcm_offset=-1;
  155959. ogg_stream_clear(&work_os);
  155960. _decode_clear(vf);
  155961. return OV_EBADLINK;
  155962. }
  155963. /* Page granularity seek (faster than sample granularity because we
  155964. don't do the last bit of decode to find a specific sample).
  155965. Seek to the last [granule marked] page preceeding the specified pos
  155966. location, such that decoding past the returned point will quickly
  155967. arrive at the requested position. */
  155968. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155969. int link=-1;
  155970. ogg_int64_t result=0;
  155971. ogg_int64_t total=ov_pcm_total(vf,-1);
  155972. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155973. if(!vf->seekable)return(OV_ENOSEEK);
  155974. if(pos<0 || pos>total)return(OV_EINVAL);
  155975. /* which bitstream section does this pcm offset occur in? */
  155976. for(link=vf->links-1;link>=0;link--){
  155977. total-=vf->pcmlengths[link*2+1];
  155978. if(pos>=total)break;
  155979. }
  155980. /* search within the logical bitstream for the page with the highest
  155981. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155982. missing pages or incorrect frame number information in the
  155983. bitstream could make our task impossible. Account for that (it
  155984. would be an error condition) */
  155985. /* new search algorithm by HB (Nicholas Vinen) */
  155986. {
  155987. ogg_int64_t end=vf->offsets[link+1];
  155988. ogg_int64_t begin=vf->offsets[link];
  155989. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155990. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155991. ogg_int64_t target=pos-total+begintime;
  155992. ogg_int64_t best=begin;
  155993. ogg_page og;
  155994. while(begin<end){
  155995. ogg_int64_t bisect;
  155996. if(end-begin<CHUNKSIZE){
  155997. bisect=begin;
  155998. }else{
  155999. /* take a (pretty decent) guess. */
  156000. bisect=begin +
  156001. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156002. if(bisect<=begin)
  156003. bisect=begin+1;
  156004. }
  156005. _seek_helper(vf,bisect);
  156006. while(begin<end){
  156007. result=_get_next_page(vf,&og,end-vf->offset);
  156008. if(result==OV_EREAD) goto seek_error;
  156009. if(result<0){
  156010. if(bisect<=begin+1)
  156011. end=begin; /* found it */
  156012. else{
  156013. if(bisect==0) goto seek_error;
  156014. bisect-=CHUNKSIZE;
  156015. if(bisect<=begin)bisect=begin+1;
  156016. _seek_helper(vf,bisect);
  156017. }
  156018. }else{
  156019. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156020. if(granulepos==-1)continue;
  156021. if(granulepos<target){
  156022. best=result; /* raw offset of packet with granulepos */
  156023. begin=vf->offset; /* raw offset of next page */
  156024. begintime=granulepos;
  156025. if(target-begintime>44100)break;
  156026. bisect=begin; /* *not* begin + 1 */
  156027. }else{
  156028. if(bisect<=begin+1)
  156029. end=begin; /* found it */
  156030. else{
  156031. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156032. end=result;
  156033. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156034. if(bisect<=begin)bisect=begin+1;
  156035. _seek_helper(vf,bisect);
  156036. }else{
  156037. end=result;
  156038. endtime=granulepos;
  156039. break;
  156040. }
  156041. }
  156042. }
  156043. }
  156044. }
  156045. }
  156046. /* found our page. seek to it, update pcm offset. Easier case than
  156047. raw_seek, don't keep packets preceeding granulepos. */
  156048. {
  156049. ogg_page og;
  156050. ogg_packet op;
  156051. /* seek */
  156052. _seek_helper(vf,best);
  156053. vf->pcm_offset=-1;
  156054. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156055. if(link!=vf->current_link){
  156056. /* Different link; dump entire decode machine */
  156057. _decode_clear(vf);
  156058. vf->current_link=link;
  156059. vf->current_serialno=ogg_page_serialno(&og);
  156060. vf->ready_state=STREAMSET;
  156061. }else{
  156062. vorbis_synthesis_restart(&vf->vd);
  156063. }
  156064. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156065. ogg_stream_pagein(&vf->os,&og);
  156066. /* pull out all but last packet; the one with granulepos */
  156067. while(1){
  156068. result=ogg_stream_packetpeek(&vf->os,&op);
  156069. if(result==0){
  156070. /* !!! the packet finishing this page originated on a
  156071. preceeding page. Keep fetching previous pages until we
  156072. get one with a granulepos or without the 'continued' flag
  156073. set. Then just use raw_seek for simplicity. */
  156074. _seek_helper(vf,best);
  156075. while(1){
  156076. result=_get_prev_page(vf,&og);
  156077. if(result<0) goto seek_error;
  156078. if(ogg_page_granulepos(&og)>-1 ||
  156079. !ogg_page_continued(&og)){
  156080. return ov_raw_seek(vf,result);
  156081. }
  156082. vf->offset=result;
  156083. }
  156084. }
  156085. if(result<0){
  156086. result = OV_EBADPACKET;
  156087. goto seek_error;
  156088. }
  156089. if(op.granulepos!=-1){
  156090. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156091. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156092. vf->pcm_offset+=total;
  156093. break;
  156094. }else
  156095. result=ogg_stream_packetout(&vf->os,NULL);
  156096. }
  156097. }
  156098. }
  156099. /* verify result */
  156100. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156101. result=OV_EFAULT;
  156102. goto seek_error;
  156103. }
  156104. vf->bittrack=0.f;
  156105. vf->samptrack=0.f;
  156106. return(0);
  156107. seek_error:
  156108. /* dump machine so we're in a known state */
  156109. vf->pcm_offset=-1;
  156110. _decode_clear(vf);
  156111. return (int)result;
  156112. }
  156113. /* seek to a sample offset relative to the decompressed pcm stream
  156114. returns zero on success, nonzero on failure */
  156115. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156116. int thisblock,lastblock=0;
  156117. int ret=ov_pcm_seek_page(vf,pos);
  156118. if(ret<0)return(ret);
  156119. if((ret=_make_decode_ready(vf)))return ret;
  156120. /* discard leading packets we don't need for the lapping of the
  156121. position we want; don't decode them */
  156122. while(1){
  156123. ogg_packet op;
  156124. ogg_page og;
  156125. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156126. if(ret>0){
  156127. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156128. if(thisblock<0){
  156129. ogg_stream_packetout(&vf->os,NULL);
  156130. continue; /* non audio packet */
  156131. }
  156132. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156133. if(vf->pcm_offset+((thisblock+
  156134. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156135. /* remove the packet from packet queue and track its granulepos */
  156136. ogg_stream_packetout(&vf->os,NULL);
  156137. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156138. only tracking, no
  156139. pcm_decode */
  156140. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156141. /* end of logical stream case is hard, especially with exact
  156142. length positioning. */
  156143. if(op.granulepos>-1){
  156144. int i;
  156145. /* always believe the stream markers */
  156146. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156147. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156148. for(i=0;i<vf->current_link;i++)
  156149. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156150. }
  156151. lastblock=thisblock;
  156152. }else{
  156153. if(ret<0 && ret!=OV_HOLE)break;
  156154. /* suck in a new page */
  156155. if(_get_next_page(vf,&og,-1)<0)break;
  156156. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156157. if(vf->ready_state<STREAMSET){
  156158. int link;
  156159. vf->current_serialno=ogg_page_serialno(&og);
  156160. for(link=0;link<vf->links;link++)
  156161. if(vf->serialnos[link]==vf->current_serialno)break;
  156162. if(link==vf->links)return(OV_EBADLINK);
  156163. vf->current_link=link;
  156164. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156165. vf->ready_state=STREAMSET;
  156166. ret=_make_decode_ready(vf);
  156167. if(ret)return ret;
  156168. lastblock=0;
  156169. }
  156170. ogg_stream_pagein(&vf->os,&og);
  156171. }
  156172. }
  156173. vf->bittrack=0.f;
  156174. vf->samptrack=0.f;
  156175. /* discard samples until we reach the desired position. Crossing a
  156176. logical bitstream boundary with abandon is OK. */
  156177. while(vf->pcm_offset<pos){
  156178. ogg_int64_t target=pos-vf->pcm_offset;
  156179. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156180. if(samples>target)samples=target;
  156181. vorbis_synthesis_read(&vf->vd,samples);
  156182. vf->pcm_offset+=samples;
  156183. if(samples<target)
  156184. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156185. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156186. }
  156187. return 0;
  156188. }
  156189. /* seek to a playback time relative to the decompressed pcm stream
  156190. returns zero on success, nonzero on failure */
  156191. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156192. /* translate time to PCM position and call ov_pcm_seek */
  156193. int link=-1;
  156194. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156195. double time_total=ov_time_total(vf,-1);
  156196. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156197. if(!vf->seekable)return(OV_ENOSEEK);
  156198. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156199. /* which bitstream section does this time offset occur in? */
  156200. for(link=vf->links-1;link>=0;link--){
  156201. pcm_total-=vf->pcmlengths[link*2+1];
  156202. time_total-=ov_time_total(vf,link);
  156203. if(seconds>=time_total)break;
  156204. }
  156205. /* enough information to convert time offset to pcm offset */
  156206. {
  156207. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156208. return(ov_pcm_seek(vf,target));
  156209. }
  156210. }
  156211. /* page-granularity version of ov_time_seek
  156212. returns zero on success, nonzero on failure */
  156213. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156214. /* translate time to PCM position and call ov_pcm_seek */
  156215. int link=-1;
  156216. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156217. double time_total=ov_time_total(vf,-1);
  156218. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156219. if(!vf->seekable)return(OV_ENOSEEK);
  156220. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156221. /* which bitstream section does this time offset occur in? */
  156222. for(link=vf->links-1;link>=0;link--){
  156223. pcm_total-=vf->pcmlengths[link*2+1];
  156224. time_total-=ov_time_total(vf,link);
  156225. if(seconds>=time_total)break;
  156226. }
  156227. /* enough information to convert time offset to pcm offset */
  156228. {
  156229. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156230. return(ov_pcm_seek_page(vf,target));
  156231. }
  156232. }
  156233. /* tell the current stream offset cursor. Note that seek followed by
  156234. tell will likely not give the set offset due to caching */
  156235. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156236. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156237. return(vf->offset);
  156238. }
  156239. /* return PCM offset (sample) of next PCM sample to be read */
  156240. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156241. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156242. return(vf->pcm_offset);
  156243. }
  156244. /* return time offset (seconds) of next PCM sample to be read */
  156245. double ov_time_tell(OggVorbis_File *vf){
  156246. int link=0;
  156247. ogg_int64_t pcm_total=0;
  156248. double time_total=0.f;
  156249. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156250. if(vf->seekable){
  156251. pcm_total=ov_pcm_total(vf,-1);
  156252. time_total=ov_time_total(vf,-1);
  156253. /* which bitstream section does this time offset occur in? */
  156254. for(link=vf->links-1;link>=0;link--){
  156255. pcm_total-=vf->pcmlengths[link*2+1];
  156256. time_total-=ov_time_total(vf,link);
  156257. if(vf->pcm_offset>=pcm_total)break;
  156258. }
  156259. }
  156260. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156261. }
  156262. /* link: -1) return the vorbis_info struct for the bitstream section
  156263. currently being decoded
  156264. 0-n) to request information for a specific bitstream section
  156265. In the case of a non-seekable bitstream, any call returns the
  156266. current bitstream. NULL in the case that the machine is not
  156267. initialized */
  156268. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156269. if(vf->seekable){
  156270. if(link<0)
  156271. if(vf->ready_state>=STREAMSET)
  156272. return vf->vi+vf->current_link;
  156273. else
  156274. return vf->vi;
  156275. else
  156276. if(link>=vf->links)
  156277. return NULL;
  156278. else
  156279. return vf->vi+link;
  156280. }else{
  156281. return vf->vi;
  156282. }
  156283. }
  156284. /* grr, strong typing, grr, no templates/inheritence, grr */
  156285. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156286. if(vf->seekable){
  156287. if(link<0)
  156288. if(vf->ready_state>=STREAMSET)
  156289. return vf->vc+vf->current_link;
  156290. else
  156291. return vf->vc;
  156292. else
  156293. if(link>=vf->links)
  156294. return NULL;
  156295. else
  156296. return vf->vc+link;
  156297. }else{
  156298. return vf->vc;
  156299. }
  156300. }
  156301. static int host_is_big_endian() {
  156302. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156303. unsigned char *bytewise = (unsigned char *)&pattern;
  156304. if (bytewise[0] == 0xfe) return 1;
  156305. return 0;
  156306. }
  156307. /* up to this point, everything could more or less hide the multiple
  156308. logical bitstream nature of chaining from the toplevel application
  156309. if the toplevel application didn't particularly care. However, at
  156310. the point that we actually read audio back, the multiple-section
  156311. nature must surface: Multiple bitstream sections do not necessarily
  156312. have to have the same number of channels or sampling rate.
  156313. ov_read returns the sequential logical bitstream number currently
  156314. being decoded along with the PCM data in order that the toplevel
  156315. application can take action on channel/sample rate changes. This
  156316. number will be incremented even for streamed (non-seekable) streams
  156317. (for seekable streams, it represents the actual logical bitstream
  156318. index within the physical bitstream. Note that the accessor
  156319. functions above are aware of this dichotomy).
  156320. input values: buffer) a buffer to hold packed PCM data for return
  156321. length) the byte length requested to be placed into buffer
  156322. bigendianp) should the data be packed LSB first (0) or
  156323. MSB first (1)
  156324. word) word size for output. currently 1 (byte) or
  156325. 2 (16 bit short)
  156326. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156327. 0) EOF
  156328. n) number of bytes of PCM actually returned. The
  156329. below works on a packet-by-packet basis, so the
  156330. return length is not related to the 'length' passed
  156331. in, just guaranteed to fit.
  156332. *section) set to the logical bitstream number */
  156333. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156334. int bigendianp,int word,int sgned,int *bitstream){
  156335. int i,j;
  156336. int host_endian = host_is_big_endian();
  156337. float **pcm;
  156338. long samples;
  156339. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156340. while(1){
  156341. if(vf->ready_state==INITSET){
  156342. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156343. if(samples)break;
  156344. }
  156345. /* suck in another packet */
  156346. {
  156347. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156348. if(ret==OV_EOF)
  156349. return(0);
  156350. if(ret<=0)
  156351. return(ret);
  156352. }
  156353. }
  156354. if(samples>0){
  156355. /* yay! proceed to pack data into the byte buffer */
  156356. long channels=ov_info(vf,-1)->channels;
  156357. long bytespersample=word * channels;
  156358. vorbis_fpu_control fpu;
  156359. (void) fpu; // (to avoid a warning about it being unused)
  156360. if(samples>length/bytespersample)samples=length/bytespersample;
  156361. if(samples <= 0)
  156362. return OV_EINVAL;
  156363. /* a tight loop to pack each size */
  156364. {
  156365. int val;
  156366. if(word==1){
  156367. int off=(sgned?0:128);
  156368. vorbis_fpu_setround(&fpu);
  156369. for(j=0;j<samples;j++)
  156370. for(i=0;i<channels;i++){
  156371. val=vorbis_ftoi(pcm[i][j]*128.f);
  156372. if(val>127)val=127;
  156373. else if(val<-128)val=-128;
  156374. *buffer++=val+off;
  156375. }
  156376. vorbis_fpu_restore(fpu);
  156377. }else{
  156378. int off=(sgned?0:32768);
  156379. if(host_endian==bigendianp){
  156380. if(sgned){
  156381. vorbis_fpu_setround(&fpu);
  156382. for(i=0;i<channels;i++) { /* It's faster in this order */
  156383. float *src=pcm[i];
  156384. short *dest=((short *)buffer)+i;
  156385. for(j=0;j<samples;j++) {
  156386. val=vorbis_ftoi(src[j]*32768.f);
  156387. if(val>32767)val=32767;
  156388. else if(val<-32768)val=-32768;
  156389. *dest=val;
  156390. dest+=channels;
  156391. }
  156392. }
  156393. vorbis_fpu_restore(fpu);
  156394. }else{
  156395. vorbis_fpu_setround(&fpu);
  156396. for(i=0;i<channels;i++) {
  156397. float *src=pcm[i];
  156398. short *dest=((short *)buffer)+i;
  156399. for(j=0;j<samples;j++) {
  156400. val=vorbis_ftoi(src[j]*32768.f);
  156401. if(val>32767)val=32767;
  156402. else if(val<-32768)val=-32768;
  156403. *dest=val+off;
  156404. dest+=channels;
  156405. }
  156406. }
  156407. vorbis_fpu_restore(fpu);
  156408. }
  156409. }else if(bigendianp){
  156410. vorbis_fpu_setround(&fpu);
  156411. for(j=0;j<samples;j++)
  156412. for(i=0;i<channels;i++){
  156413. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156414. if(val>32767)val=32767;
  156415. else if(val<-32768)val=-32768;
  156416. val+=off;
  156417. *buffer++=(val>>8);
  156418. *buffer++=(val&0xff);
  156419. }
  156420. vorbis_fpu_restore(fpu);
  156421. }else{
  156422. int val;
  156423. vorbis_fpu_setround(&fpu);
  156424. for(j=0;j<samples;j++)
  156425. for(i=0;i<channels;i++){
  156426. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156427. if(val>32767)val=32767;
  156428. else if(val<-32768)val=-32768;
  156429. val+=off;
  156430. *buffer++=(val&0xff);
  156431. *buffer++=(val>>8);
  156432. }
  156433. vorbis_fpu_restore(fpu);
  156434. }
  156435. }
  156436. }
  156437. vorbis_synthesis_read(&vf->vd,samples);
  156438. vf->pcm_offset+=samples;
  156439. if(bitstream)*bitstream=vf->current_link;
  156440. return(samples*bytespersample);
  156441. }else{
  156442. return(samples);
  156443. }
  156444. }
  156445. /* input values: pcm_channels) a float vector per channel of output
  156446. length) the sample length being read by the app
  156447. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156448. 0) EOF
  156449. n) number of samples of PCM actually returned. The
  156450. below works on a packet-by-packet basis, so the
  156451. return length is not related to the 'length' passed
  156452. in, just guaranteed to fit.
  156453. *section) set to the logical bitstream number */
  156454. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156455. int *bitstream){
  156456. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156457. while(1){
  156458. if(vf->ready_state==INITSET){
  156459. float **pcm;
  156460. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156461. if(samples){
  156462. if(pcm_channels)*pcm_channels=pcm;
  156463. if(samples>length)samples=length;
  156464. vorbis_synthesis_read(&vf->vd,samples);
  156465. vf->pcm_offset+=samples;
  156466. if(bitstream)*bitstream=vf->current_link;
  156467. return samples;
  156468. }
  156469. }
  156470. /* suck in another packet */
  156471. {
  156472. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156473. if(ret==OV_EOF)return(0);
  156474. if(ret<=0)return(ret);
  156475. }
  156476. }
  156477. }
  156478. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156479. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156480. ogg_int64_t off);
  156481. static void _ov_splice(float **pcm,float **lappcm,
  156482. int n1, int n2,
  156483. int ch1, int ch2,
  156484. float *w1, float *w2){
  156485. int i,j;
  156486. float *w=w1;
  156487. int n=n1;
  156488. if(n1>n2){
  156489. n=n2;
  156490. w=w2;
  156491. }
  156492. /* splice */
  156493. for(j=0;j<ch1 && j<ch2;j++){
  156494. float *s=lappcm[j];
  156495. float *d=pcm[j];
  156496. for(i=0;i<n;i++){
  156497. float wd=w[i]*w[i];
  156498. float ws=1.-wd;
  156499. d[i]=d[i]*wd + s[i]*ws;
  156500. }
  156501. }
  156502. /* window from zero */
  156503. for(;j<ch2;j++){
  156504. float *d=pcm[j];
  156505. for(i=0;i<n;i++){
  156506. float wd=w[i]*w[i];
  156507. d[i]=d[i]*wd;
  156508. }
  156509. }
  156510. }
  156511. /* make sure vf is INITSET */
  156512. static int _ov_initset(OggVorbis_File *vf){
  156513. while(1){
  156514. if(vf->ready_state==INITSET)break;
  156515. /* suck in another packet */
  156516. {
  156517. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156518. if(ret<0 && ret!=OV_HOLE)return(ret);
  156519. }
  156520. }
  156521. return 0;
  156522. }
  156523. /* make sure vf is INITSET and that we have a primed buffer; if
  156524. we're crosslapping at a stream section boundary, this also makes
  156525. sure we're sanity checking against the right stream information */
  156526. static int _ov_initprime(OggVorbis_File *vf){
  156527. vorbis_dsp_state *vd=&vf->vd;
  156528. while(1){
  156529. if(vf->ready_state==INITSET)
  156530. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156531. /* suck in another packet */
  156532. {
  156533. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156534. if(ret<0 && ret!=OV_HOLE)return(ret);
  156535. }
  156536. }
  156537. return 0;
  156538. }
  156539. /* grab enough data for lapping from vf; this may be in the form of
  156540. unreturned, already-decoded pcm, remaining PCM we will need to
  156541. decode, or synthetic postextrapolation from last packets. */
  156542. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156543. float **lappcm,int lapsize){
  156544. int lapcount=0,i;
  156545. float **pcm;
  156546. /* try first to decode the lapping data */
  156547. while(lapcount<lapsize){
  156548. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156549. if(samples){
  156550. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156551. for(i=0;i<vi->channels;i++)
  156552. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156553. lapcount+=samples;
  156554. vorbis_synthesis_read(vd,samples);
  156555. }else{
  156556. /* suck in another packet */
  156557. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156558. if(ret==OV_EOF)break;
  156559. }
  156560. }
  156561. if(lapcount<lapsize){
  156562. /* failed to get lapping data from normal decode; pry it from the
  156563. postextrapolation buffering, or the second half of the MDCT
  156564. from the last packet */
  156565. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156566. if(samples==0){
  156567. for(i=0;i<vi->channels;i++)
  156568. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156569. lapcount=lapsize;
  156570. }else{
  156571. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156572. for(i=0;i<vi->channels;i++)
  156573. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156574. lapcount+=samples;
  156575. }
  156576. }
  156577. }
  156578. /* this sets up crosslapping of a sample by using trailing data from
  156579. sample 1 and lapping it into the windowing buffer of sample 2 */
  156580. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156581. vorbis_info *vi1,*vi2;
  156582. float **lappcm;
  156583. float **pcm;
  156584. float *w1,*w2;
  156585. int n1,n2,i,ret,hs1,hs2;
  156586. if(vf1==vf2)return(0); /* degenerate case */
  156587. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156588. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156589. /* the relevant overlap buffers must be pre-checked and pre-primed
  156590. before looking at settings in the event that priming would cross
  156591. a bitstream boundary. So, do it now */
  156592. ret=_ov_initset(vf1);
  156593. if(ret)return(ret);
  156594. ret=_ov_initprime(vf2);
  156595. if(ret)return(ret);
  156596. vi1=ov_info(vf1,-1);
  156597. vi2=ov_info(vf2,-1);
  156598. hs1=ov_halfrate_p(vf1);
  156599. hs2=ov_halfrate_p(vf2);
  156600. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156601. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156602. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156603. w1=vorbis_window(&vf1->vd,0);
  156604. w2=vorbis_window(&vf2->vd,0);
  156605. for(i=0;i<vi1->channels;i++)
  156606. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156607. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156608. /* have a lapping buffer from vf1; now to splice it into the lapping
  156609. buffer of vf2 */
  156610. /* consolidate and expose the buffer. */
  156611. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156612. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156613. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156614. /* splice */
  156615. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156616. /* done */
  156617. return(0);
  156618. }
  156619. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156620. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156621. vorbis_info *vi;
  156622. float **lappcm;
  156623. float **pcm;
  156624. float *w1,*w2;
  156625. int n1,n2,ch1,ch2,hs;
  156626. int i,ret;
  156627. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156628. ret=_ov_initset(vf);
  156629. if(ret)return(ret);
  156630. vi=ov_info(vf,-1);
  156631. hs=ov_halfrate_p(vf);
  156632. ch1=vi->channels;
  156633. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156634. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156635. persistent; even if the decode state
  156636. from this link gets dumped, this
  156637. window array continues to exist */
  156638. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156639. for(i=0;i<ch1;i++)
  156640. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156641. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156642. /* have lapping data; seek and prime the buffer */
  156643. ret=localseek(vf,pos);
  156644. if(ret)return ret;
  156645. ret=_ov_initprime(vf);
  156646. if(ret)return(ret);
  156647. /* Guard against cross-link changes; they're perfectly legal */
  156648. vi=ov_info(vf,-1);
  156649. ch2=vi->channels;
  156650. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156651. w2=vorbis_window(&vf->vd,0);
  156652. /* consolidate and expose the buffer. */
  156653. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156654. /* splice */
  156655. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156656. /* done */
  156657. return(0);
  156658. }
  156659. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156660. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156661. }
  156662. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156663. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156664. }
  156665. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156666. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156667. }
  156668. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156669. int (*localseek)(OggVorbis_File *,double)){
  156670. vorbis_info *vi;
  156671. float **lappcm;
  156672. float **pcm;
  156673. float *w1,*w2;
  156674. int n1,n2,ch1,ch2,hs;
  156675. int i,ret;
  156676. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156677. ret=_ov_initset(vf);
  156678. if(ret)return(ret);
  156679. vi=ov_info(vf,-1);
  156680. hs=ov_halfrate_p(vf);
  156681. ch1=vi->channels;
  156682. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156683. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156684. persistent; even if the decode state
  156685. from this link gets dumped, this
  156686. window array continues to exist */
  156687. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156688. for(i=0;i<ch1;i++)
  156689. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156690. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156691. /* have lapping data; seek and prime the buffer */
  156692. ret=localseek(vf,pos);
  156693. if(ret)return ret;
  156694. ret=_ov_initprime(vf);
  156695. if(ret)return(ret);
  156696. /* Guard against cross-link changes; they're perfectly legal */
  156697. vi=ov_info(vf,-1);
  156698. ch2=vi->channels;
  156699. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156700. w2=vorbis_window(&vf->vd,0);
  156701. /* consolidate and expose the buffer. */
  156702. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156703. /* splice */
  156704. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156705. /* done */
  156706. return(0);
  156707. }
  156708. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156709. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156710. }
  156711. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156712. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156713. }
  156714. #endif
  156715. /*** End of inlined file: vorbisfile.c ***/
  156716. /*** Start of inlined file: window.c ***/
  156717. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156718. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156719. // tasks..
  156720. #if JUCE_MSVC
  156721. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156722. #endif
  156723. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156724. #if JUCE_USE_OGGVORBIS
  156725. #include <stdlib.h>
  156726. #include <math.h>
  156727. static float vwin64[32] = {
  156728. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156729. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156730. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156731. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156732. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156733. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156734. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156735. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156736. };
  156737. static float vwin128[64] = {
  156738. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156739. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156740. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156741. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156742. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156743. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156744. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156745. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156746. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156747. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156748. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156749. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156750. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156751. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156752. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156753. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156754. };
  156755. static float vwin256[128] = {
  156756. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156757. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156758. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156759. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156760. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156761. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156762. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156763. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156764. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156765. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156766. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156767. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156768. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156769. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156770. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156771. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156772. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156773. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156774. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156775. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156776. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156777. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156778. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156779. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156780. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156781. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156782. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156783. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156784. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156785. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156786. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156787. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156788. };
  156789. static float vwin512[256] = {
  156790. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156791. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156792. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156793. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156794. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156795. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156796. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156797. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156798. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156799. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156800. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156801. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156802. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156803. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156804. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156805. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156806. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156807. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156808. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156809. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156810. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156811. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156812. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156813. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156814. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156815. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156816. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156817. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156818. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156819. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156820. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156821. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156822. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156823. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156824. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156825. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156826. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156827. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156828. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156829. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156830. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156831. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156832. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156833. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156834. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156835. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156836. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156837. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156838. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156839. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156840. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156841. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156842. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156843. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156844. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156845. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156846. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156847. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156848. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156849. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156850. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156851. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156852. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156853. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156854. };
  156855. static float vwin1024[512] = {
  156856. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156857. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156858. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156859. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156860. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156861. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156862. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156863. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156864. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156865. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156866. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156867. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156868. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156869. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156870. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156871. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156872. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156873. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156874. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156875. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156876. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156877. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156878. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156879. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156880. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156881. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156882. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156883. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156884. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156885. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156886. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156887. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156888. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156889. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156890. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156891. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156892. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156893. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156894. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156895. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156896. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156897. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156898. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156899. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156900. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156901. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156902. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156903. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156904. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156905. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156906. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156907. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156908. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156909. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156910. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156911. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156912. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156913. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156914. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156915. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156916. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156917. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156918. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156919. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156920. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156921. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156922. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156923. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156924. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156925. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156926. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156927. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156928. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156929. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156930. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156931. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156932. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156933. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156934. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156935. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156936. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156937. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156938. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156939. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156940. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156941. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156942. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156943. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156944. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156945. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156946. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156947. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156948. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156949. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156950. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156951. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156952. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156953. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156954. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156955. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156956. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156957. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156958. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156959. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156960. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156961. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156962. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156963. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156964. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156965. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156966. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156967. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156968. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156969. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156970. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156971. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156972. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156973. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156974. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156975. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156976. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156977. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156978. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156979. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156980. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156981. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156982. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156983. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156984. };
  156985. static float vwin2048[1024] = {
  156986. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156987. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156988. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156989. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156990. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156991. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156992. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156993. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156994. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156995. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156996. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156997. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156998. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156999. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157000. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157001. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157002. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157003. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157004. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157005. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157006. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157007. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157008. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157009. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157010. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157011. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157012. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157013. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157014. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157015. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157016. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157017. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157018. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157019. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157020. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157021. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157022. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157023. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157024. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157025. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157026. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157027. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157028. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157029. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157030. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157031. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157032. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157033. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157034. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157035. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157036. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157037. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157038. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157039. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157040. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157041. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157042. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157043. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157044. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157045. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157046. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157047. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157048. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157049. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157050. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157051. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157052. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157053. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157054. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157055. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157056. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157057. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157058. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157059. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157060. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157061. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157062. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157063. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157064. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157065. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157066. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157067. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157068. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157069. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157070. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157071. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157072. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157073. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157074. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157075. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157076. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157077. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157078. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157079. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157080. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157081. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157082. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157083. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157084. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157085. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157086. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157087. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157088. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157089. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157090. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157091. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157092. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157093. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157094. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157095. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157096. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157097. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157098. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157099. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157100. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157101. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157102. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157103. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157104. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157105. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157106. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157107. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157108. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157109. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157110. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157111. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157112. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157113. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157114. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157115. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157116. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157117. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157118. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157119. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157120. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157121. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157122. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157123. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157124. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157125. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157126. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157127. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157128. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157129. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157130. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157131. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157132. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157133. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157134. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157135. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157136. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157137. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157138. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157139. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157140. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157141. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157142. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157143. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157144. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157145. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157146. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157147. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157148. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157149. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157150. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157151. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157152. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157153. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157154. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157155. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157156. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157157. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157158. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157159. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157160. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157161. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157162. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157163. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157164. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157165. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157166. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157167. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157168. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157169. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157170. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157171. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157172. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157173. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157174. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157175. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157176. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157177. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157178. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157179. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157180. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157181. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157182. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157183. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157184. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157185. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157186. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157187. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157188. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157189. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157190. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157191. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157192. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157193. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157194. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157195. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157196. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157197. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157198. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157199. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157200. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157201. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157202. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157203. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157204. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157205. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157206. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157207. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157208. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157209. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157210. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157211. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157212. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157213. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157214. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157215. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157216. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157217. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157218. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157219. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157220. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157221. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157222. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157223. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157224. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157225. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157226. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157227. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157228. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157229. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157230. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157231. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157232. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157233. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157234. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157235. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157236. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157237. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157238. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157239. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157240. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157241. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157242. };
  157243. static float vwin4096[2048] = {
  157244. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157245. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157246. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157247. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157248. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157249. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157250. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157251. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157252. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157253. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157254. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157255. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157256. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157257. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157258. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157259. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157260. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157261. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157262. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157263. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157264. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157265. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157266. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157267. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157268. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157269. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157270. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157271. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157272. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157273. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157274. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157275. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157276. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157277. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157278. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157279. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157280. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157281. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157282. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157283. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157284. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157285. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157286. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157287. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157288. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157289. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157290. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157291. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157292. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157293. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157294. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157295. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157296. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157297. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157298. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157299. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157300. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157301. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157302. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157303. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157304. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157305. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157306. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157307. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157308. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157309. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157310. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157311. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157312. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157313. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157314. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157315. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157316. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157317. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157318. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157319. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157320. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157321. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157322. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157323. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157324. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157325. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157326. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157327. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157328. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157329. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157330. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157331. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157332. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157333. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157334. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157335. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157336. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157337. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157338. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157339. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157340. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157341. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157342. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157343. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157344. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157345. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157346. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157347. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157348. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157349. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157350. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157351. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157352. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157353. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157354. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157355. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157356. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157357. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157358. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157359. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157360. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157361. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157362. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157363. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157364. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157365. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157366. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157367. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157368. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157369. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157370. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157371. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157372. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157373. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157374. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157375. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157376. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157377. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157378. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157379. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157380. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157381. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157382. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157383. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157384. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157385. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157386. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157387. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157388. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157389. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157390. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157391. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157392. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157393. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157394. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157395. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157396. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157397. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157398. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157399. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157400. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157401. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157402. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157403. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157404. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157405. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157406. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157407. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157408. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157409. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157410. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157411. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157412. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157413. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157414. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157415. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157416. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157417. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157418. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157419. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157420. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157421. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157422. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157423. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157424. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157425. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157426. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157427. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157428. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157429. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157430. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157431. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157432. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157433. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157434. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157435. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157436. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157437. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157438. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157439. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157440. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157441. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157442. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157443. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157444. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157445. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157446. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157447. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157448. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157449. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157450. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157451. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157452. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157453. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157454. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157455. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157456. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157457. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157458. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157459. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157460. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157461. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157462. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157463. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157464. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157465. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157466. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157467. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157468. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157469. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157470. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157471. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157472. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157473. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157474. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157475. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157476. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157477. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157478. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157479. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157480. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157481. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157482. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157483. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157484. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157485. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157486. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157487. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157488. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157489. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157490. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157491. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157492. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157493. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157494. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157495. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157496. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157497. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157498. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157499. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157500. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157501. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157502. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157503. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157504. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157505. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157506. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157507. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157508. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157509. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157510. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157511. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157512. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157513. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157514. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157515. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157516. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157517. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157518. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157519. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157520. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157521. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157522. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157523. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157524. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157525. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157526. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157527. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157528. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157529. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157530. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157531. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157532. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157533. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157534. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157535. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157536. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157537. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157538. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157539. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157540. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157541. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157542. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157543. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157544. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157545. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157546. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157547. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157548. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157549. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157550. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157551. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157552. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157553. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157554. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157555. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157556. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157557. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157558. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157559. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157560. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157561. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157562. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157563. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157564. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157565. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157566. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157567. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157568. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157569. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157570. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157571. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157572. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157573. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157574. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157575. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157576. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157577. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157578. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157579. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157580. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157581. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157582. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157583. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157584. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157585. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157586. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157587. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157588. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157589. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157590. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157591. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157592. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157593. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157594. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157595. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157596. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157597. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157598. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157599. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157600. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157601. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157602. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157603. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157604. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157605. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157606. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157607. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157608. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157609. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157610. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157611. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157612. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157613. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157614. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157615. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157616. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157617. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157618. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157619. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157620. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157621. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157622. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157623. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157624. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157625. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157626. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157627. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157628. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157629. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157630. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157631. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157632. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157633. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157634. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157635. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157636. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157637. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157638. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157639. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157640. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157641. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157642. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157643. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157644. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157645. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157646. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157647. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157648. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157649. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157650. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157651. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157652. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157653. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157654. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157655. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157656. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157657. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157658. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157659. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157660. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157661. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157662. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157663. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157664. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157665. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157666. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157667. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157668. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157669. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157670. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157671. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157672. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157673. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157674. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157675. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157676. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157677. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157678. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157679. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157680. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157681. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157682. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157683. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157684. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157685. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157686. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157687. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157688. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157689. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157690. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157691. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157692. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157693. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157694. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157695. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157696. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157697. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157698. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157699. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157700. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157701. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157702. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157703. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157704. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157705. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157706. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157707. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157708. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157709. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157710. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157711. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157712. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157713. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157714. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157715. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157716. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157717. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157718. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157719. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157720. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157721. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157722. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157723. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157724. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157725. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157726. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157727. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157728. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157729. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157730. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157731. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157732. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157733. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157734. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157735. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157736. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157737. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157738. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157739. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157740. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157741. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157742. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157743. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157744. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157745. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157746. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157747. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157748. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157749. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157750. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157751. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157752. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157753. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157754. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157755. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157756. };
  157757. static float vwin8192[4096] = {
  157758. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157759. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157760. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157761. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157762. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157763. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157764. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157765. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157766. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157767. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157768. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157769. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157770. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157771. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157772. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157773. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157774. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157775. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157776. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157777. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157778. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157779. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157780. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157781. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157782. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157783. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157784. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157785. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157786. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157787. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157788. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157789. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157790. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157791. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157792. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157793. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157794. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157795. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157796. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157797. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157798. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157799. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157800. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157801. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157802. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157803. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157804. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157805. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157806. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157807. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157808. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157809. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157810. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157811. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157812. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157813. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157814. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157815. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157816. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157817. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157818. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157819. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157820. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157821. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157822. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157823. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157824. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157825. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157826. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157827. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157828. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157829. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157830. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157831. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157832. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157833. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157834. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157835. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157836. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157837. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157838. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157839. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157840. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157841. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157842. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157843. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157844. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157845. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157846. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157847. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157848. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157849. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157850. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157851. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157852. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157853. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157854. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157855. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157856. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157857. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157858. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157859. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157860. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157861. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157862. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157863. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157864. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157865. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157866. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157867. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157868. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157869. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157870. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157871. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157872. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157873. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157874. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157875. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157876. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157877. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157878. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157879. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157880. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157881. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157882. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157883. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157884. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157885. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157886. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157887. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157888. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157889. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157890. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157891. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157892. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157893. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157894. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157895. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157896. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157897. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157898. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157899. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157900. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157901. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157902. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157903. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157904. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157905. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157906. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157907. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157908. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157909. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157910. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157911. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157912. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157913. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157914. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157915. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157916. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157917. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157918. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157919. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157920. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157921. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157922. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157923. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157924. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157925. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157926. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157927. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157928. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157929. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157930. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157931. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157932. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157933. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157934. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157935. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157936. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157937. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157938. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157939. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157940. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157941. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157942. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157943. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157944. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157945. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157946. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157947. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157948. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157949. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157950. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157951. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157952. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157953. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157954. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157955. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157956. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157957. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157958. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157959. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157960. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157961. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157962. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157963. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157964. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157965. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157966. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157967. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157968. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157969. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157970. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157971. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157972. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157973. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157974. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157975. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157976. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157977. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157978. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157979. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157980. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157981. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157982. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157983. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157984. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157985. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157986. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157987. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157988. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157989. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157990. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157991. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157992. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157993. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157994. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157995. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157996. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157997. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157998. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157999. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158000. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158001. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158002. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158003. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158004. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158005. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158006. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158007. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158008. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158009. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158010. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158011. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158012. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158013. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158014. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158015. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158016. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158017. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158018. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158019. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158020. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158021. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158022. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158023. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158024. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158025. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158026. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158027. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158028. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158029. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158030. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158031. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158032. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158033. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158034. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158035. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158036. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158037. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158038. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158039. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158040. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158041. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158042. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158043. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158044. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158045. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158046. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158047. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158048. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158049. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158050. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158051. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158052. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158053. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158054. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158055. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158056. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158057. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158058. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158059. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158060. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158061. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158062. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158063. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158064. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158065. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158066. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158067. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158068. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158069. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158070. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158071. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158072. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158073. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158074. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158075. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158076. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158077. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158078. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158079. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158080. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158081. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158082. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158083. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158084. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158085. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158086. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158087. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158088. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158089. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158090. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158091. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158092. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158093. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158094. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158095. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158096. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158097. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158098. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158099. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158100. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158101. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158102. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158103. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158104. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158105. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158106. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158107. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158108. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158109. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158110. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158111. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158112. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158113. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158114. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158115. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158116. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158117. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158118. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158119. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158120. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158121. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158122. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158123. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158124. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158125. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158126. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158127. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158128. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158129. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158130. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158131. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158132. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158133. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158134. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158135. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158136. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158137. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158138. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158139. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158140. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158141. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158142. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158143. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158144. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158145. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158146. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158147. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158148. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158149. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158150. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158151. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158152. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158153. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158154. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158155. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158156. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158157. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158158. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158159. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158160. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158161. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158162. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158163. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158164. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158165. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158166. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158167. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158168. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158169. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158170. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158171. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158172. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158173. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158174. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158175. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158176. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158177. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158178. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158179. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158180. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158181. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158182. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158183. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158184. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158185. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158186. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158187. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158188. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158189. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158190. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158191. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158192. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158193. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158194. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158195. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158196. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158197. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158198. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158199. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158200. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158201. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158202. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158203. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158204. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158205. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158206. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158207. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158208. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158209. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158210. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158211. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158212. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158213. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158214. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158215. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158216. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158217. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158218. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158219. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158220. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158221. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158222. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158223. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158224. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158225. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158226. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158227. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158228. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158229. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158230. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158231. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158232. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158233. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158234. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158235. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158236. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158237. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158238. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158239. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158240. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158241. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158242. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158243. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158244. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158245. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158246. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158247. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158248. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158249. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158250. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158251. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158252. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158253. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158254. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158255. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158256. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158257. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158258. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158259. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158260. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158261. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158262. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158263. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158264. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158265. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158266. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158267. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158268. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158269. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158270. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158271. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158272. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158273. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158274. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158275. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158276. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158277. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158278. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158279. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158280. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158281. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158282. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158283. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158284. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158285. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158286. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158287. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158288. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158289. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158290. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158291. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158292. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158293. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158294. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158295. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158296. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158297. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158298. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158299. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158300. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158301. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158302. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158303. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158304. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158305. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158306. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158307. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158308. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158309. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158310. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158311. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158312. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158313. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158314. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158315. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158316. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158317. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158318. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158319. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158320. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158321. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158322. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158323. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158324. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158325. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158326. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158327. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158328. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158329. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158330. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158331. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158332. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158333. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158334. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158335. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158336. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158337. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158338. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158339. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158340. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158341. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158342. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158343. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158344. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158345. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158346. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158347. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158348. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158349. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158350. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158351. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158352. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158353. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158354. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158355. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158356. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158357. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158358. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158359. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158360. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158361. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158362. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158363. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158364. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158365. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158366. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158367. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158368. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158369. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158370. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158371. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158372. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158373. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158374. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158375. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158376. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158377. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158378. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158379. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158380. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158381. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158382. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158383. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158384. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158385. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158386. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158387. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158388. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158389. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158390. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158391. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158392. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158393. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158394. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158395. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158396. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158397. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158398. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158399. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158400. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158401. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158402. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158403. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158404. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158405. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158406. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158407. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158408. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158409. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158410. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158411. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158412. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158413. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158414. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158415. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158416. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158417. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158418. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158419. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158420. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158421. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158422. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158423. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158424. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158425. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158426. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158427. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158428. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158429. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158430. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158431. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158432. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158433. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158434. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158435. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158436. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158437. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158438. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158439. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158440. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158441. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158442. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158443. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158444. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158445. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158446. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158447. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158448. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158449. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158450. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158451. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158452. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158453. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158454. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158455. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158456. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158457. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158458. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158459. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158460. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158461. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158462. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158463. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158464. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158465. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158466. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158467. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158468. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158469. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158470. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158471. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158472. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158473. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158474. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158475. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158476. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158477. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158478. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158479. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158480. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158481. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158482. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158483. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158484. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158485. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158486. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158487. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158488. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158489. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158490. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158491. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158492. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158493. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158494. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158495. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158496. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158497. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158498. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158499. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158500. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158501. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158502. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158503. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158504. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158505. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158506. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158507. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158508. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158509. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158510. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158511. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158512. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158513. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158514. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158515. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158516. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158517. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158518. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158519. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158520. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158521. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158522. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158523. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158524. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158525. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158526. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158527. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158528. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158529. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158530. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158531. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158532. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158533. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158534. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158535. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158536. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158537. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158538. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158539. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158540. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158541. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158542. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158543. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158544. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158545. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158546. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158547. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158548. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158549. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158550. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158551. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158552. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158553. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158554. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158555. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158556. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158557. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158558. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158559. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158560. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158561. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158562. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158563. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158564. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158565. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158566. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158567. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158568. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158569. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158570. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158571. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158572. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158573. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158574. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158575. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158576. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158577. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158578. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158579. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158580. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158581. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158582. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158583. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158584. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158585. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158586. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158587. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158588. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158589. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158590. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158591. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158592. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158593. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158594. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158595. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158596. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158597. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158598. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158599. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158600. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158601. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158602. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158603. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158604. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158605. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158606. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158607. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158608. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158609. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158610. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158611. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158612. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158613. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158614. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158615. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158616. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158617. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158618. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158619. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158620. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158621. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158622. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158623. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158624. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158625. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158626. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158627. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158628. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158629. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158630. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158631. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158632. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158633. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158634. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158635. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158636. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158637. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158638. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158639. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158640. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158641. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158642. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158643. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158644. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158645. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158646. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158647. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158648. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158649. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158650. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158651. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158652. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158653. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158654. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158655. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158656. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158657. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158658. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158659. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158660. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158661. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158662. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158663. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158664. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158665. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158666. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158667. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158668. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158669. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158670. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158671. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158672. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158673. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158674. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158675. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158676. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158677. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158678. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158679. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158680. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158681. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158682. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158683. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158684. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158685. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158686. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158687. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158688. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158689. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158690. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158691. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158692. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158693. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158694. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158695. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158696. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158697. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158698. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158699. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158700. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158701. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158702. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158703. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158704. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158705. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158706. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158707. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158708. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158709. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158710. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158711. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158712. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158713. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158714. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158715. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158716. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158717. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158718. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158719. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158720. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158721. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158722. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158723. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158724. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158725. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158726. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158727. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158728. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158729. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158730. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158731. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158732. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158733. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158734. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158735. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158736. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158737. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158738. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158739. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158740. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158741. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158742. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158743. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158744. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158745. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158746. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158747. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158748. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158749. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158750. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158751. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158752. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158753. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158754. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158755. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158756. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158757. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158758. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158759. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158760. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158761. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158762. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158763. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158764. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158765. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158766. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158767. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158768. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158769. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158770. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158771. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158772. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158773. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158774. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158775. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158776. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158777. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158778. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158779. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158780. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158781. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158782. };
  158783. static float *vwin[8] = {
  158784. vwin64,
  158785. vwin128,
  158786. vwin256,
  158787. vwin512,
  158788. vwin1024,
  158789. vwin2048,
  158790. vwin4096,
  158791. vwin8192,
  158792. };
  158793. float *_vorbis_window_get(int n){
  158794. return vwin[n];
  158795. }
  158796. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158797. int lW,int W,int nW){
  158798. lW=(W?lW:0);
  158799. nW=(W?nW:0);
  158800. {
  158801. float *windowLW=vwin[winno[lW]];
  158802. float *windowNW=vwin[winno[nW]];
  158803. long n=blocksizes[W];
  158804. long ln=blocksizes[lW];
  158805. long rn=blocksizes[nW];
  158806. long leftbegin=n/4-ln/4;
  158807. long leftend=leftbegin+ln/2;
  158808. long rightbegin=n/2+n/4-rn/4;
  158809. long rightend=rightbegin+rn/2;
  158810. int i,p;
  158811. for(i=0;i<leftbegin;i++)
  158812. d[i]=0.f;
  158813. for(p=0;i<leftend;i++,p++)
  158814. d[i]*=windowLW[p];
  158815. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158816. d[i]*=windowNW[p];
  158817. for(;i<n;i++)
  158818. d[i]=0.f;
  158819. }
  158820. }
  158821. #endif
  158822. /*** End of inlined file: window.c ***/
  158823. #else
  158824. #include <vorbis/vorbisenc.h>
  158825. #include <vorbis/codec.h>
  158826. #include <vorbis/vorbisfile.h>
  158827. #endif
  158828. }
  158829. #undef max
  158830. #undef min
  158831. BEGIN_JUCE_NAMESPACE
  158832. static const char* const oggFormatName = "Ogg-Vorbis file";
  158833. static const char* const oggExtensions[] = { ".ogg", 0 };
  158834. class OggReader : public AudioFormatReader
  158835. {
  158836. OggVorbisNamespace::OggVorbis_File ovFile;
  158837. OggVorbisNamespace::ov_callbacks callbacks;
  158838. AudioSampleBuffer reservoir;
  158839. int reservoirStart, samplesInReservoir;
  158840. public:
  158841. OggReader (InputStream* const inp)
  158842. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158843. reservoir (2, 4096),
  158844. reservoirStart (0),
  158845. samplesInReservoir (0)
  158846. {
  158847. using namespace OggVorbisNamespace;
  158848. sampleRate = 0;
  158849. usesFloatingPointData = true;
  158850. callbacks.read_func = &oggReadCallback;
  158851. callbacks.seek_func = &oggSeekCallback;
  158852. callbacks.close_func = &oggCloseCallback;
  158853. callbacks.tell_func = &oggTellCallback;
  158854. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158855. if (err == 0)
  158856. {
  158857. vorbis_info* info = ov_info (&ovFile, -1);
  158858. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158859. numChannels = info->channels;
  158860. bitsPerSample = 16;
  158861. sampleRate = info->rate;
  158862. reservoir.setSize (numChannels,
  158863. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158864. }
  158865. }
  158866. ~OggReader()
  158867. {
  158868. OggVorbisNamespace::ov_clear (&ovFile);
  158869. }
  158870. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158871. int64 startSampleInFile, int numSamples)
  158872. {
  158873. while (numSamples > 0)
  158874. {
  158875. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158876. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158877. {
  158878. // got a few samples overlapping, so use them before seeking..
  158879. const int numToUse = jmin (numSamples, numAvailable);
  158880. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158881. if (destSamples[i] != 0)
  158882. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158883. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158884. sizeof (float) * numToUse);
  158885. startSampleInFile += numToUse;
  158886. numSamples -= numToUse;
  158887. startOffsetInDestBuffer += numToUse;
  158888. if (numSamples == 0)
  158889. break;
  158890. }
  158891. if (startSampleInFile < reservoirStart
  158892. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158893. {
  158894. // buffer miss, so refill the reservoir
  158895. int bitStream = 0;
  158896. reservoirStart = jmax (0, (int) startSampleInFile);
  158897. samplesInReservoir = reservoir.getNumSamples();
  158898. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158899. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158900. int offset = 0;
  158901. int numToRead = samplesInReservoir;
  158902. while (numToRead > 0)
  158903. {
  158904. float** dataIn = 0;
  158905. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158906. if (samps <= 0)
  158907. break;
  158908. jassert (samps <= numToRead);
  158909. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158910. {
  158911. memcpy (reservoir.getSampleData (i, offset),
  158912. dataIn[i],
  158913. sizeof (float) * samps);
  158914. }
  158915. numToRead -= samps;
  158916. offset += samps;
  158917. }
  158918. if (numToRead > 0)
  158919. reservoir.clear (offset, numToRead);
  158920. }
  158921. }
  158922. if (numSamples > 0)
  158923. {
  158924. for (int i = numDestChannels; --i >= 0;)
  158925. if (destSamples[i] != 0)
  158926. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158927. sizeof (int) * numSamples);
  158928. }
  158929. return true;
  158930. }
  158931. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158932. {
  158933. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158934. }
  158935. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158936. {
  158937. InputStream* const in = static_cast <InputStream*> (datasource);
  158938. if (whence == SEEK_CUR)
  158939. offset += in->getPosition();
  158940. else if (whence == SEEK_END)
  158941. offset += in->getTotalLength();
  158942. in->setPosition (offset);
  158943. return 0;
  158944. }
  158945. static int oggCloseCallback (void*)
  158946. {
  158947. return 0;
  158948. }
  158949. static long oggTellCallback (void* datasource)
  158950. {
  158951. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158952. }
  158953. private:
  158954. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  158955. };
  158956. class OggWriter : public AudioFormatWriter
  158957. {
  158958. OggVorbisNamespace::ogg_stream_state os;
  158959. OggVorbisNamespace::ogg_page og;
  158960. OggVorbisNamespace::ogg_packet op;
  158961. OggVorbisNamespace::vorbis_info vi;
  158962. OggVorbisNamespace::vorbis_comment vc;
  158963. OggVorbisNamespace::vorbis_dsp_state vd;
  158964. OggVorbisNamespace::vorbis_block vb;
  158965. public:
  158966. bool ok;
  158967. OggWriter (OutputStream* const out,
  158968. const double sampleRate,
  158969. const int numChannels,
  158970. const int bitsPerSample,
  158971. const int qualityIndex)
  158972. : AudioFormatWriter (out, TRANS (oggFormatName),
  158973. sampleRate,
  158974. numChannels,
  158975. bitsPerSample)
  158976. {
  158977. using namespace OggVorbisNamespace;
  158978. ok = false;
  158979. vorbis_info_init (&vi);
  158980. if (vorbis_encode_init_vbr (&vi,
  158981. numChannels,
  158982. (int) sampleRate,
  158983. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158984. {
  158985. vorbis_comment_init (&vc);
  158986. if (JUCEApplication::getInstance() != 0)
  158987. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  158988. vorbis_analysis_init (&vd, &vi);
  158989. vorbis_block_init (&vd, &vb);
  158990. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158991. ogg_packet header;
  158992. ogg_packet header_comm;
  158993. ogg_packet header_code;
  158994. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158995. ogg_stream_packetin (&os, &header);
  158996. ogg_stream_packetin (&os, &header_comm);
  158997. ogg_stream_packetin (&os, &header_code);
  158998. for (;;)
  158999. {
  159000. if (ogg_stream_flush (&os, &og) == 0)
  159001. break;
  159002. output->write (og.header, og.header_len);
  159003. output->write (og.body, og.body_len);
  159004. }
  159005. ok = true;
  159006. }
  159007. }
  159008. ~OggWriter()
  159009. {
  159010. using namespace OggVorbisNamespace;
  159011. if (ok)
  159012. {
  159013. // write a zero-length packet to show ogg that we're finished..
  159014. write (0, 0);
  159015. ogg_stream_clear (&os);
  159016. vorbis_block_clear (&vb);
  159017. vorbis_dsp_clear (&vd);
  159018. vorbis_comment_clear (&vc);
  159019. vorbis_info_clear (&vi);
  159020. output->flush();
  159021. }
  159022. else
  159023. {
  159024. vorbis_info_clear (&vi);
  159025. output = 0; // to stop the base class deleting this, as it needs to be returned
  159026. // to the caller of createWriter()
  159027. }
  159028. }
  159029. bool write (const int** samplesToWrite, int numSamples)
  159030. {
  159031. using namespace OggVorbisNamespace;
  159032. if (! ok)
  159033. return false;
  159034. if (numSamples > 0)
  159035. {
  159036. const double gain = 1.0 / 0x80000000u;
  159037. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159038. for (int i = numChannels; --i >= 0;)
  159039. {
  159040. float* const dst = vorbisBuffer[i];
  159041. const int* const src = samplesToWrite [i];
  159042. if (src != 0 && dst != 0)
  159043. {
  159044. for (int j = 0; j < numSamples; ++j)
  159045. dst[j] = (float) (src[j] * gain);
  159046. }
  159047. }
  159048. }
  159049. vorbis_analysis_wrote (&vd, numSamples);
  159050. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159051. {
  159052. vorbis_analysis (&vb, 0);
  159053. vorbis_bitrate_addblock (&vb);
  159054. while (vorbis_bitrate_flushpacket (&vd, &op))
  159055. {
  159056. ogg_stream_packetin (&os, &op);
  159057. for (;;)
  159058. {
  159059. if (ogg_stream_pageout (&os, &og) == 0)
  159060. break;
  159061. output->write (og.header, og.header_len);
  159062. output->write (og.body, og.body_len);
  159063. if (ogg_page_eos (&og))
  159064. break;
  159065. }
  159066. }
  159067. }
  159068. return true;
  159069. }
  159070. private:
  159071. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159072. };
  159073. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159074. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159075. {
  159076. }
  159077. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159078. {
  159079. }
  159080. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159081. {
  159082. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159083. return Array <int> (rates);
  159084. }
  159085. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159086. {
  159087. const int depths[] = { 32, 0 };
  159088. return Array <int> (depths);
  159089. }
  159090. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159091. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159092. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159093. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159094. const bool deleteStreamIfOpeningFails)
  159095. {
  159096. ScopedPointer <OggReader> r (new OggReader (in));
  159097. if (r->sampleRate != 0)
  159098. return r.release();
  159099. if (! deleteStreamIfOpeningFails)
  159100. r->input = 0;
  159101. return 0;
  159102. }
  159103. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159104. double sampleRate,
  159105. unsigned int numChannels,
  159106. int bitsPerSample,
  159107. const StringPairArray& /*metadataValues*/,
  159108. int qualityOptionIndex)
  159109. {
  159110. ScopedPointer <OggWriter> w (new OggWriter (out,
  159111. sampleRate,
  159112. numChannels,
  159113. bitsPerSample,
  159114. qualityOptionIndex));
  159115. return w->ok ? w.release() : 0;
  159116. }
  159117. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159118. {
  159119. StringArray s;
  159120. s.add ("Low Quality");
  159121. s.add ("Medium Quality");
  159122. s.add ("High Quality");
  159123. return s;
  159124. }
  159125. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159126. {
  159127. FileInputStream* const in = source.createInputStream();
  159128. if (in != 0)
  159129. {
  159130. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159131. if (r != 0)
  159132. {
  159133. const int64 numSamps = r->lengthInSamples;
  159134. r = 0;
  159135. const int64 fileNumSamps = source.getSize() / 4;
  159136. const double ratio = numSamps / (double) fileNumSamps;
  159137. if (ratio > 12.0)
  159138. return 0;
  159139. else if (ratio > 6.0)
  159140. return 1;
  159141. else
  159142. return 2;
  159143. }
  159144. }
  159145. return 1;
  159146. }
  159147. END_JUCE_NAMESPACE
  159148. #endif
  159149. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159150. #endif
  159151. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159152. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159153. #if JUCE_MSVC
  159154. #pragma warning (push)
  159155. #endif
  159156. namespace jpeglibNamespace
  159157. {
  159158. #if JUCE_INCLUDE_JPEGLIB_CODE
  159159. #if JUCE_MINGW
  159160. typedef unsigned char boolean;
  159161. #endif
  159162. #define JPEG_INTERNALS
  159163. #undef FAR
  159164. /*** Start of inlined file: jpeglib.h ***/
  159165. #ifndef JPEGLIB_H
  159166. #define JPEGLIB_H
  159167. /*
  159168. * First we include the configuration files that record how this
  159169. * installation of the JPEG library is set up. jconfig.h can be
  159170. * generated automatically for many systems. jmorecfg.h contains
  159171. * manual configuration options that most people need not worry about.
  159172. */
  159173. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159174. /*** Start of inlined file: jconfig.h ***/
  159175. /* see jconfig.doc for explanations */
  159176. // disable all the warnings under MSVC
  159177. #ifdef _MSC_VER
  159178. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159179. #endif
  159180. #ifdef __BORLANDC__
  159181. #pragma warn -8057
  159182. #pragma warn -8019
  159183. #pragma warn -8004
  159184. #pragma warn -8008
  159185. #endif
  159186. #define HAVE_PROTOTYPES
  159187. #define HAVE_UNSIGNED_CHAR
  159188. #define HAVE_UNSIGNED_SHORT
  159189. /* #define void char */
  159190. /* #define const */
  159191. #undef CHAR_IS_UNSIGNED
  159192. #define HAVE_STDDEF_H
  159193. #define HAVE_STDLIB_H
  159194. #undef NEED_BSD_STRINGS
  159195. #undef NEED_SYS_TYPES_H
  159196. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159197. #undef NEED_SHORT_EXTERNAL_NAMES
  159198. #undef INCOMPLETE_TYPES_BROKEN
  159199. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159200. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159201. typedef unsigned char boolean;
  159202. #endif
  159203. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159204. #ifdef JPEG_INTERNALS
  159205. #undef RIGHT_SHIFT_IS_UNSIGNED
  159206. #endif /* JPEG_INTERNALS */
  159207. #ifdef JPEG_CJPEG_DJPEG
  159208. #define BMP_SUPPORTED /* BMP image file format */
  159209. #define GIF_SUPPORTED /* GIF image file format */
  159210. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159211. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159212. #define TARGA_SUPPORTED /* Targa image file format */
  159213. #define TWO_FILE_COMMANDLINE /* optional */
  159214. #define USE_SETMODE /* Microsoft has setmode() */
  159215. #undef NEED_SIGNAL_CATCHER
  159216. #undef DONT_USE_B_MODE
  159217. #undef PROGRESS_REPORT /* optional */
  159218. #endif /* JPEG_CJPEG_DJPEG */
  159219. /*** End of inlined file: jconfig.h ***/
  159220. /* widely used configuration options */
  159221. #endif
  159222. /*** Start of inlined file: jmorecfg.h ***/
  159223. /*
  159224. * Define BITS_IN_JSAMPLE as either
  159225. * 8 for 8-bit sample values (the usual setting)
  159226. * 12 for 12-bit sample values
  159227. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159228. * JPEG standard, and the IJG code does not support anything else!
  159229. * We do not support run-time selection of data precision, sorry.
  159230. */
  159231. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159232. /*
  159233. * Maximum number of components (color channels) allowed in JPEG image.
  159234. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159235. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159236. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159237. * really short on memory. (Each allowed component costs a hundred or so
  159238. * bytes of storage, whether actually used in an image or not.)
  159239. */
  159240. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159241. /*
  159242. * Basic data types.
  159243. * You may need to change these if you have a machine with unusual data
  159244. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159245. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159246. * but it had better be at least 16.
  159247. */
  159248. /* Representation of a single sample (pixel element value).
  159249. * We frequently allocate large arrays of these, so it's important to keep
  159250. * them small. But if you have memory to burn and access to char or short
  159251. * arrays is very slow on your hardware, you might want to change these.
  159252. */
  159253. #if BITS_IN_JSAMPLE == 8
  159254. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159255. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159256. */
  159257. #ifdef HAVE_UNSIGNED_CHAR
  159258. typedef unsigned char JSAMPLE;
  159259. #define GETJSAMPLE(value) ((int) (value))
  159260. #else /* not HAVE_UNSIGNED_CHAR */
  159261. typedef char JSAMPLE;
  159262. #ifdef CHAR_IS_UNSIGNED
  159263. #define GETJSAMPLE(value) ((int) (value))
  159264. #else
  159265. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159266. #endif /* CHAR_IS_UNSIGNED */
  159267. #endif /* HAVE_UNSIGNED_CHAR */
  159268. #define MAXJSAMPLE 255
  159269. #define CENTERJSAMPLE 128
  159270. #endif /* BITS_IN_JSAMPLE == 8 */
  159271. #if BITS_IN_JSAMPLE == 12
  159272. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159273. * On nearly all machines "short" will do nicely.
  159274. */
  159275. typedef short JSAMPLE;
  159276. #define GETJSAMPLE(value) ((int) (value))
  159277. #define MAXJSAMPLE 4095
  159278. #define CENTERJSAMPLE 2048
  159279. #endif /* BITS_IN_JSAMPLE == 12 */
  159280. /* Representation of a DCT frequency coefficient.
  159281. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159282. * Again, we allocate large arrays of these, but you can change to int
  159283. * if you have memory to burn and "short" is really slow.
  159284. */
  159285. typedef short JCOEF;
  159286. /* Compressed datastreams are represented as arrays of JOCTET.
  159287. * These must be EXACTLY 8 bits wide, at least once they are written to
  159288. * external storage. Note that when using the stdio data source/destination
  159289. * managers, this is also the data type passed to fread/fwrite.
  159290. */
  159291. #ifdef HAVE_UNSIGNED_CHAR
  159292. typedef unsigned char JOCTET;
  159293. #define GETJOCTET(value) (value)
  159294. #else /* not HAVE_UNSIGNED_CHAR */
  159295. typedef char JOCTET;
  159296. #ifdef CHAR_IS_UNSIGNED
  159297. #define GETJOCTET(value) (value)
  159298. #else
  159299. #define GETJOCTET(value) ((value) & 0xFF)
  159300. #endif /* CHAR_IS_UNSIGNED */
  159301. #endif /* HAVE_UNSIGNED_CHAR */
  159302. /* These typedefs are used for various table entries and so forth.
  159303. * They must be at least as wide as specified; but making them too big
  159304. * won't cost a huge amount of memory, so we don't provide special
  159305. * extraction code like we did for JSAMPLE. (In other words, these
  159306. * typedefs live at a different point on the speed/space tradeoff curve.)
  159307. */
  159308. /* UINT8 must hold at least the values 0..255. */
  159309. #ifdef HAVE_UNSIGNED_CHAR
  159310. typedef unsigned char UINT8;
  159311. #else /* not HAVE_UNSIGNED_CHAR */
  159312. #ifdef CHAR_IS_UNSIGNED
  159313. typedef char UINT8;
  159314. #else /* not CHAR_IS_UNSIGNED */
  159315. typedef short UINT8;
  159316. #endif /* CHAR_IS_UNSIGNED */
  159317. #endif /* HAVE_UNSIGNED_CHAR */
  159318. /* UINT16 must hold at least the values 0..65535. */
  159319. #ifdef HAVE_UNSIGNED_SHORT
  159320. typedef unsigned short UINT16;
  159321. #else /* not HAVE_UNSIGNED_SHORT */
  159322. typedef unsigned int UINT16;
  159323. #endif /* HAVE_UNSIGNED_SHORT */
  159324. /* INT16 must hold at least the values -32768..32767. */
  159325. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159326. typedef short INT16;
  159327. #endif
  159328. /* INT32 must hold at least signed 32-bit values. */
  159329. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159330. typedef long INT32;
  159331. #endif
  159332. /* Datatype used for image dimensions. The JPEG standard only supports
  159333. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159334. * "unsigned int" is sufficient on all machines. However, if you need to
  159335. * handle larger images and you don't mind deviating from the spec, you
  159336. * can change this datatype.
  159337. */
  159338. typedef unsigned int JDIMENSION;
  159339. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159340. /* These macros are used in all function definitions and extern declarations.
  159341. * You could modify them if you need to change function linkage conventions;
  159342. * in particular, you'll need to do that to make the library a Windows DLL.
  159343. * Another application is to make all functions global for use with debuggers
  159344. * or code profilers that require it.
  159345. */
  159346. /* a function called through method pointers: */
  159347. #define METHODDEF(type) static type
  159348. /* a function used only in its module: */
  159349. #define LOCAL(type) static type
  159350. /* a function referenced thru EXTERNs: */
  159351. #define GLOBAL(type) type
  159352. /* a reference to a GLOBAL function: */
  159353. #define EXTERN(type) extern type
  159354. /* This macro is used to declare a "method", that is, a function pointer.
  159355. * We want to supply prototype parameters if the compiler can cope.
  159356. * Note that the arglist parameter must be parenthesized!
  159357. * Again, you can customize this if you need special linkage keywords.
  159358. */
  159359. #ifdef HAVE_PROTOTYPES
  159360. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159361. #else
  159362. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159363. #endif
  159364. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159365. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159366. * by just saying "FAR *" where such a pointer is needed. In a few places
  159367. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159368. */
  159369. #ifdef NEED_FAR_POINTERS
  159370. #define FAR far
  159371. #else
  159372. #define FAR
  159373. #endif
  159374. /*
  159375. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159376. * in standard header files. Or you may have conflicts with application-
  159377. * specific header files that you want to include together with these files.
  159378. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159379. */
  159380. #ifndef HAVE_BOOLEAN
  159381. typedef int boolean;
  159382. #endif
  159383. #ifndef FALSE /* in case these macros already exist */
  159384. #define FALSE 0 /* values of boolean */
  159385. #endif
  159386. #ifndef TRUE
  159387. #define TRUE 1
  159388. #endif
  159389. /*
  159390. * The remaining options affect code selection within the JPEG library,
  159391. * but they don't need to be visible to most applications using the library.
  159392. * To minimize application namespace pollution, the symbols won't be
  159393. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159394. */
  159395. #ifdef JPEG_INTERNALS
  159396. #define JPEG_INTERNAL_OPTIONS
  159397. #endif
  159398. #ifdef JPEG_INTERNAL_OPTIONS
  159399. /*
  159400. * These defines indicate whether to include various optional functions.
  159401. * Undefining some of these symbols will produce a smaller but less capable
  159402. * library. Note that you can leave certain source files out of the
  159403. * compilation/linking process if you've #undef'd the corresponding symbols.
  159404. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159405. */
  159406. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159407. /* Capability options common to encoder and decoder: */
  159408. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159409. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159410. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159411. /* Encoder capability options: */
  159412. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159413. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159414. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159415. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159416. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159417. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159418. * precision, so jchuff.c normally uses entropy optimization to compute
  159419. * usable tables for higher precision. If you don't want to do optimization,
  159420. * you'll have to supply different default Huffman tables.
  159421. * The exact same statements apply for progressive JPEG: the default tables
  159422. * don't work for progressive mode. (This may get fixed, however.)
  159423. */
  159424. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159425. /* Decoder capability options: */
  159426. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159427. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159428. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159429. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159430. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159431. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159432. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159433. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159434. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159435. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159436. /* more capability options later, no doubt */
  159437. /*
  159438. * Ordering of RGB data in scanlines passed to or from the application.
  159439. * If your application wants to deal with data in the order B,G,R, just
  159440. * change these macros. You can also deal with formats such as R,G,B,X
  159441. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159442. * the offsets will also change the order in which colormap data is organized.
  159443. * RESTRICTIONS:
  159444. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159445. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159446. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159447. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159448. * is not 3 (they don't understand about dummy color components!). So you
  159449. * can't use color quantization if you change that value.
  159450. */
  159451. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159452. #define RGB_GREEN 1 /* Offset of Green */
  159453. #define RGB_BLUE 2 /* Offset of Blue */
  159454. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159455. /* Definitions for speed-related optimizations. */
  159456. /* If your compiler supports inline functions, define INLINE
  159457. * as the inline keyword; otherwise define it as empty.
  159458. */
  159459. #ifndef INLINE
  159460. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159461. #define INLINE __inline__
  159462. #endif
  159463. #ifndef INLINE
  159464. #define INLINE /* default is to define it as empty */
  159465. #endif
  159466. #endif
  159467. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159468. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159469. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159470. */
  159471. #ifndef MULTIPLIER
  159472. #define MULTIPLIER int /* type for fastest integer multiply */
  159473. #endif
  159474. /* FAST_FLOAT should be either float or double, whichever is done faster
  159475. * by your compiler. (Note that this type is only used in the floating point
  159476. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159477. * Typically, float is faster in ANSI C compilers, while double is faster in
  159478. * pre-ANSI compilers (because they insist on converting to double anyway).
  159479. * The code below therefore chooses float if we have ANSI-style prototypes.
  159480. */
  159481. #ifndef FAST_FLOAT
  159482. #ifdef HAVE_PROTOTYPES
  159483. #define FAST_FLOAT float
  159484. #else
  159485. #define FAST_FLOAT double
  159486. #endif
  159487. #endif
  159488. #endif /* JPEG_INTERNAL_OPTIONS */
  159489. /*** End of inlined file: jmorecfg.h ***/
  159490. /* seldom changed options */
  159491. /* Version ID for the JPEG library.
  159492. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159493. */
  159494. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159495. /* Various constants determining the sizes of things.
  159496. * All of these are specified by the JPEG standard, so don't change them
  159497. * if you want to be compatible.
  159498. */
  159499. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159500. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159501. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159502. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159503. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159504. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159505. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159506. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159507. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159508. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159509. * to handle it. We even let you do this from the jconfig.h file. However,
  159510. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159511. * sometimes emits noncompliant files doesn't mean you should too.
  159512. */
  159513. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159514. #ifndef D_MAX_BLOCKS_IN_MCU
  159515. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159516. #endif
  159517. /* Data structures for images (arrays of samples and of DCT coefficients).
  159518. * On 80x86 machines, the image arrays are too big for near pointers,
  159519. * but the pointer arrays can fit in near memory.
  159520. */
  159521. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159522. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159523. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159524. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159525. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159526. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159527. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159528. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159529. /* Types for JPEG compression parameters and working tables. */
  159530. /* DCT coefficient quantization tables. */
  159531. typedef struct {
  159532. /* This array gives the coefficient quantizers in natural array order
  159533. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159534. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159535. */
  159536. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159537. /* This field is used only during compression. It's initialized FALSE when
  159538. * the table is created, and set TRUE when it's been output to the file.
  159539. * You could suppress output of a table by setting this to TRUE.
  159540. * (See jpeg_suppress_tables for an example.)
  159541. */
  159542. boolean sent_table; /* TRUE when table has been output */
  159543. } JQUANT_TBL;
  159544. /* Huffman coding tables. */
  159545. typedef struct {
  159546. /* These two fields directly represent the contents of a JPEG DHT marker */
  159547. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159548. /* length k bits; bits[0] is unused */
  159549. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159550. /* This field is used only during compression. It's initialized FALSE when
  159551. * the table is created, and set TRUE when it's been output to the file.
  159552. * You could suppress output of a table by setting this to TRUE.
  159553. * (See jpeg_suppress_tables for an example.)
  159554. */
  159555. boolean sent_table; /* TRUE when table has been output */
  159556. } JHUFF_TBL;
  159557. /* Basic info about one component (color channel). */
  159558. typedef struct {
  159559. /* These values are fixed over the whole image. */
  159560. /* For compression, they must be supplied by parameter setup; */
  159561. /* for decompression, they are read from the SOF marker. */
  159562. int component_id; /* identifier for this component (0..255) */
  159563. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159564. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159565. int v_samp_factor; /* vertical sampling factor (1..4) */
  159566. int quant_tbl_no; /* quantization table selector (0..3) */
  159567. /* These values may vary between scans. */
  159568. /* For compression, they must be supplied by parameter setup; */
  159569. /* for decompression, they are read from the SOS marker. */
  159570. /* The decompressor output side may not use these variables. */
  159571. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159572. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159573. /* Remaining fields should be treated as private by applications. */
  159574. /* These values are computed during compression or decompression startup: */
  159575. /* Component's size in DCT blocks.
  159576. * Any dummy blocks added to complete an MCU are not counted; therefore
  159577. * these values do not depend on whether a scan is interleaved or not.
  159578. */
  159579. JDIMENSION width_in_blocks;
  159580. JDIMENSION height_in_blocks;
  159581. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159582. * For decompression this is the size of the output from one DCT block,
  159583. * reflecting any scaling we choose to apply during the IDCT step.
  159584. * Values of 1,2,4,8 are likely to be supported. Note that different
  159585. * components may receive different IDCT scalings.
  159586. */
  159587. int DCT_scaled_size;
  159588. /* The downsampled dimensions are the component's actual, unpadded number
  159589. * of samples at the main buffer (preprocessing/compression interface), thus
  159590. * downsampled_width = ceil(image_width * Hi/Hmax)
  159591. * and similarly for height. For decompression, IDCT scaling is included, so
  159592. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159593. */
  159594. JDIMENSION downsampled_width; /* actual width in samples */
  159595. JDIMENSION downsampled_height; /* actual height in samples */
  159596. /* This flag is used only for decompression. In cases where some of the
  159597. * components will be ignored (eg grayscale output from YCbCr image),
  159598. * we can skip most computations for the unused components.
  159599. */
  159600. boolean component_needed; /* do we need the value of this component? */
  159601. /* These values are computed before starting a scan of the component. */
  159602. /* The decompressor output side may not use these variables. */
  159603. int MCU_width; /* number of blocks per MCU, horizontally */
  159604. int MCU_height; /* number of blocks per MCU, vertically */
  159605. int MCU_blocks; /* MCU_width * MCU_height */
  159606. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159607. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159608. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159609. /* Saved quantization table for component; NULL if none yet saved.
  159610. * See jdinput.c comments about the need for this information.
  159611. * This field is currently used only for decompression.
  159612. */
  159613. JQUANT_TBL * quant_table;
  159614. /* Private per-component storage for DCT or IDCT subsystem. */
  159615. void * dct_table;
  159616. } jpeg_component_info;
  159617. /* The script for encoding a multiple-scan file is an array of these: */
  159618. typedef struct {
  159619. int comps_in_scan; /* number of components encoded in this scan */
  159620. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159621. int Ss, Se; /* progressive JPEG spectral selection parms */
  159622. int Ah, Al; /* progressive JPEG successive approx. parms */
  159623. } jpeg_scan_info;
  159624. /* The decompressor can save APPn and COM markers in a list of these: */
  159625. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159626. struct jpeg_marker_struct {
  159627. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159628. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159629. unsigned int original_length; /* # bytes of data in the file */
  159630. unsigned int data_length; /* # bytes of data saved at data[] */
  159631. JOCTET FAR * data; /* the data contained in the marker */
  159632. /* the marker length word is not counted in data_length or original_length */
  159633. };
  159634. /* Known color spaces. */
  159635. typedef enum {
  159636. JCS_UNKNOWN, /* error/unspecified */
  159637. JCS_GRAYSCALE, /* monochrome */
  159638. JCS_RGB, /* red/green/blue */
  159639. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159640. JCS_CMYK, /* C/M/Y/K */
  159641. JCS_YCCK /* Y/Cb/Cr/K */
  159642. } J_COLOR_SPACE;
  159643. /* DCT/IDCT algorithm options. */
  159644. typedef enum {
  159645. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159646. JDCT_IFAST, /* faster, less accurate integer method */
  159647. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159648. } J_DCT_METHOD;
  159649. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159650. #define JDCT_DEFAULT JDCT_ISLOW
  159651. #endif
  159652. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159653. #define JDCT_FASTEST JDCT_IFAST
  159654. #endif
  159655. /* Dithering options for decompression. */
  159656. typedef enum {
  159657. JDITHER_NONE, /* no dithering */
  159658. JDITHER_ORDERED, /* simple ordered dither */
  159659. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159660. } J_DITHER_MODE;
  159661. /* Common fields between JPEG compression and decompression master structs. */
  159662. #define jpeg_common_fields \
  159663. struct jpeg_error_mgr * err; /* Error handler module */\
  159664. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159665. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159666. void * client_data; /* Available for use by application */\
  159667. boolean is_decompressor; /* So common code can tell which is which */\
  159668. int global_state /* For checking call sequence validity */
  159669. /* Routines that are to be used by both halves of the library are declared
  159670. * to receive a pointer to this structure. There are no actual instances of
  159671. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159672. */
  159673. struct jpeg_common_struct {
  159674. jpeg_common_fields; /* Fields common to both master struct types */
  159675. /* Additional fields follow in an actual jpeg_compress_struct or
  159676. * jpeg_decompress_struct. All three structs must agree on these
  159677. * initial fields! (This would be a lot cleaner in C++.)
  159678. */
  159679. };
  159680. typedef struct jpeg_common_struct * j_common_ptr;
  159681. typedef struct jpeg_compress_struct * j_compress_ptr;
  159682. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159683. /* Master record for a compression instance */
  159684. struct jpeg_compress_struct {
  159685. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159686. /* Destination for compressed data */
  159687. struct jpeg_destination_mgr * dest;
  159688. /* Description of source image --- these fields must be filled in by
  159689. * outer application before starting compression. in_color_space must
  159690. * be correct before you can even call jpeg_set_defaults().
  159691. */
  159692. JDIMENSION image_width; /* input image width */
  159693. JDIMENSION image_height; /* input image height */
  159694. int input_components; /* # of color components in input image */
  159695. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159696. double input_gamma; /* image gamma of input image */
  159697. /* Compression parameters --- these fields must be set before calling
  159698. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159699. * initialize everything to reasonable defaults, then changing anything
  159700. * the application specifically wants to change. That way you won't get
  159701. * burnt when new parameters are added. Also note that there are several
  159702. * helper routines to simplify changing parameters.
  159703. */
  159704. int data_precision; /* bits of precision in image data */
  159705. int num_components; /* # of color components in JPEG image */
  159706. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159707. jpeg_component_info * comp_info;
  159708. /* comp_info[i] describes component that appears i'th in SOF */
  159709. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159710. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159711. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159712. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159713. /* ptrs to Huffman coding tables, or NULL if not defined */
  159714. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159715. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159716. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159717. int num_scans; /* # of entries in scan_info array */
  159718. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159719. /* The default value of scan_info is NULL, which causes a single-scan
  159720. * sequential JPEG file to be emitted. To create a multi-scan file,
  159721. * set num_scans and scan_info to point to an array of scan definitions.
  159722. */
  159723. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159724. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159725. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159726. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159727. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159728. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159729. /* The restart interval can be specified in absolute MCUs by setting
  159730. * restart_interval, or in MCU rows by setting restart_in_rows
  159731. * (in which case the correct restart_interval will be figured
  159732. * for each scan).
  159733. */
  159734. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159735. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159736. /* Parameters controlling emission of special markers. */
  159737. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159738. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159739. UINT8 JFIF_minor_version;
  159740. /* These three values are not used by the JPEG code, merely copied */
  159741. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159742. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159743. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159744. UINT8 density_unit; /* JFIF code for pixel size units */
  159745. UINT16 X_density; /* Horizontal pixel density */
  159746. UINT16 Y_density; /* Vertical pixel density */
  159747. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159748. /* State variable: index of next scanline to be written to
  159749. * jpeg_write_scanlines(). Application may use this to control its
  159750. * processing loop, e.g., "while (next_scanline < image_height)".
  159751. */
  159752. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159753. /* Remaining fields are known throughout compressor, but generally
  159754. * should not be touched by a surrounding application.
  159755. */
  159756. /*
  159757. * These fields are computed during compression startup
  159758. */
  159759. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159760. int max_h_samp_factor; /* largest h_samp_factor */
  159761. int max_v_samp_factor; /* largest v_samp_factor */
  159762. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159763. /* The coefficient controller receives data in units of MCU rows as defined
  159764. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159765. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159766. * "iMCU" (interleaved MCU) row.
  159767. */
  159768. /*
  159769. * These fields are valid during any one scan.
  159770. * They describe the components and MCUs actually appearing in the scan.
  159771. */
  159772. int comps_in_scan; /* # of JPEG components in this scan */
  159773. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159774. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159775. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159776. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159777. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159778. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159779. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159780. /* i'th block in an MCU */
  159781. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159782. /*
  159783. * Links to compression subobjects (methods and private variables of modules)
  159784. */
  159785. struct jpeg_comp_master * master;
  159786. struct jpeg_c_main_controller * main;
  159787. struct jpeg_c_prep_controller * prep;
  159788. struct jpeg_c_coef_controller * coef;
  159789. struct jpeg_marker_writer * marker;
  159790. struct jpeg_color_converter * cconvert;
  159791. struct jpeg_downsampler * downsample;
  159792. struct jpeg_forward_dct * fdct;
  159793. struct jpeg_entropy_encoder * entropy;
  159794. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159795. int script_space_size;
  159796. };
  159797. /* Master record for a decompression instance */
  159798. struct jpeg_decompress_struct {
  159799. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159800. /* Source of compressed data */
  159801. struct jpeg_source_mgr * src;
  159802. /* Basic description of image --- filled in by jpeg_read_header(). */
  159803. /* Application may inspect these values to decide how to process image. */
  159804. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159805. JDIMENSION image_height; /* nominal image height */
  159806. int num_components; /* # of color components in JPEG image */
  159807. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159808. /* Decompression processing parameters --- these fields must be set before
  159809. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159810. * them to default values.
  159811. */
  159812. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159813. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159814. double output_gamma; /* image gamma wanted in output */
  159815. boolean buffered_image; /* TRUE=multiple output passes */
  159816. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159817. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159818. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159819. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159820. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159821. /* the following are ignored if not quantize_colors: */
  159822. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159823. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159824. int desired_number_of_colors; /* max # colors to use in created colormap */
  159825. /* these are significant only in buffered-image mode: */
  159826. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159827. boolean enable_external_quant;/* enable future use of external colormap */
  159828. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159829. /* Description of actual output image that will be returned to application.
  159830. * These fields are computed by jpeg_start_decompress().
  159831. * You can also use jpeg_calc_output_dimensions() to determine these values
  159832. * in advance of calling jpeg_start_decompress().
  159833. */
  159834. JDIMENSION output_width; /* scaled image width */
  159835. JDIMENSION output_height; /* scaled image height */
  159836. int out_color_components; /* # of color components in out_color_space */
  159837. int output_components; /* # of color components returned */
  159838. /* output_components is 1 (a colormap index) when quantizing colors;
  159839. * otherwise it equals out_color_components.
  159840. */
  159841. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159842. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159843. * high, space and time will be wasted due to unnecessary data copying.
  159844. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159845. */
  159846. /* When quantizing colors, the output colormap is described by these fields.
  159847. * The application can supply a colormap by setting colormap non-NULL before
  159848. * calling jpeg_start_decompress; otherwise a colormap is created during
  159849. * jpeg_start_decompress or jpeg_start_output.
  159850. * The map has out_color_components rows and actual_number_of_colors columns.
  159851. */
  159852. int actual_number_of_colors; /* number of entries in use */
  159853. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159854. /* State variables: these variables indicate the progress of decompression.
  159855. * The application may examine these but must not modify them.
  159856. */
  159857. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159858. * Application may use this to control its processing loop, e.g.,
  159859. * "while (output_scanline < output_height)".
  159860. */
  159861. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159862. /* Current input scan number and number of iMCU rows completed in scan.
  159863. * These indicate the progress of the decompressor input side.
  159864. */
  159865. int input_scan_number; /* Number of SOS markers seen so far */
  159866. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159867. /* The "output scan number" is the notional scan being displayed by the
  159868. * output side. The decompressor will not allow output scan/row number
  159869. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159870. */
  159871. int output_scan_number; /* Nominal scan number being displayed */
  159872. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159873. /* Current progression status. coef_bits[c][i] indicates the precision
  159874. * with which component c's DCT coefficient i (in zigzag order) is known.
  159875. * It is -1 when no data has yet been received, otherwise it is the point
  159876. * transform (shift) value for the most recent scan of the coefficient
  159877. * (thus, 0 at completion of the progression).
  159878. * This pointer is NULL when reading a non-progressive file.
  159879. */
  159880. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159881. /* Internal JPEG parameters --- the application usually need not look at
  159882. * these fields. Note that the decompressor output side may not use
  159883. * any parameters that can change between scans.
  159884. */
  159885. /* Quantization and Huffman tables are carried forward across input
  159886. * datastreams when processing abbreviated JPEG datastreams.
  159887. */
  159888. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159889. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159890. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159891. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159892. /* ptrs to Huffman coding tables, or NULL if not defined */
  159893. /* These parameters are never carried across datastreams, since they
  159894. * are given in SOF/SOS markers or defined to be reset by SOI.
  159895. */
  159896. int data_precision; /* bits of precision in image data */
  159897. jpeg_component_info * comp_info;
  159898. /* comp_info[i] describes component that appears i'th in SOF */
  159899. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159900. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159901. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159902. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159903. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159904. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159905. /* These fields record data obtained from optional markers recognized by
  159906. * the JPEG library.
  159907. */
  159908. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159909. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159910. UINT8 JFIF_major_version; /* JFIF version number */
  159911. UINT8 JFIF_minor_version;
  159912. UINT8 density_unit; /* JFIF code for pixel size units */
  159913. UINT16 X_density; /* Horizontal pixel density */
  159914. UINT16 Y_density; /* Vertical pixel density */
  159915. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159916. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159917. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159918. /* Aside from the specific data retained from APPn markers known to the
  159919. * library, the uninterpreted contents of any or all APPn and COM markers
  159920. * can be saved in a list for examination by the application.
  159921. */
  159922. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159923. /* Remaining fields are known throughout decompressor, but generally
  159924. * should not be touched by a surrounding application.
  159925. */
  159926. /*
  159927. * These fields are computed during decompression startup
  159928. */
  159929. int max_h_samp_factor; /* largest h_samp_factor */
  159930. int max_v_samp_factor; /* largest v_samp_factor */
  159931. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159932. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159933. /* The coefficient controller's input and output progress is measured in
  159934. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159935. * in fully interleaved JPEG scans, but are used whether the scan is
  159936. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159937. * rows of each component. Therefore, the IDCT output contains
  159938. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159939. */
  159940. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159941. /*
  159942. * These fields are valid during any one scan.
  159943. * They describe the components and MCUs actually appearing in the scan.
  159944. * Note that the decompressor output side must not use these fields.
  159945. */
  159946. int comps_in_scan; /* # of JPEG components in this scan */
  159947. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159948. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159949. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159950. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159951. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159952. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159953. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159954. /* i'th block in an MCU */
  159955. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159956. /* This field is shared between entropy decoder and marker parser.
  159957. * It is either zero or the code of a JPEG marker that has been
  159958. * read from the data source, but has not yet been processed.
  159959. */
  159960. int unread_marker;
  159961. /*
  159962. * Links to decompression subobjects (methods, private variables of modules)
  159963. */
  159964. struct jpeg_decomp_master * master;
  159965. struct jpeg_d_main_controller * main;
  159966. struct jpeg_d_coef_controller * coef;
  159967. struct jpeg_d_post_controller * post;
  159968. struct jpeg_input_controller * inputctl;
  159969. struct jpeg_marker_reader * marker;
  159970. struct jpeg_entropy_decoder * entropy;
  159971. struct jpeg_inverse_dct * idct;
  159972. struct jpeg_upsampler * upsample;
  159973. struct jpeg_color_deconverter * cconvert;
  159974. struct jpeg_color_quantizer * cquantize;
  159975. };
  159976. /* "Object" declarations for JPEG modules that may be supplied or called
  159977. * directly by the surrounding application.
  159978. * As with all objects in the JPEG library, these structs only define the
  159979. * publicly visible methods and state variables of a module. Additional
  159980. * private fields may exist after the public ones.
  159981. */
  159982. /* Error handler object */
  159983. struct jpeg_error_mgr {
  159984. /* Error exit handler: does not return to caller */
  159985. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159986. /* Conditionally emit a trace or warning message */
  159987. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159988. /* Routine that actually outputs a trace or error message */
  159989. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159990. /* Format a message string for the most recent JPEG error or message */
  159991. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159992. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159993. /* Reset error state variables at start of a new image */
  159994. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159995. /* The message ID code and any parameters are saved here.
  159996. * A message can have one string parameter or up to 8 int parameters.
  159997. */
  159998. int msg_code;
  159999. #define JMSG_STR_PARM_MAX 80
  160000. union {
  160001. int i[8];
  160002. char s[JMSG_STR_PARM_MAX];
  160003. } msg_parm;
  160004. /* Standard state variables for error facility */
  160005. int trace_level; /* max msg_level that will be displayed */
  160006. /* For recoverable corrupt-data errors, we emit a warning message,
  160007. * but keep going unless emit_message chooses to abort. emit_message
  160008. * should count warnings in num_warnings. The surrounding application
  160009. * can check for bad data by seeing if num_warnings is nonzero at the
  160010. * end of processing.
  160011. */
  160012. long num_warnings; /* number of corrupt-data warnings */
  160013. /* These fields point to the table(s) of error message strings.
  160014. * An application can change the table pointer to switch to a different
  160015. * message list (typically, to change the language in which errors are
  160016. * reported). Some applications may wish to add additional error codes
  160017. * that will be handled by the JPEG library error mechanism; the second
  160018. * table pointer is used for this purpose.
  160019. *
  160020. * First table includes all errors generated by JPEG library itself.
  160021. * Error code 0 is reserved for a "no such error string" message.
  160022. */
  160023. const char * const * jpeg_message_table; /* Library errors */
  160024. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160025. /* Second table can be added by application (see cjpeg/djpeg for example).
  160026. * It contains strings numbered first_addon_message..last_addon_message.
  160027. */
  160028. const char * const * addon_message_table; /* Non-library errors */
  160029. int first_addon_message; /* code for first string in addon table */
  160030. int last_addon_message; /* code for last string in addon table */
  160031. };
  160032. /* Progress monitor object */
  160033. struct jpeg_progress_mgr {
  160034. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160035. long pass_counter; /* work units completed in this pass */
  160036. long pass_limit; /* total number of work units in this pass */
  160037. int completed_passes; /* passes completed so far */
  160038. int total_passes; /* total number of passes expected */
  160039. };
  160040. /* Data destination object for compression */
  160041. struct jpeg_destination_mgr {
  160042. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160043. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160044. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160045. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160046. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160047. };
  160048. /* Data source object for decompression */
  160049. struct jpeg_source_mgr {
  160050. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160051. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160052. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160053. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160054. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160055. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160056. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160057. };
  160058. /* Memory manager object.
  160059. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160060. * and "really big" objects (virtual arrays with backing store if needed).
  160061. * The memory manager does not allow individual objects to be freed; rather,
  160062. * each created object is assigned to a pool, and whole pools can be freed
  160063. * at once. This is faster and more convenient than remembering exactly what
  160064. * to free, especially where malloc()/free() are not too speedy.
  160065. * NB: alloc routines never return NULL. They exit to error_exit if not
  160066. * successful.
  160067. */
  160068. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160069. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160070. #define JPOOL_NUMPOOLS 2
  160071. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160072. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160073. struct jpeg_memory_mgr {
  160074. /* Method pointers */
  160075. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160076. size_t sizeofobject));
  160077. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160078. size_t sizeofobject));
  160079. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160080. JDIMENSION samplesperrow,
  160081. JDIMENSION numrows));
  160082. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160083. JDIMENSION blocksperrow,
  160084. JDIMENSION numrows));
  160085. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160086. int pool_id,
  160087. boolean pre_zero,
  160088. JDIMENSION samplesperrow,
  160089. JDIMENSION numrows,
  160090. JDIMENSION maxaccess));
  160091. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160092. int pool_id,
  160093. boolean pre_zero,
  160094. JDIMENSION blocksperrow,
  160095. JDIMENSION numrows,
  160096. JDIMENSION maxaccess));
  160097. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160098. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160099. jvirt_sarray_ptr ptr,
  160100. JDIMENSION start_row,
  160101. JDIMENSION num_rows,
  160102. boolean writable));
  160103. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160104. jvirt_barray_ptr ptr,
  160105. JDIMENSION start_row,
  160106. JDIMENSION num_rows,
  160107. boolean writable));
  160108. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160109. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160110. /* Limit on memory allocation for this JPEG object. (Note that this is
  160111. * merely advisory, not a guaranteed maximum; it only affects the space
  160112. * used for virtual-array buffers.) May be changed by outer application
  160113. * after creating the JPEG object.
  160114. */
  160115. long max_memory_to_use;
  160116. /* Maximum allocation request accepted by alloc_large. */
  160117. long max_alloc_chunk;
  160118. };
  160119. /* Routine signature for application-supplied marker processing methods.
  160120. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160121. */
  160122. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160123. /* Declarations for routines called by application.
  160124. * The JPP macro hides prototype parameters from compilers that can't cope.
  160125. * Note JPP requires double parentheses.
  160126. */
  160127. #ifdef HAVE_PROTOTYPES
  160128. #define JPP(arglist) arglist
  160129. #else
  160130. #define JPP(arglist) ()
  160131. #endif
  160132. /* Short forms of external names for systems with brain-damaged linkers.
  160133. * We shorten external names to be unique in the first six letters, which
  160134. * is good enough for all known systems.
  160135. * (If your compiler itself needs names to be unique in less than 15
  160136. * characters, you are out of luck. Get a better compiler.)
  160137. */
  160138. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160139. #define jpeg_std_error jStdError
  160140. #define jpeg_CreateCompress jCreaCompress
  160141. #define jpeg_CreateDecompress jCreaDecompress
  160142. #define jpeg_destroy_compress jDestCompress
  160143. #define jpeg_destroy_decompress jDestDecompress
  160144. #define jpeg_stdio_dest jStdDest
  160145. #define jpeg_stdio_src jStdSrc
  160146. #define jpeg_set_defaults jSetDefaults
  160147. #define jpeg_set_colorspace jSetColorspace
  160148. #define jpeg_default_colorspace jDefColorspace
  160149. #define jpeg_set_quality jSetQuality
  160150. #define jpeg_set_linear_quality jSetLQuality
  160151. #define jpeg_add_quant_table jAddQuantTable
  160152. #define jpeg_quality_scaling jQualityScaling
  160153. #define jpeg_simple_progression jSimProgress
  160154. #define jpeg_suppress_tables jSuppressTables
  160155. #define jpeg_alloc_quant_table jAlcQTable
  160156. #define jpeg_alloc_huff_table jAlcHTable
  160157. #define jpeg_start_compress jStrtCompress
  160158. #define jpeg_write_scanlines jWrtScanlines
  160159. #define jpeg_finish_compress jFinCompress
  160160. #define jpeg_write_raw_data jWrtRawData
  160161. #define jpeg_write_marker jWrtMarker
  160162. #define jpeg_write_m_header jWrtMHeader
  160163. #define jpeg_write_m_byte jWrtMByte
  160164. #define jpeg_write_tables jWrtTables
  160165. #define jpeg_read_header jReadHeader
  160166. #define jpeg_start_decompress jStrtDecompress
  160167. #define jpeg_read_scanlines jReadScanlines
  160168. #define jpeg_finish_decompress jFinDecompress
  160169. #define jpeg_read_raw_data jReadRawData
  160170. #define jpeg_has_multiple_scans jHasMultScn
  160171. #define jpeg_start_output jStrtOutput
  160172. #define jpeg_finish_output jFinOutput
  160173. #define jpeg_input_complete jInComplete
  160174. #define jpeg_new_colormap jNewCMap
  160175. #define jpeg_consume_input jConsumeInput
  160176. #define jpeg_calc_output_dimensions jCalcDimensions
  160177. #define jpeg_save_markers jSaveMarkers
  160178. #define jpeg_set_marker_processor jSetMarker
  160179. #define jpeg_read_coefficients jReadCoefs
  160180. #define jpeg_write_coefficients jWrtCoefs
  160181. #define jpeg_copy_critical_parameters jCopyCrit
  160182. #define jpeg_abort_compress jAbrtCompress
  160183. #define jpeg_abort_decompress jAbrtDecompress
  160184. #define jpeg_abort jAbort
  160185. #define jpeg_destroy jDestroy
  160186. #define jpeg_resync_to_restart jResyncRestart
  160187. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160188. /* Default error-management setup */
  160189. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160190. JPP((struct jpeg_error_mgr * err));
  160191. /* Initialization of JPEG compression objects.
  160192. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160193. * names that applications should call. These expand to calls on
  160194. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160195. * passed for version mismatch checking.
  160196. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160197. */
  160198. #define jpeg_create_compress(cinfo) \
  160199. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160200. (size_t) sizeof(struct jpeg_compress_struct))
  160201. #define jpeg_create_decompress(cinfo) \
  160202. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160203. (size_t) sizeof(struct jpeg_decompress_struct))
  160204. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160205. int version, size_t structsize));
  160206. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160207. int version, size_t structsize));
  160208. /* Destruction of JPEG compression objects */
  160209. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160210. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160211. /* Standard data source and destination managers: stdio streams. */
  160212. /* Caller is responsible for opening the file before and closing after. */
  160213. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160214. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160215. /* Default parameter setup for compression */
  160216. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160217. /* Compression parameter setup aids */
  160218. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160219. J_COLOR_SPACE colorspace));
  160220. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160221. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160222. boolean force_baseline));
  160223. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160224. int scale_factor,
  160225. boolean force_baseline));
  160226. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160227. const unsigned int *basic_table,
  160228. int scale_factor,
  160229. boolean force_baseline));
  160230. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160231. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160232. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160233. boolean suppress));
  160234. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160235. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160236. /* Main entry points for compression */
  160237. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160238. boolean write_all_tables));
  160239. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160240. JSAMPARRAY scanlines,
  160241. JDIMENSION num_lines));
  160242. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160243. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160244. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160245. JSAMPIMAGE data,
  160246. JDIMENSION num_lines));
  160247. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160248. EXTERN(void) jpeg_write_marker
  160249. JPP((j_compress_ptr cinfo, int marker,
  160250. const JOCTET * dataptr, unsigned int datalen));
  160251. /* Same, but piecemeal. */
  160252. EXTERN(void) jpeg_write_m_header
  160253. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160254. EXTERN(void) jpeg_write_m_byte
  160255. JPP((j_compress_ptr cinfo, int val));
  160256. /* Alternate compression function: just write an abbreviated table file */
  160257. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160258. /* Decompression startup: read start of JPEG datastream to see what's there */
  160259. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160260. boolean require_image));
  160261. /* Return value is one of: */
  160262. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160263. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160264. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160265. /* If you pass require_image = TRUE (normal case), you need not check for
  160266. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160267. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160268. * give a suspension return (the stdio source module doesn't).
  160269. */
  160270. /* Main entry points for decompression */
  160271. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160272. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160273. JSAMPARRAY scanlines,
  160274. JDIMENSION max_lines));
  160275. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160276. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160277. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160278. JSAMPIMAGE data,
  160279. JDIMENSION max_lines));
  160280. /* Additional entry points for buffered-image mode. */
  160281. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160282. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160283. int scan_number));
  160284. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160285. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160286. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160287. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160288. /* Return value is one of: */
  160289. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160290. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160291. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160292. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160293. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160294. /* Precalculate output dimensions for current decompression parameters. */
  160295. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160296. /* Control saving of COM and APPn markers into marker_list. */
  160297. EXTERN(void) jpeg_save_markers
  160298. JPP((j_decompress_ptr cinfo, int marker_code,
  160299. unsigned int length_limit));
  160300. /* Install a special processing method for COM or APPn markers. */
  160301. EXTERN(void) jpeg_set_marker_processor
  160302. JPP((j_decompress_ptr cinfo, int marker_code,
  160303. jpeg_marker_parser_method routine));
  160304. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160305. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160306. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160307. jvirt_barray_ptr * coef_arrays));
  160308. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160309. j_compress_ptr dstinfo));
  160310. /* If you choose to abort compression or decompression before completing
  160311. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160312. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160313. * if you're done with the JPEG object, but if you want to clean it up and
  160314. * reuse it, call this:
  160315. */
  160316. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160317. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160318. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160319. * flavor of JPEG object. These may be more convenient in some places.
  160320. */
  160321. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160322. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160323. /* Default restart-marker-resync procedure for use by data source modules */
  160324. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160325. int desired));
  160326. /* These marker codes are exported since applications and data source modules
  160327. * are likely to want to use them.
  160328. */
  160329. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160330. #define JPEG_EOI 0xD9 /* EOI marker code */
  160331. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160332. #define JPEG_COM 0xFE /* COM marker code */
  160333. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160334. * for structure definitions that are never filled in, keep it quiet by
  160335. * supplying dummy definitions for the various substructures.
  160336. */
  160337. #ifdef INCOMPLETE_TYPES_BROKEN
  160338. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160339. struct jvirt_sarray_control { long dummy; };
  160340. struct jvirt_barray_control { long dummy; };
  160341. struct jpeg_comp_master { long dummy; };
  160342. struct jpeg_c_main_controller { long dummy; };
  160343. struct jpeg_c_prep_controller { long dummy; };
  160344. struct jpeg_c_coef_controller { long dummy; };
  160345. struct jpeg_marker_writer { long dummy; };
  160346. struct jpeg_color_converter { long dummy; };
  160347. struct jpeg_downsampler { long dummy; };
  160348. struct jpeg_forward_dct { long dummy; };
  160349. struct jpeg_entropy_encoder { long dummy; };
  160350. struct jpeg_decomp_master { long dummy; };
  160351. struct jpeg_d_main_controller { long dummy; };
  160352. struct jpeg_d_coef_controller { long dummy; };
  160353. struct jpeg_d_post_controller { long dummy; };
  160354. struct jpeg_input_controller { long dummy; };
  160355. struct jpeg_marker_reader { long dummy; };
  160356. struct jpeg_entropy_decoder { long dummy; };
  160357. struct jpeg_inverse_dct { long dummy; };
  160358. struct jpeg_upsampler { long dummy; };
  160359. struct jpeg_color_deconverter { long dummy; };
  160360. struct jpeg_color_quantizer { long dummy; };
  160361. #endif /* JPEG_INTERNALS */
  160362. #endif /* INCOMPLETE_TYPES_BROKEN */
  160363. /*
  160364. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160365. * The internal structure declarations are read only when that is true.
  160366. * Applications using the library should not include jpegint.h, but may wish
  160367. * to include jerror.h.
  160368. */
  160369. #ifdef JPEG_INTERNALS
  160370. /*** Start of inlined file: jpegint.h ***/
  160371. /* Declarations for both compression & decompression */
  160372. typedef enum { /* Operating modes for buffer controllers */
  160373. JBUF_PASS_THRU, /* Plain stripwise operation */
  160374. /* Remaining modes require a full-image buffer to have been created */
  160375. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160376. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160377. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160378. } J_BUF_MODE;
  160379. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160380. #define CSTATE_START 100 /* after create_compress */
  160381. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160382. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160383. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160384. #define DSTATE_START 200 /* after create_decompress */
  160385. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160386. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160387. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160388. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160389. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160390. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160391. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160392. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160393. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160394. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160395. /* Declarations for compression modules */
  160396. /* Master control module */
  160397. struct jpeg_comp_master {
  160398. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160399. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160400. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160401. /* State variables made visible to other modules */
  160402. boolean call_pass_startup; /* True if pass_startup must be called */
  160403. boolean is_last_pass; /* True during last pass */
  160404. };
  160405. /* Main buffer control (downsampled-data buffer) */
  160406. struct jpeg_c_main_controller {
  160407. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160408. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160409. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160410. JDIMENSION in_rows_avail));
  160411. };
  160412. /* Compression preprocessing (downsampling input buffer control) */
  160413. struct jpeg_c_prep_controller {
  160414. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160415. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160416. JSAMPARRAY input_buf,
  160417. JDIMENSION *in_row_ctr,
  160418. JDIMENSION in_rows_avail,
  160419. JSAMPIMAGE output_buf,
  160420. JDIMENSION *out_row_group_ctr,
  160421. JDIMENSION out_row_groups_avail));
  160422. };
  160423. /* Coefficient buffer control */
  160424. struct jpeg_c_coef_controller {
  160425. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160426. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160427. JSAMPIMAGE input_buf));
  160428. };
  160429. /* Colorspace conversion */
  160430. struct jpeg_color_converter {
  160431. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160432. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160433. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160434. JDIMENSION output_row, int num_rows));
  160435. };
  160436. /* Downsampling */
  160437. struct jpeg_downsampler {
  160438. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160439. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160440. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160441. JSAMPIMAGE output_buf,
  160442. JDIMENSION out_row_group_index));
  160443. boolean need_context_rows; /* TRUE if need rows above & below */
  160444. };
  160445. /* Forward DCT (also controls coefficient quantization) */
  160446. struct jpeg_forward_dct {
  160447. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160448. /* perhaps this should be an array??? */
  160449. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160450. jpeg_component_info * compptr,
  160451. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160452. JDIMENSION start_row, JDIMENSION start_col,
  160453. JDIMENSION num_blocks));
  160454. };
  160455. /* Entropy encoding */
  160456. struct jpeg_entropy_encoder {
  160457. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160458. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160459. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160460. };
  160461. /* Marker writing */
  160462. struct jpeg_marker_writer {
  160463. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160464. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160465. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160466. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160467. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160468. /* These routines are exported to allow insertion of extra markers */
  160469. /* Probably only COM and APPn markers should be written this way */
  160470. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160471. unsigned int datalen));
  160472. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160473. };
  160474. /* Declarations for decompression modules */
  160475. /* Master control module */
  160476. struct jpeg_decomp_master {
  160477. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160478. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160479. /* State variables made visible to other modules */
  160480. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160481. };
  160482. /* Input control module */
  160483. struct jpeg_input_controller {
  160484. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160485. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160486. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160487. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160488. /* State variables made visible to other modules */
  160489. boolean has_multiple_scans; /* True if file has multiple scans */
  160490. boolean eoi_reached; /* True when EOI has been consumed */
  160491. };
  160492. /* Main buffer control (downsampled-data buffer) */
  160493. struct jpeg_d_main_controller {
  160494. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160495. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160496. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160497. JDIMENSION out_rows_avail));
  160498. };
  160499. /* Coefficient buffer control */
  160500. struct jpeg_d_coef_controller {
  160501. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160502. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160503. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160504. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160505. JSAMPIMAGE output_buf));
  160506. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160507. jvirt_barray_ptr *coef_arrays;
  160508. };
  160509. /* Decompression postprocessing (color quantization buffer control) */
  160510. struct jpeg_d_post_controller {
  160511. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160512. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160513. JSAMPIMAGE input_buf,
  160514. JDIMENSION *in_row_group_ctr,
  160515. JDIMENSION in_row_groups_avail,
  160516. JSAMPARRAY output_buf,
  160517. JDIMENSION *out_row_ctr,
  160518. JDIMENSION out_rows_avail));
  160519. };
  160520. /* Marker reading & parsing */
  160521. struct jpeg_marker_reader {
  160522. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160523. /* Read markers until SOS or EOI.
  160524. * Returns same codes as are defined for jpeg_consume_input:
  160525. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160526. */
  160527. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160528. /* Read a restart marker --- exported for use by entropy decoder only */
  160529. jpeg_marker_parser_method read_restart_marker;
  160530. /* State of marker reader --- nominally internal, but applications
  160531. * supplying COM or APPn handlers might like to know the state.
  160532. */
  160533. boolean saw_SOI; /* found SOI? */
  160534. boolean saw_SOF; /* found SOF? */
  160535. int next_restart_num; /* next restart number expected (0-7) */
  160536. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160537. };
  160538. /* Entropy decoding */
  160539. struct jpeg_entropy_decoder {
  160540. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160541. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160542. JBLOCKROW *MCU_data));
  160543. /* This is here to share code between baseline and progressive decoders; */
  160544. /* other modules probably should not use it */
  160545. boolean insufficient_data; /* set TRUE after emitting warning */
  160546. };
  160547. /* Inverse DCT (also performs dequantization) */
  160548. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160549. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160550. JCOEFPTR coef_block,
  160551. JSAMPARRAY output_buf, JDIMENSION output_col));
  160552. struct jpeg_inverse_dct {
  160553. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160554. /* It is useful to allow each component to have a separate IDCT method. */
  160555. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160556. };
  160557. /* Upsampling (note that upsampler must also call color converter) */
  160558. struct jpeg_upsampler {
  160559. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160560. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160561. JSAMPIMAGE input_buf,
  160562. JDIMENSION *in_row_group_ctr,
  160563. JDIMENSION in_row_groups_avail,
  160564. JSAMPARRAY output_buf,
  160565. JDIMENSION *out_row_ctr,
  160566. JDIMENSION out_rows_avail));
  160567. boolean need_context_rows; /* TRUE if need rows above & below */
  160568. };
  160569. /* Colorspace conversion */
  160570. struct jpeg_color_deconverter {
  160571. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160572. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160573. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160574. JSAMPARRAY output_buf, int num_rows));
  160575. };
  160576. /* Color quantization or color precision reduction */
  160577. struct jpeg_color_quantizer {
  160578. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160579. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160580. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160581. int num_rows));
  160582. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160583. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160584. };
  160585. /* Miscellaneous useful macros */
  160586. #undef MAX
  160587. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160588. #undef MIN
  160589. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160590. /* We assume that right shift corresponds to signed division by 2 with
  160591. * rounding towards minus infinity. This is correct for typical "arithmetic
  160592. * shift" instructions that shift in copies of the sign bit. But some
  160593. * C compilers implement >> with an unsigned shift. For these machines you
  160594. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160595. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160596. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160597. * included in the variables of any routine using RIGHT_SHIFT.
  160598. */
  160599. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160600. #define SHIFT_TEMPS INT32 shift_temp;
  160601. #define RIGHT_SHIFT(x,shft) \
  160602. ((shift_temp = (x)) < 0 ? \
  160603. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160604. (shift_temp >> (shft)))
  160605. #else
  160606. #define SHIFT_TEMPS
  160607. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160608. #endif
  160609. /* Short forms of external names for systems with brain-damaged linkers. */
  160610. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160611. #define jinit_compress_master jICompress
  160612. #define jinit_c_master_control jICMaster
  160613. #define jinit_c_main_controller jICMainC
  160614. #define jinit_c_prep_controller jICPrepC
  160615. #define jinit_c_coef_controller jICCoefC
  160616. #define jinit_color_converter jICColor
  160617. #define jinit_downsampler jIDownsampler
  160618. #define jinit_forward_dct jIFDCT
  160619. #define jinit_huff_encoder jIHEncoder
  160620. #define jinit_phuff_encoder jIPHEncoder
  160621. #define jinit_marker_writer jIMWriter
  160622. #define jinit_master_decompress jIDMaster
  160623. #define jinit_d_main_controller jIDMainC
  160624. #define jinit_d_coef_controller jIDCoefC
  160625. #define jinit_d_post_controller jIDPostC
  160626. #define jinit_input_controller jIInCtlr
  160627. #define jinit_marker_reader jIMReader
  160628. #define jinit_huff_decoder jIHDecoder
  160629. #define jinit_phuff_decoder jIPHDecoder
  160630. #define jinit_inverse_dct jIIDCT
  160631. #define jinit_upsampler jIUpsampler
  160632. #define jinit_color_deconverter jIDColor
  160633. #define jinit_1pass_quantizer jI1Quant
  160634. #define jinit_2pass_quantizer jI2Quant
  160635. #define jinit_merged_upsampler jIMUpsampler
  160636. #define jinit_memory_mgr jIMemMgr
  160637. #define jdiv_round_up jDivRound
  160638. #define jround_up jRound
  160639. #define jcopy_sample_rows jCopySamples
  160640. #define jcopy_block_row jCopyBlocks
  160641. #define jzero_far jZeroFar
  160642. #define jpeg_zigzag_order jZIGTable
  160643. #define jpeg_natural_order jZAGTable
  160644. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160645. /* Compression module initialization routines */
  160646. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160647. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160648. boolean transcode_only));
  160649. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160650. boolean need_full_buffer));
  160651. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160652. boolean need_full_buffer));
  160653. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160654. boolean need_full_buffer));
  160655. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160656. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160657. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160658. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160659. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160660. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160661. /* Decompression module initialization routines */
  160662. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160663. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160664. boolean need_full_buffer));
  160665. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160666. boolean need_full_buffer));
  160667. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160668. boolean need_full_buffer));
  160669. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160670. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160671. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160672. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160673. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160674. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160675. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160676. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160677. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160678. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160679. /* Memory manager initialization */
  160680. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160681. /* Utility routines in jutils.c */
  160682. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160683. EXTERN(long) jround_up JPP((long a, long b));
  160684. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160685. JSAMPARRAY output_array, int dest_row,
  160686. int num_rows, JDIMENSION num_cols));
  160687. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160688. JDIMENSION num_blocks));
  160689. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160690. /* Constant tables in jutils.c */
  160691. #if 0 /* This table is not actually needed in v6a */
  160692. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160693. #endif
  160694. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160695. /* Suppress undefined-structure complaints if necessary. */
  160696. #ifdef INCOMPLETE_TYPES_BROKEN
  160697. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160698. struct jvirt_sarray_control { long dummy; };
  160699. struct jvirt_barray_control { long dummy; };
  160700. #endif
  160701. #endif /* INCOMPLETE_TYPES_BROKEN */
  160702. /*** End of inlined file: jpegint.h ***/
  160703. /* fetch private declarations */
  160704. /*** Start of inlined file: jerror.h ***/
  160705. /*
  160706. * To define the enum list of message codes, include this file without
  160707. * defining macro JMESSAGE. To create a message string table, include it
  160708. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160709. */
  160710. #ifndef JMESSAGE
  160711. #ifndef JERROR_H
  160712. /* First time through, define the enum list */
  160713. #define JMAKE_ENUM_LIST
  160714. #else
  160715. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160716. #define JMESSAGE(code,string)
  160717. #endif /* JERROR_H */
  160718. #endif /* JMESSAGE */
  160719. #ifdef JMAKE_ENUM_LIST
  160720. typedef enum {
  160721. #define JMESSAGE(code,string) code ,
  160722. #endif /* JMAKE_ENUM_LIST */
  160723. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160724. /* For maintenance convenience, list is alphabetical by message code name */
  160725. JMESSAGE(JERR_ARITH_NOTIMPL,
  160726. "Sorry, there are legal restrictions on arithmetic coding")
  160727. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160728. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160729. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160730. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160731. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160732. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160733. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160734. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160735. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160736. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160737. JMESSAGE(JERR_BAD_LIB_VERSION,
  160738. "Wrong JPEG library version: library is %d, caller expects %d")
  160739. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160740. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160741. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160742. JMESSAGE(JERR_BAD_PROGRESSION,
  160743. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160744. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160745. "Invalid progressive parameters at scan script entry %d")
  160746. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160747. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160748. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160749. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160750. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160751. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160752. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160753. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160754. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160755. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160756. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160757. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160758. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160759. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160760. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160761. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160762. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160763. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160764. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160765. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160766. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160767. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160768. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160769. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160770. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160771. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160772. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160773. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160774. "Cannot transcode due to multiple use of quantization table %d")
  160775. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160776. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160777. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160778. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160779. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160780. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160781. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160782. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160783. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160784. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160785. JMESSAGE(JERR_QUANT_COMPONENTS,
  160786. "Cannot quantize more than %d color components")
  160787. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160788. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160789. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160790. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160791. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160792. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160793. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160794. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160795. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160796. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160797. JMESSAGE(JERR_TFILE_WRITE,
  160798. "Write failed on temporary file --- out of disk space?")
  160799. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160800. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160801. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160802. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160803. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160804. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160805. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160806. JMESSAGE(JMSG_VERSION, JVERSION)
  160807. JMESSAGE(JTRC_16BIT_TABLES,
  160808. "Caution: quantization tables are too coarse for baseline JPEG")
  160809. JMESSAGE(JTRC_ADOBE,
  160810. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160811. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160812. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160813. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160814. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160815. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160816. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160817. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160818. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160819. JMESSAGE(JTRC_EOI, "End Of Image")
  160820. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160821. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160822. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160823. "Warning: thumbnail image size does not match data length %u")
  160824. JMESSAGE(JTRC_JFIF_EXTENSION,
  160825. "JFIF extension marker: type 0x%02x, length %u")
  160826. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160827. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160828. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160829. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160830. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160831. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160832. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160833. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160834. JMESSAGE(JTRC_RST, "RST%d")
  160835. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160836. "Smoothing not supported with nonstandard sampling ratios")
  160837. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160838. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160839. JMESSAGE(JTRC_SOI, "Start of Image")
  160840. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160841. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160842. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160843. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160844. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160845. JMESSAGE(JTRC_THUMB_JPEG,
  160846. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160847. JMESSAGE(JTRC_THUMB_PALETTE,
  160848. "JFIF extension marker: palette thumbnail image, length %u")
  160849. JMESSAGE(JTRC_THUMB_RGB,
  160850. "JFIF extension marker: RGB thumbnail image, length %u")
  160851. JMESSAGE(JTRC_UNKNOWN_IDS,
  160852. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160853. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160854. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160855. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160856. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160857. "Inconsistent progression sequence for component %d coefficient %d")
  160858. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160859. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160860. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160861. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160862. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160863. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160864. JMESSAGE(JWRN_MUST_RESYNC,
  160865. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160866. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160867. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160868. #ifdef JMAKE_ENUM_LIST
  160869. JMSG_LASTMSGCODE
  160870. } J_MESSAGE_CODE;
  160871. #undef JMAKE_ENUM_LIST
  160872. #endif /* JMAKE_ENUM_LIST */
  160873. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160874. #undef JMESSAGE
  160875. #ifndef JERROR_H
  160876. #define JERROR_H
  160877. /* Macros to simplify using the error and trace message stuff */
  160878. /* The first parameter is either type of cinfo pointer */
  160879. /* Fatal errors (print message and exit) */
  160880. #define ERREXIT(cinfo,code) \
  160881. ((cinfo)->err->msg_code = (code), \
  160882. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160883. #define ERREXIT1(cinfo,code,p1) \
  160884. ((cinfo)->err->msg_code = (code), \
  160885. (cinfo)->err->msg_parm.i[0] = (p1), \
  160886. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160887. #define ERREXIT2(cinfo,code,p1,p2) \
  160888. ((cinfo)->err->msg_code = (code), \
  160889. (cinfo)->err->msg_parm.i[0] = (p1), \
  160890. (cinfo)->err->msg_parm.i[1] = (p2), \
  160891. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160892. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160893. ((cinfo)->err->msg_code = (code), \
  160894. (cinfo)->err->msg_parm.i[0] = (p1), \
  160895. (cinfo)->err->msg_parm.i[1] = (p2), \
  160896. (cinfo)->err->msg_parm.i[2] = (p3), \
  160897. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160898. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160899. ((cinfo)->err->msg_code = (code), \
  160900. (cinfo)->err->msg_parm.i[0] = (p1), \
  160901. (cinfo)->err->msg_parm.i[1] = (p2), \
  160902. (cinfo)->err->msg_parm.i[2] = (p3), \
  160903. (cinfo)->err->msg_parm.i[3] = (p4), \
  160904. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160905. #define ERREXITS(cinfo,code,str) \
  160906. ((cinfo)->err->msg_code = (code), \
  160907. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160908. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160909. #define MAKESTMT(stuff) do { stuff } while (0)
  160910. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160911. #define WARNMS(cinfo,code) \
  160912. ((cinfo)->err->msg_code = (code), \
  160913. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160914. #define WARNMS1(cinfo,code,p1) \
  160915. ((cinfo)->err->msg_code = (code), \
  160916. (cinfo)->err->msg_parm.i[0] = (p1), \
  160917. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160918. #define WARNMS2(cinfo,code,p1,p2) \
  160919. ((cinfo)->err->msg_code = (code), \
  160920. (cinfo)->err->msg_parm.i[0] = (p1), \
  160921. (cinfo)->err->msg_parm.i[1] = (p2), \
  160922. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160923. /* Informational/debugging messages */
  160924. #define TRACEMS(cinfo,lvl,code) \
  160925. ((cinfo)->err->msg_code = (code), \
  160926. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160927. #define TRACEMS1(cinfo,lvl,code,p1) \
  160928. ((cinfo)->err->msg_code = (code), \
  160929. (cinfo)->err->msg_parm.i[0] = (p1), \
  160930. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160931. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160932. ((cinfo)->err->msg_code = (code), \
  160933. (cinfo)->err->msg_parm.i[0] = (p1), \
  160934. (cinfo)->err->msg_parm.i[1] = (p2), \
  160935. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160936. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160937. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160938. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160939. (cinfo)->err->msg_code = (code); \
  160940. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160941. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160942. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160943. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160944. (cinfo)->err->msg_code = (code); \
  160945. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160946. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160947. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160948. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160949. _mp[4] = (p5); \
  160950. (cinfo)->err->msg_code = (code); \
  160951. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160952. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160953. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160954. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160955. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160956. (cinfo)->err->msg_code = (code); \
  160957. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160958. #define TRACEMSS(cinfo,lvl,code,str) \
  160959. ((cinfo)->err->msg_code = (code), \
  160960. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160961. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160962. #endif /* JERROR_H */
  160963. /*** End of inlined file: jerror.h ***/
  160964. /* fetch error codes too */
  160965. #endif
  160966. #endif /* JPEGLIB_H */
  160967. /*** End of inlined file: jpeglib.h ***/
  160968. /*** Start of inlined file: jcapimin.c ***/
  160969. #define JPEG_INTERNALS
  160970. /*** Start of inlined file: jinclude.h ***/
  160971. /* Include auto-config file to find out which system include files we need. */
  160972. #ifndef __jinclude_h__
  160973. #define __jinclude_h__
  160974. /*** Start of inlined file: jconfig.h ***/
  160975. /* see jconfig.doc for explanations */
  160976. // disable all the warnings under MSVC
  160977. #ifdef _MSC_VER
  160978. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160979. #endif
  160980. #ifdef __BORLANDC__
  160981. #pragma warn -8057
  160982. #pragma warn -8019
  160983. #pragma warn -8004
  160984. #pragma warn -8008
  160985. #endif
  160986. #define HAVE_PROTOTYPES
  160987. #define HAVE_UNSIGNED_CHAR
  160988. #define HAVE_UNSIGNED_SHORT
  160989. /* #define void char */
  160990. /* #define const */
  160991. #undef CHAR_IS_UNSIGNED
  160992. #define HAVE_STDDEF_H
  160993. #define HAVE_STDLIB_H
  160994. #undef NEED_BSD_STRINGS
  160995. #undef NEED_SYS_TYPES_H
  160996. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160997. #undef NEED_SHORT_EXTERNAL_NAMES
  160998. #undef INCOMPLETE_TYPES_BROKEN
  160999. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161000. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161001. typedef unsigned char boolean;
  161002. #endif
  161003. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161004. #ifdef JPEG_INTERNALS
  161005. #undef RIGHT_SHIFT_IS_UNSIGNED
  161006. #endif /* JPEG_INTERNALS */
  161007. #ifdef JPEG_CJPEG_DJPEG
  161008. #define BMP_SUPPORTED /* BMP image file format */
  161009. #define GIF_SUPPORTED /* GIF image file format */
  161010. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161011. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161012. #define TARGA_SUPPORTED /* Targa image file format */
  161013. #define TWO_FILE_COMMANDLINE /* optional */
  161014. #define USE_SETMODE /* Microsoft has setmode() */
  161015. #undef NEED_SIGNAL_CATCHER
  161016. #undef DONT_USE_B_MODE
  161017. #undef PROGRESS_REPORT /* optional */
  161018. #endif /* JPEG_CJPEG_DJPEG */
  161019. /*** End of inlined file: jconfig.h ***/
  161020. /* auto configuration options */
  161021. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161022. /*
  161023. * We need the NULL macro and size_t typedef.
  161024. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161025. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161026. * pull in <sys/types.h> as well.
  161027. * Note that the core JPEG library does not require <stdio.h>;
  161028. * only the default error handler and data source/destination modules do.
  161029. * But we must pull it in because of the references to FILE in jpeglib.h.
  161030. * You can remove those references if you want to compile without <stdio.h>.
  161031. */
  161032. #ifdef HAVE_STDDEF_H
  161033. #include <stddef.h>
  161034. #endif
  161035. #ifdef HAVE_STDLIB_H
  161036. #include <stdlib.h>
  161037. #endif
  161038. #ifdef NEED_SYS_TYPES_H
  161039. #include <sys/types.h>
  161040. #endif
  161041. #include <stdio.h>
  161042. /*
  161043. * We need memory copying and zeroing functions, plus strncpy().
  161044. * ANSI and System V implementations declare these in <string.h>.
  161045. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161046. * Some systems may declare memset and memcpy in <memory.h>.
  161047. *
  161048. * NOTE: we assume the size parameters to these functions are of type size_t.
  161049. * Change the casts in these macros if not!
  161050. */
  161051. #ifdef NEED_BSD_STRINGS
  161052. #include <strings.h>
  161053. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161054. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161055. #else /* not BSD, assume ANSI/SysV string lib */
  161056. #include <string.h>
  161057. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161058. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161059. #endif
  161060. /*
  161061. * In ANSI C, and indeed any rational implementation, size_t is also the
  161062. * type returned by sizeof(). However, it seems there are some irrational
  161063. * implementations out there, in which sizeof() returns an int even though
  161064. * size_t is defined as long or unsigned long. To ensure consistent results
  161065. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161066. */
  161067. #define SIZEOF(object) ((size_t) sizeof(object))
  161068. /*
  161069. * The modules that use fread() and fwrite() always invoke them through
  161070. * these macros. On some systems you may need to twiddle the argument casts.
  161071. * CAUTION: argument order is different from underlying functions!
  161072. */
  161073. #define JFREAD(file,buf,sizeofbuf) \
  161074. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161075. #define JFWRITE(file,buf,sizeofbuf) \
  161076. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161077. typedef enum { /* JPEG marker codes */
  161078. M_SOF0 = 0xc0,
  161079. M_SOF1 = 0xc1,
  161080. M_SOF2 = 0xc2,
  161081. M_SOF3 = 0xc3,
  161082. M_SOF5 = 0xc5,
  161083. M_SOF6 = 0xc6,
  161084. M_SOF7 = 0xc7,
  161085. M_JPG = 0xc8,
  161086. M_SOF9 = 0xc9,
  161087. M_SOF10 = 0xca,
  161088. M_SOF11 = 0xcb,
  161089. M_SOF13 = 0xcd,
  161090. M_SOF14 = 0xce,
  161091. M_SOF15 = 0xcf,
  161092. M_DHT = 0xc4,
  161093. M_DAC = 0xcc,
  161094. M_RST0 = 0xd0,
  161095. M_RST1 = 0xd1,
  161096. M_RST2 = 0xd2,
  161097. M_RST3 = 0xd3,
  161098. M_RST4 = 0xd4,
  161099. M_RST5 = 0xd5,
  161100. M_RST6 = 0xd6,
  161101. M_RST7 = 0xd7,
  161102. M_SOI = 0xd8,
  161103. M_EOI = 0xd9,
  161104. M_SOS = 0xda,
  161105. M_DQT = 0xdb,
  161106. M_DNL = 0xdc,
  161107. M_DRI = 0xdd,
  161108. M_DHP = 0xde,
  161109. M_EXP = 0xdf,
  161110. M_APP0 = 0xe0,
  161111. M_APP1 = 0xe1,
  161112. M_APP2 = 0xe2,
  161113. M_APP3 = 0xe3,
  161114. M_APP4 = 0xe4,
  161115. M_APP5 = 0xe5,
  161116. M_APP6 = 0xe6,
  161117. M_APP7 = 0xe7,
  161118. M_APP8 = 0xe8,
  161119. M_APP9 = 0xe9,
  161120. M_APP10 = 0xea,
  161121. M_APP11 = 0xeb,
  161122. M_APP12 = 0xec,
  161123. M_APP13 = 0xed,
  161124. M_APP14 = 0xee,
  161125. M_APP15 = 0xef,
  161126. M_JPG0 = 0xf0,
  161127. M_JPG13 = 0xfd,
  161128. M_COM = 0xfe,
  161129. M_TEM = 0x01,
  161130. M_ERROR = 0x100
  161131. } JPEG_MARKER;
  161132. /*
  161133. * Figure F.12: extend sign bit.
  161134. * On some machines, a shift and add will be faster than a table lookup.
  161135. */
  161136. #ifdef AVOID_TABLES
  161137. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161138. #else
  161139. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161140. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161141. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161142. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161143. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161144. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161145. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161146. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161147. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161148. #endif /* AVOID_TABLES */
  161149. #endif
  161150. /*** End of inlined file: jinclude.h ***/
  161151. /*
  161152. * Initialization of a JPEG compression object.
  161153. * The error manager must already be set up (in case memory manager fails).
  161154. */
  161155. GLOBAL(void)
  161156. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161157. {
  161158. int i;
  161159. /* Guard against version mismatches between library and caller. */
  161160. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161161. if (version != JPEG_LIB_VERSION)
  161162. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161163. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161164. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161165. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161166. /* For debugging purposes, we zero the whole master structure.
  161167. * But the application has already set the err pointer, and may have set
  161168. * client_data, so we have to save and restore those fields.
  161169. * Note: if application hasn't set client_data, tools like Purify may
  161170. * complain here.
  161171. */
  161172. {
  161173. struct jpeg_error_mgr * err = cinfo->err;
  161174. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161175. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161176. cinfo->err = err;
  161177. cinfo->client_data = client_data;
  161178. }
  161179. cinfo->is_decompressor = FALSE;
  161180. /* Initialize a memory manager instance for this object */
  161181. jinit_memory_mgr((j_common_ptr) cinfo);
  161182. /* Zero out pointers to permanent structures. */
  161183. cinfo->progress = NULL;
  161184. cinfo->dest = NULL;
  161185. cinfo->comp_info = NULL;
  161186. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161187. cinfo->quant_tbl_ptrs[i] = NULL;
  161188. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161189. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161190. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161191. }
  161192. cinfo->script_space = NULL;
  161193. cinfo->input_gamma = 1.0; /* in case application forgets */
  161194. /* OK, I'm ready */
  161195. cinfo->global_state = CSTATE_START;
  161196. }
  161197. /*
  161198. * Destruction of a JPEG compression object
  161199. */
  161200. GLOBAL(void)
  161201. jpeg_destroy_compress (j_compress_ptr cinfo)
  161202. {
  161203. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161204. }
  161205. /*
  161206. * Abort processing of a JPEG compression operation,
  161207. * but don't destroy the object itself.
  161208. */
  161209. GLOBAL(void)
  161210. jpeg_abort_compress (j_compress_ptr cinfo)
  161211. {
  161212. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161213. }
  161214. /*
  161215. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161216. * Marks all currently defined tables as already written (if suppress)
  161217. * or not written (if !suppress). This will control whether they get emitted
  161218. * by a subsequent jpeg_start_compress call.
  161219. *
  161220. * This routine is exported for use by applications that want to produce
  161221. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161222. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161223. * jcparam.o would be linked whether the application used it or not.
  161224. */
  161225. GLOBAL(void)
  161226. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161227. {
  161228. int i;
  161229. JQUANT_TBL * qtbl;
  161230. JHUFF_TBL * htbl;
  161231. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161232. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161233. qtbl->sent_table = suppress;
  161234. }
  161235. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161236. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161237. htbl->sent_table = suppress;
  161238. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161239. htbl->sent_table = suppress;
  161240. }
  161241. }
  161242. /*
  161243. * Finish JPEG compression.
  161244. *
  161245. * If a multipass operating mode was selected, this may do a great deal of
  161246. * work including most of the actual output.
  161247. */
  161248. GLOBAL(void)
  161249. jpeg_finish_compress (j_compress_ptr cinfo)
  161250. {
  161251. JDIMENSION iMCU_row;
  161252. if (cinfo->global_state == CSTATE_SCANNING ||
  161253. cinfo->global_state == CSTATE_RAW_OK) {
  161254. /* Terminate first pass */
  161255. if (cinfo->next_scanline < cinfo->image_height)
  161256. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161257. (*cinfo->master->finish_pass) (cinfo);
  161258. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161259. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161260. /* Perform any remaining passes */
  161261. while (! cinfo->master->is_last_pass) {
  161262. (*cinfo->master->prepare_for_pass) (cinfo);
  161263. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161264. if (cinfo->progress != NULL) {
  161265. cinfo->progress->pass_counter = (long) iMCU_row;
  161266. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161267. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161268. }
  161269. /* We bypass the main controller and invoke coef controller directly;
  161270. * all work is being done from the coefficient buffer.
  161271. */
  161272. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161273. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161274. }
  161275. (*cinfo->master->finish_pass) (cinfo);
  161276. }
  161277. /* Write EOI, do final cleanup */
  161278. (*cinfo->marker->write_file_trailer) (cinfo);
  161279. (*cinfo->dest->term_destination) (cinfo);
  161280. /* We can use jpeg_abort to release memory and reset global_state */
  161281. jpeg_abort((j_common_ptr) cinfo);
  161282. }
  161283. /*
  161284. * Write a special marker.
  161285. * This is only recommended for writing COM or APPn markers.
  161286. * Must be called after jpeg_start_compress() and before
  161287. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161288. */
  161289. GLOBAL(void)
  161290. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161291. const JOCTET *dataptr, unsigned int datalen)
  161292. {
  161293. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161294. if (cinfo->next_scanline != 0 ||
  161295. (cinfo->global_state != CSTATE_SCANNING &&
  161296. cinfo->global_state != CSTATE_RAW_OK &&
  161297. cinfo->global_state != CSTATE_WRCOEFS))
  161298. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161299. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161300. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161301. while (datalen--) {
  161302. (*write_marker_byte) (cinfo, *dataptr);
  161303. dataptr++;
  161304. }
  161305. }
  161306. /* Same, but piecemeal. */
  161307. GLOBAL(void)
  161308. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161309. {
  161310. if (cinfo->next_scanline != 0 ||
  161311. (cinfo->global_state != CSTATE_SCANNING &&
  161312. cinfo->global_state != CSTATE_RAW_OK &&
  161313. cinfo->global_state != CSTATE_WRCOEFS))
  161314. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161315. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161316. }
  161317. GLOBAL(void)
  161318. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161319. {
  161320. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161321. }
  161322. /*
  161323. * Alternate compression function: just write an abbreviated table file.
  161324. * Before calling this, all parameters and a data destination must be set up.
  161325. *
  161326. * To produce a pair of files containing abbreviated tables and abbreviated
  161327. * image data, one would proceed as follows:
  161328. *
  161329. * initialize JPEG object
  161330. * set JPEG parameters
  161331. * set destination to table file
  161332. * jpeg_write_tables(cinfo);
  161333. * set destination to image file
  161334. * jpeg_start_compress(cinfo, FALSE);
  161335. * write data...
  161336. * jpeg_finish_compress(cinfo);
  161337. *
  161338. * jpeg_write_tables has the side effect of marking all tables written
  161339. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161340. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161341. */
  161342. GLOBAL(void)
  161343. jpeg_write_tables (j_compress_ptr cinfo)
  161344. {
  161345. if (cinfo->global_state != CSTATE_START)
  161346. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161347. /* (Re)initialize error mgr and destination modules */
  161348. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161349. (*cinfo->dest->init_destination) (cinfo);
  161350. /* Initialize the marker writer ... bit of a crock to do it here. */
  161351. jinit_marker_writer(cinfo);
  161352. /* Write them tables! */
  161353. (*cinfo->marker->write_tables_only) (cinfo);
  161354. /* And clean up. */
  161355. (*cinfo->dest->term_destination) (cinfo);
  161356. /*
  161357. * In library releases up through v6a, we called jpeg_abort() here to free
  161358. * any working memory allocated by the destination manager and marker
  161359. * writer. Some applications had a problem with that: they allocated space
  161360. * of their own from the library memory manager, and didn't want it to go
  161361. * away during write_tables. So now we do nothing. This will cause a
  161362. * memory leak if an app calls write_tables repeatedly without doing a full
  161363. * compression cycle or otherwise resetting the JPEG object. However, that
  161364. * seems less bad than unexpectedly freeing memory in the normal case.
  161365. * An app that prefers the old behavior can call jpeg_abort for itself after
  161366. * each call to jpeg_write_tables().
  161367. */
  161368. }
  161369. /*** End of inlined file: jcapimin.c ***/
  161370. /*** Start of inlined file: jcapistd.c ***/
  161371. #define JPEG_INTERNALS
  161372. /*
  161373. * Compression initialization.
  161374. * Before calling this, all parameters and a data destination must be set up.
  161375. *
  161376. * We require a write_all_tables parameter as a failsafe check when writing
  161377. * multiple datastreams from the same compression object. Since prior runs
  161378. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161379. * would emit an abbreviated stream (no tables) by default. This may be what
  161380. * is wanted, but for safety's sake it should not be the default behavior:
  161381. * programmers should have to make a deliberate choice to emit abbreviated
  161382. * images. Therefore the documentation and examples should encourage people
  161383. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161384. * wrong thing.
  161385. */
  161386. GLOBAL(void)
  161387. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161388. {
  161389. if (cinfo->global_state != CSTATE_START)
  161390. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161391. if (write_all_tables)
  161392. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161393. /* (Re)initialize error mgr and destination modules */
  161394. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161395. (*cinfo->dest->init_destination) (cinfo);
  161396. /* Perform master selection of active modules */
  161397. jinit_compress_master(cinfo);
  161398. /* Set up for the first pass */
  161399. (*cinfo->master->prepare_for_pass) (cinfo);
  161400. /* Ready for application to drive first pass through jpeg_write_scanlines
  161401. * or jpeg_write_raw_data.
  161402. */
  161403. cinfo->next_scanline = 0;
  161404. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161405. }
  161406. /*
  161407. * Write some scanlines of data to the JPEG compressor.
  161408. *
  161409. * The return value will be the number of lines actually written.
  161410. * This should be less than the supplied num_lines only in case that
  161411. * the data destination module has requested suspension of the compressor,
  161412. * or if more than image_height scanlines are passed in.
  161413. *
  161414. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161415. * this likely signals an application programmer error. However,
  161416. * excess scanlines passed in the last valid call are *silently* ignored,
  161417. * so that the application need not adjust num_lines for end-of-image
  161418. * when using a multiple-scanline buffer.
  161419. */
  161420. GLOBAL(JDIMENSION)
  161421. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161422. JDIMENSION num_lines)
  161423. {
  161424. JDIMENSION row_ctr, rows_left;
  161425. if (cinfo->global_state != CSTATE_SCANNING)
  161426. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161427. if (cinfo->next_scanline >= cinfo->image_height)
  161428. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161429. /* Call progress monitor hook if present */
  161430. if (cinfo->progress != NULL) {
  161431. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161432. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161433. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161434. }
  161435. /* Give master control module another chance if this is first call to
  161436. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161437. * delayed so that application can write COM, etc, markers between
  161438. * jpeg_start_compress and jpeg_write_scanlines.
  161439. */
  161440. if (cinfo->master->call_pass_startup)
  161441. (*cinfo->master->pass_startup) (cinfo);
  161442. /* Ignore any extra scanlines at bottom of image. */
  161443. rows_left = cinfo->image_height - cinfo->next_scanline;
  161444. if (num_lines > rows_left)
  161445. num_lines = rows_left;
  161446. row_ctr = 0;
  161447. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161448. cinfo->next_scanline += row_ctr;
  161449. return row_ctr;
  161450. }
  161451. /*
  161452. * Alternate entry point to write raw data.
  161453. * Processes exactly one iMCU row per call, unless suspended.
  161454. */
  161455. GLOBAL(JDIMENSION)
  161456. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161457. JDIMENSION num_lines)
  161458. {
  161459. JDIMENSION lines_per_iMCU_row;
  161460. if (cinfo->global_state != CSTATE_RAW_OK)
  161461. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161462. if (cinfo->next_scanline >= cinfo->image_height) {
  161463. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161464. return 0;
  161465. }
  161466. /* Call progress monitor hook if present */
  161467. if (cinfo->progress != NULL) {
  161468. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161469. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161470. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161471. }
  161472. /* Give master control module another chance if this is first call to
  161473. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161474. * delayed so that application can write COM, etc, markers between
  161475. * jpeg_start_compress and jpeg_write_raw_data.
  161476. */
  161477. if (cinfo->master->call_pass_startup)
  161478. (*cinfo->master->pass_startup) (cinfo);
  161479. /* Verify that at least one iMCU row has been passed. */
  161480. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161481. if (num_lines < lines_per_iMCU_row)
  161482. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161483. /* Directly compress the row. */
  161484. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161485. /* If compressor did not consume the whole row, suspend processing. */
  161486. return 0;
  161487. }
  161488. /* OK, we processed one iMCU row. */
  161489. cinfo->next_scanline += lines_per_iMCU_row;
  161490. return lines_per_iMCU_row;
  161491. }
  161492. /*** End of inlined file: jcapistd.c ***/
  161493. /*** Start of inlined file: jccoefct.c ***/
  161494. #define JPEG_INTERNALS
  161495. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161496. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161497. * step is run during the first pass, and subsequent passes need only read
  161498. * the buffered coefficients.
  161499. */
  161500. #ifdef ENTROPY_OPT_SUPPORTED
  161501. #define FULL_COEF_BUFFER_SUPPORTED
  161502. #else
  161503. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161504. #define FULL_COEF_BUFFER_SUPPORTED
  161505. #endif
  161506. #endif
  161507. /* Private buffer controller object */
  161508. typedef struct {
  161509. struct jpeg_c_coef_controller pub; /* public fields */
  161510. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161511. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161512. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161513. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161514. /* For single-pass compression, it's sufficient to buffer just one MCU
  161515. * (although this may prove a bit slow in practice). We allocate a
  161516. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161517. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161518. * it's not really very big; this is to keep the module interfaces unchanged
  161519. * when a large coefficient buffer is necessary.)
  161520. * In multi-pass modes, this array points to the current MCU's blocks
  161521. * within the virtual arrays.
  161522. */
  161523. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161524. /* In multi-pass modes, we need a virtual block array for each component. */
  161525. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161526. } my_coef_controller;
  161527. typedef my_coef_controller * my_coef_ptr;
  161528. /* Forward declarations */
  161529. METHODDEF(boolean) compress_data
  161530. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161531. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161532. METHODDEF(boolean) compress_first_pass
  161533. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161534. METHODDEF(boolean) compress_output
  161535. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161536. #endif
  161537. LOCAL(void)
  161538. start_iMCU_row (j_compress_ptr cinfo)
  161539. /* Reset within-iMCU-row counters for a new row */
  161540. {
  161541. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161542. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161543. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161544. * But at the bottom of the image, process only what's left.
  161545. */
  161546. if (cinfo->comps_in_scan > 1) {
  161547. coef->MCU_rows_per_iMCU_row = 1;
  161548. } else {
  161549. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161550. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161551. else
  161552. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161553. }
  161554. coef->mcu_ctr = 0;
  161555. coef->MCU_vert_offset = 0;
  161556. }
  161557. /*
  161558. * Initialize for a processing pass.
  161559. */
  161560. METHODDEF(void)
  161561. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161562. {
  161563. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161564. coef->iMCU_row_num = 0;
  161565. start_iMCU_row(cinfo);
  161566. switch (pass_mode) {
  161567. case JBUF_PASS_THRU:
  161568. if (coef->whole_image[0] != NULL)
  161569. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161570. coef->pub.compress_data = compress_data;
  161571. break;
  161572. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161573. case JBUF_SAVE_AND_PASS:
  161574. if (coef->whole_image[0] == NULL)
  161575. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161576. coef->pub.compress_data = compress_first_pass;
  161577. break;
  161578. case JBUF_CRANK_DEST:
  161579. if (coef->whole_image[0] == NULL)
  161580. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161581. coef->pub.compress_data = compress_output;
  161582. break;
  161583. #endif
  161584. default:
  161585. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161586. break;
  161587. }
  161588. }
  161589. /*
  161590. * Process some data in the single-pass case.
  161591. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161592. * per call, ie, v_samp_factor block rows for each component in the image.
  161593. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161594. *
  161595. * NB: input_buf contains a plane for each component in image,
  161596. * which we index according to the component's SOF position.
  161597. */
  161598. METHODDEF(boolean)
  161599. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161600. {
  161601. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161602. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161603. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161604. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161605. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161606. JDIMENSION ypos, xpos;
  161607. jpeg_component_info *compptr;
  161608. /* Loop to write as much as one whole iMCU row */
  161609. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161610. yoffset++) {
  161611. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161612. MCU_col_num++) {
  161613. /* Determine where data comes from in input_buf and do the DCT thing.
  161614. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161615. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161616. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161617. * specially. The data in them does not matter for image reconstruction,
  161618. * so we fill them with values that will encode to the smallest amount of
  161619. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161620. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161621. */
  161622. blkn = 0;
  161623. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161624. compptr = cinfo->cur_comp_info[ci];
  161625. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161626. : compptr->last_col_width;
  161627. xpos = MCU_col_num * compptr->MCU_sample_width;
  161628. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161629. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161630. if (coef->iMCU_row_num < last_iMCU_row ||
  161631. yoffset+yindex < compptr->last_row_height) {
  161632. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161633. input_buf[compptr->component_index],
  161634. coef->MCU_buffer[blkn],
  161635. ypos, xpos, (JDIMENSION) blockcnt);
  161636. if (blockcnt < compptr->MCU_width) {
  161637. /* Create some dummy blocks at the right edge of the image. */
  161638. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161639. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161640. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161641. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161642. }
  161643. }
  161644. } else {
  161645. /* Create a row of dummy blocks at the bottom of the image. */
  161646. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161647. compptr->MCU_width * SIZEOF(JBLOCK));
  161648. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161649. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161650. }
  161651. }
  161652. blkn += compptr->MCU_width;
  161653. ypos += DCTSIZE;
  161654. }
  161655. }
  161656. /* Try to write the MCU. In event of a suspension failure, we will
  161657. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161658. */
  161659. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161660. /* Suspension forced; update state counters and exit */
  161661. coef->MCU_vert_offset = yoffset;
  161662. coef->mcu_ctr = MCU_col_num;
  161663. return FALSE;
  161664. }
  161665. }
  161666. /* Completed an MCU row, but perhaps not an iMCU row */
  161667. coef->mcu_ctr = 0;
  161668. }
  161669. /* Completed the iMCU row, advance counters for next one */
  161670. coef->iMCU_row_num++;
  161671. start_iMCU_row(cinfo);
  161672. return TRUE;
  161673. }
  161674. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161675. /*
  161676. * Process some data in the first pass of a multi-pass case.
  161677. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161678. * per call, ie, v_samp_factor block rows for each component in the image.
  161679. * This amount of data is read from the source buffer, DCT'd and quantized,
  161680. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161681. * as needed at the right and lower edges. (The dummy blocks are constructed
  161682. * in the virtual arrays, which have been padded appropriately.) This makes
  161683. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161684. *
  161685. * We must also emit the data to the entropy encoder. This is conveniently
  161686. * done by calling compress_output() after we've loaded the current strip
  161687. * of the virtual arrays.
  161688. *
  161689. * NB: input_buf contains a plane for each component in image. All
  161690. * components are DCT'd and loaded into the virtual arrays in this pass.
  161691. * However, it may be that only a subset of the components are emitted to
  161692. * the entropy encoder during this first pass; be careful about looking
  161693. * at the scan-dependent variables (MCU dimensions, etc).
  161694. */
  161695. METHODDEF(boolean)
  161696. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161697. {
  161698. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161699. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161700. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161701. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161702. JCOEF lastDC;
  161703. jpeg_component_info *compptr;
  161704. JBLOCKARRAY buffer;
  161705. JBLOCKROW thisblockrow, lastblockrow;
  161706. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161707. ci++, compptr++) {
  161708. /* Align the virtual buffer for this component. */
  161709. buffer = (*cinfo->mem->access_virt_barray)
  161710. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161711. coef->iMCU_row_num * compptr->v_samp_factor,
  161712. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161713. /* Count non-dummy DCT block rows in this iMCU row. */
  161714. if (coef->iMCU_row_num < last_iMCU_row)
  161715. block_rows = compptr->v_samp_factor;
  161716. else {
  161717. /* NB: can't use last_row_height here, since may not be set! */
  161718. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161719. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161720. }
  161721. blocks_across = compptr->width_in_blocks;
  161722. h_samp_factor = compptr->h_samp_factor;
  161723. /* Count number of dummy blocks to be added at the right margin. */
  161724. ndummy = (int) (blocks_across % h_samp_factor);
  161725. if (ndummy > 0)
  161726. ndummy = h_samp_factor - ndummy;
  161727. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161728. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161729. */
  161730. for (block_row = 0; block_row < block_rows; block_row++) {
  161731. thisblockrow = buffer[block_row];
  161732. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161733. input_buf[ci], thisblockrow,
  161734. (JDIMENSION) (block_row * DCTSIZE),
  161735. (JDIMENSION) 0, blocks_across);
  161736. if (ndummy > 0) {
  161737. /* Create dummy blocks at the right edge of the image. */
  161738. thisblockrow += blocks_across; /* => first dummy block */
  161739. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161740. lastDC = thisblockrow[-1][0];
  161741. for (bi = 0; bi < ndummy; bi++) {
  161742. thisblockrow[bi][0] = lastDC;
  161743. }
  161744. }
  161745. }
  161746. /* If at end of image, create dummy block rows as needed.
  161747. * The tricky part here is that within each MCU, we want the DC values
  161748. * of the dummy blocks to match the last real block's DC value.
  161749. * This squeezes a few more bytes out of the resulting file...
  161750. */
  161751. if (coef->iMCU_row_num == last_iMCU_row) {
  161752. blocks_across += ndummy; /* include lower right corner */
  161753. MCUs_across = blocks_across / h_samp_factor;
  161754. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161755. block_row++) {
  161756. thisblockrow = buffer[block_row];
  161757. lastblockrow = buffer[block_row-1];
  161758. jzero_far((void FAR *) thisblockrow,
  161759. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161760. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161761. lastDC = lastblockrow[h_samp_factor-1][0];
  161762. for (bi = 0; bi < h_samp_factor; bi++) {
  161763. thisblockrow[bi][0] = lastDC;
  161764. }
  161765. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161766. lastblockrow += h_samp_factor;
  161767. }
  161768. }
  161769. }
  161770. }
  161771. /* NB: compress_output will increment iMCU_row_num if successful.
  161772. * A suspension return will result in redoing all the work above next time.
  161773. */
  161774. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161775. return compress_output(cinfo, input_buf);
  161776. }
  161777. /*
  161778. * Process some data in subsequent passes of a multi-pass case.
  161779. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161780. * per call, ie, v_samp_factor block rows for each component in the scan.
  161781. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161782. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161783. *
  161784. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161785. */
  161786. METHODDEF(boolean)
  161787. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161788. {
  161789. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161790. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161791. int blkn, ci, xindex, yindex, yoffset;
  161792. JDIMENSION start_col;
  161793. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161794. JBLOCKROW buffer_ptr;
  161795. jpeg_component_info *compptr;
  161796. /* Align the virtual buffers for the components used in this scan.
  161797. * NB: during first pass, this is safe only because the buffers will
  161798. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161799. */
  161800. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161801. compptr = cinfo->cur_comp_info[ci];
  161802. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161803. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161804. coef->iMCU_row_num * compptr->v_samp_factor,
  161805. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161806. }
  161807. /* Loop to process one whole iMCU row */
  161808. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161809. yoffset++) {
  161810. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161811. MCU_col_num++) {
  161812. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161813. blkn = 0; /* index of current DCT block within MCU */
  161814. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161815. compptr = cinfo->cur_comp_info[ci];
  161816. start_col = MCU_col_num * compptr->MCU_width;
  161817. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161818. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161819. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161820. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161821. }
  161822. }
  161823. }
  161824. /* Try to write the MCU. */
  161825. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161826. /* Suspension forced; update state counters and exit */
  161827. coef->MCU_vert_offset = yoffset;
  161828. coef->mcu_ctr = MCU_col_num;
  161829. return FALSE;
  161830. }
  161831. }
  161832. /* Completed an MCU row, but perhaps not an iMCU row */
  161833. coef->mcu_ctr = 0;
  161834. }
  161835. /* Completed the iMCU row, advance counters for next one */
  161836. coef->iMCU_row_num++;
  161837. start_iMCU_row(cinfo);
  161838. return TRUE;
  161839. }
  161840. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161841. /*
  161842. * Initialize coefficient buffer controller.
  161843. */
  161844. GLOBAL(void)
  161845. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161846. {
  161847. my_coef_ptr coef;
  161848. coef = (my_coef_ptr)
  161849. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161850. SIZEOF(my_coef_controller));
  161851. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161852. coef->pub.start_pass = start_pass_coef;
  161853. /* Create the coefficient buffer. */
  161854. if (need_full_buffer) {
  161855. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161856. /* Allocate a full-image virtual array for each component, */
  161857. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161858. int ci;
  161859. jpeg_component_info *compptr;
  161860. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161861. ci++, compptr++) {
  161862. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161863. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161864. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161865. (long) compptr->h_samp_factor),
  161866. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161867. (long) compptr->v_samp_factor),
  161868. (JDIMENSION) compptr->v_samp_factor);
  161869. }
  161870. #else
  161871. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161872. #endif
  161873. } else {
  161874. /* We only need a single-MCU buffer. */
  161875. JBLOCKROW buffer;
  161876. int i;
  161877. buffer = (JBLOCKROW)
  161878. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161879. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161880. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161881. coef->MCU_buffer[i] = buffer + i;
  161882. }
  161883. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161884. }
  161885. }
  161886. /*** End of inlined file: jccoefct.c ***/
  161887. /*** Start of inlined file: jccolor.c ***/
  161888. #define JPEG_INTERNALS
  161889. /* Private subobject */
  161890. typedef struct {
  161891. struct jpeg_color_converter pub; /* public fields */
  161892. /* Private state for RGB->YCC conversion */
  161893. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161894. } my_color_converter;
  161895. typedef my_color_converter * my_cconvert_ptr;
  161896. /**************** RGB -> YCbCr conversion: most common case **************/
  161897. /*
  161898. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161899. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161900. * The conversion equations to be implemented are therefore
  161901. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161902. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161903. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161904. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161905. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161906. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161907. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161908. * were not represented exactly. Now we sacrifice exact representation of
  161909. * maximum red and maximum blue in order to get exact grayscales.
  161910. *
  161911. * To avoid floating-point arithmetic, we represent the fractional constants
  161912. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161913. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161914. *
  161915. * For even more speed, we avoid doing any multiplications in the inner loop
  161916. * by precalculating the constants times R,G,B for all possible values.
  161917. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161918. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161919. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161920. * colorspace anyway.
  161921. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161922. * in the tables to save adding them separately in the inner loop.
  161923. */
  161924. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161925. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161926. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161927. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161928. /* We allocate one big table and divide it up into eight parts, instead of
  161929. * doing eight alloc_small requests. This lets us use a single table base
  161930. * address, which can be held in a register in the inner loops on many
  161931. * machines (more than can hold all eight addresses, anyway).
  161932. */
  161933. #define R_Y_OFF 0 /* offset to R => Y section */
  161934. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161935. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161936. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161937. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161938. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161939. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161940. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161941. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161942. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161943. /*
  161944. * Initialize for RGB->YCC colorspace conversion.
  161945. */
  161946. METHODDEF(void)
  161947. rgb_ycc_start (j_compress_ptr cinfo)
  161948. {
  161949. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161950. INT32 * rgb_ycc_tab;
  161951. INT32 i;
  161952. /* Allocate and fill in the conversion tables. */
  161953. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161954. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161955. (TABLE_SIZE * SIZEOF(INT32)));
  161956. for (i = 0; i <= MAXJSAMPLE; i++) {
  161957. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161958. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161959. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161960. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161961. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161962. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161963. * This ensures that the maximum output will round to MAXJSAMPLE
  161964. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161965. */
  161966. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161967. /* B=>Cb and R=>Cr tables are the same
  161968. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161969. */
  161970. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161971. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161972. }
  161973. }
  161974. /*
  161975. * Convert some rows of samples to the JPEG colorspace.
  161976. *
  161977. * Note that we change from the application's interleaved-pixel format
  161978. * to our internal noninterleaved, one-plane-per-component format.
  161979. * The input buffer is therefore three times as wide as the output buffer.
  161980. *
  161981. * A starting row offset is provided only for the output buffer. The caller
  161982. * can easily adjust the passed input_buf value to accommodate any row
  161983. * offset required on that side.
  161984. */
  161985. METHODDEF(void)
  161986. rgb_ycc_convert (j_compress_ptr cinfo,
  161987. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161988. JDIMENSION output_row, int num_rows)
  161989. {
  161990. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161991. register int r, g, b;
  161992. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161993. register JSAMPROW inptr;
  161994. register JSAMPROW outptr0, outptr1, outptr2;
  161995. register JDIMENSION col;
  161996. JDIMENSION num_cols = cinfo->image_width;
  161997. while (--num_rows >= 0) {
  161998. inptr = *input_buf++;
  161999. outptr0 = output_buf[0][output_row];
  162000. outptr1 = output_buf[1][output_row];
  162001. outptr2 = output_buf[2][output_row];
  162002. output_row++;
  162003. for (col = 0; col < num_cols; col++) {
  162004. r = GETJSAMPLE(inptr[RGB_RED]);
  162005. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162006. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162007. inptr += RGB_PIXELSIZE;
  162008. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162009. * must be too; we do not need an explicit range-limiting operation.
  162010. * Hence the value being shifted is never negative, and we don't
  162011. * need the general RIGHT_SHIFT macro.
  162012. */
  162013. /* Y */
  162014. outptr0[col] = (JSAMPLE)
  162015. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162016. >> SCALEBITS);
  162017. /* Cb */
  162018. outptr1[col] = (JSAMPLE)
  162019. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162020. >> SCALEBITS);
  162021. /* Cr */
  162022. outptr2[col] = (JSAMPLE)
  162023. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162024. >> SCALEBITS);
  162025. }
  162026. }
  162027. }
  162028. /**************** Cases other than RGB -> YCbCr **************/
  162029. /*
  162030. * Convert some rows of samples to the JPEG colorspace.
  162031. * This version handles RGB->grayscale conversion, which is the same
  162032. * as the RGB->Y portion of RGB->YCbCr.
  162033. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162034. */
  162035. METHODDEF(void)
  162036. rgb_gray_convert (j_compress_ptr cinfo,
  162037. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162038. JDIMENSION output_row, int num_rows)
  162039. {
  162040. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162041. register int r, g, b;
  162042. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162043. register JSAMPROW inptr;
  162044. register JSAMPROW outptr;
  162045. register JDIMENSION col;
  162046. JDIMENSION num_cols = cinfo->image_width;
  162047. while (--num_rows >= 0) {
  162048. inptr = *input_buf++;
  162049. outptr = output_buf[0][output_row];
  162050. output_row++;
  162051. for (col = 0; col < num_cols; col++) {
  162052. r = GETJSAMPLE(inptr[RGB_RED]);
  162053. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162054. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162055. inptr += RGB_PIXELSIZE;
  162056. /* Y */
  162057. outptr[col] = (JSAMPLE)
  162058. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162059. >> SCALEBITS);
  162060. }
  162061. }
  162062. }
  162063. /*
  162064. * Convert some rows of samples to the JPEG colorspace.
  162065. * This version handles Adobe-style CMYK->YCCK conversion,
  162066. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162067. * conversion as above, while passing K (black) unchanged.
  162068. * We assume rgb_ycc_start has been called.
  162069. */
  162070. METHODDEF(void)
  162071. cmyk_ycck_convert (j_compress_ptr cinfo,
  162072. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162073. JDIMENSION output_row, int num_rows)
  162074. {
  162075. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162076. register int r, g, b;
  162077. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162078. register JSAMPROW inptr;
  162079. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162080. register JDIMENSION col;
  162081. JDIMENSION num_cols = cinfo->image_width;
  162082. while (--num_rows >= 0) {
  162083. inptr = *input_buf++;
  162084. outptr0 = output_buf[0][output_row];
  162085. outptr1 = output_buf[1][output_row];
  162086. outptr2 = output_buf[2][output_row];
  162087. outptr3 = output_buf[3][output_row];
  162088. output_row++;
  162089. for (col = 0; col < num_cols; col++) {
  162090. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162091. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162092. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162093. /* K passes through as-is */
  162094. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162095. inptr += 4;
  162096. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162097. * must be too; we do not need an explicit range-limiting operation.
  162098. * Hence the value being shifted is never negative, and we don't
  162099. * need the general RIGHT_SHIFT macro.
  162100. */
  162101. /* Y */
  162102. outptr0[col] = (JSAMPLE)
  162103. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162104. >> SCALEBITS);
  162105. /* Cb */
  162106. outptr1[col] = (JSAMPLE)
  162107. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162108. >> SCALEBITS);
  162109. /* Cr */
  162110. outptr2[col] = (JSAMPLE)
  162111. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162112. >> SCALEBITS);
  162113. }
  162114. }
  162115. }
  162116. /*
  162117. * Convert some rows of samples to the JPEG colorspace.
  162118. * This version handles grayscale output with no conversion.
  162119. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162120. */
  162121. METHODDEF(void)
  162122. grayscale_convert (j_compress_ptr cinfo,
  162123. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162124. JDIMENSION output_row, int num_rows)
  162125. {
  162126. register JSAMPROW inptr;
  162127. register JSAMPROW outptr;
  162128. register JDIMENSION col;
  162129. JDIMENSION num_cols = cinfo->image_width;
  162130. int instride = cinfo->input_components;
  162131. while (--num_rows >= 0) {
  162132. inptr = *input_buf++;
  162133. outptr = output_buf[0][output_row];
  162134. output_row++;
  162135. for (col = 0; col < num_cols; col++) {
  162136. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162137. inptr += instride;
  162138. }
  162139. }
  162140. }
  162141. /*
  162142. * Convert some rows of samples to the JPEG colorspace.
  162143. * This version handles multi-component colorspaces without conversion.
  162144. * We assume input_components == num_components.
  162145. */
  162146. METHODDEF(void)
  162147. null_convert (j_compress_ptr cinfo,
  162148. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162149. JDIMENSION output_row, int num_rows)
  162150. {
  162151. register JSAMPROW inptr;
  162152. register JSAMPROW outptr;
  162153. register JDIMENSION col;
  162154. register int ci;
  162155. int nc = cinfo->num_components;
  162156. JDIMENSION num_cols = cinfo->image_width;
  162157. while (--num_rows >= 0) {
  162158. /* It seems fastest to make a separate pass for each component. */
  162159. for (ci = 0; ci < nc; ci++) {
  162160. inptr = *input_buf;
  162161. outptr = output_buf[ci][output_row];
  162162. for (col = 0; col < num_cols; col++) {
  162163. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162164. inptr += nc;
  162165. }
  162166. }
  162167. input_buf++;
  162168. output_row++;
  162169. }
  162170. }
  162171. /*
  162172. * Empty method for start_pass.
  162173. */
  162174. METHODDEF(void)
  162175. null_method (j_compress_ptr)
  162176. {
  162177. /* no work needed */
  162178. }
  162179. /*
  162180. * Module initialization routine for input colorspace conversion.
  162181. */
  162182. GLOBAL(void)
  162183. jinit_color_converter (j_compress_ptr cinfo)
  162184. {
  162185. my_cconvert_ptr cconvert;
  162186. cconvert = (my_cconvert_ptr)
  162187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162188. SIZEOF(my_color_converter));
  162189. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162190. /* set start_pass to null method until we find out differently */
  162191. cconvert->pub.start_pass = null_method;
  162192. /* Make sure input_components agrees with in_color_space */
  162193. switch (cinfo->in_color_space) {
  162194. case JCS_GRAYSCALE:
  162195. if (cinfo->input_components != 1)
  162196. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162197. break;
  162198. case JCS_RGB:
  162199. #if RGB_PIXELSIZE != 3
  162200. if (cinfo->input_components != RGB_PIXELSIZE)
  162201. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162202. break;
  162203. #endif /* else share code with YCbCr */
  162204. case JCS_YCbCr:
  162205. if (cinfo->input_components != 3)
  162206. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162207. break;
  162208. case JCS_CMYK:
  162209. case JCS_YCCK:
  162210. if (cinfo->input_components != 4)
  162211. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162212. break;
  162213. default: /* JCS_UNKNOWN can be anything */
  162214. if (cinfo->input_components < 1)
  162215. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162216. break;
  162217. }
  162218. /* Check num_components, set conversion method based on requested space */
  162219. switch (cinfo->jpeg_color_space) {
  162220. case JCS_GRAYSCALE:
  162221. if (cinfo->num_components != 1)
  162222. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162223. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162224. cconvert->pub.color_convert = grayscale_convert;
  162225. else if (cinfo->in_color_space == JCS_RGB) {
  162226. cconvert->pub.start_pass = rgb_ycc_start;
  162227. cconvert->pub.color_convert = rgb_gray_convert;
  162228. } else if (cinfo->in_color_space == JCS_YCbCr)
  162229. cconvert->pub.color_convert = grayscale_convert;
  162230. else
  162231. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162232. break;
  162233. case JCS_RGB:
  162234. if (cinfo->num_components != 3)
  162235. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162236. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162237. cconvert->pub.color_convert = null_convert;
  162238. else
  162239. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162240. break;
  162241. case JCS_YCbCr:
  162242. if (cinfo->num_components != 3)
  162243. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162244. if (cinfo->in_color_space == JCS_RGB) {
  162245. cconvert->pub.start_pass = rgb_ycc_start;
  162246. cconvert->pub.color_convert = rgb_ycc_convert;
  162247. } else if (cinfo->in_color_space == JCS_YCbCr)
  162248. cconvert->pub.color_convert = null_convert;
  162249. else
  162250. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162251. break;
  162252. case JCS_CMYK:
  162253. if (cinfo->num_components != 4)
  162254. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162255. if (cinfo->in_color_space == JCS_CMYK)
  162256. cconvert->pub.color_convert = null_convert;
  162257. else
  162258. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162259. break;
  162260. case JCS_YCCK:
  162261. if (cinfo->num_components != 4)
  162262. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162263. if (cinfo->in_color_space == JCS_CMYK) {
  162264. cconvert->pub.start_pass = rgb_ycc_start;
  162265. cconvert->pub.color_convert = cmyk_ycck_convert;
  162266. } else if (cinfo->in_color_space == JCS_YCCK)
  162267. cconvert->pub.color_convert = null_convert;
  162268. else
  162269. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162270. break;
  162271. default: /* allow null conversion of JCS_UNKNOWN */
  162272. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162273. cinfo->num_components != cinfo->input_components)
  162274. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162275. cconvert->pub.color_convert = null_convert;
  162276. break;
  162277. }
  162278. }
  162279. /*** End of inlined file: jccolor.c ***/
  162280. #undef FIX
  162281. /*** Start of inlined file: jcdctmgr.c ***/
  162282. #define JPEG_INTERNALS
  162283. /*** Start of inlined file: jdct.h ***/
  162284. /*
  162285. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162286. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162287. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162288. * implementations use an array of type FAST_FLOAT, instead.)
  162289. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162290. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162291. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162292. * convention improves accuracy in integer implementations and saves some
  162293. * work in floating-point ones.
  162294. * Quantization of the output coefficients is done by jcdctmgr.c.
  162295. */
  162296. #ifndef __jdct_h__
  162297. #define __jdct_h__
  162298. #if BITS_IN_JSAMPLE == 8
  162299. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162300. #else
  162301. typedef INT32 DCTELEM; /* must have 32 bits */
  162302. #endif
  162303. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162304. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162305. /*
  162306. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162307. * to an output sample array. The routine must dequantize the input data as
  162308. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162309. * pointed to by compptr->dct_table. The output data is to be placed into the
  162310. * sample array starting at a specified column. (Any row offset needed will
  162311. * be applied to the array pointer before it is passed to the IDCT code.)
  162312. * Note that the number of samples emitted by the IDCT routine is
  162313. * DCT_scaled_size * DCT_scaled_size.
  162314. */
  162315. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162316. /*
  162317. * Each IDCT routine has its own ideas about the best dct_table element type.
  162318. */
  162319. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162320. #if BITS_IN_JSAMPLE == 8
  162321. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162322. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162323. #else
  162324. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162325. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162326. #endif
  162327. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162328. /*
  162329. * Each IDCT routine is responsible for range-limiting its results and
  162330. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162331. * be quite far out of range if the input data is corrupt, so a bulletproof
  162332. * range-limiting step is required. We use a mask-and-table-lookup method
  162333. * to do the combined operations quickly. See the comments with
  162334. * prepare_range_limit_table (in jdmaster.c) for more info.
  162335. */
  162336. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162337. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162338. /* Short forms of external names for systems with brain-damaged linkers. */
  162339. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162340. #define jpeg_fdct_islow jFDislow
  162341. #define jpeg_fdct_ifast jFDifast
  162342. #define jpeg_fdct_float jFDfloat
  162343. #define jpeg_idct_islow jRDislow
  162344. #define jpeg_idct_ifast jRDifast
  162345. #define jpeg_idct_float jRDfloat
  162346. #define jpeg_idct_4x4 jRD4x4
  162347. #define jpeg_idct_2x2 jRD2x2
  162348. #define jpeg_idct_1x1 jRD1x1
  162349. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162350. /* Extern declarations for the forward and inverse DCT routines. */
  162351. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162352. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162353. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162354. EXTERN(void) jpeg_idct_islow
  162355. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162356. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162357. EXTERN(void) jpeg_idct_ifast
  162358. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162359. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162360. EXTERN(void) jpeg_idct_float
  162361. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162362. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162363. EXTERN(void) jpeg_idct_4x4
  162364. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162365. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162366. EXTERN(void) jpeg_idct_2x2
  162367. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162368. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162369. EXTERN(void) jpeg_idct_1x1
  162370. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162371. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162372. /*
  162373. * Macros for handling fixed-point arithmetic; these are used by many
  162374. * but not all of the DCT/IDCT modules.
  162375. *
  162376. * All values are expected to be of type INT32.
  162377. * Fractional constants are scaled left by CONST_BITS bits.
  162378. * CONST_BITS is defined within each module using these macros,
  162379. * and may differ from one module to the next.
  162380. */
  162381. #define ONE ((INT32) 1)
  162382. #define CONST_SCALE (ONE << CONST_BITS)
  162383. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162384. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162385. * thus causing a lot of useless floating-point operations at run time.
  162386. */
  162387. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162388. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162389. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162390. * the fudge factor is correct for either sign of X.
  162391. */
  162392. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162393. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162394. * This macro is used only when the two inputs will actually be no more than
  162395. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162396. * full 32x32 multiply. This provides a useful speedup on many machines.
  162397. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162398. * in C, but some C compilers will do the right thing if you provide the
  162399. * correct combination of casts.
  162400. */
  162401. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162402. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162403. #endif
  162404. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162405. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162406. #endif
  162407. #ifndef MULTIPLY16C16 /* default definition */
  162408. #define MULTIPLY16C16(var,const) ((var) * (const))
  162409. #endif
  162410. /* Same except both inputs are variables. */
  162411. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162412. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162413. #endif
  162414. #ifndef MULTIPLY16V16 /* default definition */
  162415. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162416. #endif
  162417. #endif
  162418. /*** End of inlined file: jdct.h ***/
  162419. /* Private declarations for DCT subsystem */
  162420. /* Private subobject for this module */
  162421. typedef struct {
  162422. struct jpeg_forward_dct pub; /* public fields */
  162423. /* Pointer to the DCT routine actually in use */
  162424. forward_DCT_method_ptr do_dct;
  162425. /* The actual post-DCT divisors --- not identical to the quant table
  162426. * entries, because of scaling (especially for an unnormalized DCT).
  162427. * Each table is given in normal array order.
  162428. */
  162429. DCTELEM * divisors[NUM_QUANT_TBLS];
  162430. #ifdef DCT_FLOAT_SUPPORTED
  162431. /* Same as above for the floating-point case. */
  162432. float_DCT_method_ptr do_float_dct;
  162433. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162434. #endif
  162435. } my_fdct_controller;
  162436. typedef my_fdct_controller * my_fdct_ptr;
  162437. /*
  162438. * Initialize for a processing pass.
  162439. * Verify that all referenced Q-tables are present, and set up
  162440. * the divisor table for each one.
  162441. * In the current implementation, DCT of all components is done during
  162442. * the first pass, even if only some components will be output in the
  162443. * first scan. Hence all components should be examined here.
  162444. */
  162445. METHODDEF(void)
  162446. start_pass_fdctmgr (j_compress_ptr cinfo)
  162447. {
  162448. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162449. int ci, qtblno, i;
  162450. jpeg_component_info *compptr;
  162451. JQUANT_TBL * qtbl;
  162452. DCTELEM * dtbl;
  162453. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162454. ci++, compptr++) {
  162455. qtblno = compptr->quant_tbl_no;
  162456. /* Make sure specified quantization table is present */
  162457. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162458. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162459. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162460. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162461. /* Compute divisors for this quant table */
  162462. /* We may do this more than once for same table, but it's not a big deal */
  162463. switch (cinfo->dct_method) {
  162464. #ifdef DCT_ISLOW_SUPPORTED
  162465. case JDCT_ISLOW:
  162466. /* For LL&M IDCT method, divisors are equal to raw quantization
  162467. * coefficients multiplied by 8 (to counteract scaling).
  162468. */
  162469. if (fdct->divisors[qtblno] == NULL) {
  162470. fdct->divisors[qtblno] = (DCTELEM *)
  162471. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162472. DCTSIZE2 * SIZEOF(DCTELEM));
  162473. }
  162474. dtbl = fdct->divisors[qtblno];
  162475. for (i = 0; i < DCTSIZE2; i++) {
  162476. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162477. }
  162478. break;
  162479. #endif
  162480. #ifdef DCT_IFAST_SUPPORTED
  162481. case JDCT_IFAST:
  162482. {
  162483. /* For AA&N IDCT method, divisors are equal to quantization
  162484. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162485. * scalefactor[0] = 1
  162486. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162487. * We apply a further scale factor of 8.
  162488. */
  162489. #define CONST_BITS 14
  162490. static const INT16 aanscales[DCTSIZE2] = {
  162491. /* precomputed values scaled up by 14 bits */
  162492. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162493. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162494. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162495. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162496. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162497. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162498. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162499. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162500. };
  162501. SHIFT_TEMPS
  162502. if (fdct->divisors[qtblno] == NULL) {
  162503. fdct->divisors[qtblno] = (DCTELEM *)
  162504. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162505. DCTSIZE2 * SIZEOF(DCTELEM));
  162506. }
  162507. dtbl = fdct->divisors[qtblno];
  162508. for (i = 0; i < DCTSIZE2; i++) {
  162509. dtbl[i] = (DCTELEM)
  162510. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162511. (INT32) aanscales[i]),
  162512. CONST_BITS-3);
  162513. }
  162514. }
  162515. break;
  162516. #endif
  162517. #ifdef DCT_FLOAT_SUPPORTED
  162518. case JDCT_FLOAT:
  162519. {
  162520. /* For float AA&N IDCT method, divisors are equal to quantization
  162521. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162522. * scalefactor[0] = 1
  162523. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162524. * We apply a further scale factor of 8.
  162525. * What's actually stored is 1/divisor so that the inner loop can
  162526. * use a multiplication rather than a division.
  162527. */
  162528. FAST_FLOAT * fdtbl;
  162529. int row, col;
  162530. static const double aanscalefactor[DCTSIZE] = {
  162531. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162532. 1.0, 0.785694958, 0.541196100, 0.275899379
  162533. };
  162534. if (fdct->float_divisors[qtblno] == NULL) {
  162535. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162536. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162537. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162538. }
  162539. fdtbl = fdct->float_divisors[qtblno];
  162540. i = 0;
  162541. for (row = 0; row < DCTSIZE; row++) {
  162542. for (col = 0; col < DCTSIZE; col++) {
  162543. fdtbl[i] = (FAST_FLOAT)
  162544. (1.0 / (((double) qtbl->quantval[i] *
  162545. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162546. i++;
  162547. }
  162548. }
  162549. }
  162550. break;
  162551. #endif
  162552. default:
  162553. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162554. break;
  162555. }
  162556. }
  162557. }
  162558. /*
  162559. * Perform forward DCT on one or more blocks of a component.
  162560. *
  162561. * The input samples are taken from the sample_data[] array starting at
  162562. * position start_row/start_col, and moving to the right for any additional
  162563. * blocks. The quantized coefficients are returned in coef_blocks[].
  162564. */
  162565. METHODDEF(void)
  162566. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162567. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162568. JDIMENSION start_row, JDIMENSION start_col,
  162569. JDIMENSION num_blocks)
  162570. /* This version is used for integer DCT implementations. */
  162571. {
  162572. /* This routine is heavily used, so it's worth coding it tightly. */
  162573. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162574. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162575. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162576. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162577. JDIMENSION bi;
  162578. sample_data += start_row; /* fold in the vertical offset once */
  162579. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162580. /* Load data into workspace, applying unsigned->signed conversion */
  162581. { register DCTELEM *workspaceptr;
  162582. register JSAMPROW elemptr;
  162583. register int elemr;
  162584. workspaceptr = workspace;
  162585. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162586. elemptr = sample_data[elemr] + start_col;
  162587. #if DCTSIZE == 8 /* unroll the inner loop */
  162588. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162589. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162590. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162591. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162592. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162593. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162594. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162595. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162596. #else
  162597. { register int elemc;
  162598. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162599. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162600. }
  162601. }
  162602. #endif
  162603. }
  162604. }
  162605. /* Perform the DCT */
  162606. (*do_dct) (workspace);
  162607. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162608. { register DCTELEM temp, qval;
  162609. register int i;
  162610. register JCOEFPTR output_ptr = coef_blocks[bi];
  162611. for (i = 0; i < DCTSIZE2; i++) {
  162612. qval = divisors[i];
  162613. temp = workspace[i];
  162614. /* Divide the coefficient value by qval, ensuring proper rounding.
  162615. * Since C does not specify the direction of rounding for negative
  162616. * quotients, we have to force the dividend positive for portability.
  162617. *
  162618. * In most files, at least half of the output values will be zero
  162619. * (at default quantization settings, more like three-quarters...)
  162620. * so we should ensure that this case is fast. On many machines,
  162621. * a comparison is enough cheaper than a divide to make a special test
  162622. * a win. Since both inputs will be nonnegative, we need only test
  162623. * for a < b to discover whether a/b is 0.
  162624. * If your machine's division is fast enough, define FAST_DIVIDE.
  162625. */
  162626. #ifdef FAST_DIVIDE
  162627. #define DIVIDE_BY(a,b) a /= b
  162628. #else
  162629. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162630. #endif
  162631. if (temp < 0) {
  162632. temp = -temp;
  162633. temp += qval>>1; /* for rounding */
  162634. DIVIDE_BY(temp, qval);
  162635. temp = -temp;
  162636. } else {
  162637. temp += qval>>1; /* for rounding */
  162638. DIVIDE_BY(temp, qval);
  162639. }
  162640. output_ptr[i] = (JCOEF) temp;
  162641. }
  162642. }
  162643. }
  162644. }
  162645. #ifdef DCT_FLOAT_SUPPORTED
  162646. METHODDEF(void)
  162647. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162648. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162649. JDIMENSION start_row, JDIMENSION start_col,
  162650. JDIMENSION num_blocks)
  162651. /* This version is used for floating-point DCT implementations. */
  162652. {
  162653. /* This routine is heavily used, so it's worth coding it tightly. */
  162654. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162655. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162656. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162657. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162658. JDIMENSION bi;
  162659. sample_data += start_row; /* fold in the vertical offset once */
  162660. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162661. /* Load data into workspace, applying unsigned->signed conversion */
  162662. { register FAST_FLOAT *workspaceptr;
  162663. register JSAMPROW elemptr;
  162664. register int elemr;
  162665. workspaceptr = workspace;
  162666. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162667. elemptr = sample_data[elemr] + start_col;
  162668. #if DCTSIZE == 8 /* unroll the inner loop */
  162669. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162670. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162671. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162672. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162673. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162674. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162675. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162676. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162677. #else
  162678. { register int elemc;
  162679. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162680. *workspaceptr++ = (FAST_FLOAT)
  162681. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162682. }
  162683. }
  162684. #endif
  162685. }
  162686. }
  162687. /* Perform the DCT */
  162688. (*do_dct) (workspace);
  162689. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162690. { register FAST_FLOAT temp;
  162691. register int i;
  162692. register JCOEFPTR output_ptr = coef_blocks[bi];
  162693. for (i = 0; i < DCTSIZE2; i++) {
  162694. /* Apply the quantization and scaling factor */
  162695. temp = workspace[i] * divisors[i];
  162696. /* Round to nearest integer.
  162697. * Since C does not specify the direction of rounding for negative
  162698. * quotients, we have to force the dividend positive for portability.
  162699. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162700. * code should work for either 16-bit or 32-bit ints.
  162701. */
  162702. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162703. }
  162704. }
  162705. }
  162706. }
  162707. #endif /* DCT_FLOAT_SUPPORTED */
  162708. /*
  162709. * Initialize FDCT manager.
  162710. */
  162711. GLOBAL(void)
  162712. jinit_forward_dct (j_compress_ptr cinfo)
  162713. {
  162714. my_fdct_ptr fdct;
  162715. int i;
  162716. fdct = (my_fdct_ptr)
  162717. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162718. SIZEOF(my_fdct_controller));
  162719. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162720. fdct->pub.start_pass = start_pass_fdctmgr;
  162721. switch (cinfo->dct_method) {
  162722. #ifdef DCT_ISLOW_SUPPORTED
  162723. case JDCT_ISLOW:
  162724. fdct->pub.forward_DCT = forward_DCT;
  162725. fdct->do_dct = jpeg_fdct_islow;
  162726. break;
  162727. #endif
  162728. #ifdef DCT_IFAST_SUPPORTED
  162729. case JDCT_IFAST:
  162730. fdct->pub.forward_DCT = forward_DCT;
  162731. fdct->do_dct = jpeg_fdct_ifast;
  162732. break;
  162733. #endif
  162734. #ifdef DCT_FLOAT_SUPPORTED
  162735. case JDCT_FLOAT:
  162736. fdct->pub.forward_DCT = forward_DCT_float;
  162737. fdct->do_float_dct = jpeg_fdct_float;
  162738. break;
  162739. #endif
  162740. default:
  162741. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162742. break;
  162743. }
  162744. /* Mark divisor tables unallocated */
  162745. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162746. fdct->divisors[i] = NULL;
  162747. #ifdef DCT_FLOAT_SUPPORTED
  162748. fdct->float_divisors[i] = NULL;
  162749. #endif
  162750. }
  162751. }
  162752. /*** End of inlined file: jcdctmgr.c ***/
  162753. #undef CONST_BITS
  162754. /*** Start of inlined file: jchuff.c ***/
  162755. #define JPEG_INTERNALS
  162756. /*** Start of inlined file: jchuff.h ***/
  162757. /* The legal range of a DCT coefficient is
  162758. * -1024 .. +1023 for 8-bit data;
  162759. * -16384 .. +16383 for 12-bit data.
  162760. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162761. */
  162762. #ifndef _jchuff_h_
  162763. #define _jchuff_h_
  162764. #if BITS_IN_JSAMPLE == 8
  162765. #define MAX_COEF_BITS 10
  162766. #else
  162767. #define MAX_COEF_BITS 14
  162768. #endif
  162769. /* Derived data constructed for each Huffman table */
  162770. typedef struct {
  162771. unsigned int ehufco[256]; /* code for each symbol */
  162772. char ehufsi[256]; /* length of code for each symbol */
  162773. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162774. } c_derived_tbl;
  162775. /* Short forms of external names for systems with brain-damaged linkers. */
  162776. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162777. #define jpeg_make_c_derived_tbl jMkCDerived
  162778. #define jpeg_gen_optimal_table jGenOptTbl
  162779. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162780. /* Expand a Huffman table definition into the derived format */
  162781. EXTERN(void) jpeg_make_c_derived_tbl
  162782. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162783. c_derived_tbl ** pdtbl));
  162784. /* Generate an optimal table definition given the specified counts */
  162785. EXTERN(void) jpeg_gen_optimal_table
  162786. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162787. #endif
  162788. /*** End of inlined file: jchuff.h ***/
  162789. /* Declarations shared with jcphuff.c */
  162790. /* Expanded entropy encoder object for Huffman encoding.
  162791. *
  162792. * The savable_state subrecord contains fields that change within an MCU,
  162793. * but must not be updated permanently until we complete the MCU.
  162794. */
  162795. typedef struct {
  162796. INT32 put_buffer; /* current bit-accumulation buffer */
  162797. int put_bits; /* # of bits now in it */
  162798. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162799. } savable_state;
  162800. /* This macro is to work around compilers with missing or broken
  162801. * structure assignment. You'll need to fix this code if you have
  162802. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162803. */
  162804. #ifndef NO_STRUCT_ASSIGN
  162805. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162806. #else
  162807. #if MAX_COMPS_IN_SCAN == 4
  162808. #define ASSIGN_STATE(dest,src) \
  162809. ((dest).put_buffer = (src).put_buffer, \
  162810. (dest).put_bits = (src).put_bits, \
  162811. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162812. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162813. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162814. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162815. #endif
  162816. #endif
  162817. typedef struct {
  162818. struct jpeg_entropy_encoder pub; /* public fields */
  162819. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162820. /* These fields are NOT loaded into local working state. */
  162821. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162822. int next_restart_num; /* next restart number to write (0-7) */
  162823. /* Pointers to derived tables (these workspaces have image lifespan) */
  162824. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162825. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162826. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162827. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162828. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162829. #endif
  162830. } huff_entropy_encoder;
  162831. typedef huff_entropy_encoder * huff_entropy_ptr;
  162832. /* Working state while writing an MCU.
  162833. * This struct contains all the fields that are needed by subroutines.
  162834. */
  162835. typedef struct {
  162836. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162837. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162838. savable_state cur; /* Current bit buffer & DC state */
  162839. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162840. } working_state;
  162841. /* Forward declarations */
  162842. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162843. JBLOCKROW *MCU_data));
  162844. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162845. #ifdef ENTROPY_OPT_SUPPORTED
  162846. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162847. JBLOCKROW *MCU_data));
  162848. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162849. #endif
  162850. /*
  162851. * Initialize for a Huffman-compressed scan.
  162852. * If gather_statistics is TRUE, we do not output anything during the scan,
  162853. * just count the Huffman symbols used and generate Huffman code tables.
  162854. */
  162855. METHODDEF(void)
  162856. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162857. {
  162858. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162859. int ci, dctbl, actbl;
  162860. jpeg_component_info * compptr;
  162861. if (gather_statistics) {
  162862. #ifdef ENTROPY_OPT_SUPPORTED
  162863. entropy->pub.encode_mcu = encode_mcu_gather;
  162864. entropy->pub.finish_pass = finish_pass_gather;
  162865. #else
  162866. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162867. #endif
  162868. } else {
  162869. entropy->pub.encode_mcu = encode_mcu_huff;
  162870. entropy->pub.finish_pass = finish_pass_huff;
  162871. }
  162872. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162873. compptr = cinfo->cur_comp_info[ci];
  162874. dctbl = compptr->dc_tbl_no;
  162875. actbl = compptr->ac_tbl_no;
  162876. if (gather_statistics) {
  162877. #ifdef ENTROPY_OPT_SUPPORTED
  162878. /* Check for invalid table indexes */
  162879. /* (make_c_derived_tbl does this in the other path) */
  162880. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162881. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162882. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162883. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162884. /* Allocate and zero the statistics tables */
  162885. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162886. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162887. entropy->dc_count_ptrs[dctbl] = (long *)
  162888. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162889. 257 * SIZEOF(long));
  162890. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162891. if (entropy->ac_count_ptrs[actbl] == NULL)
  162892. entropy->ac_count_ptrs[actbl] = (long *)
  162893. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162894. 257 * SIZEOF(long));
  162895. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162896. #endif
  162897. } else {
  162898. /* Compute derived values for Huffman tables */
  162899. /* We may do this more than once for a table, but it's not expensive */
  162900. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162901. & entropy->dc_derived_tbls[dctbl]);
  162902. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162903. & entropy->ac_derived_tbls[actbl]);
  162904. }
  162905. /* Initialize DC predictions to 0 */
  162906. entropy->saved.last_dc_val[ci] = 0;
  162907. }
  162908. /* Initialize bit buffer to empty */
  162909. entropy->saved.put_buffer = 0;
  162910. entropy->saved.put_bits = 0;
  162911. /* Initialize restart stuff */
  162912. entropy->restarts_to_go = cinfo->restart_interval;
  162913. entropy->next_restart_num = 0;
  162914. }
  162915. /*
  162916. * Compute the derived values for a Huffman table.
  162917. * This routine also performs some validation checks on the table.
  162918. *
  162919. * Note this is also used by jcphuff.c.
  162920. */
  162921. GLOBAL(void)
  162922. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162923. c_derived_tbl ** pdtbl)
  162924. {
  162925. JHUFF_TBL *htbl;
  162926. c_derived_tbl *dtbl;
  162927. int p, i, l, lastp, si, maxsymbol;
  162928. char huffsize[257];
  162929. unsigned int huffcode[257];
  162930. unsigned int code;
  162931. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162932. * paralleling the order of the symbols themselves in htbl->huffval[].
  162933. */
  162934. /* Find the input Huffman table */
  162935. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162936. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162937. htbl =
  162938. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162939. if (htbl == NULL)
  162940. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162941. /* Allocate a workspace if we haven't already done so. */
  162942. if (*pdtbl == NULL)
  162943. *pdtbl = (c_derived_tbl *)
  162944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162945. SIZEOF(c_derived_tbl));
  162946. dtbl = *pdtbl;
  162947. /* Figure C.1: make table of Huffman code length for each symbol */
  162948. p = 0;
  162949. for (l = 1; l <= 16; l++) {
  162950. i = (int) htbl->bits[l];
  162951. if (i < 0 || p + i > 256) /* protect against table overrun */
  162952. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162953. while (i--)
  162954. huffsize[p++] = (char) l;
  162955. }
  162956. huffsize[p] = 0;
  162957. lastp = p;
  162958. /* Figure C.2: generate the codes themselves */
  162959. /* We also validate that the counts represent a legal Huffman code tree. */
  162960. code = 0;
  162961. si = huffsize[0];
  162962. p = 0;
  162963. while (huffsize[p]) {
  162964. while (((int) huffsize[p]) == si) {
  162965. huffcode[p++] = code;
  162966. code++;
  162967. }
  162968. /* code is now 1 more than the last code used for codelength si; but
  162969. * it must still fit in si bits, since no code is allowed to be all ones.
  162970. */
  162971. if (((INT32) code) >= (((INT32) 1) << si))
  162972. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162973. code <<= 1;
  162974. si++;
  162975. }
  162976. /* Figure C.3: generate encoding tables */
  162977. /* These are code and size indexed by symbol value */
  162978. /* Set all codeless symbols to have code length 0;
  162979. * this lets us detect duplicate VAL entries here, and later
  162980. * allows emit_bits to detect any attempt to emit such symbols.
  162981. */
  162982. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162983. /* This is also a convenient place to check for out-of-range
  162984. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162985. * but only 0..15 for DC. (We could constrain them further
  162986. * based on data depth and mode, but this seems enough.)
  162987. */
  162988. maxsymbol = isDC ? 15 : 255;
  162989. for (p = 0; p < lastp; p++) {
  162990. i = htbl->huffval[p];
  162991. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162992. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162993. dtbl->ehufco[i] = huffcode[p];
  162994. dtbl->ehufsi[i] = huffsize[p];
  162995. }
  162996. }
  162997. /* Outputting bytes to the file */
  162998. /* Emit a byte, taking 'action' if must suspend. */
  162999. #define emit_byte(state,val,action) \
  163000. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163001. if (--(state)->free_in_buffer == 0) \
  163002. if (! dump_buffer(state)) \
  163003. { action; } }
  163004. LOCAL(boolean)
  163005. dump_buffer (working_state * state)
  163006. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163007. {
  163008. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163009. if (! (*dest->empty_output_buffer) (state->cinfo))
  163010. return FALSE;
  163011. /* After a successful buffer dump, must reset buffer pointers */
  163012. state->next_output_byte = dest->next_output_byte;
  163013. state->free_in_buffer = dest->free_in_buffer;
  163014. return TRUE;
  163015. }
  163016. /* Outputting bits to the file */
  163017. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163018. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163019. * in one call, and we never retain more than 7 bits in put_buffer
  163020. * between calls, so 24 bits are sufficient.
  163021. */
  163022. INLINE
  163023. LOCAL(boolean)
  163024. emit_bits (working_state * state, unsigned int code, int size)
  163025. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163026. {
  163027. /* This routine is heavily used, so it's worth coding tightly. */
  163028. register INT32 put_buffer = (INT32) code;
  163029. register int put_bits = state->cur.put_bits;
  163030. /* if size is 0, caller used an invalid Huffman table entry */
  163031. if (size == 0)
  163032. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163033. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163034. put_bits += size; /* new number of bits in buffer */
  163035. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163036. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163037. while (put_bits >= 8) {
  163038. int c = (int) ((put_buffer >> 16) & 0xFF);
  163039. emit_byte(state, c, return FALSE);
  163040. if (c == 0xFF) { /* need to stuff a zero byte? */
  163041. emit_byte(state, 0, return FALSE);
  163042. }
  163043. put_buffer <<= 8;
  163044. put_bits -= 8;
  163045. }
  163046. state->cur.put_buffer = put_buffer; /* update state variables */
  163047. state->cur.put_bits = put_bits;
  163048. return TRUE;
  163049. }
  163050. LOCAL(boolean)
  163051. flush_bits (working_state * state)
  163052. {
  163053. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163054. return FALSE;
  163055. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163056. state->cur.put_bits = 0;
  163057. return TRUE;
  163058. }
  163059. /* Encode a single block's worth of coefficients */
  163060. LOCAL(boolean)
  163061. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163062. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163063. {
  163064. register int temp, temp2;
  163065. register int nbits;
  163066. register int k, r, i;
  163067. /* Encode the DC coefficient difference per section F.1.2.1 */
  163068. temp = temp2 = block[0] - last_dc_val;
  163069. if (temp < 0) {
  163070. temp = -temp; /* temp is abs value of input */
  163071. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163072. /* This code assumes we are on a two's complement machine */
  163073. temp2--;
  163074. }
  163075. /* Find the number of bits needed for the magnitude of the coefficient */
  163076. nbits = 0;
  163077. while (temp) {
  163078. nbits++;
  163079. temp >>= 1;
  163080. }
  163081. /* Check for out-of-range coefficient values.
  163082. * Since we're encoding a difference, the range limit is twice as much.
  163083. */
  163084. if (nbits > MAX_COEF_BITS+1)
  163085. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163086. /* Emit the Huffman-coded symbol for the number of bits */
  163087. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163088. return FALSE;
  163089. /* Emit that number of bits of the value, if positive, */
  163090. /* or the complement of its magnitude, if negative. */
  163091. if (nbits) /* emit_bits rejects calls with size 0 */
  163092. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163093. return FALSE;
  163094. /* Encode the AC coefficients per section F.1.2.2 */
  163095. r = 0; /* r = run length of zeros */
  163096. for (k = 1; k < DCTSIZE2; k++) {
  163097. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163098. r++;
  163099. } else {
  163100. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163101. while (r > 15) {
  163102. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163103. return FALSE;
  163104. r -= 16;
  163105. }
  163106. temp2 = temp;
  163107. if (temp < 0) {
  163108. temp = -temp; /* temp is abs value of input */
  163109. /* This code assumes we are on a two's complement machine */
  163110. temp2--;
  163111. }
  163112. /* Find the number of bits needed for the magnitude of the coefficient */
  163113. nbits = 1; /* there must be at least one 1 bit */
  163114. while ((temp >>= 1))
  163115. nbits++;
  163116. /* Check for out-of-range coefficient values */
  163117. if (nbits > MAX_COEF_BITS)
  163118. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163119. /* Emit Huffman symbol for run length / number of bits */
  163120. i = (r << 4) + nbits;
  163121. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163122. return FALSE;
  163123. /* Emit that number of bits of the value, if positive, */
  163124. /* or the complement of its magnitude, if negative. */
  163125. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163126. return FALSE;
  163127. r = 0;
  163128. }
  163129. }
  163130. /* If the last coef(s) were zero, emit an end-of-block code */
  163131. if (r > 0)
  163132. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163133. return FALSE;
  163134. return TRUE;
  163135. }
  163136. /*
  163137. * Emit a restart marker & resynchronize predictions.
  163138. */
  163139. LOCAL(boolean)
  163140. emit_restart (working_state * state, int restart_num)
  163141. {
  163142. int ci;
  163143. if (! flush_bits(state))
  163144. return FALSE;
  163145. emit_byte(state, 0xFF, return FALSE);
  163146. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163147. /* Re-initialize DC predictions to 0 */
  163148. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163149. state->cur.last_dc_val[ci] = 0;
  163150. /* The restart counter is not updated until we successfully write the MCU. */
  163151. return TRUE;
  163152. }
  163153. /*
  163154. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163155. */
  163156. METHODDEF(boolean)
  163157. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163158. {
  163159. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163160. working_state state;
  163161. int blkn, ci;
  163162. jpeg_component_info * compptr;
  163163. /* Load up working state */
  163164. state.next_output_byte = cinfo->dest->next_output_byte;
  163165. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163166. ASSIGN_STATE(state.cur, entropy->saved);
  163167. state.cinfo = cinfo;
  163168. /* Emit restart marker if needed */
  163169. if (cinfo->restart_interval) {
  163170. if (entropy->restarts_to_go == 0)
  163171. if (! emit_restart(&state, entropy->next_restart_num))
  163172. return FALSE;
  163173. }
  163174. /* Encode the MCU data blocks */
  163175. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163176. ci = cinfo->MCU_membership[blkn];
  163177. compptr = cinfo->cur_comp_info[ci];
  163178. if (! encode_one_block(&state,
  163179. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163180. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163181. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163182. return FALSE;
  163183. /* Update last_dc_val */
  163184. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163185. }
  163186. /* Completed MCU, so update state */
  163187. cinfo->dest->next_output_byte = state.next_output_byte;
  163188. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163189. ASSIGN_STATE(entropy->saved, state.cur);
  163190. /* Update restart-interval state too */
  163191. if (cinfo->restart_interval) {
  163192. if (entropy->restarts_to_go == 0) {
  163193. entropy->restarts_to_go = cinfo->restart_interval;
  163194. entropy->next_restart_num++;
  163195. entropy->next_restart_num &= 7;
  163196. }
  163197. entropy->restarts_to_go--;
  163198. }
  163199. return TRUE;
  163200. }
  163201. /*
  163202. * Finish up at the end of a Huffman-compressed scan.
  163203. */
  163204. METHODDEF(void)
  163205. finish_pass_huff (j_compress_ptr cinfo)
  163206. {
  163207. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163208. working_state state;
  163209. /* Load up working state ... flush_bits needs it */
  163210. state.next_output_byte = cinfo->dest->next_output_byte;
  163211. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163212. ASSIGN_STATE(state.cur, entropy->saved);
  163213. state.cinfo = cinfo;
  163214. /* Flush out the last data */
  163215. if (! flush_bits(&state))
  163216. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163217. /* Update state */
  163218. cinfo->dest->next_output_byte = state.next_output_byte;
  163219. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163220. ASSIGN_STATE(entropy->saved, state.cur);
  163221. }
  163222. /*
  163223. * Huffman coding optimization.
  163224. *
  163225. * We first scan the supplied data and count the number of uses of each symbol
  163226. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163227. * Then we build a Huffman coding tree for the observed counts.
  163228. * Symbols which are not needed at all for the particular image are not
  163229. * assigned any code, which saves space in the DHT marker as well as in
  163230. * the compressed data.
  163231. */
  163232. #ifdef ENTROPY_OPT_SUPPORTED
  163233. /* Process a single block's worth of coefficients */
  163234. LOCAL(void)
  163235. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163236. long dc_counts[], long ac_counts[])
  163237. {
  163238. register int temp;
  163239. register int nbits;
  163240. register int k, r;
  163241. /* Encode the DC coefficient difference per section F.1.2.1 */
  163242. temp = block[0] - last_dc_val;
  163243. if (temp < 0)
  163244. temp = -temp;
  163245. /* Find the number of bits needed for the magnitude of the coefficient */
  163246. nbits = 0;
  163247. while (temp) {
  163248. nbits++;
  163249. temp >>= 1;
  163250. }
  163251. /* Check for out-of-range coefficient values.
  163252. * Since we're encoding a difference, the range limit is twice as much.
  163253. */
  163254. if (nbits > MAX_COEF_BITS+1)
  163255. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163256. /* Count the Huffman symbol for the number of bits */
  163257. dc_counts[nbits]++;
  163258. /* Encode the AC coefficients per section F.1.2.2 */
  163259. r = 0; /* r = run length of zeros */
  163260. for (k = 1; k < DCTSIZE2; k++) {
  163261. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163262. r++;
  163263. } else {
  163264. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163265. while (r > 15) {
  163266. ac_counts[0xF0]++;
  163267. r -= 16;
  163268. }
  163269. /* Find the number of bits needed for the magnitude of the coefficient */
  163270. if (temp < 0)
  163271. temp = -temp;
  163272. /* Find the number of bits needed for the magnitude of the coefficient */
  163273. nbits = 1; /* there must be at least one 1 bit */
  163274. while ((temp >>= 1))
  163275. nbits++;
  163276. /* Check for out-of-range coefficient values */
  163277. if (nbits > MAX_COEF_BITS)
  163278. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163279. /* Count Huffman symbol for run length / number of bits */
  163280. ac_counts[(r << 4) + nbits]++;
  163281. r = 0;
  163282. }
  163283. }
  163284. /* If the last coef(s) were zero, emit an end-of-block code */
  163285. if (r > 0)
  163286. ac_counts[0]++;
  163287. }
  163288. /*
  163289. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163290. * No data is actually output, so no suspension return is possible.
  163291. */
  163292. METHODDEF(boolean)
  163293. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163294. {
  163295. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163296. int blkn, ci;
  163297. jpeg_component_info * compptr;
  163298. /* Take care of restart intervals if needed */
  163299. if (cinfo->restart_interval) {
  163300. if (entropy->restarts_to_go == 0) {
  163301. /* Re-initialize DC predictions to 0 */
  163302. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163303. entropy->saved.last_dc_val[ci] = 0;
  163304. /* Update restart state */
  163305. entropy->restarts_to_go = cinfo->restart_interval;
  163306. }
  163307. entropy->restarts_to_go--;
  163308. }
  163309. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163310. ci = cinfo->MCU_membership[blkn];
  163311. compptr = cinfo->cur_comp_info[ci];
  163312. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163313. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163314. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163315. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163316. }
  163317. return TRUE;
  163318. }
  163319. /*
  163320. * Generate the best Huffman code table for the given counts, fill htbl.
  163321. * Note this is also used by jcphuff.c.
  163322. *
  163323. * The JPEG standard requires that no symbol be assigned a codeword of all
  163324. * one bits (so that padding bits added at the end of a compressed segment
  163325. * can't look like a valid code). Because of the canonical ordering of
  163326. * codewords, this just means that there must be an unused slot in the
  163327. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163328. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163329. * with count 1. In theory that's not optimal; giving it count zero but
  163330. * including it in the symbol set anyway should give a better Huffman code.
  163331. * But the theoretically better code actually seems to come out worse in
  163332. * practice, because it produces more all-ones bytes (which incur stuffed
  163333. * zero bytes in the final file). In any case the difference is tiny.
  163334. *
  163335. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163336. * If some symbols have a very small but nonzero probability, the Huffman tree
  163337. * must be adjusted to meet the code length restriction. We currently use
  163338. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163339. * optimal; it may not choose the best possible limited-length code. But
  163340. * typically only very-low-frequency symbols will be given less-than-optimal
  163341. * lengths, so the code is almost optimal. Experimental comparisons against
  163342. * an optimal limited-length-code algorithm indicate that the difference is
  163343. * microscopic --- usually less than a hundredth of a percent of total size.
  163344. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163345. */
  163346. GLOBAL(void)
  163347. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163348. {
  163349. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163350. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163351. int codesize[257]; /* codesize[k] = code length of symbol k */
  163352. int others[257]; /* next symbol in current branch of tree */
  163353. int c1, c2;
  163354. int p, i, j;
  163355. long v;
  163356. /* This algorithm is explained in section K.2 of the JPEG standard */
  163357. MEMZERO(bits, SIZEOF(bits));
  163358. MEMZERO(codesize, SIZEOF(codesize));
  163359. for (i = 0; i < 257; i++)
  163360. others[i] = -1; /* init links to empty */
  163361. freq[256] = 1; /* make sure 256 has a nonzero count */
  163362. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163363. * that no real symbol is given code-value of all ones, because 256
  163364. * will be placed last in the largest codeword category.
  163365. */
  163366. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163367. for (;;) {
  163368. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163369. /* In case of ties, take the larger symbol number */
  163370. c1 = -1;
  163371. v = 1000000000L;
  163372. for (i = 0; i <= 256; i++) {
  163373. if (freq[i] && freq[i] <= v) {
  163374. v = freq[i];
  163375. c1 = i;
  163376. }
  163377. }
  163378. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163379. /* In case of ties, take the larger symbol number */
  163380. c2 = -1;
  163381. v = 1000000000L;
  163382. for (i = 0; i <= 256; i++) {
  163383. if (freq[i] && freq[i] <= v && i != c1) {
  163384. v = freq[i];
  163385. c2 = i;
  163386. }
  163387. }
  163388. /* Done if we've merged everything into one frequency */
  163389. if (c2 < 0)
  163390. break;
  163391. /* Else merge the two counts/trees */
  163392. freq[c1] += freq[c2];
  163393. freq[c2] = 0;
  163394. /* Increment the codesize of everything in c1's tree branch */
  163395. codesize[c1]++;
  163396. while (others[c1] >= 0) {
  163397. c1 = others[c1];
  163398. codesize[c1]++;
  163399. }
  163400. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163401. /* Increment the codesize of everything in c2's tree branch */
  163402. codesize[c2]++;
  163403. while (others[c2] >= 0) {
  163404. c2 = others[c2];
  163405. codesize[c2]++;
  163406. }
  163407. }
  163408. /* Now count the number of symbols of each code length */
  163409. for (i = 0; i <= 256; i++) {
  163410. if (codesize[i]) {
  163411. /* The JPEG standard seems to think that this can't happen, */
  163412. /* but I'm paranoid... */
  163413. if (codesize[i] > MAX_CLEN)
  163414. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163415. bits[codesize[i]]++;
  163416. }
  163417. }
  163418. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163419. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163420. * Here is what the JPEG spec says about how this next bit works:
  163421. * Since symbols are paired for the longest Huffman code, the symbols are
  163422. * removed from this length category two at a time. The prefix for the pair
  163423. * (which is one bit shorter) is allocated to one of the pair; then,
  163424. * skipping the BITS entry for that prefix length, a code word from the next
  163425. * shortest nonzero BITS entry is converted into a prefix for two code words
  163426. * one bit longer.
  163427. */
  163428. for (i = MAX_CLEN; i > 16; i--) {
  163429. while (bits[i] > 0) {
  163430. j = i - 2; /* find length of new prefix to be used */
  163431. while (bits[j] == 0)
  163432. j--;
  163433. bits[i] -= 2; /* remove two symbols */
  163434. bits[i-1]++; /* one goes in this length */
  163435. bits[j+1] += 2; /* two new symbols in this length */
  163436. bits[j]--; /* symbol of this length is now a prefix */
  163437. }
  163438. }
  163439. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163440. while (bits[i] == 0) /* find largest codelength still in use */
  163441. i--;
  163442. bits[i]--;
  163443. /* Return final symbol counts (only for lengths 0..16) */
  163444. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163445. /* Return a list of the symbols sorted by code length */
  163446. /* It's not real clear to me why we don't need to consider the codelength
  163447. * changes made above, but the JPEG spec seems to think this works.
  163448. */
  163449. p = 0;
  163450. for (i = 1; i <= MAX_CLEN; i++) {
  163451. for (j = 0; j <= 255; j++) {
  163452. if (codesize[j] == i) {
  163453. htbl->huffval[p] = (UINT8) j;
  163454. p++;
  163455. }
  163456. }
  163457. }
  163458. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163459. htbl->sent_table = FALSE;
  163460. }
  163461. /*
  163462. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163463. */
  163464. METHODDEF(void)
  163465. finish_pass_gather (j_compress_ptr cinfo)
  163466. {
  163467. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163468. int ci, dctbl, actbl;
  163469. jpeg_component_info * compptr;
  163470. JHUFF_TBL **htblptr;
  163471. boolean did_dc[NUM_HUFF_TBLS];
  163472. boolean did_ac[NUM_HUFF_TBLS];
  163473. /* It's important not to apply jpeg_gen_optimal_table more than once
  163474. * per table, because it clobbers the input frequency counts!
  163475. */
  163476. MEMZERO(did_dc, SIZEOF(did_dc));
  163477. MEMZERO(did_ac, SIZEOF(did_ac));
  163478. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163479. compptr = cinfo->cur_comp_info[ci];
  163480. dctbl = compptr->dc_tbl_no;
  163481. actbl = compptr->ac_tbl_no;
  163482. if (! did_dc[dctbl]) {
  163483. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163484. if (*htblptr == NULL)
  163485. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163486. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163487. did_dc[dctbl] = TRUE;
  163488. }
  163489. if (! did_ac[actbl]) {
  163490. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163491. if (*htblptr == NULL)
  163492. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163493. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163494. did_ac[actbl] = TRUE;
  163495. }
  163496. }
  163497. }
  163498. #endif /* ENTROPY_OPT_SUPPORTED */
  163499. /*
  163500. * Module initialization routine for Huffman entropy encoding.
  163501. */
  163502. GLOBAL(void)
  163503. jinit_huff_encoder (j_compress_ptr cinfo)
  163504. {
  163505. huff_entropy_ptr entropy;
  163506. int i;
  163507. entropy = (huff_entropy_ptr)
  163508. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163509. SIZEOF(huff_entropy_encoder));
  163510. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163511. entropy->pub.start_pass = start_pass_huff;
  163512. /* Mark tables unallocated */
  163513. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163514. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163515. #ifdef ENTROPY_OPT_SUPPORTED
  163516. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163517. #endif
  163518. }
  163519. }
  163520. /*** End of inlined file: jchuff.c ***/
  163521. #undef emit_byte
  163522. /*** Start of inlined file: jcinit.c ***/
  163523. #define JPEG_INTERNALS
  163524. /*
  163525. * Master selection of compression modules.
  163526. * This is done once at the start of processing an image. We determine
  163527. * which modules will be used and give them appropriate initialization calls.
  163528. */
  163529. GLOBAL(void)
  163530. jinit_compress_master (j_compress_ptr cinfo)
  163531. {
  163532. /* Initialize master control (includes parameter checking/processing) */
  163533. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163534. /* Preprocessing */
  163535. if (! cinfo->raw_data_in) {
  163536. jinit_color_converter(cinfo);
  163537. jinit_downsampler(cinfo);
  163538. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163539. }
  163540. /* Forward DCT */
  163541. jinit_forward_dct(cinfo);
  163542. /* Entropy encoding: either Huffman or arithmetic coding. */
  163543. if (cinfo->arith_code) {
  163544. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163545. } else {
  163546. if (cinfo->progressive_mode) {
  163547. #ifdef C_PROGRESSIVE_SUPPORTED
  163548. jinit_phuff_encoder(cinfo);
  163549. #else
  163550. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163551. #endif
  163552. } else
  163553. jinit_huff_encoder(cinfo);
  163554. }
  163555. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163556. jinit_c_coef_controller(cinfo,
  163557. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163558. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163559. jinit_marker_writer(cinfo);
  163560. /* We can now tell the memory manager to allocate virtual arrays. */
  163561. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163562. /* Write the datastream header (SOI) immediately.
  163563. * Frame and scan headers are postponed till later.
  163564. * This lets application insert special markers after the SOI.
  163565. */
  163566. (*cinfo->marker->write_file_header) (cinfo);
  163567. }
  163568. /*** End of inlined file: jcinit.c ***/
  163569. /*** Start of inlined file: jcmainct.c ***/
  163570. #define JPEG_INTERNALS
  163571. /* Note: currently, there is no operating mode in which a full-image buffer
  163572. * is needed at this step. If there were, that mode could not be used with
  163573. * "raw data" input, since this module is bypassed in that case. However,
  163574. * we've left the code here for possible use in special applications.
  163575. */
  163576. #undef FULL_MAIN_BUFFER_SUPPORTED
  163577. /* Private buffer controller object */
  163578. typedef struct {
  163579. struct jpeg_c_main_controller pub; /* public fields */
  163580. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163581. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163582. boolean suspended; /* remember if we suspended output */
  163583. J_BUF_MODE pass_mode; /* current operating mode */
  163584. /* If using just a strip buffer, this points to the entire set of buffers
  163585. * (we allocate one for each component). In the full-image case, this
  163586. * points to the currently accessible strips of the virtual arrays.
  163587. */
  163588. JSAMPARRAY buffer[MAX_COMPONENTS];
  163589. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163590. /* If using full-image storage, this array holds pointers to virtual-array
  163591. * control blocks for each component. Unused if not full-image storage.
  163592. */
  163593. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163594. #endif
  163595. } my_main_controller;
  163596. typedef my_main_controller * my_main_ptr;
  163597. /* Forward declarations */
  163598. METHODDEF(void) process_data_simple_main
  163599. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163600. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163601. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163602. METHODDEF(void) process_data_buffer_main
  163603. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163604. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163605. #endif
  163606. /*
  163607. * Initialize for a processing pass.
  163608. */
  163609. METHODDEF(void)
  163610. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163611. {
  163612. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163613. /* Do nothing in raw-data mode. */
  163614. if (cinfo->raw_data_in)
  163615. return;
  163616. main_->cur_iMCU_row = 0; /* initialize counters */
  163617. main_->rowgroup_ctr = 0;
  163618. main_->suspended = FALSE;
  163619. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163620. switch (pass_mode) {
  163621. case JBUF_PASS_THRU:
  163622. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163623. if (main_->whole_image[0] != NULL)
  163624. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163625. #endif
  163626. main_->pub.process_data = process_data_simple_main;
  163627. break;
  163628. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163629. case JBUF_SAVE_SOURCE:
  163630. case JBUF_CRANK_DEST:
  163631. case JBUF_SAVE_AND_PASS:
  163632. if (main_->whole_image[0] == NULL)
  163633. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163634. main_->pub.process_data = process_data_buffer_main;
  163635. break;
  163636. #endif
  163637. default:
  163638. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163639. break;
  163640. }
  163641. }
  163642. /*
  163643. * Process some data.
  163644. * This routine handles the simple pass-through mode,
  163645. * where we have only a strip buffer.
  163646. */
  163647. METHODDEF(void)
  163648. process_data_simple_main (j_compress_ptr cinfo,
  163649. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163650. JDIMENSION in_rows_avail)
  163651. {
  163652. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163653. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163654. /* Read input data if we haven't filled the main buffer yet */
  163655. if (main_->rowgroup_ctr < DCTSIZE)
  163656. (*cinfo->prep->pre_process_data) (cinfo,
  163657. input_buf, in_row_ctr, in_rows_avail,
  163658. main_->buffer, &main_->rowgroup_ctr,
  163659. (JDIMENSION) DCTSIZE);
  163660. /* If we don't have a full iMCU row buffered, return to application for
  163661. * more data. Note that preprocessor will always pad to fill the iMCU row
  163662. * at the bottom of the image.
  163663. */
  163664. if (main_->rowgroup_ctr != DCTSIZE)
  163665. return;
  163666. /* Send the completed row to the compressor */
  163667. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163668. /* If compressor did not consume the whole row, then we must need to
  163669. * suspend processing and return to the application. In this situation
  163670. * we pretend we didn't yet consume the last input row; otherwise, if
  163671. * it happened to be the last row of the image, the application would
  163672. * think we were done.
  163673. */
  163674. if (! main_->suspended) {
  163675. (*in_row_ctr)--;
  163676. main_->suspended = TRUE;
  163677. }
  163678. return;
  163679. }
  163680. /* We did finish the row. Undo our little suspension hack if a previous
  163681. * call suspended; then mark the main buffer empty.
  163682. */
  163683. if (main_->suspended) {
  163684. (*in_row_ctr)++;
  163685. main_->suspended = FALSE;
  163686. }
  163687. main_->rowgroup_ctr = 0;
  163688. main_->cur_iMCU_row++;
  163689. }
  163690. }
  163691. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163692. /*
  163693. * Process some data.
  163694. * This routine handles all of the modes that use a full-size buffer.
  163695. */
  163696. METHODDEF(void)
  163697. process_data_buffer_main (j_compress_ptr cinfo,
  163698. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163699. JDIMENSION in_rows_avail)
  163700. {
  163701. my_main_ptr main = (my_main_ptr) cinfo->main;
  163702. int ci;
  163703. jpeg_component_info *compptr;
  163704. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163705. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163706. /* Realign the virtual buffers if at the start of an iMCU row. */
  163707. if (main->rowgroup_ctr == 0) {
  163708. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163709. ci++, compptr++) {
  163710. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163711. ((j_common_ptr) cinfo, main->whole_image[ci],
  163712. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163713. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163714. }
  163715. /* In a read pass, pretend we just read some source data. */
  163716. if (! writing) {
  163717. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163718. main->rowgroup_ctr = DCTSIZE;
  163719. }
  163720. }
  163721. /* If a write pass, read input data until the current iMCU row is full. */
  163722. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163723. if (writing) {
  163724. (*cinfo->prep->pre_process_data) (cinfo,
  163725. input_buf, in_row_ctr, in_rows_avail,
  163726. main->buffer, &main->rowgroup_ctr,
  163727. (JDIMENSION) DCTSIZE);
  163728. /* Return to application if we need more data to fill the iMCU row. */
  163729. if (main->rowgroup_ctr < DCTSIZE)
  163730. return;
  163731. }
  163732. /* Emit data, unless this is a sink-only pass. */
  163733. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163734. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163735. /* If compressor did not consume the whole row, then we must need to
  163736. * suspend processing and return to the application. In this situation
  163737. * we pretend we didn't yet consume the last input row; otherwise, if
  163738. * it happened to be the last row of the image, the application would
  163739. * think we were done.
  163740. */
  163741. if (! main->suspended) {
  163742. (*in_row_ctr)--;
  163743. main->suspended = TRUE;
  163744. }
  163745. return;
  163746. }
  163747. /* We did finish the row. Undo our little suspension hack if a previous
  163748. * call suspended; then mark the main buffer empty.
  163749. */
  163750. if (main->suspended) {
  163751. (*in_row_ctr)++;
  163752. main->suspended = FALSE;
  163753. }
  163754. }
  163755. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163756. main->rowgroup_ctr = 0;
  163757. main->cur_iMCU_row++;
  163758. }
  163759. }
  163760. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163761. /*
  163762. * Initialize main buffer controller.
  163763. */
  163764. GLOBAL(void)
  163765. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163766. {
  163767. my_main_ptr main_;
  163768. int ci;
  163769. jpeg_component_info *compptr;
  163770. main_ = (my_main_ptr)
  163771. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163772. SIZEOF(my_main_controller));
  163773. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163774. main_->pub.start_pass = start_pass_main;
  163775. /* We don't need to create a buffer in raw-data mode. */
  163776. if (cinfo->raw_data_in)
  163777. return;
  163778. /* Create the buffer. It holds downsampled data, so each component
  163779. * may be of a different size.
  163780. */
  163781. if (need_full_buffer) {
  163782. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163783. /* Allocate a full-image virtual array for each component */
  163784. /* Note we pad the bottom to a multiple of the iMCU height */
  163785. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163786. ci++, compptr++) {
  163787. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163788. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163789. compptr->width_in_blocks * DCTSIZE,
  163790. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163791. (long) compptr->v_samp_factor) * DCTSIZE,
  163792. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163793. }
  163794. #else
  163795. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163796. #endif
  163797. } else {
  163798. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163799. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163800. #endif
  163801. /* Allocate a strip buffer for each component */
  163802. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163803. ci++, compptr++) {
  163804. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163805. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163806. compptr->width_in_blocks * DCTSIZE,
  163807. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163808. }
  163809. }
  163810. }
  163811. /*** End of inlined file: jcmainct.c ***/
  163812. /*** Start of inlined file: jcmarker.c ***/
  163813. #define JPEG_INTERNALS
  163814. /* Private state */
  163815. typedef struct {
  163816. struct jpeg_marker_writer pub; /* public fields */
  163817. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163818. } my_marker_writer;
  163819. typedef my_marker_writer * my_marker_ptr;
  163820. /*
  163821. * Basic output routines.
  163822. *
  163823. * Note that we do not support suspension while writing a marker.
  163824. * Therefore, an application using suspension must ensure that there is
  163825. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163826. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163827. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163828. * modes are not supported at all with suspension, so those two are the only
  163829. * points where markers will be written.
  163830. */
  163831. LOCAL(void)
  163832. emit_byte (j_compress_ptr cinfo, int val)
  163833. /* Emit a byte */
  163834. {
  163835. struct jpeg_destination_mgr * dest = cinfo->dest;
  163836. *(dest->next_output_byte)++ = (JOCTET) val;
  163837. if (--dest->free_in_buffer == 0) {
  163838. if (! (*dest->empty_output_buffer) (cinfo))
  163839. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163840. }
  163841. }
  163842. LOCAL(void)
  163843. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163844. /* Emit a marker code */
  163845. {
  163846. emit_byte(cinfo, 0xFF);
  163847. emit_byte(cinfo, (int) mark);
  163848. }
  163849. LOCAL(void)
  163850. emit_2bytes (j_compress_ptr cinfo, int value)
  163851. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163852. {
  163853. emit_byte(cinfo, (value >> 8) & 0xFF);
  163854. emit_byte(cinfo, value & 0xFF);
  163855. }
  163856. /*
  163857. * Routines to write specific marker types.
  163858. */
  163859. LOCAL(int)
  163860. emit_dqt (j_compress_ptr cinfo, int index)
  163861. /* Emit a DQT marker */
  163862. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163863. {
  163864. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163865. int prec;
  163866. int i;
  163867. if (qtbl == NULL)
  163868. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163869. prec = 0;
  163870. for (i = 0; i < DCTSIZE2; i++) {
  163871. if (qtbl->quantval[i] > 255)
  163872. prec = 1;
  163873. }
  163874. if (! qtbl->sent_table) {
  163875. emit_marker(cinfo, M_DQT);
  163876. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163877. emit_byte(cinfo, index + (prec<<4));
  163878. for (i = 0; i < DCTSIZE2; i++) {
  163879. /* The table entries must be emitted in zigzag order. */
  163880. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163881. if (prec)
  163882. emit_byte(cinfo, (int) (qval >> 8));
  163883. emit_byte(cinfo, (int) (qval & 0xFF));
  163884. }
  163885. qtbl->sent_table = TRUE;
  163886. }
  163887. return prec;
  163888. }
  163889. LOCAL(void)
  163890. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163891. /* Emit a DHT marker */
  163892. {
  163893. JHUFF_TBL * htbl;
  163894. int length, i;
  163895. if (is_ac) {
  163896. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163897. index += 0x10; /* output index has AC bit set */
  163898. } else {
  163899. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163900. }
  163901. if (htbl == NULL)
  163902. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163903. if (! htbl->sent_table) {
  163904. emit_marker(cinfo, M_DHT);
  163905. length = 0;
  163906. for (i = 1; i <= 16; i++)
  163907. length += htbl->bits[i];
  163908. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163909. emit_byte(cinfo, index);
  163910. for (i = 1; i <= 16; i++)
  163911. emit_byte(cinfo, htbl->bits[i]);
  163912. for (i = 0; i < length; i++)
  163913. emit_byte(cinfo, htbl->huffval[i]);
  163914. htbl->sent_table = TRUE;
  163915. }
  163916. }
  163917. LOCAL(void)
  163918. emit_dac (j_compress_ptr)
  163919. /* Emit a DAC marker */
  163920. /* Since the useful info is so small, we want to emit all the tables in */
  163921. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163922. {
  163923. #ifdef C_ARITH_CODING_SUPPORTED
  163924. char dc_in_use[NUM_ARITH_TBLS];
  163925. char ac_in_use[NUM_ARITH_TBLS];
  163926. int length, i;
  163927. jpeg_component_info *compptr;
  163928. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163929. dc_in_use[i] = ac_in_use[i] = 0;
  163930. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163931. compptr = cinfo->cur_comp_info[i];
  163932. dc_in_use[compptr->dc_tbl_no] = 1;
  163933. ac_in_use[compptr->ac_tbl_no] = 1;
  163934. }
  163935. length = 0;
  163936. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163937. length += dc_in_use[i] + ac_in_use[i];
  163938. emit_marker(cinfo, M_DAC);
  163939. emit_2bytes(cinfo, length*2 + 2);
  163940. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163941. if (dc_in_use[i]) {
  163942. emit_byte(cinfo, i);
  163943. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163944. }
  163945. if (ac_in_use[i]) {
  163946. emit_byte(cinfo, i + 0x10);
  163947. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163948. }
  163949. }
  163950. #endif /* C_ARITH_CODING_SUPPORTED */
  163951. }
  163952. LOCAL(void)
  163953. emit_dri (j_compress_ptr cinfo)
  163954. /* Emit a DRI marker */
  163955. {
  163956. emit_marker(cinfo, M_DRI);
  163957. emit_2bytes(cinfo, 4); /* fixed length */
  163958. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163959. }
  163960. LOCAL(void)
  163961. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163962. /* Emit a SOF marker */
  163963. {
  163964. int ci;
  163965. jpeg_component_info *compptr;
  163966. emit_marker(cinfo, code);
  163967. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163968. /* Make sure image isn't bigger than SOF field can handle */
  163969. if ((long) cinfo->image_height > 65535L ||
  163970. (long) cinfo->image_width > 65535L)
  163971. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163972. emit_byte(cinfo, cinfo->data_precision);
  163973. emit_2bytes(cinfo, (int) cinfo->image_height);
  163974. emit_2bytes(cinfo, (int) cinfo->image_width);
  163975. emit_byte(cinfo, cinfo->num_components);
  163976. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163977. ci++, compptr++) {
  163978. emit_byte(cinfo, compptr->component_id);
  163979. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163980. emit_byte(cinfo, compptr->quant_tbl_no);
  163981. }
  163982. }
  163983. LOCAL(void)
  163984. emit_sos (j_compress_ptr cinfo)
  163985. /* Emit a SOS marker */
  163986. {
  163987. int i, td, ta;
  163988. jpeg_component_info *compptr;
  163989. emit_marker(cinfo, M_SOS);
  163990. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163991. emit_byte(cinfo, cinfo->comps_in_scan);
  163992. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163993. compptr = cinfo->cur_comp_info[i];
  163994. emit_byte(cinfo, compptr->component_id);
  163995. td = compptr->dc_tbl_no;
  163996. ta = compptr->ac_tbl_no;
  163997. if (cinfo->progressive_mode) {
  163998. /* Progressive mode: only DC or only AC tables are used in one scan;
  163999. * furthermore, Huffman coding of DC refinement uses no table at all.
  164000. * We emit 0 for unused field(s); this is recommended by the P&M text
  164001. * but does not seem to be specified in the standard.
  164002. */
  164003. if (cinfo->Ss == 0) {
  164004. ta = 0; /* DC scan */
  164005. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164006. td = 0; /* no DC table either */
  164007. } else {
  164008. td = 0; /* AC scan */
  164009. }
  164010. }
  164011. emit_byte(cinfo, (td << 4) + ta);
  164012. }
  164013. emit_byte(cinfo, cinfo->Ss);
  164014. emit_byte(cinfo, cinfo->Se);
  164015. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164016. }
  164017. LOCAL(void)
  164018. emit_jfif_app0 (j_compress_ptr cinfo)
  164019. /* Emit a JFIF-compliant APP0 marker */
  164020. {
  164021. /*
  164022. * Length of APP0 block (2 bytes)
  164023. * Block ID (4 bytes - ASCII "JFIF")
  164024. * Zero byte (1 byte to terminate the ID string)
  164025. * Version Major, Minor (2 bytes - major first)
  164026. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164027. * Xdpu (2 bytes - dots per unit horizontal)
  164028. * Ydpu (2 bytes - dots per unit vertical)
  164029. * Thumbnail X size (1 byte)
  164030. * Thumbnail Y size (1 byte)
  164031. */
  164032. emit_marker(cinfo, M_APP0);
  164033. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164034. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164035. emit_byte(cinfo, 0x46);
  164036. emit_byte(cinfo, 0x49);
  164037. emit_byte(cinfo, 0x46);
  164038. emit_byte(cinfo, 0);
  164039. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164040. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164041. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164042. emit_2bytes(cinfo, (int) cinfo->X_density);
  164043. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164044. emit_byte(cinfo, 0); /* No thumbnail image */
  164045. emit_byte(cinfo, 0);
  164046. }
  164047. LOCAL(void)
  164048. emit_adobe_app14 (j_compress_ptr cinfo)
  164049. /* Emit an Adobe APP14 marker */
  164050. {
  164051. /*
  164052. * Length of APP14 block (2 bytes)
  164053. * Block ID (5 bytes - ASCII "Adobe")
  164054. * Version Number (2 bytes - currently 100)
  164055. * Flags0 (2 bytes - currently 0)
  164056. * Flags1 (2 bytes - currently 0)
  164057. * Color transform (1 byte)
  164058. *
  164059. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164060. * now in circulation seem to use Version = 100, so that's what we write.
  164061. *
  164062. * We write the color transform byte as 1 if the JPEG color space is
  164063. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164064. * whether the encoder performed a transformation, which is pretty useless.
  164065. */
  164066. emit_marker(cinfo, M_APP14);
  164067. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164068. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164069. emit_byte(cinfo, 0x64);
  164070. emit_byte(cinfo, 0x6F);
  164071. emit_byte(cinfo, 0x62);
  164072. emit_byte(cinfo, 0x65);
  164073. emit_2bytes(cinfo, 100); /* Version */
  164074. emit_2bytes(cinfo, 0); /* Flags0 */
  164075. emit_2bytes(cinfo, 0); /* Flags1 */
  164076. switch (cinfo->jpeg_color_space) {
  164077. case JCS_YCbCr:
  164078. emit_byte(cinfo, 1); /* Color transform = 1 */
  164079. break;
  164080. case JCS_YCCK:
  164081. emit_byte(cinfo, 2); /* Color transform = 2 */
  164082. break;
  164083. default:
  164084. emit_byte(cinfo, 0); /* Color transform = 0 */
  164085. break;
  164086. }
  164087. }
  164088. /*
  164089. * These routines allow writing an arbitrary marker with parameters.
  164090. * The only intended use is to emit COM or APPn markers after calling
  164091. * write_file_header and before calling write_frame_header.
  164092. * Other uses are not guaranteed to produce desirable results.
  164093. * Counting the parameter bytes properly is the caller's responsibility.
  164094. */
  164095. METHODDEF(void)
  164096. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164097. /* Emit an arbitrary marker header */
  164098. {
  164099. if (datalen > (unsigned int) 65533) /* safety check */
  164100. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164101. emit_marker(cinfo, (JPEG_MARKER) marker);
  164102. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164103. }
  164104. METHODDEF(void)
  164105. write_marker_byte (j_compress_ptr cinfo, int val)
  164106. /* Emit one byte of marker parameters following write_marker_header */
  164107. {
  164108. emit_byte(cinfo, val);
  164109. }
  164110. /*
  164111. * Write datastream header.
  164112. * This consists of an SOI and optional APPn markers.
  164113. * We recommend use of the JFIF marker, but not the Adobe marker,
  164114. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164115. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164116. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164117. * Note that an application can write additional header markers after
  164118. * jpeg_start_compress returns.
  164119. */
  164120. METHODDEF(void)
  164121. write_file_header (j_compress_ptr cinfo)
  164122. {
  164123. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164124. emit_marker(cinfo, M_SOI); /* first the SOI */
  164125. /* SOI is defined to reset restart interval to 0 */
  164126. marker->last_restart_interval = 0;
  164127. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164128. emit_jfif_app0(cinfo);
  164129. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164130. emit_adobe_app14(cinfo);
  164131. }
  164132. /*
  164133. * Write frame header.
  164134. * This consists of DQT and SOFn markers.
  164135. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164136. * This avoids compatibility problems with incorrect implementations that
  164137. * try to error-check the quant table numbers as soon as they see the SOF.
  164138. */
  164139. METHODDEF(void)
  164140. write_frame_header (j_compress_ptr cinfo)
  164141. {
  164142. int ci, prec;
  164143. boolean is_baseline;
  164144. jpeg_component_info *compptr;
  164145. /* Emit DQT for each quantization table.
  164146. * Note that emit_dqt() suppresses any duplicate tables.
  164147. */
  164148. prec = 0;
  164149. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164150. ci++, compptr++) {
  164151. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164152. }
  164153. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164154. /* Check for a non-baseline specification.
  164155. * Note we assume that Huffman table numbers won't be changed later.
  164156. */
  164157. if (cinfo->arith_code || cinfo->progressive_mode ||
  164158. cinfo->data_precision != 8) {
  164159. is_baseline = FALSE;
  164160. } else {
  164161. is_baseline = TRUE;
  164162. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164163. ci++, compptr++) {
  164164. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164165. is_baseline = FALSE;
  164166. }
  164167. if (prec && is_baseline) {
  164168. is_baseline = FALSE;
  164169. /* If it's baseline except for quantizer size, warn the user */
  164170. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164171. }
  164172. }
  164173. /* Emit the proper SOF marker */
  164174. if (cinfo->arith_code) {
  164175. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164176. } else {
  164177. if (cinfo->progressive_mode)
  164178. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164179. else if (is_baseline)
  164180. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164181. else
  164182. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164183. }
  164184. }
  164185. /*
  164186. * Write scan header.
  164187. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164188. * Compressed data will be written following the SOS.
  164189. */
  164190. METHODDEF(void)
  164191. write_scan_header (j_compress_ptr cinfo)
  164192. {
  164193. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164194. int i;
  164195. jpeg_component_info *compptr;
  164196. if (cinfo->arith_code) {
  164197. /* Emit arith conditioning info. We may have some duplication
  164198. * if the file has multiple scans, but it's so small it's hardly
  164199. * worth worrying about.
  164200. */
  164201. emit_dac(cinfo);
  164202. } else {
  164203. /* Emit Huffman tables.
  164204. * Note that emit_dht() suppresses any duplicate tables.
  164205. */
  164206. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164207. compptr = cinfo->cur_comp_info[i];
  164208. if (cinfo->progressive_mode) {
  164209. /* Progressive mode: only DC or only AC tables are used in one scan */
  164210. if (cinfo->Ss == 0) {
  164211. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164212. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164213. } else {
  164214. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164215. }
  164216. } else {
  164217. /* Sequential mode: need both DC and AC tables */
  164218. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164219. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164220. }
  164221. }
  164222. }
  164223. /* Emit DRI if required --- note that DRI value could change for each scan.
  164224. * We avoid wasting space with unnecessary DRIs, however.
  164225. */
  164226. if (cinfo->restart_interval != marker->last_restart_interval) {
  164227. emit_dri(cinfo);
  164228. marker->last_restart_interval = cinfo->restart_interval;
  164229. }
  164230. emit_sos(cinfo);
  164231. }
  164232. /*
  164233. * Write datastream trailer.
  164234. */
  164235. METHODDEF(void)
  164236. write_file_trailer (j_compress_ptr cinfo)
  164237. {
  164238. emit_marker(cinfo, M_EOI);
  164239. }
  164240. /*
  164241. * Write an abbreviated table-specification datastream.
  164242. * This consists of SOI, DQT and DHT tables, and EOI.
  164243. * Any table that is defined and not marked sent_table = TRUE will be
  164244. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164245. */
  164246. METHODDEF(void)
  164247. write_tables_only (j_compress_ptr cinfo)
  164248. {
  164249. int i;
  164250. emit_marker(cinfo, M_SOI);
  164251. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164252. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164253. (void) emit_dqt(cinfo, i);
  164254. }
  164255. if (! cinfo->arith_code) {
  164256. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164257. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164258. emit_dht(cinfo, i, FALSE);
  164259. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164260. emit_dht(cinfo, i, TRUE);
  164261. }
  164262. }
  164263. emit_marker(cinfo, M_EOI);
  164264. }
  164265. /*
  164266. * Initialize the marker writer module.
  164267. */
  164268. GLOBAL(void)
  164269. jinit_marker_writer (j_compress_ptr cinfo)
  164270. {
  164271. my_marker_ptr marker;
  164272. /* Create the subobject */
  164273. marker = (my_marker_ptr)
  164274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164275. SIZEOF(my_marker_writer));
  164276. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164277. /* Initialize method pointers */
  164278. marker->pub.write_file_header = write_file_header;
  164279. marker->pub.write_frame_header = write_frame_header;
  164280. marker->pub.write_scan_header = write_scan_header;
  164281. marker->pub.write_file_trailer = write_file_trailer;
  164282. marker->pub.write_tables_only = write_tables_only;
  164283. marker->pub.write_marker_header = write_marker_header;
  164284. marker->pub.write_marker_byte = write_marker_byte;
  164285. /* Initialize private state */
  164286. marker->last_restart_interval = 0;
  164287. }
  164288. /*** End of inlined file: jcmarker.c ***/
  164289. /*** Start of inlined file: jcmaster.c ***/
  164290. #define JPEG_INTERNALS
  164291. /* Private state */
  164292. typedef enum {
  164293. main_pass, /* input data, also do first output step */
  164294. huff_opt_pass, /* Huffman code optimization pass */
  164295. output_pass /* data output pass */
  164296. } c_pass_type;
  164297. typedef struct {
  164298. struct jpeg_comp_master pub; /* public fields */
  164299. c_pass_type pass_type; /* the type of the current pass */
  164300. int pass_number; /* # of passes completed */
  164301. int total_passes; /* total # of passes needed */
  164302. int scan_number; /* current index in scan_info[] */
  164303. } my_comp_master;
  164304. typedef my_comp_master * my_master_ptr;
  164305. /*
  164306. * Support routines that do various essential calculations.
  164307. */
  164308. LOCAL(void)
  164309. initial_setup (j_compress_ptr cinfo)
  164310. /* Do computations that are needed before master selection phase */
  164311. {
  164312. int ci;
  164313. jpeg_component_info *compptr;
  164314. long samplesperrow;
  164315. JDIMENSION jd_samplesperrow;
  164316. /* Sanity check on image dimensions */
  164317. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164318. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164319. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164320. /* Make sure image isn't bigger than I can handle */
  164321. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164322. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164323. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164324. /* Width of an input scanline must be representable as JDIMENSION. */
  164325. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164326. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164327. if ((long) jd_samplesperrow != samplesperrow)
  164328. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164329. /* For now, precision must match compiled-in value... */
  164330. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164331. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164332. /* Check that number of components won't exceed internal array sizes */
  164333. if (cinfo->num_components > MAX_COMPONENTS)
  164334. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164335. MAX_COMPONENTS);
  164336. /* Compute maximum sampling factors; check factor validity */
  164337. cinfo->max_h_samp_factor = 1;
  164338. cinfo->max_v_samp_factor = 1;
  164339. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164340. ci++, compptr++) {
  164341. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164342. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164343. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164344. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164345. compptr->h_samp_factor);
  164346. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164347. compptr->v_samp_factor);
  164348. }
  164349. /* Compute dimensions of components */
  164350. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164351. ci++, compptr++) {
  164352. /* Fill in the correct component_index value; don't rely on application */
  164353. compptr->component_index = ci;
  164354. /* For compression, we never do DCT scaling. */
  164355. compptr->DCT_scaled_size = DCTSIZE;
  164356. /* Size in DCT blocks */
  164357. compptr->width_in_blocks = (JDIMENSION)
  164358. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164359. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164360. compptr->height_in_blocks = (JDIMENSION)
  164361. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164362. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164363. /* Size in samples */
  164364. compptr->downsampled_width = (JDIMENSION)
  164365. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164366. (long) cinfo->max_h_samp_factor);
  164367. compptr->downsampled_height = (JDIMENSION)
  164368. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164369. (long) cinfo->max_v_samp_factor);
  164370. /* Mark component needed (this flag isn't actually used for compression) */
  164371. compptr->component_needed = TRUE;
  164372. }
  164373. /* Compute number of fully interleaved MCU rows (number of times that
  164374. * main controller will call coefficient controller).
  164375. */
  164376. cinfo->total_iMCU_rows = (JDIMENSION)
  164377. jdiv_round_up((long) cinfo->image_height,
  164378. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164379. }
  164380. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164381. LOCAL(void)
  164382. validate_script (j_compress_ptr cinfo)
  164383. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164384. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164385. */
  164386. {
  164387. const jpeg_scan_info * scanptr;
  164388. int scanno, ncomps, ci, coefi, thisi;
  164389. int Ss, Se, Ah, Al;
  164390. boolean component_sent[MAX_COMPONENTS];
  164391. #ifdef C_PROGRESSIVE_SUPPORTED
  164392. int * last_bitpos_ptr;
  164393. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164394. /* -1 until that coefficient has been seen; then last Al for it */
  164395. #endif
  164396. if (cinfo->num_scans <= 0)
  164397. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164398. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164399. * for progressive JPEG, no scan can have this.
  164400. */
  164401. scanptr = cinfo->scan_info;
  164402. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164403. #ifdef C_PROGRESSIVE_SUPPORTED
  164404. cinfo->progressive_mode = TRUE;
  164405. last_bitpos_ptr = & last_bitpos[0][0];
  164406. for (ci = 0; ci < cinfo->num_components; ci++)
  164407. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164408. *last_bitpos_ptr++ = -1;
  164409. #else
  164410. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164411. #endif
  164412. } else {
  164413. cinfo->progressive_mode = FALSE;
  164414. for (ci = 0; ci < cinfo->num_components; ci++)
  164415. component_sent[ci] = FALSE;
  164416. }
  164417. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164418. /* Validate component indexes */
  164419. ncomps = scanptr->comps_in_scan;
  164420. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164421. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164422. for (ci = 0; ci < ncomps; ci++) {
  164423. thisi = scanptr->component_index[ci];
  164424. if (thisi < 0 || thisi >= cinfo->num_components)
  164425. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164426. /* Components must appear in SOF order within each scan */
  164427. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164428. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164429. }
  164430. /* Validate progression parameters */
  164431. Ss = scanptr->Ss;
  164432. Se = scanptr->Se;
  164433. Ah = scanptr->Ah;
  164434. Al = scanptr->Al;
  164435. if (cinfo->progressive_mode) {
  164436. #ifdef C_PROGRESSIVE_SUPPORTED
  164437. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164438. * seems wrong: the upper bound ought to depend on data precision.
  164439. * Perhaps they really meant 0..N+1 for N-bit precision.
  164440. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164441. * out-of-range reconstructed DC values during the first DC scan,
  164442. * which might cause problems for some decoders.
  164443. */
  164444. #if BITS_IN_JSAMPLE == 8
  164445. #define MAX_AH_AL 10
  164446. #else
  164447. #define MAX_AH_AL 13
  164448. #endif
  164449. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164450. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164451. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164452. if (Ss == 0) {
  164453. if (Se != 0) /* DC and AC together not OK */
  164454. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164455. } else {
  164456. if (ncomps != 1) /* AC scans must be for only one component */
  164457. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164458. }
  164459. for (ci = 0; ci < ncomps; ci++) {
  164460. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164461. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164462. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164463. for (coefi = Ss; coefi <= Se; coefi++) {
  164464. if (last_bitpos_ptr[coefi] < 0) {
  164465. /* first scan of this coefficient */
  164466. if (Ah != 0)
  164467. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164468. } else {
  164469. /* not first scan */
  164470. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164471. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164472. }
  164473. last_bitpos_ptr[coefi] = Al;
  164474. }
  164475. }
  164476. #endif
  164477. } else {
  164478. /* For sequential JPEG, all progression parameters must be these: */
  164479. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164480. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164481. /* Make sure components are not sent twice */
  164482. for (ci = 0; ci < ncomps; ci++) {
  164483. thisi = scanptr->component_index[ci];
  164484. if (component_sent[thisi])
  164485. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164486. component_sent[thisi] = TRUE;
  164487. }
  164488. }
  164489. }
  164490. /* Now verify that everything got sent. */
  164491. if (cinfo->progressive_mode) {
  164492. #ifdef C_PROGRESSIVE_SUPPORTED
  164493. /* For progressive mode, we only check that at least some DC data
  164494. * got sent for each component; the spec does not require that all bits
  164495. * of all coefficients be transmitted. Would it be wiser to enforce
  164496. * transmission of all coefficient bits??
  164497. */
  164498. for (ci = 0; ci < cinfo->num_components; ci++) {
  164499. if (last_bitpos[ci][0] < 0)
  164500. ERREXIT(cinfo, JERR_MISSING_DATA);
  164501. }
  164502. #endif
  164503. } else {
  164504. for (ci = 0; ci < cinfo->num_components; ci++) {
  164505. if (! component_sent[ci])
  164506. ERREXIT(cinfo, JERR_MISSING_DATA);
  164507. }
  164508. }
  164509. }
  164510. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164511. LOCAL(void)
  164512. select_scan_parameters (j_compress_ptr cinfo)
  164513. /* Set up the scan parameters for the current scan */
  164514. {
  164515. int ci;
  164516. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164517. if (cinfo->scan_info != NULL) {
  164518. /* Prepare for current scan --- the script is already validated */
  164519. my_master_ptr master = (my_master_ptr) cinfo->master;
  164520. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164521. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164522. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164523. cinfo->cur_comp_info[ci] =
  164524. &cinfo->comp_info[scanptr->component_index[ci]];
  164525. }
  164526. cinfo->Ss = scanptr->Ss;
  164527. cinfo->Se = scanptr->Se;
  164528. cinfo->Ah = scanptr->Ah;
  164529. cinfo->Al = scanptr->Al;
  164530. }
  164531. else
  164532. #endif
  164533. {
  164534. /* Prepare for single sequential-JPEG scan containing all components */
  164535. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164536. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164537. MAX_COMPS_IN_SCAN);
  164538. cinfo->comps_in_scan = cinfo->num_components;
  164539. for (ci = 0; ci < cinfo->num_components; ci++) {
  164540. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164541. }
  164542. cinfo->Ss = 0;
  164543. cinfo->Se = DCTSIZE2-1;
  164544. cinfo->Ah = 0;
  164545. cinfo->Al = 0;
  164546. }
  164547. }
  164548. LOCAL(void)
  164549. per_scan_setup (j_compress_ptr cinfo)
  164550. /* Do computations that are needed before processing a JPEG scan */
  164551. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164552. {
  164553. int ci, mcublks, tmp;
  164554. jpeg_component_info *compptr;
  164555. if (cinfo->comps_in_scan == 1) {
  164556. /* Noninterleaved (single-component) scan */
  164557. compptr = cinfo->cur_comp_info[0];
  164558. /* Overall image size in MCUs */
  164559. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164560. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164561. /* For noninterleaved scan, always one block per MCU */
  164562. compptr->MCU_width = 1;
  164563. compptr->MCU_height = 1;
  164564. compptr->MCU_blocks = 1;
  164565. compptr->MCU_sample_width = DCTSIZE;
  164566. compptr->last_col_width = 1;
  164567. /* For noninterleaved scans, it is convenient to define last_row_height
  164568. * as the number of block rows present in the last iMCU row.
  164569. */
  164570. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164571. if (tmp == 0) tmp = compptr->v_samp_factor;
  164572. compptr->last_row_height = tmp;
  164573. /* Prepare array describing MCU composition */
  164574. cinfo->blocks_in_MCU = 1;
  164575. cinfo->MCU_membership[0] = 0;
  164576. } else {
  164577. /* Interleaved (multi-component) scan */
  164578. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164579. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164580. MAX_COMPS_IN_SCAN);
  164581. /* Overall image size in MCUs */
  164582. cinfo->MCUs_per_row = (JDIMENSION)
  164583. jdiv_round_up((long) cinfo->image_width,
  164584. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164585. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164586. jdiv_round_up((long) cinfo->image_height,
  164587. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164588. cinfo->blocks_in_MCU = 0;
  164589. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164590. compptr = cinfo->cur_comp_info[ci];
  164591. /* Sampling factors give # of blocks of component in each MCU */
  164592. compptr->MCU_width = compptr->h_samp_factor;
  164593. compptr->MCU_height = compptr->v_samp_factor;
  164594. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164595. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164596. /* Figure number of non-dummy blocks in last MCU column & row */
  164597. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164598. if (tmp == 0) tmp = compptr->MCU_width;
  164599. compptr->last_col_width = tmp;
  164600. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164601. if (tmp == 0) tmp = compptr->MCU_height;
  164602. compptr->last_row_height = tmp;
  164603. /* Prepare array describing MCU composition */
  164604. mcublks = compptr->MCU_blocks;
  164605. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164606. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164607. while (mcublks-- > 0) {
  164608. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164609. }
  164610. }
  164611. }
  164612. /* Convert restart specified in rows to actual MCU count. */
  164613. /* Note that count must fit in 16 bits, so we provide limiting. */
  164614. if (cinfo->restart_in_rows > 0) {
  164615. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164616. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164617. }
  164618. }
  164619. /*
  164620. * Per-pass setup.
  164621. * This is called at the beginning of each pass. We determine which modules
  164622. * will be active during this pass and give them appropriate start_pass calls.
  164623. * We also set is_last_pass to indicate whether any more passes will be
  164624. * required.
  164625. */
  164626. METHODDEF(void)
  164627. prepare_for_pass (j_compress_ptr cinfo)
  164628. {
  164629. my_master_ptr master = (my_master_ptr) cinfo->master;
  164630. switch (master->pass_type) {
  164631. case main_pass:
  164632. /* Initial pass: will collect input data, and do either Huffman
  164633. * optimization or data output for the first scan.
  164634. */
  164635. select_scan_parameters(cinfo);
  164636. per_scan_setup(cinfo);
  164637. if (! cinfo->raw_data_in) {
  164638. (*cinfo->cconvert->start_pass) (cinfo);
  164639. (*cinfo->downsample->start_pass) (cinfo);
  164640. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164641. }
  164642. (*cinfo->fdct->start_pass) (cinfo);
  164643. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164644. (*cinfo->coef->start_pass) (cinfo,
  164645. (master->total_passes > 1 ?
  164646. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164647. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164648. if (cinfo->optimize_coding) {
  164649. /* No immediate data output; postpone writing frame/scan headers */
  164650. master->pub.call_pass_startup = FALSE;
  164651. } else {
  164652. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164653. master->pub.call_pass_startup = TRUE;
  164654. }
  164655. break;
  164656. #ifdef ENTROPY_OPT_SUPPORTED
  164657. case huff_opt_pass:
  164658. /* Do Huffman optimization for a scan after the first one. */
  164659. select_scan_parameters(cinfo);
  164660. per_scan_setup(cinfo);
  164661. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164662. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164663. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164664. master->pub.call_pass_startup = FALSE;
  164665. break;
  164666. }
  164667. /* Special case: Huffman DC refinement scans need no Huffman table
  164668. * and therefore we can skip the optimization pass for them.
  164669. */
  164670. master->pass_type = output_pass;
  164671. master->pass_number++;
  164672. /*FALLTHROUGH*/
  164673. #endif
  164674. case output_pass:
  164675. /* Do a data-output pass. */
  164676. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164677. if (! cinfo->optimize_coding) {
  164678. select_scan_parameters(cinfo);
  164679. per_scan_setup(cinfo);
  164680. }
  164681. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164682. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164683. /* We emit frame/scan headers now */
  164684. if (master->scan_number == 0)
  164685. (*cinfo->marker->write_frame_header) (cinfo);
  164686. (*cinfo->marker->write_scan_header) (cinfo);
  164687. master->pub.call_pass_startup = FALSE;
  164688. break;
  164689. default:
  164690. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164691. }
  164692. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164693. /* Set up progress monitor's pass info if present */
  164694. if (cinfo->progress != NULL) {
  164695. cinfo->progress->completed_passes = master->pass_number;
  164696. cinfo->progress->total_passes = master->total_passes;
  164697. }
  164698. }
  164699. /*
  164700. * Special start-of-pass hook.
  164701. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164702. * In single-pass processing, we need this hook because we don't want to
  164703. * write frame/scan headers during jpeg_start_compress; we want to let the
  164704. * application write COM markers etc. between jpeg_start_compress and the
  164705. * jpeg_write_scanlines loop.
  164706. * In multi-pass processing, this routine is not used.
  164707. */
  164708. METHODDEF(void)
  164709. pass_startup (j_compress_ptr cinfo)
  164710. {
  164711. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164712. (*cinfo->marker->write_frame_header) (cinfo);
  164713. (*cinfo->marker->write_scan_header) (cinfo);
  164714. }
  164715. /*
  164716. * Finish up at end of pass.
  164717. */
  164718. METHODDEF(void)
  164719. finish_pass_master (j_compress_ptr cinfo)
  164720. {
  164721. my_master_ptr master = (my_master_ptr) cinfo->master;
  164722. /* The entropy coder always needs an end-of-pass call,
  164723. * either to analyze statistics or to flush its output buffer.
  164724. */
  164725. (*cinfo->entropy->finish_pass) (cinfo);
  164726. /* Update state for next pass */
  164727. switch (master->pass_type) {
  164728. case main_pass:
  164729. /* next pass is either output of scan 0 (after optimization)
  164730. * or output of scan 1 (if no optimization).
  164731. */
  164732. master->pass_type = output_pass;
  164733. if (! cinfo->optimize_coding)
  164734. master->scan_number++;
  164735. break;
  164736. case huff_opt_pass:
  164737. /* next pass is always output of current scan */
  164738. master->pass_type = output_pass;
  164739. break;
  164740. case output_pass:
  164741. /* next pass is either optimization or output of next scan */
  164742. if (cinfo->optimize_coding)
  164743. master->pass_type = huff_opt_pass;
  164744. master->scan_number++;
  164745. break;
  164746. }
  164747. master->pass_number++;
  164748. }
  164749. /*
  164750. * Initialize master compression control.
  164751. */
  164752. GLOBAL(void)
  164753. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164754. {
  164755. my_master_ptr master;
  164756. master = (my_master_ptr)
  164757. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164758. SIZEOF(my_comp_master));
  164759. cinfo->master = (struct jpeg_comp_master *) master;
  164760. master->pub.prepare_for_pass = prepare_for_pass;
  164761. master->pub.pass_startup = pass_startup;
  164762. master->pub.finish_pass = finish_pass_master;
  164763. master->pub.is_last_pass = FALSE;
  164764. /* Validate parameters, determine derived values */
  164765. initial_setup(cinfo);
  164766. if (cinfo->scan_info != NULL) {
  164767. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164768. validate_script(cinfo);
  164769. #else
  164770. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164771. #endif
  164772. } else {
  164773. cinfo->progressive_mode = FALSE;
  164774. cinfo->num_scans = 1;
  164775. }
  164776. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164777. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164778. /* Initialize my private state */
  164779. if (transcode_only) {
  164780. /* no main pass in transcoding */
  164781. if (cinfo->optimize_coding)
  164782. master->pass_type = huff_opt_pass;
  164783. else
  164784. master->pass_type = output_pass;
  164785. } else {
  164786. /* for normal compression, first pass is always this type: */
  164787. master->pass_type = main_pass;
  164788. }
  164789. master->scan_number = 0;
  164790. master->pass_number = 0;
  164791. if (cinfo->optimize_coding)
  164792. master->total_passes = cinfo->num_scans * 2;
  164793. else
  164794. master->total_passes = cinfo->num_scans;
  164795. }
  164796. /*** End of inlined file: jcmaster.c ***/
  164797. /*** Start of inlined file: jcomapi.c ***/
  164798. #define JPEG_INTERNALS
  164799. /*
  164800. * Abort processing of a JPEG compression or decompression operation,
  164801. * but don't destroy the object itself.
  164802. *
  164803. * For this, we merely clean up all the nonpermanent memory pools.
  164804. * Note that temp files (virtual arrays) are not allowed to belong to
  164805. * the permanent pool, so we will be able to close all temp files here.
  164806. * Closing a data source or destination, if necessary, is the application's
  164807. * responsibility.
  164808. */
  164809. GLOBAL(void)
  164810. jpeg_abort (j_common_ptr cinfo)
  164811. {
  164812. int pool;
  164813. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164814. if (cinfo->mem == NULL)
  164815. return;
  164816. /* Releasing pools in reverse order might help avoid fragmentation
  164817. * with some (brain-damaged) malloc libraries.
  164818. */
  164819. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164820. (*cinfo->mem->free_pool) (cinfo, pool);
  164821. }
  164822. /* Reset overall state for possible reuse of object */
  164823. if (cinfo->is_decompressor) {
  164824. cinfo->global_state = DSTATE_START;
  164825. /* Try to keep application from accessing now-deleted marker list.
  164826. * A bit kludgy to do it here, but this is the most central place.
  164827. */
  164828. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164829. } else {
  164830. cinfo->global_state = CSTATE_START;
  164831. }
  164832. }
  164833. /*
  164834. * Destruction of a JPEG object.
  164835. *
  164836. * Everything gets deallocated except the master jpeg_compress_struct itself
  164837. * and the error manager struct. Both of these are supplied by the application
  164838. * and must be freed, if necessary, by the application. (Often they are on
  164839. * the stack and so don't need to be freed anyway.)
  164840. * Closing a data source or destination, if necessary, is the application's
  164841. * responsibility.
  164842. */
  164843. GLOBAL(void)
  164844. jpeg_destroy (j_common_ptr cinfo)
  164845. {
  164846. /* We need only tell the memory manager to release everything. */
  164847. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164848. if (cinfo->mem != NULL)
  164849. (*cinfo->mem->self_destruct) (cinfo);
  164850. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164851. cinfo->global_state = 0; /* mark it destroyed */
  164852. }
  164853. /*
  164854. * Convenience routines for allocating quantization and Huffman tables.
  164855. * (Would jutils.c be a more reasonable place to put these?)
  164856. */
  164857. GLOBAL(JQUANT_TBL *)
  164858. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164859. {
  164860. JQUANT_TBL *tbl;
  164861. tbl = (JQUANT_TBL *)
  164862. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164863. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164864. return tbl;
  164865. }
  164866. GLOBAL(JHUFF_TBL *)
  164867. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164868. {
  164869. JHUFF_TBL *tbl;
  164870. tbl = (JHUFF_TBL *)
  164871. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164872. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164873. return tbl;
  164874. }
  164875. /*** End of inlined file: jcomapi.c ***/
  164876. /*** Start of inlined file: jcparam.c ***/
  164877. #define JPEG_INTERNALS
  164878. /*
  164879. * Quantization table setup routines
  164880. */
  164881. GLOBAL(void)
  164882. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164883. const unsigned int *basic_table,
  164884. int scale_factor, boolean force_baseline)
  164885. /* Define a quantization table equal to the basic_table times
  164886. * a scale factor (given as a percentage).
  164887. * If force_baseline is TRUE, the computed quantization table entries
  164888. * are limited to 1..255 for JPEG baseline compatibility.
  164889. */
  164890. {
  164891. JQUANT_TBL ** qtblptr;
  164892. int i;
  164893. long temp;
  164894. /* Safety check to ensure start_compress not called yet. */
  164895. if (cinfo->global_state != CSTATE_START)
  164896. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164897. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164898. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164899. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164900. if (*qtblptr == NULL)
  164901. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164902. for (i = 0; i < DCTSIZE2; i++) {
  164903. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164904. /* limit the values to the valid range */
  164905. if (temp <= 0L) temp = 1L;
  164906. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164907. if (force_baseline && temp > 255L)
  164908. temp = 255L; /* limit to baseline range if requested */
  164909. (*qtblptr)->quantval[i] = (UINT16) temp;
  164910. }
  164911. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164912. (*qtblptr)->sent_table = FALSE;
  164913. }
  164914. GLOBAL(void)
  164915. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164916. boolean force_baseline)
  164917. /* Set or change the 'quality' (quantization) setting, using default tables
  164918. * and a straight percentage-scaling quality scale. In most cases it's better
  164919. * to use jpeg_set_quality (below); this entry point is provided for
  164920. * applications that insist on a linear percentage scaling.
  164921. */
  164922. {
  164923. /* These are the sample quantization tables given in JPEG spec section K.1.
  164924. * The spec says that the values given produce "good" quality, and
  164925. * when divided by 2, "very good" quality.
  164926. */
  164927. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164928. 16, 11, 10, 16, 24, 40, 51, 61,
  164929. 12, 12, 14, 19, 26, 58, 60, 55,
  164930. 14, 13, 16, 24, 40, 57, 69, 56,
  164931. 14, 17, 22, 29, 51, 87, 80, 62,
  164932. 18, 22, 37, 56, 68, 109, 103, 77,
  164933. 24, 35, 55, 64, 81, 104, 113, 92,
  164934. 49, 64, 78, 87, 103, 121, 120, 101,
  164935. 72, 92, 95, 98, 112, 100, 103, 99
  164936. };
  164937. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164938. 17, 18, 24, 47, 99, 99, 99, 99,
  164939. 18, 21, 26, 66, 99, 99, 99, 99,
  164940. 24, 26, 56, 99, 99, 99, 99, 99,
  164941. 47, 66, 99, 99, 99, 99, 99, 99,
  164942. 99, 99, 99, 99, 99, 99, 99, 99,
  164943. 99, 99, 99, 99, 99, 99, 99, 99,
  164944. 99, 99, 99, 99, 99, 99, 99, 99,
  164945. 99, 99, 99, 99, 99, 99, 99, 99
  164946. };
  164947. /* Set up two quantization tables using the specified scaling */
  164948. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164949. scale_factor, force_baseline);
  164950. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164951. scale_factor, force_baseline);
  164952. }
  164953. GLOBAL(int)
  164954. jpeg_quality_scaling (int quality)
  164955. /* Convert a user-specified quality rating to a percentage scaling factor
  164956. * for an underlying quantization table, using our recommended scaling curve.
  164957. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164958. */
  164959. {
  164960. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164961. if (quality <= 0) quality = 1;
  164962. if (quality > 100) quality = 100;
  164963. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164964. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164965. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164966. * to make all the table entries 1 (hence, minimum quantization loss).
  164967. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164968. */
  164969. if (quality < 50)
  164970. quality = 5000 / quality;
  164971. else
  164972. quality = 200 - quality*2;
  164973. return quality;
  164974. }
  164975. GLOBAL(void)
  164976. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164977. /* Set or change the 'quality' (quantization) setting, using default tables.
  164978. * This is the standard quality-adjusting entry point for typical user
  164979. * interfaces; only those who want detailed control over quantization tables
  164980. * would use the preceding three routines directly.
  164981. */
  164982. {
  164983. /* Convert user 0-100 rating to percentage scaling */
  164984. quality = jpeg_quality_scaling(quality);
  164985. /* Set up standard quality tables */
  164986. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164987. }
  164988. /*
  164989. * Huffman table setup routines
  164990. */
  164991. LOCAL(void)
  164992. add_huff_table (j_compress_ptr cinfo,
  164993. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164994. /* Define a Huffman table */
  164995. {
  164996. int nsymbols, len;
  164997. if (*htblptr == NULL)
  164998. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164999. /* Copy the number-of-symbols-of-each-code-length counts */
  165000. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165001. /* Validate the counts. We do this here mainly so we can copy the right
  165002. * number of symbols from the val[] array, without risking marching off
  165003. * the end of memory. jchuff.c will do a more thorough test later.
  165004. */
  165005. nsymbols = 0;
  165006. for (len = 1; len <= 16; len++)
  165007. nsymbols += bits[len];
  165008. if (nsymbols < 1 || nsymbols > 256)
  165009. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165010. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165011. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165012. (*htblptr)->sent_table = FALSE;
  165013. }
  165014. LOCAL(void)
  165015. std_huff_tables (j_compress_ptr cinfo)
  165016. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165017. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165018. {
  165019. static const UINT8 bits_dc_luminance[17] =
  165020. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165021. static const UINT8 val_dc_luminance[] =
  165022. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165023. static const UINT8 bits_dc_chrominance[17] =
  165024. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165025. static const UINT8 val_dc_chrominance[] =
  165026. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165027. static const UINT8 bits_ac_luminance[17] =
  165028. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165029. static const UINT8 val_ac_luminance[] =
  165030. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165031. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165032. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165033. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165034. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165035. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165036. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165037. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165038. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165039. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165040. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165041. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165042. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165043. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165044. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165045. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165046. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165047. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165048. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165049. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165050. 0xf9, 0xfa };
  165051. static const UINT8 bits_ac_chrominance[17] =
  165052. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165053. static const UINT8 val_ac_chrominance[] =
  165054. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165055. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165056. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165057. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165058. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165059. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165060. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165061. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165062. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165063. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165064. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165065. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165066. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165067. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165068. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165069. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165070. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165071. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165072. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165073. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165074. 0xf9, 0xfa };
  165075. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165076. bits_dc_luminance, val_dc_luminance);
  165077. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165078. bits_ac_luminance, val_ac_luminance);
  165079. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165080. bits_dc_chrominance, val_dc_chrominance);
  165081. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165082. bits_ac_chrominance, val_ac_chrominance);
  165083. }
  165084. /*
  165085. * Default parameter setup for compression.
  165086. *
  165087. * Applications that don't choose to use this routine must do their
  165088. * own setup of all these parameters. Alternately, you can call this
  165089. * to establish defaults and then alter parameters selectively. This
  165090. * is the recommended approach since, if we add any new parameters,
  165091. * your code will still work (they'll be set to reasonable defaults).
  165092. */
  165093. GLOBAL(void)
  165094. jpeg_set_defaults (j_compress_ptr cinfo)
  165095. {
  165096. int i;
  165097. /* Safety check to ensure start_compress not called yet. */
  165098. if (cinfo->global_state != CSTATE_START)
  165099. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165100. /* Allocate comp_info array large enough for maximum component count.
  165101. * Array is made permanent in case application wants to compress
  165102. * multiple images at same param settings.
  165103. */
  165104. if (cinfo->comp_info == NULL)
  165105. cinfo->comp_info = (jpeg_component_info *)
  165106. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165107. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165108. /* Initialize everything not dependent on the color space */
  165109. cinfo->data_precision = BITS_IN_JSAMPLE;
  165110. /* Set up two quantization tables using default quality of 75 */
  165111. jpeg_set_quality(cinfo, 75, TRUE);
  165112. /* Set up two Huffman tables */
  165113. std_huff_tables(cinfo);
  165114. /* Initialize default arithmetic coding conditioning */
  165115. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165116. cinfo->arith_dc_L[i] = 0;
  165117. cinfo->arith_dc_U[i] = 1;
  165118. cinfo->arith_ac_K[i] = 5;
  165119. }
  165120. /* Default is no multiple-scan output */
  165121. cinfo->scan_info = NULL;
  165122. cinfo->num_scans = 0;
  165123. /* Expect normal source image, not raw downsampled data */
  165124. cinfo->raw_data_in = FALSE;
  165125. /* Use Huffman coding, not arithmetic coding, by default */
  165126. cinfo->arith_code = FALSE;
  165127. /* By default, don't do extra passes to optimize entropy coding */
  165128. cinfo->optimize_coding = FALSE;
  165129. /* The standard Huffman tables are only valid for 8-bit data precision.
  165130. * If the precision is higher, force optimization on so that usable
  165131. * tables will be computed. This test can be removed if default tables
  165132. * are supplied that are valid for the desired precision.
  165133. */
  165134. if (cinfo->data_precision > 8)
  165135. cinfo->optimize_coding = TRUE;
  165136. /* By default, use the simpler non-cosited sampling alignment */
  165137. cinfo->CCIR601_sampling = FALSE;
  165138. /* No input smoothing */
  165139. cinfo->smoothing_factor = 0;
  165140. /* DCT algorithm preference */
  165141. cinfo->dct_method = JDCT_DEFAULT;
  165142. /* No restart markers */
  165143. cinfo->restart_interval = 0;
  165144. cinfo->restart_in_rows = 0;
  165145. /* Fill in default JFIF marker parameters. Note that whether the marker
  165146. * will actually be written is determined by jpeg_set_colorspace.
  165147. *
  165148. * By default, the library emits JFIF version code 1.01.
  165149. * An application that wants to emit JFIF 1.02 extension markers should set
  165150. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165151. * to 1.02, but there may still be some decoders in use that will complain
  165152. * about that; saying 1.01 should minimize compatibility problems.
  165153. */
  165154. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165155. cinfo->JFIF_minor_version = 1;
  165156. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165157. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165158. cinfo->Y_density = 1;
  165159. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165160. jpeg_default_colorspace(cinfo);
  165161. }
  165162. /*
  165163. * Select an appropriate JPEG colorspace for in_color_space.
  165164. */
  165165. GLOBAL(void)
  165166. jpeg_default_colorspace (j_compress_ptr cinfo)
  165167. {
  165168. switch (cinfo->in_color_space) {
  165169. case JCS_GRAYSCALE:
  165170. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165171. break;
  165172. case JCS_RGB:
  165173. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165174. break;
  165175. case JCS_YCbCr:
  165176. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165177. break;
  165178. case JCS_CMYK:
  165179. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165180. break;
  165181. case JCS_YCCK:
  165182. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165183. break;
  165184. case JCS_UNKNOWN:
  165185. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165186. break;
  165187. default:
  165188. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165189. }
  165190. }
  165191. /*
  165192. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165193. */
  165194. GLOBAL(void)
  165195. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165196. {
  165197. jpeg_component_info * compptr;
  165198. int ci;
  165199. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165200. (compptr = &cinfo->comp_info[index], \
  165201. compptr->component_id = (id), \
  165202. compptr->h_samp_factor = (hsamp), \
  165203. compptr->v_samp_factor = (vsamp), \
  165204. compptr->quant_tbl_no = (quant), \
  165205. compptr->dc_tbl_no = (dctbl), \
  165206. compptr->ac_tbl_no = (actbl) )
  165207. /* Safety check to ensure start_compress not called yet. */
  165208. if (cinfo->global_state != CSTATE_START)
  165209. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165210. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165211. * tables 1 for chrominance components.
  165212. */
  165213. cinfo->jpeg_color_space = colorspace;
  165214. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165215. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165216. switch (colorspace) {
  165217. case JCS_GRAYSCALE:
  165218. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165219. cinfo->num_components = 1;
  165220. /* JFIF specifies component ID 1 */
  165221. SET_COMP(0, 1, 1,1, 0, 0,0);
  165222. break;
  165223. case JCS_RGB:
  165224. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165225. cinfo->num_components = 3;
  165226. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165227. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165228. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165229. break;
  165230. case JCS_YCbCr:
  165231. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165232. cinfo->num_components = 3;
  165233. /* JFIF specifies component IDs 1,2,3 */
  165234. /* We default to 2x2 subsamples of chrominance */
  165235. SET_COMP(0, 1, 2,2, 0, 0,0);
  165236. SET_COMP(1, 2, 1,1, 1, 1,1);
  165237. SET_COMP(2, 3, 1,1, 1, 1,1);
  165238. break;
  165239. case JCS_CMYK:
  165240. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165241. cinfo->num_components = 4;
  165242. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165243. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165244. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165245. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165246. break;
  165247. case JCS_YCCK:
  165248. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165249. cinfo->num_components = 4;
  165250. SET_COMP(0, 1, 2,2, 0, 0,0);
  165251. SET_COMP(1, 2, 1,1, 1, 1,1);
  165252. SET_COMP(2, 3, 1,1, 1, 1,1);
  165253. SET_COMP(3, 4, 2,2, 0, 0,0);
  165254. break;
  165255. case JCS_UNKNOWN:
  165256. cinfo->num_components = cinfo->input_components;
  165257. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165258. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165259. MAX_COMPONENTS);
  165260. for (ci = 0; ci < cinfo->num_components; ci++) {
  165261. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165262. }
  165263. break;
  165264. default:
  165265. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165266. }
  165267. }
  165268. #ifdef C_PROGRESSIVE_SUPPORTED
  165269. LOCAL(jpeg_scan_info *)
  165270. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165271. int Ss, int Se, int Ah, int Al)
  165272. /* Support routine: generate one scan for specified component */
  165273. {
  165274. scanptr->comps_in_scan = 1;
  165275. scanptr->component_index[0] = ci;
  165276. scanptr->Ss = Ss;
  165277. scanptr->Se = Se;
  165278. scanptr->Ah = Ah;
  165279. scanptr->Al = Al;
  165280. scanptr++;
  165281. return scanptr;
  165282. }
  165283. LOCAL(jpeg_scan_info *)
  165284. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165285. int Ss, int Se, int Ah, int Al)
  165286. /* Support routine: generate one scan for each component */
  165287. {
  165288. int ci;
  165289. for (ci = 0; ci < ncomps; ci++) {
  165290. scanptr->comps_in_scan = 1;
  165291. scanptr->component_index[0] = ci;
  165292. scanptr->Ss = Ss;
  165293. scanptr->Se = Se;
  165294. scanptr->Ah = Ah;
  165295. scanptr->Al = Al;
  165296. scanptr++;
  165297. }
  165298. return scanptr;
  165299. }
  165300. LOCAL(jpeg_scan_info *)
  165301. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165302. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165303. {
  165304. int ci;
  165305. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165306. /* Single interleaved DC scan */
  165307. scanptr->comps_in_scan = ncomps;
  165308. for (ci = 0; ci < ncomps; ci++)
  165309. scanptr->component_index[ci] = ci;
  165310. scanptr->Ss = scanptr->Se = 0;
  165311. scanptr->Ah = Ah;
  165312. scanptr->Al = Al;
  165313. scanptr++;
  165314. } else {
  165315. /* Noninterleaved DC scan for each component */
  165316. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165317. }
  165318. return scanptr;
  165319. }
  165320. /*
  165321. * Create a recommended progressive-JPEG script.
  165322. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165323. */
  165324. GLOBAL(void)
  165325. jpeg_simple_progression (j_compress_ptr cinfo)
  165326. {
  165327. int ncomps = cinfo->num_components;
  165328. int nscans;
  165329. jpeg_scan_info * scanptr;
  165330. /* Safety check to ensure start_compress not called yet. */
  165331. if (cinfo->global_state != CSTATE_START)
  165332. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165333. /* Figure space needed for script. Calculation must match code below! */
  165334. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165335. /* Custom script for YCbCr color images. */
  165336. nscans = 10;
  165337. } else {
  165338. /* All-purpose script for other color spaces. */
  165339. if (ncomps > MAX_COMPS_IN_SCAN)
  165340. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165341. else
  165342. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165343. }
  165344. /* Allocate space for script.
  165345. * We need to put it in the permanent pool in case the application performs
  165346. * multiple compressions without changing the settings. To avoid a memory
  165347. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165348. * object, we try to re-use previously allocated space, and we allocate
  165349. * enough space to handle YCbCr even if initially asked for grayscale.
  165350. */
  165351. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165352. cinfo->script_space_size = MAX(nscans, 10);
  165353. cinfo->script_space = (jpeg_scan_info *)
  165354. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165355. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165356. }
  165357. scanptr = cinfo->script_space;
  165358. cinfo->scan_info = scanptr;
  165359. cinfo->num_scans = nscans;
  165360. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165361. /* Custom script for YCbCr color images. */
  165362. /* Initial DC scan */
  165363. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165364. /* Initial AC scan: get some luma data out in a hurry */
  165365. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165366. /* Chroma data is too small to be worth expending many scans on */
  165367. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165368. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165369. /* Complete spectral selection for luma AC */
  165370. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165371. /* Refine next bit of luma AC */
  165372. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165373. /* Finish DC successive approximation */
  165374. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165375. /* Finish AC successive approximation */
  165376. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165377. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165378. /* Luma bottom bit comes last since it's usually largest scan */
  165379. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165380. } else {
  165381. /* All-purpose script for other color spaces. */
  165382. /* Successive approximation first pass */
  165383. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165384. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165385. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165386. /* Successive approximation second pass */
  165387. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165388. /* Successive approximation final pass */
  165389. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165390. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165391. }
  165392. }
  165393. #endif /* C_PROGRESSIVE_SUPPORTED */
  165394. /*** End of inlined file: jcparam.c ***/
  165395. /*** Start of inlined file: jcphuff.c ***/
  165396. #define JPEG_INTERNALS
  165397. #ifdef C_PROGRESSIVE_SUPPORTED
  165398. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165399. typedef struct {
  165400. struct jpeg_entropy_encoder pub; /* public fields */
  165401. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165402. boolean gather_statistics;
  165403. /* Bit-level coding status.
  165404. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165405. */
  165406. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165407. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165408. INT32 put_buffer; /* current bit-accumulation buffer */
  165409. int put_bits; /* # of bits now in it */
  165410. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165411. /* Coding status for DC components */
  165412. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165413. /* Coding status for AC components */
  165414. int ac_tbl_no; /* the table number of the single component */
  165415. unsigned int EOBRUN; /* run length of EOBs */
  165416. unsigned int BE; /* # of buffered correction bits before MCU */
  165417. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165418. /* packing correction bits tightly would save some space but cost time... */
  165419. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165420. int next_restart_num; /* next restart number to write (0-7) */
  165421. /* Pointers to derived tables (these workspaces have image lifespan).
  165422. * Since any one scan codes only DC or only AC, we only need one set
  165423. * of tables, not one for DC and one for AC.
  165424. */
  165425. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165426. /* Statistics tables for optimization; again, one set is enough */
  165427. long * count_ptrs[NUM_HUFF_TBLS];
  165428. } phuff_entropy_encoder;
  165429. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165430. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165431. * buffer can hold. Larger sizes may slightly improve compression, but
  165432. * 1000 is already well into the realm of overkill.
  165433. * The minimum safe size is 64 bits.
  165434. */
  165435. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165436. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165437. * We assume that int right shift is unsigned if INT32 right shift is,
  165438. * which should be safe.
  165439. */
  165440. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165441. #define ISHIFT_TEMPS int ishift_temp;
  165442. #define IRIGHT_SHIFT(x,shft) \
  165443. ((ishift_temp = (x)) < 0 ? \
  165444. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165445. (ishift_temp >> (shft)))
  165446. #else
  165447. #define ISHIFT_TEMPS
  165448. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165449. #endif
  165450. /* Forward declarations */
  165451. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165452. JBLOCKROW *MCU_data));
  165453. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165454. JBLOCKROW *MCU_data));
  165455. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165456. JBLOCKROW *MCU_data));
  165457. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165458. JBLOCKROW *MCU_data));
  165459. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165460. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165461. /*
  165462. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165463. */
  165464. METHODDEF(void)
  165465. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165466. {
  165467. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165468. boolean is_DC_band;
  165469. int ci, tbl;
  165470. jpeg_component_info * compptr;
  165471. entropy->cinfo = cinfo;
  165472. entropy->gather_statistics = gather_statistics;
  165473. is_DC_band = (cinfo->Ss == 0);
  165474. /* We assume jcmaster.c already validated the scan parameters. */
  165475. /* Select execution routines */
  165476. if (cinfo->Ah == 0) {
  165477. if (is_DC_band)
  165478. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165479. else
  165480. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165481. } else {
  165482. if (is_DC_band)
  165483. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165484. else {
  165485. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165486. /* AC refinement needs a correction bit buffer */
  165487. if (entropy->bit_buffer == NULL)
  165488. entropy->bit_buffer = (char *)
  165489. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165490. MAX_CORR_BITS * SIZEOF(char));
  165491. }
  165492. }
  165493. if (gather_statistics)
  165494. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165495. else
  165496. entropy->pub.finish_pass = finish_pass_phuff;
  165497. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165498. * for AC coefficients.
  165499. */
  165500. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165501. compptr = cinfo->cur_comp_info[ci];
  165502. /* Initialize DC predictions to 0 */
  165503. entropy->last_dc_val[ci] = 0;
  165504. /* Get table index */
  165505. if (is_DC_band) {
  165506. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165507. continue;
  165508. tbl = compptr->dc_tbl_no;
  165509. } else {
  165510. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165511. }
  165512. if (gather_statistics) {
  165513. /* Check for invalid table index */
  165514. /* (make_c_derived_tbl does this in the other path) */
  165515. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165516. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165517. /* Allocate and zero the statistics tables */
  165518. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165519. if (entropy->count_ptrs[tbl] == NULL)
  165520. entropy->count_ptrs[tbl] = (long *)
  165521. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165522. 257 * SIZEOF(long));
  165523. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165524. } else {
  165525. /* Compute derived values for Huffman table */
  165526. /* We may do this more than once for a table, but it's not expensive */
  165527. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165528. & entropy->derived_tbls[tbl]);
  165529. }
  165530. }
  165531. /* Initialize AC stuff */
  165532. entropy->EOBRUN = 0;
  165533. entropy->BE = 0;
  165534. /* Initialize bit buffer to empty */
  165535. entropy->put_buffer = 0;
  165536. entropy->put_bits = 0;
  165537. /* Initialize restart stuff */
  165538. entropy->restarts_to_go = cinfo->restart_interval;
  165539. entropy->next_restart_num = 0;
  165540. }
  165541. /* Outputting bytes to the file.
  165542. * NB: these must be called only when actually outputting,
  165543. * that is, entropy->gather_statistics == FALSE.
  165544. */
  165545. /* Emit a byte */
  165546. #define emit_byte(entropy,val) \
  165547. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165548. if (--(entropy)->free_in_buffer == 0) \
  165549. dump_buffer_p(entropy); }
  165550. LOCAL(void)
  165551. dump_buffer_p (phuff_entropy_ptr entropy)
  165552. /* Empty the output buffer; we do not support suspension in this module. */
  165553. {
  165554. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165555. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165556. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165557. /* After a successful buffer dump, must reset buffer pointers */
  165558. entropy->next_output_byte = dest->next_output_byte;
  165559. entropy->free_in_buffer = dest->free_in_buffer;
  165560. }
  165561. /* Outputting bits to the file */
  165562. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165563. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165564. * in one call, and we never retain more than 7 bits in put_buffer
  165565. * between calls, so 24 bits are sufficient.
  165566. */
  165567. INLINE
  165568. LOCAL(void)
  165569. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165570. /* Emit some bits, unless we are in gather mode */
  165571. {
  165572. /* This routine is heavily used, so it's worth coding tightly. */
  165573. register INT32 put_buffer = (INT32) code;
  165574. register int put_bits = entropy->put_bits;
  165575. /* if size is 0, caller used an invalid Huffman table entry */
  165576. if (size == 0)
  165577. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165578. if (entropy->gather_statistics)
  165579. return; /* do nothing if we're only getting stats */
  165580. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165581. put_bits += size; /* new number of bits in buffer */
  165582. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165583. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165584. while (put_bits >= 8) {
  165585. int c = (int) ((put_buffer >> 16) & 0xFF);
  165586. emit_byte(entropy, c);
  165587. if (c == 0xFF) { /* need to stuff a zero byte? */
  165588. emit_byte(entropy, 0);
  165589. }
  165590. put_buffer <<= 8;
  165591. put_bits -= 8;
  165592. }
  165593. entropy->put_buffer = put_buffer; /* update variables */
  165594. entropy->put_bits = put_bits;
  165595. }
  165596. LOCAL(void)
  165597. flush_bits_p (phuff_entropy_ptr entropy)
  165598. {
  165599. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165600. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165601. entropy->put_bits = 0;
  165602. }
  165603. /*
  165604. * Emit (or just count) a Huffman symbol.
  165605. */
  165606. INLINE
  165607. LOCAL(void)
  165608. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165609. {
  165610. if (entropy->gather_statistics)
  165611. entropy->count_ptrs[tbl_no][symbol]++;
  165612. else {
  165613. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165614. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165615. }
  165616. }
  165617. /*
  165618. * Emit bits from a correction bit buffer.
  165619. */
  165620. LOCAL(void)
  165621. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165622. unsigned int nbits)
  165623. {
  165624. if (entropy->gather_statistics)
  165625. return; /* no real work */
  165626. while (nbits > 0) {
  165627. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165628. bufstart++;
  165629. nbits--;
  165630. }
  165631. }
  165632. /*
  165633. * Emit any pending EOBRUN symbol.
  165634. */
  165635. LOCAL(void)
  165636. emit_eobrun (phuff_entropy_ptr entropy)
  165637. {
  165638. register int temp, nbits;
  165639. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165640. temp = entropy->EOBRUN;
  165641. nbits = 0;
  165642. while ((temp >>= 1))
  165643. nbits++;
  165644. /* safety check: shouldn't happen given limited correction-bit buffer */
  165645. if (nbits > 14)
  165646. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165647. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165648. if (nbits)
  165649. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165650. entropy->EOBRUN = 0;
  165651. /* Emit any buffered correction bits */
  165652. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165653. entropy->BE = 0;
  165654. }
  165655. }
  165656. /*
  165657. * Emit a restart marker & resynchronize predictions.
  165658. */
  165659. LOCAL(void)
  165660. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165661. {
  165662. int ci;
  165663. emit_eobrun(entropy);
  165664. if (! entropy->gather_statistics) {
  165665. flush_bits_p(entropy);
  165666. emit_byte(entropy, 0xFF);
  165667. emit_byte(entropy, JPEG_RST0 + restart_num);
  165668. }
  165669. if (entropy->cinfo->Ss == 0) {
  165670. /* Re-initialize DC predictions to 0 */
  165671. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165672. entropy->last_dc_val[ci] = 0;
  165673. } else {
  165674. /* Re-initialize all AC-related fields to 0 */
  165675. entropy->EOBRUN = 0;
  165676. entropy->BE = 0;
  165677. }
  165678. }
  165679. /*
  165680. * MCU encoding for DC initial scan (either spectral selection,
  165681. * or first pass of successive approximation).
  165682. */
  165683. METHODDEF(boolean)
  165684. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165685. {
  165686. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165687. register int temp, temp2;
  165688. register int nbits;
  165689. int blkn, ci;
  165690. int Al = cinfo->Al;
  165691. JBLOCKROW block;
  165692. jpeg_component_info * compptr;
  165693. ISHIFT_TEMPS
  165694. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165695. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165696. /* Emit restart marker if needed */
  165697. if (cinfo->restart_interval)
  165698. if (entropy->restarts_to_go == 0)
  165699. emit_restart_p(entropy, entropy->next_restart_num);
  165700. /* Encode the MCU data blocks */
  165701. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165702. block = MCU_data[blkn];
  165703. ci = cinfo->MCU_membership[blkn];
  165704. compptr = cinfo->cur_comp_info[ci];
  165705. /* Compute the DC value after the required point transform by Al.
  165706. * This is simply an arithmetic right shift.
  165707. */
  165708. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165709. /* DC differences are figured on the point-transformed values. */
  165710. temp = temp2 - entropy->last_dc_val[ci];
  165711. entropy->last_dc_val[ci] = temp2;
  165712. /* Encode the DC coefficient difference per section G.1.2.1 */
  165713. temp2 = temp;
  165714. if (temp < 0) {
  165715. temp = -temp; /* temp is abs value of input */
  165716. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165717. /* This code assumes we are on a two's complement machine */
  165718. temp2--;
  165719. }
  165720. /* Find the number of bits needed for the magnitude of the coefficient */
  165721. nbits = 0;
  165722. while (temp) {
  165723. nbits++;
  165724. temp >>= 1;
  165725. }
  165726. /* Check for out-of-range coefficient values.
  165727. * Since we're encoding a difference, the range limit is twice as much.
  165728. */
  165729. if (nbits > MAX_COEF_BITS+1)
  165730. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165731. /* Count/emit the Huffman-coded symbol for the number of bits */
  165732. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165733. /* Emit that number of bits of the value, if positive, */
  165734. /* or the complement of its magnitude, if negative. */
  165735. if (nbits) /* emit_bits rejects calls with size 0 */
  165736. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165737. }
  165738. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165739. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165740. /* Update restart-interval state too */
  165741. if (cinfo->restart_interval) {
  165742. if (entropy->restarts_to_go == 0) {
  165743. entropy->restarts_to_go = cinfo->restart_interval;
  165744. entropy->next_restart_num++;
  165745. entropy->next_restart_num &= 7;
  165746. }
  165747. entropy->restarts_to_go--;
  165748. }
  165749. return TRUE;
  165750. }
  165751. /*
  165752. * MCU encoding for AC initial scan (either spectral selection,
  165753. * or first pass of successive approximation).
  165754. */
  165755. METHODDEF(boolean)
  165756. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165757. {
  165758. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165759. register int temp, temp2;
  165760. register int nbits;
  165761. register int r, k;
  165762. int Se = cinfo->Se;
  165763. int Al = cinfo->Al;
  165764. JBLOCKROW block;
  165765. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165766. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165767. /* Emit restart marker if needed */
  165768. if (cinfo->restart_interval)
  165769. if (entropy->restarts_to_go == 0)
  165770. emit_restart_p(entropy, entropy->next_restart_num);
  165771. /* Encode the MCU data block */
  165772. block = MCU_data[0];
  165773. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165774. r = 0; /* r = run length of zeros */
  165775. for (k = cinfo->Ss; k <= Se; k++) {
  165776. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165777. r++;
  165778. continue;
  165779. }
  165780. /* We must apply the point transform by Al. For AC coefficients this
  165781. * is an integer division with rounding towards 0. To do this portably
  165782. * in C, we shift after obtaining the absolute value; so the code is
  165783. * interwoven with finding the abs value (temp) and output bits (temp2).
  165784. */
  165785. if (temp < 0) {
  165786. temp = -temp; /* temp is abs value of input */
  165787. temp >>= Al; /* apply the point transform */
  165788. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165789. temp2 = ~temp;
  165790. } else {
  165791. temp >>= Al; /* apply the point transform */
  165792. temp2 = temp;
  165793. }
  165794. /* Watch out for case that nonzero coef is zero after point transform */
  165795. if (temp == 0) {
  165796. r++;
  165797. continue;
  165798. }
  165799. /* Emit any pending EOBRUN */
  165800. if (entropy->EOBRUN > 0)
  165801. emit_eobrun(entropy);
  165802. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165803. while (r > 15) {
  165804. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165805. r -= 16;
  165806. }
  165807. /* Find the number of bits needed for the magnitude of the coefficient */
  165808. nbits = 1; /* there must be at least one 1 bit */
  165809. while ((temp >>= 1))
  165810. nbits++;
  165811. /* Check for out-of-range coefficient values */
  165812. if (nbits > MAX_COEF_BITS)
  165813. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165814. /* Count/emit Huffman symbol for run length / number of bits */
  165815. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165816. /* Emit that number of bits of the value, if positive, */
  165817. /* or the complement of its magnitude, if negative. */
  165818. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165819. r = 0; /* reset zero run length */
  165820. }
  165821. if (r > 0) { /* If there are trailing zeroes, */
  165822. entropy->EOBRUN++; /* count an EOB */
  165823. if (entropy->EOBRUN == 0x7FFF)
  165824. emit_eobrun(entropy); /* force it out to avoid overflow */
  165825. }
  165826. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165827. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165828. /* Update restart-interval state too */
  165829. if (cinfo->restart_interval) {
  165830. if (entropy->restarts_to_go == 0) {
  165831. entropy->restarts_to_go = cinfo->restart_interval;
  165832. entropy->next_restart_num++;
  165833. entropy->next_restart_num &= 7;
  165834. }
  165835. entropy->restarts_to_go--;
  165836. }
  165837. return TRUE;
  165838. }
  165839. /*
  165840. * MCU encoding for DC successive approximation refinement scan.
  165841. * Note: we assume such scans can be multi-component, although the spec
  165842. * is not very clear on the point.
  165843. */
  165844. METHODDEF(boolean)
  165845. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165846. {
  165847. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165848. register int temp;
  165849. int blkn;
  165850. int Al = cinfo->Al;
  165851. JBLOCKROW block;
  165852. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165853. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165854. /* Emit restart marker if needed */
  165855. if (cinfo->restart_interval)
  165856. if (entropy->restarts_to_go == 0)
  165857. emit_restart_p(entropy, entropy->next_restart_num);
  165858. /* Encode the MCU data blocks */
  165859. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165860. block = MCU_data[blkn];
  165861. /* We simply emit the Al'th bit of the DC coefficient value. */
  165862. temp = (*block)[0];
  165863. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165864. }
  165865. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165866. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165867. /* Update restart-interval state too */
  165868. if (cinfo->restart_interval) {
  165869. if (entropy->restarts_to_go == 0) {
  165870. entropy->restarts_to_go = cinfo->restart_interval;
  165871. entropy->next_restart_num++;
  165872. entropy->next_restart_num &= 7;
  165873. }
  165874. entropy->restarts_to_go--;
  165875. }
  165876. return TRUE;
  165877. }
  165878. /*
  165879. * MCU encoding for AC successive approximation refinement scan.
  165880. */
  165881. METHODDEF(boolean)
  165882. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165883. {
  165884. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165885. register int temp;
  165886. register int r, k;
  165887. int EOB;
  165888. char *BR_buffer;
  165889. unsigned int BR;
  165890. int Se = cinfo->Se;
  165891. int Al = cinfo->Al;
  165892. JBLOCKROW block;
  165893. int absvalues[DCTSIZE2];
  165894. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165895. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165896. /* Emit restart marker if needed */
  165897. if (cinfo->restart_interval)
  165898. if (entropy->restarts_to_go == 0)
  165899. emit_restart_p(entropy, entropy->next_restart_num);
  165900. /* Encode the MCU data block */
  165901. block = MCU_data[0];
  165902. /* It is convenient to make a pre-pass to determine the transformed
  165903. * coefficients' absolute values and the EOB position.
  165904. */
  165905. EOB = 0;
  165906. for (k = cinfo->Ss; k <= Se; k++) {
  165907. temp = (*block)[jpeg_natural_order[k]];
  165908. /* We must apply the point transform by Al. For AC coefficients this
  165909. * is an integer division with rounding towards 0. To do this portably
  165910. * in C, we shift after obtaining the absolute value.
  165911. */
  165912. if (temp < 0)
  165913. temp = -temp; /* temp is abs value of input */
  165914. temp >>= Al; /* apply the point transform */
  165915. absvalues[k] = temp; /* save abs value for main pass */
  165916. if (temp == 1)
  165917. EOB = k; /* EOB = index of last newly-nonzero coef */
  165918. }
  165919. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165920. r = 0; /* r = run length of zeros */
  165921. BR = 0; /* BR = count of buffered bits added now */
  165922. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165923. for (k = cinfo->Ss; k <= Se; k++) {
  165924. if ((temp = absvalues[k]) == 0) {
  165925. r++;
  165926. continue;
  165927. }
  165928. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165929. while (r > 15 && k <= EOB) {
  165930. /* emit any pending EOBRUN and the BE correction bits */
  165931. emit_eobrun(entropy);
  165932. /* Emit ZRL */
  165933. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165934. r -= 16;
  165935. /* Emit buffered correction bits that must be associated with ZRL */
  165936. emit_buffered_bits(entropy, BR_buffer, BR);
  165937. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165938. BR = 0;
  165939. }
  165940. /* If the coef was previously nonzero, it only needs a correction bit.
  165941. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165942. * that we also need to test r > 15. But if r > 15, we can only get here
  165943. * if k > EOB, which implies that this coefficient is not 1.
  165944. */
  165945. if (temp > 1) {
  165946. /* The correction bit is the next bit of the absolute value. */
  165947. BR_buffer[BR++] = (char) (temp & 1);
  165948. continue;
  165949. }
  165950. /* Emit any pending EOBRUN and the BE correction bits */
  165951. emit_eobrun(entropy);
  165952. /* Count/emit Huffman symbol for run length / number of bits */
  165953. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165954. /* Emit output bit for newly-nonzero coef */
  165955. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165956. emit_bits_p(entropy, (unsigned int) temp, 1);
  165957. /* Emit buffered correction bits that must be associated with this code */
  165958. emit_buffered_bits(entropy, BR_buffer, BR);
  165959. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165960. BR = 0;
  165961. r = 0; /* reset zero run length */
  165962. }
  165963. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165964. entropy->EOBRUN++; /* count an EOB */
  165965. entropy->BE += BR; /* concat my correction bits to older ones */
  165966. /* We force out the EOB if we risk either:
  165967. * 1. overflow of the EOB counter;
  165968. * 2. overflow of the correction bit buffer during the next MCU.
  165969. */
  165970. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165971. emit_eobrun(entropy);
  165972. }
  165973. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165974. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165975. /* Update restart-interval state too */
  165976. if (cinfo->restart_interval) {
  165977. if (entropy->restarts_to_go == 0) {
  165978. entropy->restarts_to_go = cinfo->restart_interval;
  165979. entropy->next_restart_num++;
  165980. entropy->next_restart_num &= 7;
  165981. }
  165982. entropy->restarts_to_go--;
  165983. }
  165984. return TRUE;
  165985. }
  165986. /*
  165987. * Finish up at the end of a Huffman-compressed progressive scan.
  165988. */
  165989. METHODDEF(void)
  165990. finish_pass_phuff (j_compress_ptr cinfo)
  165991. {
  165992. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165993. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165994. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165995. /* Flush out any buffered data */
  165996. emit_eobrun(entropy);
  165997. flush_bits_p(entropy);
  165998. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165999. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166000. }
  166001. /*
  166002. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166003. */
  166004. METHODDEF(void)
  166005. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166006. {
  166007. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166008. boolean is_DC_band;
  166009. int ci, tbl;
  166010. jpeg_component_info * compptr;
  166011. JHUFF_TBL **htblptr;
  166012. boolean did[NUM_HUFF_TBLS];
  166013. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166014. emit_eobrun(entropy);
  166015. is_DC_band = (cinfo->Ss == 0);
  166016. /* It's important not to apply jpeg_gen_optimal_table more than once
  166017. * per table, because it clobbers the input frequency counts!
  166018. */
  166019. MEMZERO(did, SIZEOF(did));
  166020. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166021. compptr = cinfo->cur_comp_info[ci];
  166022. if (is_DC_band) {
  166023. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166024. continue;
  166025. tbl = compptr->dc_tbl_no;
  166026. } else {
  166027. tbl = compptr->ac_tbl_no;
  166028. }
  166029. if (! did[tbl]) {
  166030. if (is_DC_band)
  166031. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166032. else
  166033. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166034. if (*htblptr == NULL)
  166035. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166036. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166037. did[tbl] = TRUE;
  166038. }
  166039. }
  166040. }
  166041. /*
  166042. * Module initialization routine for progressive Huffman entropy encoding.
  166043. */
  166044. GLOBAL(void)
  166045. jinit_phuff_encoder (j_compress_ptr cinfo)
  166046. {
  166047. phuff_entropy_ptr entropy;
  166048. int i;
  166049. entropy = (phuff_entropy_ptr)
  166050. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166051. SIZEOF(phuff_entropy_encoder));
  166052. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166053. entropy->pub.start_pass = start_pass_phuff;
  166054. /* Mark tables unallocated */
  166055. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166056. entropy->derived_tbls[i] = NULL;
  166057. entropy->count_ptrs[i] = NULL;
  166058. }
  166059. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166060. }
  166061. #endif /* C_PROGRESSIVE_SUPPORTED */
  166062. /*** End of inlined file: jcphuff.c ***/
  166063. /*** Start of inlined file: jcprepct.c ***/
  166064. #define JPEG_INTERNALS
  166065. /* At present, jcsample.c can request context rows only for smoothing.
  166066. * In the future, we might also need context rows for CCIR601 sampling
  166067. * or other more-complex downsampling procedures. The code to support
  166068. * context rows should be compiled only if needed.
  166069. */
  166070. #ifdef INPUT_SMOOTHING_SUPPORTED
  166071. #define CONTEXT_ROWS_SUPPORTED
  166072. #endif
  166073. /*
  166074. * For the simple (no-context-row) case, we just need to buffer one
  166075. * row group's worth of pixels for the downsampling step. At the bottom of
  166076. * the image, we pad to a full row group by replicating the last pixel row.
  166077. * The downsampler's last output row is then replicated if needed to pad
  166078. * out to a full iMCU row.
  166079. *
  166080. * When providing context rows, we must buffer three row groups' worth of
  166081. * pixels. Three row groups are physically allocated, but the row pointer
  166082. * arrays are made five row groups high, with the extra pointers above and
  166083. * below "wrapping around" to point to the last and first real row groups.
  166084. * This allows the downsampler to access the proper context rows.
  166085. * At the top and bottom of the image, we create dummy context rows by
  166086. * copying the first or last real pixel row. This copying could be avoided
  166087. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166088. * trouble on the compression side.
  166089. */
  166090. /* Private buffer controller object */
  166091. typedef struct {
  166092. struct jpeg_c_prep_controller pub; /* public fields */
  166093. /* Downsampling input buffer. This buffer holds color-converted data
  166094. * until we have enough to do a downsample step.
  166095. */
  166096. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166097. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166098. int next_buf_row; /* index of next row to store in color_buf */
  166099. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166100. int this_row_group; /* starting row index of group to process */
  166101. int next_buf_stop; /* downsample when we reach this index */
  166102. #endif
  166103. } my_prep_controller;
  166104. typedef my_prep_controller * my_prep_ptr;
  166105. /*
  166106. * Initialize for a processing pass.
  166107. */
  166108. METHODDEF(void)
  166109. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166110. {
  166111. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166112. if (pass_mode != JBUF_PASS_THRU)
  166113. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166114. /* Initialize total-height counter for detecting bottom of image */
  166115. prep->rows_to_go = cinfo->image_height;
  166116. /* Mark the conversion buffer empty */
  166117. prep->next_buf_row = 0;
  166118. #ifdef CONTEXT_ROWS_SUPPORTED
  166119. /* Preset additional state variables for context mode.
  166120. * These aren't used in non-context mode, so we needn't test which mode.
  166121. */
  166122. prep->this_row_group = 0;
  166123. /* Set next_buf_stop to stop after two row groups have been read in. */
  166124. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166125. #endif
  166126. }
  166127. /*
  166128. * Expand an image vertically from height input_rows to height output_rows,
  166129. * by duplicating the bottom row.
  166130. */
  166131. LOCAL(void)
  166132. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166133. int input_rows, int output_rows)
  166134. {
  166135. register int row;
  166136. for (row = input_rows; row < output_rows; row++) {
  166137. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166138. 1, num_cols);
  166139. }
  166140. }
  166141. /*
  166142. * Process some data in the simple no-context case.
  166143. *
  166144. * Preprocessor output data is counted in "row groups". A row group
  166145. * is defined to be v_samp_factor sample rows of each component.
  166146. * Downsampling will produce this much data from each max_v_samp_factor
  166147. * input rows.
  166148. */
  166149. METHODDEF(void)
  166150. pre_process_data (j_compress_ptr cinfo,
  166151. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166152. JDIMENSION in_rows_avail,
  166153. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166154. JDIMENSION out_row_groups_avail)
  166155. {
  166156. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166157. int numrows, ci;
  166158. JDIMENSION inrows;
  166159. jpeg_component_info * compptr;
  166160. while (*in_row_ctr < in_rows_avail &&
  166161. *out_row_group_ctr < out_row_groups_avail) {
  166162. /* Do color conversion to fill the conversion buffer. */
  166163. inrows = in_rows_avail - *in_row_ctr;
  166164. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166165. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166166. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166167. prep->color_buf,
  166168. (JDIMENSION) prep->next_buf_row,
  166169. numrows);
  166170. *in_row_ctr += numrows;
  166171. prep->next_buf_row += numrows;
  166172. prep->rows_to_go -= numrows;
  166173. /* If at bottom of image, pad to fill the conversion buffer. */
  166174. if (prep->rows_to_go == 0 &&
  166175. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166176. for (ci = 0; ci < cinfo->num_components; ci++) {
  166177. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166178. prep->next_buf_row, cinfo->max_v_samp_factor);
  166179. }
  166180. prep->next_buf_row = cinfo->max_v_samp_factor;
  166181. }
  166182. /* If we've filled the conversion buffer, empty it. */
  166183. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166184. (*cinfo->downsample->downsample) (cinfo,
  166185. prep->color_buf, (JDIMENSION) 0,
  166186. output_buf, *out_row_group_ctr);
  166187. prep->next_buf_row = 0;
  166188. (*out_row_group_ctr)++;
  166189. }
  166190. /* If at bottom of image, pad the output to a full iMCU height.
  166191. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166192. */
  166193. if (prep->rows_to_go == 0 &&
  166194. *out_row_group_ctr < out_row_groups_avail) {
  166195. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166196. ci++, compptr++) {
  166197. expand_bottom_edge(output_buf[ci],
  166198. compptr->width_in_blocks * DCTSIZE,
  166199. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166200. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166201. }
  166202. *out_row_group_ctr = out_row_groups_avail;
  166203. break; /* can exit outer loop without test */
  166204. }
  166205. }
  166206. }
  166207. #ifdef CONTEXT_ROWS_SUPPORTED
  166208. /*
  166209. * Process some data in the context case.
  166210. */
  166211. METHODDEF(void)
  166212. pre_process_context (j_compress_ptr cinfo,
  166213. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166214. JDIMENSION in_rows_avail,
  166215. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166216. JDIMENSION out_row_groups_avail)
  166217. {
  166218. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166219. int numrows, ci;
  166220. int buf_height = cinfo->max_v_samp_factor * 3;
  166221. JDIMENSION inrows;
  166222. while (*out_row_group_ctr < out_row_groups_avail) {
  166223. if (*in_row_ctr < in_rows_avail) {
  166224. /* Do color conversion to fill the conversion buffer. */
  166225. inrows = in_rows_avail - *in_row_ctr;
  166226. numrows = prep->next_buf_stop - prep->next_buf_row;
  166227. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166228. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166229. prep->color_buf,
  166230. (JDIMENSION) prep->next_buf_row,
  166231. numrows);
  166232. /* Pad at top of image, if first time through */
  166233. if (prep->rows_to_go == cinfo->image_height) {
  166234. for (ci = 0; ci < cinfo->num_components; ci++) {
  166235. int row;
  166236. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166237. jcopy_sample_rows(prep->color_buf[ci], 0,
  166238. prep->color_buf[ci], -row,
  166239. 1, cinfo->image_width);
  166240. }
  166241. }
  166242. }
  166243. *in_row_ctr += numrows;
  166244. prep->next_buf_row += numrows;
  166245. prep->rows_to_go -= numrows;
  166246. } else {
  166247. /* Return for more data, unless we are at the bottom of the image. */
  166248. if (prep->rows_to_go != 0)
  166249. break;
  166250. /* When at bottom of image, pad to fill the conversion buffer. */
  166251. if (prep->next_buf_row < prep->next_buf_stop) {
  166252. for (ci = 0; ci < cinfo->num_components; ci++) {
  166253. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166254. prep->next_buf_row, prep->next_buf_stop);
  166255. }
  166256. prep->next_buf_row = prep->next_buf_stop;
  166257. }
  166258. }
  166259. /* If we've gotten enough data, downsample a row group. */
  166260. if (prep->next_buf_row == prep->next_buf_stop) {
  166261. (*cinfo->downsample->downsample) (cinfo,
  166262. prep->color_buf,
  166263. (JDIMENSION) prep->this_row_group,
  166264. output_buf, *out_row_group_ctr);
  166265. (*out_row_group_ctr)++;
  166266. /* Advance pointers with wraparound as necessary. */
  166267. prep->this_row_group += cinfo->max_v_samp_factor;
  166268. if (prep->this_row_group >= buf_height)
  166269. prep->this_row_group = 0;
  166270. if (prep->next_buf_row >= buf_height)
  166271. prep->next_buf_row = 0;
  166272. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166273. }
  166274. }
  166275. }
  166276. /*
  166277. * Create the wrapped-around downsampling input buffer needed for context mode.
  166278. */
  166279. LOCAL(void)
  166280. create_context_buffer (j_compress_ptr cinfo)
  166281. {
  166282. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166283. int rgroup_height = cinfo->max_v_samp_factor;
  166284. int ci, i;
  166285. jpeg_component_info * compptr;
  166286. JSAMPARRAY true_buffer, fake_buffer;
  166287. /* Grab enough space for fake row pointers for all the components;
  166288. * we need five row groups' worth of pointers for each component.
  166289. */
  166290. fake_buffer = (JSAMPARRAY)
  166291. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166292. (cinfo->num_components * 5 * rgroup_height) *
  166293. SIZEOF(JSAMPROW));
  166294. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166295. ci++, compptr++) {
  166296. /* Allocate the actual buffer space (3 row groups) for this component.
  166297. * We make the buffer wide enough to allow the downsampler to edge-expand
  166298. * horizontally within the buffer, if it so chooses.
  166299. */
  166300. true_buffer = (*cinfo->mem->alloc_sarray)
  166301. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166302. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166303. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166304. (JDIMENSION) (3 * rgroup_height));
  166305. /* Copy true buffer row pointers into the middle of the fake row array */
  166306. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166307. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166308. /* Fill in the above and below wraparound pointers */
  166309. for (i = 0; i < rgroup_height; i++) {
  166310. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166311. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166312. }
  166313. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166314. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166315. }
  166316. }
  166317. #endif /* CONTEXT_ROWS_SUPPORTED */
  166318. /*
  166319. * Initialize preprocessing controller.
  166320. */
  166321. GLOBAL(void)
  166322. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166323. {
  166324. my_prep_ptr prep;
  166325. int ci;
  166326. jpeg_component_info * compptr;
  166327. if (need_full_buffer) /* safety check */
  166328. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166329. prep = (my_prep_ptr)
  166330. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166331. SIZEOF(my_prep_controller));
  166332. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166333. prep->pub.start_pass = start_pass_prep;
  166334. /* Allocate the color conversion buffer.
  166335. * We make the buffer wide enough to allow the downsampler to edge-expand
  166336. * horizontally within the buffer, if it so chooses.
  166337. */
  166338. if (cinfo->downsample->need_context_rows) {
  166339. /* Set up to provide context rows */
  166340. #ifdef CONTEXT_ROWS_SUPPORTED
  166341. prep->pub.pre_process_data = pre_process_context;
  166342. create_context_buffer(cinfo);
  166343. #else
  166344. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166345. #endif
  166346. } else {
  166347. /* No context, just make it tall enough for one row group */
  166348. prep->pub.pre_process_data = pre_process_data;
  166349. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166350. ci++, compptr++) {
  166351. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166352. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166353. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166354. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166355. (JDIMENSION) cinfo->max_v_samp_factor);
  166356. }
  166357. }
  166358. }
  166359. /*** End of inlined file: jcprepct.c ***/
  166360. /*** Start of inlined file: jcsample.c ***/
  166361. #define JPEG_INTERNALS
  166362. /* Pointer to routine to downsample a single component */
  166363. typedef JMETHOD(void, downsample1_ptr,
  166364. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166365. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166366. /* Private subobject */
  166367. typedef struct {
  166368. struct jpeg_downsampler pub; /* public fields */
  166369. /* Downsampling method pointers, one per component */
  166370. downsample1_ptr methods[MAX_COMPONENTS];
  166371. } my_downsampler;
  166372. typedef my_downsampler * my_downsample_ptr;
  166373. /*
  166374. * Initialize for a downsampling pass.
  166375. */
  166376. METHODDEF(void)
  166377. start_pass_downsample (j_compress_ptr)
  166378. {
  166379. /* no work for now */
  166380. }
  166381. /*
  166382. * Expand a component horizontally from width input_cols to width output_cols,
  166383. * by duplicating the rightmost samples.
  166384. */
  166385. LOCAL(void)
  166386. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166387. JDIMENSION input_cols, JDIMENSION output_cols)
  166388. {
  166389. register JSAMPROW ptr;
  166390. register JSAMPLE pixval;
  166391. register int count;
  166392. int row;
  166393. int numcols = (int) (output_cols - input_cols);
  166394. if (numcols > 0) {
  166395. for (row = 0; row < num_rows; row++) {
  166396. ptr = image_data[row] + input_cols;
  166397. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166398. for (count = numcols; count > 0; count--)
  166399. *ptr++ = pixval;
  166400. }
  166401. }
  166402. }
  166403. /*
  166404. * Do downsampling for a whole row group (all components).
  166405. *
  166406. * In this version we simply downsample each component independently.
  166407. */
  166408. METHODDEF(void)
  166409. sep_downsample (j_compress_ptr cinfo,
  166410. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166411. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166412. {
  166413. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166414. int ci;
  166415. jpeg_component_info * compptr;
  166416. JSAMPARRAY in_ptr, out_ptr;
  166417. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166418. ci++, compptr++) {
  166419. in_ptr = input_buf[ci] + in_row_index;
  166420. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166421. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166422. }
  166423. }
  166424. /*
  166425. * Downsample pixel values of a single component.
  166426. * One row group is processed per call.
  166427. * This version handles arbitrary integral sampling ratios, without smoothing.
  166428. * Note that this version is not actually used for customary sampling ratios.
  166429. */
  166430. METHODDEF(void)
  166431. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166432. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166433. {
  166434. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166435. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166436. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166437. JSAMPROW inptr, outptr;
  166438. INT32 outvalue;
  166439. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166440. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166441. numpix = h_expand * v_expand;
  166442. numpix2 = numpix/2;
  166443. /* Expand input data enough to let all the output samples be generated
  166444. * by the standard loop. Special-casing padded output would be more
  166445. * efficient.
  166446. */
  166447. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166448. cinfo->image_width, output_cols * h_expand);
  166449. inrow = 0;
  166450. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166451. outptr = output_data[outrow];
  166452. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166453. outcol++, outcol_h += h_expand) {
  166454. outvalue = 0;
  166455. for (v = 0; v < v_expand; v++) {
  166456. inptr = input_data[inrow+v] + outcol_h;
  166457. for (h = 0; h < h_expand; h++) {
  166458. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166459. }
  166460. }
  166461. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166462. }
  166463. inrow += v_expand;
  166464. }
  166465. }
  166466. /*
  166467. * Downsample pixel values of a single component.
  166468. * This version handles the special case of a full-size component,
  166469. * without smoothing.
  166470. */
  166471. METHODDEF(void)
  166472. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166473. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166474. {
  166475. /* Copy the data */
  166476. jcopy_sample_rows(input_data, 0, output_data, 0,
  166477. cinfo->max_v_samp_factor, cinfo->image_width);
  166478. /* Edge-expand */
  166479. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166480. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166481. }
  166482. /*
  166483. * Downsample pixel values of a single component.
  166484. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166485. * without smoothing.
  166486. *
  166487. * A note about the "bias" calculations: when rounding fractional values to
  166488. * integer, we do not want to always round 0.5 up to the next integer.
  166489. * If we did that, we'd introduce a noticeable bias towards larger values.
  166490. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166491. * alternate pixel locations (a simple ordered dither pattern).
  166492. */
  166493. METHODDEF(void)
  166494. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166495. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166496. {
  166497. int outrow;
  166498. JDIMENSION outcol;
  166499. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166500. register JSAMPROW inptr, outptr;
  166501. register int bias;
  166502. /* Expand input data enough to let all the output samples be generated
  166503. * by the standard loop. Special-casing padded output would be more
  166504. * efficient.
  166505. */
  166506. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166507. cinfo->image_width, output_cols * 2);
  166508. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166509. outptr = output_data[outrow];
  166510. inptr = input_data[outrow];
  166511. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166512. for (outcol = 0; outcol < output_cols; outcol++) {
  166513. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166514. + bias) >> 1);
  166515. bias ^= 1; /* 0=>1, 1=>0 */
  166516. inptr += 2;
  166517. }
  166518. }
  166519. }
  166520. /*
  166521. * Downsample pixel values of a single component.
  166522. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166523. * without smoothing.
  166524. */
  166525. METHODDEF(void)
  166526. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166527. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166528. {
  166529. int inrow, outrow;
  166530. JDIMENSION outcol;
  166531. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166532. register JSAMPROW inptr0, inptr1, outptr;
  166533. register int bias;
  166534. /* Expand input data enough to let all the output samples be generated
  166535. * by the standard loop. Special-casing padded output would be more
  166536. * efficient.
  166537. */
  166538. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166539. cinfo->image_width, output_cols * 2);
  166540. inrow = 0;
  166541. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166542. outptr = output_data[outrow];
  166543. inptr0 = input_data[inrow];
  166544. inptr1 = input_data[inrow+1];
  166545. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166546. for (outcol = 0; outcol < output_cols; outcol++) {
  166547. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166548. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166549. + bias) >> 2);
  166550. bias ^= 3; /* 1=>2, 2=>1 */
  166551. inptr0 += 2; inptr1 += 2;
  166552. }
  166553. inrow += 2;
  166554. }
  166555. }
  166556. #ifdef INPUT_SMOOTHING_SUPPORTED
  166557. /*
  166558. * Downsample pixel values of a single component.
  166559. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166560. * with smoothing. One row of context is required.
  166561. */
  166562. METHODDEF(void)
  166563. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166564. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166565. {
  166566. int inrow, outrow;
  166567. JDIMENSION colctr;
  166568. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166569. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166570. INT32 membersum, neighsum, memberscale, neighscale;
  166571. /* Expand input data enough to let all the output samples be generated
  166572. * by the standard loop. Special-casing padded output would be more
  166573. * efficient.
  166574. */
  166575. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166576. cinfo->image_width, output_cols * 2);
  166577. /* We don't bother to form the individual "smoothed" input pixel values;
  166578. * we can directly compute the output which is the average of the four
  166579. * smoothed values. Each of the four member pixels contributes a fraction
  166580. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166581. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166582. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166583. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166584. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166585. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166586. * factors are scaled by 2^16 = 65536.
  166587. * Also recall that SF = smoothing_factor / 1024.
  166588. */
  166589. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166590. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166591. inrow = 0;
  166592. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166593. outptr = output_data[outrow];
  166594. inptr0 = input_data[inrow];
  166595. inptr1 = input_data[inrow+1];
  166596. above_ptr = input_data[inrow-1];
  166597. below_ptr = input_data[inrow+2];
  166598. /* Special case for first column: pretend column -1 is same as column 0 */
  166599. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166600. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166601. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166602. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166603. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166604. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166605. neighsum += neighsum;
  166606. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166607. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166608. membersum = membersum * memberscale + neighsum * neighscale;
  166609. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166610. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166611. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166612. /* sum of pixels directly mapped to this output element */
  166613. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166614. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166615. /* sum of edge-neighbor pixels */
  166616. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166617. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166618. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166619. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166620. /* The edge-neighbors count twice as much as corner-neighbors */
  166621. neighsum += neighsum;
  166622. /* Add in the corner-neighbors */
  166623. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166624. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166625. /* form final output scaled up by 2^16 */
  166626. membersum = membersum * memberscale + neighsum * neighscale;
  166627. /* round, descale and output it */
  166628. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166629. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166630. }
  166631. /* Special case for last column */
  166632. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166633. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166634. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166635. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166636. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166637. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166638. neighsum += neighsum;
  166639. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166640. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166641. membersum = membersum * memberscale + neighsum * neighscale;
  166642. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166643. inrow += 2;
  166644. }
  166645. }
  166646. /*
  166647. * Downsample pixel values of a single component.
  166648. * This version handles the special case of a full-size component,
  166649. * with smoothing. One row of context is required.
  166650. */
  166651. METHODDEF(void)
  166652. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166653. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166654. {
  166655. int outrow;
  166656. JDIMENSION colctr;
  166657. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166658. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166659. INT32 membersum, neighsum, memberscale, neighscale;
  166660. int colsum, lastcolsum, nextcolsum;
  166661. /* Expand input data enough to let all the output samples be generated
  166662. * by the standard loop. Special-casing padded output would be more
  166663. * efficient.
  166664. */
  166665. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166666. cinfo->image_width, output_cols);
  166667. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166668. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166669. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166670. * Also recall that SF = smoothing_factor / 1024.
  166671. */
  166672. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166673. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166674. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166675. outptr = output_data[outrow];
  166676. inptr = input_data[outrow];
  166677. above_ptr = input_data[outrow-1];
  166678. below_ptr = input_data[outrow+1];
  166679. /* Special case for first column */
  166680. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166681. GETJSAMPLE(*inptr);
  166682. membersum = GETJSAMPLE(*inptr++);
  166683. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166684. GETJSAMPLE(*inptr);
  166685. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166686. membersum = membersum * memberscale + neighsum * neighscale;
  166687. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166688. lastcolsum = colsum; colsum = nextcolsum;
  166689. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166690. membersum = GETJSAMPLE(*inptr++);
  166691. above_ptr++; below_ptr++;
  166692. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166693. GETJSAMPLE(*inptr);
  166694. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166695. membersum = membersum * memberscale + neighsum * neighscale;
  166696. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166697. lastcolsum = colsum; colsum = nextcolsum;
  166698. }
  166699. /* Special case for last column */
  166700. membersum = GETJSAMPLE(*inptr);
  166701. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166702. membersum = membersum * memberscale + neighsum * neighscale;
  166703. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166704. }
  166705. }
  166706. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166707. /*
  166708. * Module initialization routine for downsampling.
  166709. * Note that we must select a routine for each component.
  166710. */
  166711. GLOBAL(void)
  166712. jinit_downsampler (j_compress_ptr cinfo)
  166713. {
  166714. my_downsample_ptr downsample;
  166715. int ci;
  166716. jpeg_component_info * compptr;
  166717. boolean smoothok = TRUE;
  166718. downsample = (my_downsample_ptr)
  166719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166720. SIZEOF(my_downsampler));
  166721. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166722. downsample->pub.start_pass = start_pass_downsample;
  166723. downsample->pub.downsample = sep_downsample;
  166724. downsample->pub.need_context_rows = FALSE;
  166725. if (cinfo->CCIR601_sampling)
  166726. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166727. /* Verify we can handle the sampling factors, and set up method pointers */
  166728. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166729. ci++, compptr++) {
  166730. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166731. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166732. #ifdef INPUT_SMOOTHING_SUPPORTED
  166733. if (cinfo->smoothing_factor) {
  166734. downsample->methods[ci] = fullsize_smooth_downsample;
  166735. downsample->pub.need_context_rows = TRUE;
  166736. } else
  166737. #endif
  166738. downsample->methods[ci] = fullsize_downsample;
  166739. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166740. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166741. smoothok = FALSE;
  166742. downsample->methods[ci] = h2v1_downsample;
  166743. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166744. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166745. #ifdef INPUT_SMOOTHING_SUPPORTED
  166746. if (cinfo->smoothing_factor) {
  166747. downsample->methods[ci] = h2v2_smooth_downsample;
  166748. downsample->pub.need_context_rows = TRUE;
  166749. } else
  166750. #endif
  166751. downsample->methods[ci] = h2v2_downsample;
  166752. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166753. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166754. smoothok = FALSE;
  166755. downsample->methods[ci] = int_downsample;
  166756. } else
  166757. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166758. }
  166759. #ifdef INPUT_SMOOTHING_SUPPORTED
  166760. if (cinfo->smoothing_factor && !smoothok)
  166761. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166762. #endif
  166763. }
  166764. /*** End of inlined file: jcsample.c ***/
  166765. /*** Start of inlined file: jctrans.c ***/
  166766. #define JPEG_INTERNALS
  166767. /* Forward declarations */
  166768. LOCAL(void) transencode_master_selection
  166769. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166770. LOCAL(void) transencode_coef_controller
  166771. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166772. /*
  166773. * Compression initialization for writing raw-coefficient data.
  166774. * Before calling this, all parameters and a data destination must be set up.
  166775. * Call jpeg_finish_compress() to actually write the data.
  166776. *
  166777. * The number of passed virtual arrays must match cinfo->num_components.
  166778. * Note that the virtual arrays need not be filled or even realized at
  166779. * the time write_coefficients is called; indeed, if the virtual arrays
  166780. * were requested from this compression object's memory manager, they
  166781. * typically will be realized during this routine and filled afterwards.
  166782. */
  166783. GLOBAL(void)
  166784. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166785. {
  166786. if (cinfo->global_state != CSTATE_START)
  166787. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166788. /* Mark all tables to be written */
  166789. jpeg_suppress_tables(cinfo, FALSE);
  166790. /* (Re)initialize error mgr and destination modules */
  166791. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166792. (*cinfo->dest->init_destination) (cinfo);
  166793. /* Perform master selection of active modules */
  166794. transencode_master_selection(cinfo, coef_arrays);
  166795. /* Wait for jpeg_finish_compress() call */
  166796. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166797. cinfo->global_state = CSTATE_WRCOEFS;
  166798. }
  166799. /*
  166800. * Initialize the compression object with default parameters,
  166801. * then copy from the source object all parameters needed for lossless
  166802. * transcoding. Parameters that can be varied without loss (such as
  166803. * scan script and Huffman optimization) are left in their default states.
  166804. */
  166805. GLOBAL(void)
  166806. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166807. j_compress_ptr dstinfo)
  166808. {
  166809. JQUANT_TBL ** qtblptr;
  166810. jpeg_component_info *incomp, *outcomp;
  166811. JQUANT_TBL *c_quant, *slot_quant;
  166812. int tblno, ci, coefi;
  166813. /* Safety check to ensure start_compress not called yet. */
  166814. if (dstinfo->global_state != CSTATE_START)
  166815. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166816. /* Copy fundamental image dimensions */
  166817. dstinfo->image_width = srcinfo->image_width;
  166818. dstinfo->image_height = srcinfo->image_height;
  166819. dstinfo->input_components = srcinfo->num_components;
  166820. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166821. /* Initialize all parameters to default values */
  166822. jpeg_set_defaults(dstinfo);
  166823. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166824. * Fix it to get the right header markers for the image colorspace.
  166825. */
  166826. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166827. dstinfo->data_precision = srcinfo->data_precision;
  166828. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166829. /* Copy the source's quantization tables. */
  166830. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166831. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166832. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166833. if (*qtblptr == NULL)
  166834. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166835. MEMCOPY((*qtblptr)->quantval,
  166836. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166837. SIZEOF((*qtblptr)->quantval));
  166838. (*qtblptr)->sent_table = FALSE;
  166839. }
  166840. }
  166841. /* Copy the source's per-component info.
  166842. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166843. */
  166844. dstinfo->num_components = srcinfo->num_components;
  166845. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166846. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166847. MAX_COMPONENTS);
  166848. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166849. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166850. outcomp->component_id = incomp->component_id;
  166851. outcomp->h_samp_factor = incomp->h_samp_factor;
  166852. outcomp->v_samp_factor = incomp->v_samp_factor;
  166853. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166854. /* Make sure saved quantization table for component matches the qtable
  166855. * slot. If not, the input file re-used this qtable slot.
  166856. * IJG encoder currently cannot duplicate this.
  166857. */
  166858. tblno = outcomp->quant_tbl_no;
  166859. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166860. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166861. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166862. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166863. c_quant = incomp->quant_table;
  166864. if (c_quant != NULL) {
  166865. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166866. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166867. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166868. }
  166869. }
  166870. /* Note: we do not copy the source's Huffman table assignments;
  166871. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166872. */
  166873. }
  166874. /* Also copy JFIF version and resolution information, if available.
  166875. * Strictly speaking this isn't "critical" info, but it's nearly
  166876. * always appropriate to copy it if available. In particular,
  166877. * if the application chooses to copy JFIF 1.02 extension markers from
  166878. * the source file, we need to copy the version to make sure we don't
  166879. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166880. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166881. */
  166882. if (srcinfo->saw_JFIF_marker) {
  166883. if (srcinfo->JFIF_major_version == 1) {
  166884. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166885. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166886. }
  166887. dstinfo->density_unit = srcinfo->density_unit;
  166888. dstinfo->X_density = srcinfo->X_density;
  166889. dstinfo->Y_density = srcinfo->Y_density;
  166890. }
  166891. }
  166892. /*
  166893. * Master selection of compression modules for transcoding.
  166894. * This substitutes for jcinit.c's initialization of the full compressor.
  166895. */
  166896. LOCAL(void)
  166897. transencode_master_selection (j_compress_ptr cinfo,
  166898. jvirt_barray_ptr * coef_arrays)
  166899. {
  166900. /* Although we don't actually use input_components for transcoding,
  166901. * jcmaster.c's initial_setup will complain if input_components is 0.
  166902. */
  166903. cinfo->input_components = 1;
  166904. /* Initialize master control (includes parameter checking/processing) */
  166905. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166906. /* Entropy encoding: either Huffman or arithmetic coding. */
  166907. if (cinfo->arith_code) {
  166908. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166909. } else {
  166910. if (cinfo->progressive_mode) {
  166911. #ifdef C_PROGRESSIVE_SUPPORTED
  166912. jinit_phuff_encoder(cinfo);
  166913. #else
  166914. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166915. #endif
  166916. } else
  166917. jinit_huff_encoder(cinfo);
  166918. }
  166919. /* We need a special coefficient buffer controller. */
  166920. transencode_coef_controller(cinfo, coef_arrays);
  166921. jinit_marker_writer(cinfo);
  166922. /* We can now tell the memory manager to allocate virtual arrays. */
  166923. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166924. /* Write the datastream header (SOI, JFIF) immediately.
  166925. * Frame and scan headers are postponed till later.
  166926. * This lets application insert special markers after the SOI.
  166927. */
  166928. (*cinfo->marker->write_file_header) (cinfo);
  166929. }
  166930. /*
  166931. * The rest of this file is a special implementation of the coefficient
  166932. * buffer controller. This is similar to jccoefct.c, but it handles only
  166933. * output from presupplied virtual arrays. Furthermore, we generate any
  166934. * dummy padding blocks on-the-fly rather than expecting them to be present
  166935. * in the arrays.
  166936. */
  166937. /* Private buffer controller object */
  166938. typedef struct {
  166939. struct jpeg_c_coef_controller pub; /* public fields */
  166940. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166941. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166942. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166943. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166944. /* Virtual block array for each component. */
  166945. jvirt_barray_ptr * whole_image;
  166946. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166947. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166948. } my_coef_controller2;
  166949. typedef my_coef_controller2 * my_coef_ptr2;
  166950. LOCAL(void)
  166951. start_iMCU_row2 (j_compress_ptr cinfo)
  166952. /* Reset within-iMCU-row counters for a new row */
  166953. {
  166954. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166955. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166956. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166957. * But at the bottom of the image, process only what's left.
  166958. */
  166959. if (cinfo->comps_in_scan > 1) {
  166960. coef->MCU_rows_per_iMCU_row = 1;
  166961. } else {
  166962. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166963. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166964. else
  166965. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166966. }
  166967. coef->mcu_ctr = 0;
  166968. coef->MCU_vert_offset = 0;
  166969. }
  166970. /*
  166971. * Initialize for a processing pass.
  166972. */
  166973. METHODDEF(void)
  166974. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166975. {
  166976. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166977. if (pass_mode != JBUF_CRANK_DEST)
  166978. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166979. coef->iMCU_row_num = 0;
  166980. start_iMCU_row2(cinfo);
  166981. }
  166982. /*
  166983. * Process some data.
  166984. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166985. * per call, ie, v_samp_factor block rows for each component in the scan.
  166986. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166987. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166988. *
  166989. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166990. */
  166991. METHODDEF(boolean)
  166992. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166993. {
  166994. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166995. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166996. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166997. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166998. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166999. JDIMENSION start_col;
  167000. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167001. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167002. JBLOCKROW buffer_ptr;
  167003. jpeg_component_info *compptr;
  167004. /* Align the virtual buffers for the components used in this scan. */
  167005. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167006. compptr = cinfo->cur_comp_info[ci];
  167007. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167008. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167009. coef->iMCU_row_num * compptr->v_samp_factor,
  167010. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167011. }
  167012. /* Loop to process one whole iMCU row */
  167013. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167014. yoffset++) {
  167015. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167016. MCU_col_num++) {
  167017. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167018. blkn = 0; /* index of current DCT block within MCU */
  167019. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167020. compptr = cinfo->cur_comp_info[ci];
  167021. start_col = MCU_col_num * compptr->MCU_width;
  167022. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167023. : compptr->last_col_width;
  167024. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167025. if (coef->iMCU_row_num < last_iMCU_row ||
  167026. yindex+yoffset < compptr->last_row_height) {
  167027. /* Fill in pointers to real blocks in this row */
  167028. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167029. for (xindex = 0; xindex < blockcnt; xindex++)
  167030. MCU_buffer[blkn++] = buffer_ptr++;
  167031. } else {
  167032. /* At bottom of image, need a whole row of dummy blocks */
  167033. xindex = 0;
  167034. }
  167035. /* Fill in any dummy blocks needed in this row.
  167036. * Dummy blocks are filled in the same way as in jccoefct.c:
  167037. * all zeroes in the AC entries, DC entries equal to previous
  167038. * block's DC value. The init routine has already zeroed the
  167039. * AC entries, so we need only set the DC entries correctly.
  167040. */
  167041. for (; xindex < compptr->MCU_width; xindex++) {
  167042. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167043. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167044. blkn++;
  167045. }
  167046. }
  167047. }
  167048. /* Try to write the MCU. */
  167049. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167050. /* Suspension forced; update state counters and exit */
  167051. coef->MCU_vert_offset = yoffset;
  167052. coef->mcu_ctr = MCU_col_num;
  167053. return FALSE;
  167054. }
  167055. }
  167056. /* Completed an MCU row, but perhaps not an iMCU row */
  167057. coef->mcu_ctr = 0;
  167058. }
  167059. /* Completed the iMCU row, advance counters for next one */
  167060. coef->iMCU_row_num++;
  167061. start_iMCU_row2(cinfo);
  167062. return TRUE;
  167063. }
  167064. /*
  167065. * Initialize coefficient buffer controller.
  167066. *
  167067. * Each passed coefficient array must be the right size for that
  167068. * coefficient: width_in_blocks wide and height_in_blocks high,
  167069. * with unitheight at least v_samp_factor.
  167070. */
  167071. LOCAL(void)
  167072. transencode_coef_controller (j_compress_ptr cinfo,
  167073. jvirt_barray_ptr * coef_arrays)
  167074. {
  167075. my_coef_ptr2 coef;
  167076. JBLOCKROW buffer;
  167077. int i;
  167078. coef = (my_coef_ptr2)
  167079. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167080. SIZEOF(my_coef_controller2));
  167081. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167082. coef->pub.start_pass = start_pass_coef2;
  167083. coef->pub.compress_data = compress_output2;
  167084. /* Save pointer to virtual arrays */
  167085. coef->whole_image = coef_arrays;
  167086. /* Allocate and pre-zero space for dummy DCT blocks. */
  167087. buffer = (JBLOCKROW)
  167088. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167089. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167090. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167091. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167092. coef->dummy_buffer[i] = buffer + i;
  167093. }
  167094. }
  167095. /*** End of inlined file: jctrans.c ***/
  167096. /*** Start of inlined file: jdapistd.c ***/
  167097. #define JPEG_INTERNALS
  167098. /* Forward declarations */
  167099. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167100. /*
  167101. * Decompression initialization.
  167102. * jpeg_read_header must be completed before calling this.
  167103. *
  167104. * If a multipass operating mode was selected, this will do all but the
  167105. * last pass, and thus may take a great deal of time.
  167106. *
  167107. * Returns FALSE if suspended. The return value need be inspected only if
  167108. * a suspending data source is used.
  167109. */
  167110. GLOBAL(boolean)
  167111. jpeg_start_decompress (j_decompress_ptr cinfo)
  167112. {
  167113. if (cinfo->global_state == DSTATE_READY) {
  167114. /* First call: initialize master control, select active modules */
  167115. jinit_master_decompress(cinfo);
  167116. if (cinfo->buffered_image) {
  167117. /* No more work here; expecting jpeg_start_output next */
  167118. cinfo->global_state = DSTATE_BUFIMAGE;
  167119. return TRUE;
  167120. }
  167121. cinfo->global_state = DSTATE_PRELOAD;
  167122. }
  167123. if (cinfo->global_state == DSTATE_PRELOAD) {
  167124. /* If file has multiple scans, absorb them all into the coef buffer */
  167125. if (cinfo->inputctl->has_multiple_scans) {
  167126. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167127. for (;;) {
  167128. int retcode;
  167129. /* Call progress monitor hook if present */
  167130. if (cinfo->progress != NULL)
  167131. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167132. /* Absorb some more input */
  167133. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167134. if (retcode == JPEG_SUSPENDED)
  167135. return FALSE;
  167136. if (retcode == JPEG_REACHED_EOI)
  167137. break;
  167138. /* Advance progress counter if appropriate */
  167139. if (cinfo->progress != NULL &&
  167140. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167141. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167142. /* jdmaster underestimated number of scans; ratchet up one scan */
  167143. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167144. }
  167145. }
  167146. }
  167147. #else
  167148. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167149. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167150. }
  167151. cinfo->output_scan_number = cinfo->input_scan_number;
  167152. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167153. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167154. /* Perform any dummy output passes, and set up for the final pass */
  167155. return output_pass_setup(cinfo);
  167156. }
  167157. /*
  167158. * Set up for an output pass, and perform any dummy pass(es) needed.
  167159. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167160. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167161. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167162. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167163. */
  167164. LOCAL(boolean)
  167165. output_pass_setup (j_decompress_ptr cinfo)
  167166. {
  167167. if (cinfo->global_state != DSTATE_PRESCAN) {
  167168. /* First call: do pass setup */
  167169. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167170. cinfo->output_scanline = 0;
  167171. cinfo->global_state = DSTATE_PRESCAN;
  167172. }
  167173. /* Loop over any required dummy passes */
  167174. while (cinfo->master->is_dummy_pass) {
  167175. #ifdef QUANT_2PASS_SUPPORTED
  167176. /* Crank through the dummy pass */
  167177. while (cinfo->output_scanline < cinfo->output_height) {
  167178. JDIMENSION last_scanline;
  167179. /* Call progress monitor hook if present */
  167180. if (cinfo->progress != NULL) {
  167181. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167182. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167183. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167184. }
  167185. /* Process some data */
  167186. last_scanline = cinfo->output_scanline;
  167187. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167188. &cinfo->output_scanline, (JDIMENSION) 0);
  167189. if (cinfo->output_scanline == last_scanline)
  167190. return FALSE; /* No progress made, must suspend */
  167191. }
  167192. /* Finish up dummy pass, and set up for another one */
  167193. (*cinfo->master->finish_output_pass) (cinfo);
  167194. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167195. cinfo->output_scanline = 0;
  167196. #else
  167197. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167198. #endif /* QUANT_2PASS_SUPPORTED */
  167199. }
  167200. /* Ready for application to drive output pass through
  167201. * jpeg_read_scanlines or jpeg_read_raw_data.
  167202. */
  167203. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167204. return TRUE;
  167205. }
  167206. /*
  167207. * Read some scanlines of data from the JPEG decompressor.
  167208. *
  167209. * The return value will be the number of lines actually read.
  167210. * This may be less than the number requested in several cases,
  167211. * including bottom of image, data source suspension, and operating
  167212. * modes that emit multiple scanlines at a time.
  167213. *
  167214. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167215. * this likely signals an application programmer error. However,
  167216. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167217. */
  167218. GLOBAL(JDIMENSION)
  167219. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167220. JDIMENSION max_lines)
  167221. {
  167222. JDIMENSION row_ctr;
  167223. if (cinfo->global_state != DSTATE_SCANNING)
  167224. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167225. if (cinfo->output_scanline >= cinfo->output_height) {
  167226. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167227. return 0;
  167228. }
  167229. /* Call progress monitor hook if present */
  167230. if (cinfo->progress != NULL) {
  167231. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167232. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167233. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167234. }
  167235. /* Process some data */
  167236. row_ctr = 0;
  167237. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167238. cinfo->output_scanline += row_ctr;
  167239. return row_ctr;
  167240. }
  167241. /*
  167242. * Alternate entry point to read raw data.
  167243. * Processes exactly one iMCU row per call, unless suspended.
  167244. */
  167245. GLOBAL(JDIMENSION)
  167246. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167247. JDIMENSION max_lines)
  167248. {
  167249. JDIMENSION lines_per_iMCU_row;
  167250. if (cinfo->global_state != DSTATE_RAW_OK)
  167251. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167252. if (cinfo->output_scanline >= cinfo->output_height) {
  167253. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167254. return 0;
  167255. }
  167256. /* Call progress monitor hook if present */
  167257. if (cinfo->progress != NULL) {
  167258. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167259. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167260. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167261. }
  167262. /* Verify that at least one iMCU row can be returned. */
  167263. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167264. if (max_lines < lines_per_iMCU_row)
  167265. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167266. /* Decompress directly into user's buffer. */
  167267. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167268. return 0; /* suspension forced, can do nothing more */
  167269. /* OK, we processed one iMCU row. */
  167270. cinfo->output_scanline += lines_per_iMCU_row;
  167271. return lines_per_iMCU_row;
  167272. }
  167273. /* Additional entry points for buffered-image mode. */
  167274. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167275. /*
  167276. * Initialize for an output pass in buffered-image mode.
  167277. */
  167278. GLOBAL(boolean)
  167279. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167280. {
  167281. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167282. cinfo->global_state != DSTATE_PRESCAN)
  167283. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167284. /* Limit scan number to valid range */
  167285. if (scan_number <= 0)
  167286. scan_number = 1;
  167287. if (cinfo->inputctl->eoi_reached &&
  167288. scan_number > cinfo->input_scan_number)
  167289. scan_number = cinfo->input_scan_number;
  167290. cinfo->output_scan_number = scan_number;
  167291. /* Perform any dummy output passes, and set up for the real pass */
  167292. return output_pass_setup(cinfo);
  167293. }
  167294. /*
  167295. * Finish up after an output pass in buffered-image mode.
  167296. *
  167297. * Returns FALSE if suspended. The return value need be inspected only if
  167298. * a suspending data source is used.
  167299. */
  167300. GLOBAL(boolean)
  167301. jpeg_finish_output (j_decompress_ptr cinfo)
  167302. {
  167303. if ((cinfo->global_state == DSTATE_SCANNING ||
  167304. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167305. /* Terminate this pass. */
  167306. /* We do not require the whole pass to have been completed. */
  167307. (*cinfo->master->finish_output_pass) (cinfo);
  167308. cinfo->global_state = DSTATE_BUFPOST;
  167309. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167310. /* BUFPOST = repeat call after a suspension, anything else is error */
  167311. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167312. }
  167313. /* Read markers looking for SOS or EOI */
  167314. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167315. ! cinfo->inputctl->eoi_reached) {
  167316. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167317. return FALSE; /* Suspend, come back later */
  167318. }
  167319. cinfo->global_state = DSTATE_BUFIMAGE;
  167320. return TRUE;
  167321. }
  167322. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167323. /*** End of inlined file: jdapistd.c ***/
  167324. /*** Start of inlined file: jdapimin.c ***/
  167325. #define JPEG_INTERNALS
  167326. /*
  167327. * Initialization of a JPEG decompression object.
  167328. * The error manager must already be set up (in case memory manager fails).
  167329. */
  167330. GLOBAL(void)
  167331. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167332. {
  167333. int i;
  167334. /* Guard against version mismatches between library and caller. */
  167335. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167336. if (version != JPEG_LIB_VERSION)
  167337. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167338. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167339. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167340. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167341. /* For debugging purposes, we zero the whole master structure.
  167342. * But the application has already set the err pointer, and may have set
  167343. * client_data, so we have to save and restore those fields.
  167344. * Note: if application hasn't set client_data, tools like Purify may
  167345. * complain here.
  167346. */
  167347. {
  167348. struct jpeg_error_mgr * err = cinfo->err;
  167349. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167350. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167351. cinfo->err = err;
  167352. cinfo->client_data = client_data;
  167353. }
  167354. cinfo->is_decompressor = TRUE;
  167355. /* Initialize a memory manager instance for this object */
  167356. jinit_memory_mgr((j_common_ptr) cinfo);
  167357. /* Zero out pointers to permanent structures. */
  167358. cinfo->progress = NULL;
  167359. cinfo->src = NULL;
  167360. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167361. cinfo->quant_tbl_ptrs[i] = NULL;
  167362. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167363. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167364. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167365. }
  167366. /* Initialize marker processor so application can override methods
  167367. * for COM, APPn markers before calling jpeg_read_header.
  167368. */
  167369. cinfo->marker_list = NULL;
  167370. jinit_marker_reader(cinfo);
  167371. /* And initialize the overall input controller. */
  167372. jinit_input_controller(cinfo);
  167373. /* OK, I'm ready */
  167374. cinfo->global_state = DSTATE_START;
  167375. }
  167376. /*
  167377. * Destruction of a JPEG decompression object
  167378. */
  167379. GLOBAL(void)
  167380. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167381. {
  167382. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167383. }
  167384. /*
  167385. * Abort processing of a JPEG decompression operation,
  167386. * but don't destroy the object itself.
  167387. */
  167388. GLOBAL(void)
  167389. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167390. {
  167391. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167392. }
  167393. /*
  167394. * Set default decompression parameters.
  167395. */
  167396. LOCAL(void)
  167397. default_decompress_parms (j_decompress_ptr cinfo)
  167398. {
  167399. /* Guess the input colorspace, and set output colorspace accordingly. */
  167400. /* (Wish JPEG committee had provided a real way to specify this...) */
  167401. /* Note application may override our guesses. */
  167402. switch (cinfo->num_components) {
  167403. case 1:
  167404. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167405. cinfo->out_color_space = JCS_GRAYSCALE;
  167406. break;
  167407. case 3:
  167408. if (cinfo->saw_JFIF_marker) {
  167409. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167410. } else if (cinfo->saw_Adobe_marker) {
  167411. switch (cinfo->Adobe_transform) {
  167412. case 0:
  167413. cinfo->jpeg_color_space = JCS_RGB;
  167414. break;
  167415. case 1:
  167416. cinfo->jpeg_color_space = JCS_YCbCr;
  167417. break;
  167418. default:
  167419. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167420. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167421. break;
  167422. }
  167423. } else {
  167424. /* Saw no special markers, try to guess from the component IDs */
  167425. int cid0 = cinfo->comp_info[0].component_id;
  167426. int cid1 = cinfo->comp_info[1].component_id;
  167427. int cid2 = cinfo->comp_info[2].component_id;
  167428. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167429. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167430. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167431. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167432. else {
  167433. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167434. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167435. }
  167436. }
  167437. /* Always guess RGB is proper output colorspace. */
  167438. cinfo->out_color_space = JCS_RGB;
  167439. break;
  167440. case 4:
  167441. if (cinfo->saw_Adobe_marker) {
  167442. switch (cinfo->Adobe_transform) {
  167443. case 0:
  167444. cinfo->jpeg_color_space = JCS_CMYK;
  167445. break;
  167446. case 2:
  167447. cinfo->jpeg_color_space = JCS_YCCK;
  167448. break;
  167449. default:
  167450. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167451. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167452. break;
  167453. }
  167454. } else {
  167455. /* No special markers, assume straight CMYK. */
  167456. cinfo->jpeg_color_space = JCS_CMYK;
  167457. }
  167458. cinfo->out_color_space = JCS_CMYK;
  167459. break;
  167460. default:
  167461. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167462. cinfo->out_color_space = JCS_UNKNOWN;
  167463. break;
  167464. }
  167465. /* Set defaults for other decompression parameters. */
  167466. cinfo->scale_num = 1; /* 1:1 scaling */
  167467. cinfo->scale_denom = 1;
  167468. cinfo->output_gamma = 1.0;
  167469. cinfo->buffered_image = FALSE;
  167470. cinfo->raw_data_out = FALSE;
  167471. cinfo->dct_method = JDCT_DEFAULT;
  167472. cinfo->do_fancy_upsampling = TRUE;
  167473. cinfo->do_block_smoothing = TRUE;
  167474. cinfo->quantize_colors = FALSE;
  167475. /* We set these in case application only sets quantize_colors. */
  167476. cinfo->dither_mode = JDITHER_FS;
  167477. #ifdef QUANT_2PASS_SUPPORTED
  167478. cinfo->two_pass_quantize = TRUE;
  167479. #else
  167480. cinfo->two_pass_quantize = FALSE;
  167481. #endif
  167482. cinfo->desired_number_of_colors = 256;
  167483. cinfo->colormap = NULL;
  167484. /* Initialize for no mode change in buffered-image mode. */
  167485. cinfo->enable_1pass_quant = FALSE;
  167486. cinfo->enable_external_quant = FALSE;
  167487. cinfo->enable_2pass_quant = FALSE;
  167488. }
  167489. /*
  167490. * Decompression startup: read start of JPEG datastream to see what's there.
  167491. * Need only initialize JPEG object and supply a data source before calling.
  167492. *
  167493. * This routine will read as far as the first SOS marker (ie, actual start of
  167494. * compressed data), and will save all tables and parameters in the JPEG
  167495. * object. It will also initialize the decompression parameters to default
  167496. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167497. * adjust the decompression parameters and then call jpeg_start_decompress.
  167498. * (Or, if the application only wanted to determine the image parameters,
  167499. * the data need not be decompressed. In that case, call jpeg_abort or
  167500. * jpeg_destroy to release any temporary space.)
  167501. * If an abbreviated (tables only) datastream is presented, the routine will
  167502. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167503. * re-use the JPEG object to read the abbreviated image datastream(s).
  167504. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167505. * The JPEG_SUSPENDED return code only occurs if the data source module
  167506. * requests suspension of the decompressor. In this case the application
  167507. * should load more source data and then re-call jpeg_read_header to resume
  167508. * processing.
  167509. * If a non-suspending data source is used and require_image is TRUE, then the
  167510. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167511. *
  167512. * This routine is now just a front end to jpeg_consume_input, with some
  167513. * extra error checking.
  167514. */
  167515. GLOBAL(int)
  167516. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167517. {
  167518. int retcode;
  167519. if (cinfo->global_state != DSTATE_START &&
  167520. cinfo->global_state != DSTATE_INHEADER)
  167521. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167522. retcode = jpeg_consume_input(cinfo);
  167523. switch (retcode) {
  167524. case JPEG_REACHED_SOS:
  167525. retcode = JPEG_HEADER_OK;
  167526. break;
  167527. case JPEG_REACHED_EOI:
  167528. if (require_image) /* Complain if application wanted an image */
  167529. ERREXIT(cinfo, JERR_NO_IMAGE);
  167530. /* Reset to start state; it would be safer to require the application to
  167531. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167532. * A side effect is to free any temporary memory (there shouldn't be any).
  167533. */
  167534. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167535. retcode = JPEG_HEADER_TABLES_ONLY;
  167536. break;
  167537. case JPEG_SUSPENDED:
  167538. /* no work */
  167539. break;
  167540. }
  167541. return retcode;
  167542. }
  167543. /*
  167544. * Consume data in advance of what the decompressor requires.
  167545. * This can be called at any time once the decompressor object has
  167546. * been created and a data source has been set up.
  167547. *
  167548. * This routine is essentially a state machine that handles a couple
  167549. * of critical state-transition actions, namely initial setup and
  167550. * transition from header scanning to ready-for-start_decompress.
  167551. * All the actual input is done via the input controller's consume_input
  167552. * method.
  167553. */
  167554. GLOBAL(int)
  167555. jpeg_consume_input (j_decompress_ptr cinfo)
  167556. {
  167557. int retcode = JPEG_SUSPENDED;
  167558. /* NB: every possible DSTATE value should be listed in this switch */
  167559. switch (cinfo->global_state) {
  167560. case DSTATE_START:
  167561. /* Start-of-datastream actions: reset appropriate modules */
  167562. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167563. /* Initialize application's data source module */
  167564. (*cinfo->src->init_source) (cinfo);
  167565. cinfo->global_state = DSTATE_INHEADER;
  167566. /*FALLTHROUGH*/
  167567. case DSTATE_INHEADER:
  167568. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167569. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167570. /* Set up default parameters based on header data */
  167571. default_decompress_parms(cinfo);
  167572. /* Set global state: ready for start_decompress */
  167573. cinfo->global_state = DSTATE_READY;
  167574. }
  167575. break;
  167576. case DSTATE_READY:
  167577. /* Can't advance past first SOS until start_decompress is called */
  167578. retcode = JPEG_REACHED_SOS;
  167579. break;
  167580. case DSTATE_PRELOAD:
  167581. case DSTATE_PRESCAN:
  167582. case DSTATE_SCANNING:
  167583. case DSTATE_RAW_OK:
  167584. case DSTATE_BUFIMAGE:
  167585. case DSTATE_BUFPOST:
  167586. case DSTATE_STOPPING:
  167587. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167588. break;
  167589. default:
  167590. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167591. }
  167592. return retcode;
  167593. }
  167594. /*
  167595. * Have we finished reading the input file?
  167596. */
  167597. GLOBAL(boolean)
  167598. jpeg_input_complete (j_decompress_ptr cinfo)
  167599. {
  167600. /* Check for valid jpeg object */
  167601. if (cinfo->global_state < DSTATE_START ||
  167602. cinfo->global_state > DSTATE_STOPPING)
  167603. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167604. return cinfo->inputctl->eoi_reached;
  167605. }
  167606. /*
  167607. * Is there more than one scan?
  167608. */
  167609. GLOBAL(boolean)
  167610. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167611. {
  167612. /* Only valid after jpeg_read_header completes */
  167613. if (cinfo->global_state < DSTATE_READY ||
  167614. cinfo->global_state > DSTATE_STOPPING)
  167615. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167616. return cinfo->inputctl->has_multiple_scans;
  167617. }
  167618. /*
  167619. * Finish JPEG decompression.
  167620. *
  167621. * This will normally just verify the file trailer and release temp storage.
  167622. *
  167623. * Returns FALSE if suspended. The return value need be inspected only if
  167624. * a suspending data source is used.
  167625. */
  167626. GLOBAL(boolean)
  167627. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167628. {
  167629. if ((cinfo->global_state == DSTATE_SCANNING ||
  167630. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167631. /* Terminate final pass of non-buffered mode */
  167632. if (cinfo->output_scanline < cinfo->output_height)
  167633. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167634. (*cinfo->master->finish_output_pass) (cinfo);
  167635. cinfo->global_state = DSTATE_STOPPING;
  167636. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167637. /* Finishing after a buffered-image operation */
  167638. cinfo->global_state = DSTATE_STOPPING;
  167639. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167640. /* STOPPING = repeat call after a suspension, anything else is error */
  167641. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167642. }
  167643. /* Read until EOI */
  167644. while (! cinfo->inputctl->eoi_reached) {
  167645. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167646. return FALSE; /* Suspend, come back later */
  167647. }
  167648. /* Do final cleanup */
  167649. (*cinfo->src->term_source) (cinfo);
  167650. /* We can use jpeg_abort to release memory and reset global_state */
  167651. jpeg_abort((j_common_ptr) cinfo);
  167652. return TRUE;
  167653. }
  167654. /*** End of inlined file: jdapimin.c ***/
  167655. /*** Start of inlined file: jdatasrc.c ***/
  167656. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167657. /*** Start of inlined file: jerror.h ***/
  167658. /*
  167659. * To define the enum list of message codes, include this file without
  167660. * defining macro JMESSAGE. To create a message string table, include it
  167661. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167662. */
  167663. #ifndef JMESSAGE
  167664. #ifndef JERROR_H
  167665. /* First time through, define the enum list */
  167666. #define JMAKE_ENUM_LIST
  167667. #else
  167668. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167669. #define JMESSAGE(code,string)
  167670. #endif /* JERROR_H */
  167671. #endif /* JMESSAGE */
  167672. #ifdef JMAKE_ENUM_LIST
  167673. typedef enum {
  167674. #define JMESSAGE(code,string) code ,
  167675. #endif /* JMAKE_ENUM_LIST */
  167676. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167677. /* For maintenance convenience, list is alphabetical by message code name */
  167678. JMESSAGE(JERR_ARITH_NOTIMPL,
  167679. "Sorry, there are legal restrictions on arithmetic coding")
  167680. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167681. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167682. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167683. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167684. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167685. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167686. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167687. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167688. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167689. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167690. JMESSAGE(JERR_BAD_LIB_VERSION,
  167691. "Wrong JPEG library version: library is %d, caller expects %d")
  167692. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167693. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167694. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167695. JMESSAGE(JERR_BAD_PROGRESSION,
  167696. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167697. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167698. "Invalid progressive parameters at scan script entry %d")
  167699. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167700. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167701. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167702. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167703. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167704. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167705. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167706. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167707. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167708. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167709. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167710. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167711. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167712. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167713. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167714. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167715. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167716. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167717. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167718. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167719. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167720. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167721. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167722. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167723. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167724. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167725. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167726. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167727. "Cannot transcode due to multiple use of quantization table %d")
  167728. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167729. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167730. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167731. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167732. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167733. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167734. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167735. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167736. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167737. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167738. JMESSAGE(JERR_QUANT_COMPONENTS,
  167739. "Cannot quantize more than %d color components")
  167740. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167741. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167742. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167743. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167744. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167745. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167746. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167747. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167748. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167749. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167750. JMESSAGE(JERR_TFILE_WRITE,
  167751. "Write failed on temporary file --- out of disk space?")
  167752. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167753. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167754. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167755. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167756. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167757. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167758. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167759. JMESSAGE(JMSG_VERSION, JVERSION)
  167760. JMESSAGE(JTRC_16BIT_TABLES,
  167761. "Caution: quantization tables are too coarse for baseline JPEG")
  167762. JMESSAGE(JTRC_ADOBE,
  167763. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167764. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167765. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167766. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167767. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167768. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167769. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167770. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167771. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167772. JMESSAGE(JTRC_EOI, "End Of Image")
  167773. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167774. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167775. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167776. "Warning: thumbnail image size does not match data length %u")
  167777. JMESSAGE(JTRC_JFIF_EXTENSION,
  167778. "JFIF extension marker: type 0x%02x, length %u")
  167779. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167780. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167781. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167782. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167783. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167784. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167785. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167786. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167787. JMESSAGE(JTRC_RST, "RST%d")
  167788. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167789. "Smoothing not supported with nonstandard sampling ratios")
  167790. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167791. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167792. JMESSAGE(JTRC_SOI, "Start of Image")
  167793. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167794. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167795. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167796. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167797. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167798. JMESSAGE(JTRC_THUMB_JPEG,
  167799. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167800. JMESSAGE(JTRC_THUMB_PALETTE,
  167801. "JFIF extension marker: palette thumbnail image, length %u")
  167802. JMESSAGE(JTRC_THUMB_RGB,
  167803. "JFIF extension marker: RGB thumbnail image, length %u")
  167804. JMESSAGE(JTRC_UNKNOWN_IDS,
  167805. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167806. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167807. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167808. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167809. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167810. "Inconsistent progression sequence for component %d coefficient %d")
  167811. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167812. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167813. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167814. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167815. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167816. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167817. JMESSAGE(JWRN_MUST_RESYNC,
  167818. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167819. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167820. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167821. #ifdef JMAKE_ENUM_LIST
  167822. JMSG_LASTMSGCODE
  167823. } J_MESSAGE_CODE;
  167824. #undef JMAKE_ENUM_LIST
  167825. #endif /* JMAKE_ENUM_LIST */
  167826. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167827. #undef JMESSAGE
  167828. #ifndef JERROR_H
  167829. #define JERROR_H
  167830. /* Macros to simplify using the error and trace message stuff */
  167831. /* The first parameter is either type of cinfo pointer */
  167832. /* Fatal errors (print message and exit) */
  167833. #define ERREXIT(cinfo,code) \
  167834. ((cinfo)->err->msg_code = (code), \
  167835. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167836. #define ERREXIT1(cinfo,code,p1) \
  167837. ((cinfo)->err->msg_code = (code), \
  167838. (cinfo)->err->msg_parm.i[0] = (p1), \
  167839. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167840. #define ERREXIT2(cinfo,code,p1,p2) \
  167841. ((cinfo)->err->msg_code = (code), \
  167842. (cinfo)->err->msg_parm.i[0] = (p1), \
  167843. (cinfo)->err->msg_parm.i[1] = (p2), \
  167844. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167845. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167846. ((cinfo)->err->msg_code = (code), \
  167847. (cinfo)->err->msg_parm.i[0] = (p1), \
  167848. (cinfo)->err->msg_parm.i[1] = (p2), \
  167849. (cinfo)->err->msg_parm.i[2] = (p3), \
  167850. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167851. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167852. ((cinfo)->err->msg_code = (code), \
  167853. (cinfo)->err->msg_parm.i[0] = (p1), \
  167854. (cinfo)->err->msg_parm.i[1] = (p2), \
  167855. (cinfo)->err->msg_parm.i[2] = (p3), \
  167856. (cinfo)->err->msg_parm.i[3] = (p4), \
  167857. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167858. #define ERREXITS(cinfo,code,str) \
  167859. ((cinfo)->err->msg_code = (code), \
  167860. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167861. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167862. #define MAKESTMT(stuff) do { stuff } while (0)
  167863. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167864. #define WARNMS(cinfo,code) \
  167865. ((cinfo)->err->msg_code = (code), \
  167866. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167867. #define WARNMS1(cinfo,code,p1) \
  167868. ((cinfo)->err->msg_code = (code), \
  167869. (cinfo)->err->msg_parm.i[0] = (p1), \
  167870. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167871. #define WARNMS2(cinfo,code,p1,p2) \
  167872. ((cinfo)->err->msg_code = (code), \
  167873. (cinfo)->err->msg_parm.i[0] = (p1), \
  167874. (cinfo)->err->msg_parm.i[1] = (p2), \
  167875. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167876. /* Informational/debugging messages */
  167877. #define TRACEMS(cinfo,lvl,code) \
  167878. ((cinfo)->err->msg_code = (code), \
  167879. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167880. #define TRACEMS1(cinfo,lvl,code,p1) \
  167881. ((cinfo)->err->msg_code = (code), \
  167882. (cinfo)->err->msg_parm.i[0] = (p1), \
  167883. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167884. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167885. ((cinfo)->err->msg_code = (code), \
  167886. (cinfo)->err->msg_parm.i[0] = (p1), \
  167887. (cinfo)->err->msg_parm.i[1] = (p2), \
  167888. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167889. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167890. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167891. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167892. (cinfo)->err->msg_code = (code); \
  167893. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167894. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167895. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167896. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167897. (cinfo)->err->msg_code = (code); \
  167898. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167899. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167900. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167901. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167902. _mp[4] = (p5); \
  167903. (cinfo)->err->msg_code = (code); \
  167904. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167905. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167906. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167907. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167908. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167909. (cinfo)->err->msg_code = (code); \
  167910. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167911. #define TRACEMSS(cinfo,lvl,code,str) \
  167912. ((cinfo)->err->msg_code = (code), \
  167913. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167914. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167915. #endif /* JERROR_H */
  167916. /*** End of inlined file: jerror.h ***/
  167917. /* Expanded data source object for stdio input */
  167918. typedef struct {
  167919. struct jpeg_source_mgr pub; /* public fields */
  167920. FILE * infile; /* source stream */
  167921. JOCTET * buffer; /* start of buffer */
  167922. boolean start_of_file; /* have we gotten any data yet? */
  167923. } my_source_mgr;
  167924. typedef my_source_mgr * my_src_ptr;
  167925. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167926. /*
  167927. * Initialize source --- called by jpeg_read_header
  167928. * before any data is actually read.
  167929. */
  167930. METHODDEF(void)
  167931. init_source (j_decompress_ptr cinfo)
  167932. {
  167933. my_src_ptr src = (my_src_ptr) cinfo->src;
  167934. /* We reset the empty-input-file flag for each image,
  167935. * but we don't clear the input buffer.
  167936. * This is correct behavior for reading a series of images from one source.
  167937. */
  167938. src->start_of_file = TRUE;
  167939. }
  167940. /*
  167941. * Fill the input buffer --- called whenever buffer is emptied.
  167942. *
  167943. * In typical applications, this should read fresh data into the buffer
  167944. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167945. * reset the pointer & count to the start of the buffer, and return TRUE
  167946. * indicating that the buffer has been reloaded. It is not necessary to
  167947. * fill the buffer entirely, only to obtain at least one more byte.
  167948. *
  167949. * There is no such thing as an EOF return. If the end of the file has been
  167950. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167951. * the buffer. In most cases, generating a warning message and inserting a
  167952. * fake EOI marker is the best course of action --- this will allow the
  167953. * decompressor to output however much of the image is there. However,
  167954. * the resulting error message is misleading if the real problem is an empty
  167955. * input file, so we handle that case specially.
  167956. *
  167957. * In applications that need to be able to suspend compression due to input
  167958. * not being available yet, a FALSE return indicates that no more data can be
  167959. * obtained right now, but more may be forthcoming later. In this situation,
  167960. * the decompressor will return to its caller (with an indication of the
  167961. * number of scanlines it has read, if any). The application should resume
  167962. * decompression after it has loaded more data into the input buffer. Note
  167963. * that there are substantial restrictions on the use of suspension --- see
  167964. * the documentation.
  167965. *
  167966. * When suspending, the decompressor will back up to a convenient restart point
  167967. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167968. * indicate where the restart point will be if the current call returns FALSE.
  167969. * Data beyond this point must be rescanned after resumption, so move it to
  167970. * the front of the buffer rather than discarding it.
  167971. */
  167972. METHODDEF(boolean)
  167973. fill_input_buffer (j_decompress_ptr cinfo)
  167974. {
  167975. my_src_ptr src = (my_src_ptr) cinfo->src;
  167976. size_t nbytes;
  167977. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167978. if (nbytes <= 0) {
  167979. if (src->start_of_file) /* Treat empty input file as fatal error */
  167980. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167981. WARNMS(cinfo, JWRN_JPEG_EOF);
  167982. /* Insert a fake EOI marker */
  167983. src->buffer[0] = (JOCTET) 0xFF;
  167984. src->buffer[1] = (JOCTET) JPEG_EOI;
  167985. nbytes = 2;
  167986. }
  167987. src->pub.next_input_byte = src->buffer;
  167988. src->pub.bytes_in_buffer = nbytes;
  167989. src->start_of_file = FALSE;
  167990. return TRUE;
  167991. }
  167992. /*
  167993. * Skip data --- used to skip over a potentially large amount of
  167994. * uninteresting data (such as an APPn marker).
  167995. *
  167996. * Writers of suspendable-input applications must note that skip_input_data
  167997. * is not granted the right to give a suspension return. If the skip extends
  167998. * beyond the data currently in the buffer, the buffer can be marked empty so
  167999. * that the next read will cause a fill_input_buffer call that can suspend.
  168000. * Arranging for additional bytes to be discarded before reloading the input
  168001. * buffer is the application writer's problem.
  168002. */
  168003. METHODDEF(void)
  168004. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168005. {
  168006. my_src_ptr src = (my_src_ptr) cinfo->src;
  168007. /* Just a dumb implementation for now. Could use fseek() except
  168008. * it doesn't work on pipes. Not clear that being smart is worth
  168009. * any trouble anyway --- large skips are infrequent.
  168010. */
  168011. if (num_bytes > 0) {
  168012. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168013. num_bytes -= (long) src->pub.bytes_in_buffer;
  168014. (void) fill_input_buffer(cinfo);
  168015. /* note we assume that fill_input_buffer will never return FALSE,
  168016. * so suspension need not be handled.
  168017. */
  168018. }
  168019. src->pub.next_input_byte += (size_t) num_bytes;
  168020. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168021. }
  168022. }
  168023. /*
  168024. * An additional method that can be provided by data source modules is the
  168025. * resync_to_restart method for error recovery in the presence of RST markers.
  168026. * For the moment, this source module just uses the default resync method
  168027. * provided by the JPEG library. That method assumes that no backtracking
  168028. * is possible.
  168029. */
  168030. /*
  168031. * Terminate source --- called by jpeg_finish_decompress
  168032. * after all data has been read. Often a no-op.
  168033. *
  168034. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168035. * application must deal with any cleanup that should happen even
  168036. * for error exit.
  168037. */
  168038. METHODDEF(void)
  168039. term_source (j_decompress_ptr)
  168040. {
  168041. /* no work necessary here */
  168042. }
  168043. /*
  168044. * Prepare for input from a stdio stream.
  168045. * The caller must have already opened the stream, and is responsible
  168046. * for closing it after finishing decompression.
  168047. */
  168048. GLOBAL(void)
  168049. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168050. {
  168051. my_src_ptr src;
  168052. /* The source object and input buffer are made permanent so that a series
  168053. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168054. * only before the first one. (If we discarded the buffer at the end of
  168055. * one image, we'd likely lose the start of the next one.)
  168056. * This makes it unsafe to use this manager and a different source
  168057. * manager serially with the same JPEG object. Caveat programmer.
  168058. */
  168059. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168060. cinfo->src = (struct jpeg_source_mgr *)
  168061. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168062. SIZEOF(my_source_mgr));
  168063. src = (my_src_ptr) cinfo->src;
  168064. src->buffer = (JOCTET *)
  168065. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168066. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168067. }
  168068. src = (my_src_ptr) cinfo->src;
  168069. src->pub.init_source = init_source;
  168070. src->pub.fill_input_buffer = fill_input_buffer;
  168071. src->pub.skip_input_data = skip_input_data;
  168072. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168073. src->pub.term_source = term_source;
  168074. src->infile = infile;
  168075. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168076. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168077. }
  168078. /*** End of inlined file: jdatasrc.c ***/
  168079. /*** Start of inlined file: jdcoefct.c ***/
  168080. #define JPEG_INTERNALS
  168081. /* Block smoothing is only applicable for progressive JPEG, so: */
  168082. #ifndef D_PROGRESSIVE_SUPPORTED
  168083. #undef BLOCK_SMOOTHING_SUPPORTED
  168084. #endif
  168085. /* Private buffer controller object */
  168086. typedef struct {
  168087. struct jpeg_d_coef_controller pub; /* public fields */
  168088. /* These variables keep track of the current location of the input side. */
  168089. /* cinfo->input_iMCU_row is also used for this. */
  168090. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168091. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168092. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168093. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168094. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168095. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168096. * and let the entropy decoder write into that workspace each time.
  168097. * (On 80x86, the workspace is FAR even though it's not really very big;
  168098. * this is to keep the module interfaces unchanged when a large coefficient
  168099. * buffer is necessary.)
  168100. * In multi-pass modes, this array points to the current MCU's blocks
  168101. * within the virtual arrays; it is used only by the input side.
  168102. */
  168103. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168104. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168105. /* In multi-pass modes, we need a virtual block array for each component. */
  168106. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168107. #endif
  168108. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168109. /* When doing block smoothing, we latch coefficient Al values here */
  168110. int * coef_bits_latch;
  168111. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168112. #endif
  168113. } my_coef_controller3;
  168114. typedef my_coef_controller3 * my_coef_ptr3;
  168115. /* Forward declarations */
  168116. METHODDEF(int) decompress_onepass
  168117. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168118. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168119. METHODDEF(int) decompress_data
  168120. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168121. #endif
  168122. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168123. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168124. METHODDEF(int) decompress_smooth_data
  168125. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168126. #endif
  168127. LOCAL(void)
  168128. start_iMCU_row3 (j_decompress_ptr cinfo)
  168129. /* Reset within-iMCU-row counters for a new row (input side) */
  168130. {
  168131. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168132. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168133. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168134. * But at the bottom of the image, process only what's left.
  168135. */
  168136. if (cinfo->comps_in_scan > 1) {
  168137. coef->MCU_rows_per_iMCU_row = 1;
  168138. } else {
  168139. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168140. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168141. else
  168142. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168143. }
  168144. coef->MCU_ctr = 0;
  168145. coef->MCU_vert_offset = 0;
  168146. }
  168147. /*
  168148. * Initialize for an input processing pass.
  168149. */
  168150. METHODDEF(void)
  168151. start_input_pass (j_decompress_ptr cinfo)
  168152. {
  168153. cinfo->input_iMCU_row = 0;
  168154. start_iMCU_row3(cinfo);
  168155. }
  168156. /*
  168157. * Initialize for an output processing pass.
  168158. */
  168159. METHODDEF(void)
  168160. start_output_pass (j_decompress_ptr cinfo)
  168161. {
  168162. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168163. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168164. /* If multipass, check to see whether to use block smoothing on this pass */
  168165. if (coef->pub.coef_arrays != NULL) {
  168166. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168167. coef->pub.decompress_data = decompress_smooth_data;
  168168. else
  168169. coef->pub.decompress_data = decompress_data;
  168170. }
  168171. #endif
  168172. cinfo->output_iMCU_row = 0;
  168173. }
  168174. /*
  168175. * Decompress and return some data in the single-pass case.
  168176. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168177. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168178. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168179. *
  168180. * NB: output_buf contains a plane for each component in image,
  168181. * which we index according to the component's SOF position.
  168182. */
  168183. METHODDEF(int)
  168184. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168185. {
  168186. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168187. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168188. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168189. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168190. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168191. JSAMPARRAY output_ptr;
  168192. JDIMENSION start_col, output_col;
  168193. jpeg_component_info *compptr;
  168194. inverse_DCT_method_ptr inverse_DCT;
  168195. /* Loop to process as much as one whole iMCU row */
  168196. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168197. yoffset++) {
  168198. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168199. MCU_col_num++) {
  168200. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168201. jzero_far((void FAR *) coef->MCU_buffer[0],
  168202. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168203. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168204. /* Suspension forced; update state counters and exit */
  168205. coef->MCU_vert_offset = yoffset;
  168206. coef->MCU_ctr = MCU_col_num;
  168207. return JPEG_SUSPENDED;
  168208. }
  168209. /* Determine where data should go in output_buf and do the IDCT thing.
  168210. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168211. * incremented past them!). Note the inner loop relies on having
  168212. * allocated the MCU_buffer[] blocks sequentially.
  168213. */
  168214. blkn = 0; /* index of current DCT block within MCU */
  168215. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168216. compptr = cinfo->cur_comp_info[ci];
  168217. /* Don't bother to IDCT an uninteresting component. */
  168218. if (! compptr->component_needed) {
  168219. blkn += compptr->MCU_blocks;
  168220. continue;
  168221. }
  168222. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168223. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168224. : compptr->last_col_width;
  168225. output_ptr = output_buf[compptr->component_index] +
  168226. yoffset * compptr->DCT_scaled_size;
  168227. start_col = MCU_col_num * compptr->MCU_sample_width;
  168228. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168229. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168230. yoffset+yindex < compptr->last_row_height) {
  168231. output_col = start_col;
  168232. for (xindex = 0; xindex < useful_width; xindex++) {
  168233. (*inverse_DCT) (cinfo, compptr,
  168234. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168235. output_ptr, output_col);
  168236. output_col += compptr->DCT_scaled_size;
  168237. }
  168238. }
  168239. blkn += compptr->MCU_width;
  168240. output_ptr += compptr->DCT_scaled_size;
  168241. }
  168242. }
  168243. }
  168244. /* Completed an MCU row, but perhaps not an iMCU row */
  168245. coef->MCU_ctr = 0;
  168246. }
  168247. /* Completed the iMCU row, advance counters for next one */
  168248. cinfo->output_iMCU_row++;
  168249. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168250. start_iMCU_row3(cinfo);
  168251. return JPEG_ROW_COMPLETED;
  168252. }
  168253. /* Completed the scan */
  168254. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168255. return JPEG_SCAN_COMPLETED;
  168256. }
  168257. /*
  168258. * Dummy consume-input routine for single-pass operation.
  168259. */
  168260. METHODDEF(int)
  168261. dummy_consume_data (j_decompress_ptr)
  168262. {
  168263. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168264. }
  168265. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168266. /*
  168267. * Consume input data and store it in the full-image coefficient buffer.
  168268. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168269. * ie, v_samp_factor block rows for each component in the scan.
  168270. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168271. */
  168272. METHODDEF(int)
  168273. consume_data (j_decompress_ptr cinfo)
  168274. {
  168275. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168276. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168277. int blkn, ci, xindex, yindex, yoffset;
  168278. JDIMENSION start_col;
  168279. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168280. JBLOCKROW buffer_ptr;
  168281. jpeg_component_info *compptr;
  168282. /* Align the virtual buffers for the components used in this scan. */
  168283. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168284. compptr = cinfo->cur_comp_info[ci];
  168285. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168286. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168287. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168288. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168289. /* Note: entropy decoder expects buffer to be zeroed,
  168290. * but this is handled automatically by the memory manager
  168291. * because we requested a pre-zeroed array.
  168292. */
  168293. }
  168294. /* Loop to process one whole iMCU row */
  168295. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168296. yoffset++) {
  168297. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168298. MCU_col_num++) {
  168299. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168300. blkn = 0; /* index of current DCT block within MCU */
  168301. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168302. compptr = cinfo->cur_comp_info[ci];
  168303. start_col = MCU_col_num * compptr->MCU_width;
  168304. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168305. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168306. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168307. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168308. }
  168309. }
  168310. }
  168311. /* Try to fetch the MCU. */
  168312. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168313. /* Suspension forced; update state counters and exit */
  168314. coef->MCU_vert_offset = yoffset;
  168315. coef->MCU_ctr = MCU_col_num;
  168316. return JPEG_SUSPENDED;
  168317. }
  168318. }
  168319. /* Completed an MCU row, but perhaps not an iMCU row */
  168320. coef->MCU_ctr = 0;
  168321. }
  168322. /* Completed the iMCU row, advance counters for next one */
  168323. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168324. start_iMCU_row3(cinfo);
  168325. return JPEG_ROW_COMPLETED;
  168326. }
  168327. /* Completed the scan */
  168328. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168329. return JPEG_SCAN_COMPLETED;
  168330. }
  168331. /*
  168332. * Decompress and return some data in the multi-pass case.
  168333. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168334. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168335. *
  168336. * NB: output_buf contains a plane for each component in image.
  168337. */
  168338. METHODDEF(int)
  168339. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168340. {
  168341. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168342. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168343. JDIMENSION block_num;
  168344. int ci, block_row, block_rows;
  168345. JBLOCKARRAY buffer;
  168346. JBLOCKROW buffer_ptr;
  168347. JSAMPARRAY output_ptr;
  168348. JDIMENSION output_col;
  168349. jpeg_component_info *compptr;
  168350. inverse_DCT_method_ptr inverse_DCT;
  168351. /* Force some input to be done if we are getting ahead of the input. */
  168352. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168353. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168354. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168355. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168356. return JPEG_SUSPENDED;
  168357. }
  168358. /* OK, output from the virtual arrays. */
  168359. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168360. ci++, compptr++) {
  168361. /* Don't bother to IDCT an uninteresting component. */
  168362. if (! compptr->component_needed)
  168363. continue;
  168364. /* Align the virtual buffer for this component. */
  168365. buffer = (*cinfo->mem->access_virt_barray)
  168366. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168367. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168368. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168369. /* Count non-dummy DCT block rows in this iMCU row. */
  168370. if (cinfo->output_iMCU_row < last_iMCU_row)
  168371. block_rows = compptr->v_samp_factor;
  168372. else {
  168373. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168374. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168375. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168376. }
  168377. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168378. output_ptr = output_buf[ci];
  168379. /* Loop over all DCT blocks to be processed. */
  168380. for (block_row = 0; block_row < block_rows; block_row++) {
  168381. buffer_ptr = buffer[block_row];
  168382. output_col = 0;
  168383. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168384. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168385. output_ptr, output_col);
  168386. buffer_ptr++;
  168387. output_col += compptr->DCT_scaled_size;
  168388. }
  168389. output_ptr += compptr->DCT_scaled_size;
  168390. }
  168391. }
  168392. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168393. return JPEG_ROW_COMPLETED;
  168394. return JPEG_SCAN_COMPLETED;
  168395. }
  168396. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168397. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168398. /*
  168399. * This code applies interblock smoothing as described by section K.8
  168400. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168401. * the DC values of a DCT block and its 8 neighboring blocks.
  168402. * We apply smoothing only for progressive JPEG decoding, and only if
  168403. * the coefficients it can estimate are not yet known to full precision.
  168404. */
  168405. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168406. #define Q01_POS 1
  168407. #define Q10_POS 8
  168408. #define Q20_POS 16
  168409. #define Q11_POS 9
  168410. #define Q02_POS 2
  168411. /*
  168412. * Determine whether block smoothing is applicable and safe.
  168413. * We also latch the current states of the coef_bits[] entries for the
  168414. * AC coefficients; otherwise, if the input side of the decompressor
  168415. * advances into a new scan, we might think the coefficients are known
  168416. * more accurately than they really are.
  168417. */
  168418. LOCAL(boolean)
  168419. smoothing_ok (j_decompress_ptr cinfo)
  168420. {
  168421. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168422. boolean smoothing_useful = FALSE;
  168423. int ci, coefi;
  168424. jpeg_component_info *compptr;
  168425. JQUANT_TBL * qtable;
  168426. int * coef_bits;
  168427. int * coef_bits_latch;
  168428. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168429. return FALSE;
  168430. /* Allocate latch area if not already done */
  168431. if (coef->coef_bits_latch == NULL)
  168432. coef->coef_bits_latch = (int *)
  168433. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168434. cinfo->num_components *
  168435. (SAVED_COEFS * SIZEOF(int)));
  168436. coef_bits_latch = coef->coef_bits_latch;
  168437. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168438. ci++, compptr++) {
  168439. /* All components' quantization values must already be latched. */
  168440. if ((qtable = compptr->quant_table) == NULL)
  168441. return FALSE;
  168442. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168443. if (qtable->quantval[0] == 0 ||
  168444. qtable->quantval[Q01_POS] == 0 ||
  168445. qtable->quantval[Q10_POS] == 0 ||
  168446. qtable->quantval[Q20_POS] == 0 ||
  168447. qtable->quantval[Q11_POS] == 0 ||
  168448. qtable->quantval[Q02_POS] == 0)
  168449. return FALSE;
  168450. /* DC values must be at least partly known for all components. */
  168451. coef_bits = cinfo->coef_bits[ci];
  168452. if (coef_bits[0] < 0)
  168453. return FALSE;
  168454. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168455. for (coefi = 1; coefi <= 5; coefi++) {
  168456. coef_bits_latch[coefi] = coef_bits[coefi];
  168457. if (coef_bits[coefi] != 0)
  168458. smoothing_useful = TRUE;
  168459. }
  168460. coef_bits_latch += SAVED_COEFS;
  168461. }
  168462. return smoothing_useful;
  168463. }
  168464. /*
  168465. * Variant of decompress_data for use when doing block smoothing.
  168466. */
  168467. METHODDEF(int)
  168468. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168469. {
  168470. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168471. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168472. JDIMENSION block_num, last_block_column;
  168473. int ci, block_row, block_rows, access_rows;
  168474. JBLOCKARRAY buffer;
  168475. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168476. JSAMPARRAY output_ptr;
  168477. JDIMENSION output_col;
  168478. jpeg_component_info *compptr;
  168479. inverse_DCT_method_ptr inverse_DCT;
  168480. boolean first_row, last_row;
  168481. JBLOCK workspace;
  168482. int *coef_bits;
  168483. JQUANT_TBL *quanttbl;
  168484. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168485. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168486. int Al, pred;
  168487. /* Force some input to be done if we are getting ahead of the input. */
  168488. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168489. ! cinfo->inputctl->eoi_reached) {
  168490. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168491. /* If input is working on current scan, we ordinarily want it to
  168492. * have completed the current row. But if input scan is DC,
  168493. * we want it to keep one row ahead so that next block row's DC
  168494. * values are up to date.
  168495. */
  168496. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168497. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168498. break;
  168499. }
  168500. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168501. return JPEG_SUSPENDED;
  168502. }
  168503. /* OK, output from the virtual arrays. */
  168504. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168505. ci++, compptr++) {
  168506. /* Don't bother to IDCT an uninteresting component. */
  168507. if (! compptr->component_needed)
  168508. continue;
  168509. /* Count non-dummy DCT block rows in this iMCU row. */
  168510. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168511. block_rows = compptr->v_samp_factor;
  168512. access_rows = block_rows * 2; /* this and next iMCU row */
  168513. last_row = FALSE;
  168514. } else {
  168515. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168516. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168517. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168518. access_rows = block_rows; /* this iMCU row only */
  168519. last_row = TRUE;
  168520. }
  168521. /* Align the virtual buffer for this component. */
  168522. if (cinfo->output_iMCU_row > 0) {
  168523. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168524. buffer = (*cinfo->mem->access_virt_barray)
  168525. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168526. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168527. (JDIMENSION) access_rows, FALSE);
  168528. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168529. first_row = FALSE;
  168530. } else {
  168531. buffer = (*cinfo->mem->access_virt_barray)
  168532. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168533. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168534. first_row = TRUE;
  168535. }
  168536. /* Fetch component-dependent info */
  168537. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168538. quanttbl = compptr->quant_table;
  168539. Q00 = quanttbl->quantval[0];
  168540. Q01 = quanttbl->quantval[Q01_POS];
  168541. Q10 = quanttbl->quantval[Q10_POS];
  168542. Q20 = quanttbl->quantval[Q20_POS];
  168543. Q11 = quanttbl->quantval[Q11_POS];
  168544. Q02 = quanttbl->quantval[Q02_POS];
  168545. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168546. output_ptr = output_buf[ci];
  168547. /* Loop over all DCT blocks to be processed. */
  168548. for (block_row = 0; block_row < block_rows; block_row++) {
  168549. buffer_ptr = buffer[block_row];
  168550. if (first_row && block_row == 0)
  168551. prev_block_row = buffer_ptr;
  168552. else
  168553. prev_block_row = buffer[block_row-1];
  168554. if (last_row && block_row == block_rows-1)
  168555. next_block_row = buffer_ptr;
  168556. else
  168557. next_block_row = buffer[block_row+1];
  168558. /* We fetch the surrounding DC values using a sliding-register approach.
  168559. * Initialize all nine here so as to do the right thing on narrow pics.
  168560. */
  168561. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168562. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168563. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168564. output_col = 0;
  168565. last_block_column = compptr->width_in_blocks - 1;
  168566. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168567. /* Fetch current DCT block into workspace so we can modify it. */
  168568. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168569. /* Update DC values */
  168570. if (block_num < last_block_column) {
  168571. DC3 = (int) prev_block_row[1][0];
  168572. DC6 = (int) buffer_ptr[1][0];
  168573. DC9 = (int) next_block_row[1][0];
  168574. }
  168575. /* Compute coefficient estimates per K.8.
  168576. * An estimate is applied only if coefficient is still zero,
  168577. * and is not known to be fully accurate.
  168578. */
  168579. /* AC01 */
  168580. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168581. num = 36 * Q00 * (DC4 - DC6);
  168582. if (num >= 0) {
  168583. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168584. if (Al > 0 && pred >= (1<<Al))
  168585. pred = (1<<Al)-1;
  168586. } else {
  168587. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168588. if (Al > 0 && pred >= (1<<Al))
  168589. pred = (1<<Al)-1;
  168590. pred = -pred;
  168591. }
  168592. workspace[1] = (JCOEF) pred;
  168593. }
  168594. /* AC10 */
  168595. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168596. num = 36 * Q00 * (DC2 - DC8);
  168597. if (num >= 0) {
  168598. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168599. if (Al > 0 && pred >= (1<<Al))
  168600. pred = (1<<Al)-1;
  168601. } else {
  168602. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168603. if (Al > 0 && pred >= (1<<Al))
  168604. pred = (1<<Al)-1;
  168605. pred = -pred;
  168606. }
  168607. workspace[8] = (JCOEF) pred;
  168608. }
  168609. /* AC20 */
  168610. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168611. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168612. if (num >= 0) {
  168613. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168614. if (Al > 0 && pred >= (1<<Al))
  168615. pred = (1<<Al)-1;
  168616. } else {
  168617. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168618. if (Al > 0 && pred >= (1<<Al))
  168619. pred = (1<<Al)-1;
  168620. pred = -pred;
  168621. }
  168622. workspace[16] = (JCOEF) pred;
  168623. }
  168624. /* AC11 */
  168625. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168626. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168627. if (num >= 0) {
  168628. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168629. if (Al > 0 && pred >= (1<<Al))
  168630. pred = (1<<Al)-1;
  168631. } else {
  168632. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168633. if (Al > 0 && pred >= (1<<Al))
  168634. pred = (1<<Al)-1;
  168635. pred = -pred;
  168636. }
  168637. workspace[9] = (JCOEF) pred;
  168638. }
  168639. /* AC02 */
  168640. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168641. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168642. if (num >= 0) {
  168643. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168644. if (Al > 0 && pred >= (1<<Al))
  168645. pred = (1<<Al)-1;
  168646. } else {
  168647. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168648. if (Al > 0 && pred >= (1<<Al))
  168649. pred = (1<<Al)-1;
  168650. pred = -pred;
  168651. }
  168652. workspace[2] = (JCOEF) pred;
  168653. }
  168654. /* OK, do the IDCT */
  168655. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168656. output_ptr, output_col);
  168657. /* Advance for next column */
  168658. DC1 = DC2; DC2 = DC3;
  168659. DC4 = DC5; DC5 = DC6;
  168660. DC7 = DC8; DC8 = DC9;
  168661. buffer_ptr++, prev_block_row++, next_block_row++;
  168662. output_col += compptr->DCT_scaled_size;
  168663. }
  168664. output_ptr += compptr->DCT_scaled_size;
  168665. }
  168666. }
  168667. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168668. return JPEG_ROW_COMPLETED;
  168669. return JPEG_SCAN_COMPLETED;
  168670. }
  168671. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168672. /*
  168673. * Initialize coefficient buffer controller.
  168674. */
  168675. GLOBAL(void)
  168676. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168677. {
  168678. my_coef_ptr3 coef;
  168679. coef = (my_coef_ptr3)
  168680. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168681. SIZEOF(my_coef_controller3));
  168682. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168683. coef->pub.start_input_pass = start_input_pass;
  168684. coef->pub.start_output_pass = start_output_pass;
  168685. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168686. coef->coef_bits_latch = NULL;
  168687. #endif
  168688. /* Create the coefficient buffer. */
  168689. if (need_full_buffer) {
  168690. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168691. /* Allocate a full-image virtual array for each component, */
  168692. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168693. /* Note we ask for a pre-zeroed array. */
  168694. int ci, access_rows;
  168695. jpeg_component_info *compptr;
  168696. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168697. ci++, compptr++) {
  168698. access_rows = compptr->v_samp_factor;
  168699. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168700. /* If block smoothing could be used, need a bigger window */
  168701. if (cinfo->progressive_mode)
  168702. access_rows *= 3;
  168703. #endif
  168704. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168705. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168706. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168707. (long) compptr->h_samp_factor),
  168708. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168709. (long) compptr->v_samp_factor),
  168710. (JDIMENSION) access_rows);
  168711. }
  168712. coef->pub.consume_data = consume_data;
  168713. coef->pub.decompress_data = decompress_data;
  168714. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168715. #else
  168716. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168717. #endif
  168718. } else {
  168719. /* We only need a single-MCU buffer. */
  168720. JBLOCKROW buffer;
  168721. int i;
  168722. buffer = (JBLOCKROW)
  168723. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168724. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168725. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168726. coef->MCU_buffer[i] = buffer + i;
  168727. }
  168728. coef->pub.consume_data = dummy_consume_data;
  168729. coef->pub.decompress_data = decompress_onepass;
  168730. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168731. }
  168732. }
  168733. /*** End of inlined file: jdcoefct.c ***/
  168734. #undef FIX
  168735. /*** Start of inlined file: jdcolor.c ***/
  168736. #define JPEG_INTERNALS
  168737. /* Private subobject */
  168738. typedef struct {
  168739. struct jpeg_color_deconverter pub; /* public fields */
  168740. /* Private state for YCC->RGB conversion */
  168741. int * Cr_r_tab; /* => table for Cr to R conversion */
  168742. int * Cb_b_tab; /* => table for Cb to B conversion */
  168743. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168744. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168745. } my_color_deconverter2;
  168746. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168747. /**************** YCbCr -> RGB conversion: most common case **************/
  168748. /*
  168749. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168750. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168751. * The conversion equations to be implemented are therefore
  168752. * R = Y + 1.40200 * Cr
  168753. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168754. * B = Y + 1.77200 * Cb
  168755. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168756. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168757. *
  168758. * To avoid floating-point arithmetic, we represent the fractional constants
  168759. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168760. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168761. * Notice that Y, being an integral input, does not contribute any fraction
  168762. * so it need not participate in the rounding.
  168763. *
  168764. * For even more speed, we avoid doing any multiplications in the inner loop
  168765. * by precalculating the constants times Cb and Cr for all possible values.
  168766. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168767. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168768. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168769. * colorspace anyway.
  168770. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168771. * values for the G calculation are left scaled up, since we must add them
  168772. * together before rounding.
  168773. */
  168774. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168775. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168776. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168777. /*
  168778. * Initialize tables for YCC->RGB colorspace conversion.
  168779. */
  168780. LOCAL(void)
  168781. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168782. {
  168783. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168784. int i;
  168785. INT32 x;
  168786. SHIFT_TEMPS
  168787. cconvert->Cr_r_tab = (int *)
  168788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168789. (MAXJSAMPLE+1) * SIZEOF(int));
  168790. cconvert->Cb_b_tab = (int *)
  168791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168792. (MAXJSAMPLE+1) * SIZEOF(int));
  168793. cconvert->Cr_g_tab = (INT32 *)
  168794. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168795. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168796. cconvert->Cb_g_tab = (INT32 *)
  168797. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168798. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168799. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168800. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168801. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168802. /* Cr=>R value is nearest int to 1.40200 * x */
  168803. cconvert->Cr_r_tab[i] = (int)
  168804. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168805. /* Cb=>B value is nearest int to 1.77200 * x */
  168806. cconvert->Cb_b_tab[i] = (int)
  168807. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168808. /* Cr=>G value is scaled-up -0.71414 * x */
  168809. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168810. /* Cb=>G value is scaled-up -0.34414 * x */
  168811. /* We also add in ONE_HALF so that need not do it in inner loop */
  168812. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168813. }
  168814. }
  168815. /*
  168816. * Convert some rows of samples to the output colorspace.
  168817. *
  168818. * Note that we change from noninterleaved, one-plane-per-component format
  168819. * to interleaved-pixel format. The output buffer is therefore three times
  168820. * as wide as the input buffer.
  168821. * A starting row offset is provided only for the input buffer. The caller
  168822. * can easily adjust the passed output_buf value to accommodate any row
  168823. * offset required on that side.
  168824. */
  168825. METHODDEF(void)
  168826. ycc_rgb_convert (j_decompress_ptr cinfo,
  168827. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168828. JSAMPARRAY output_buf, int num_rows)
  168829. {
  168830. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168831. register int y, cb, cr;
  168832. register JSAMPROW outptr;
  168833. register JSAMPROW inptr0, inptr1, inptr2;
  168834. register JDIMENSION col;
  168835. JDIMENSION num_cols = cinfo->output_width;
  168836. /* copy these pointers into registers if possible */
  168837. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168838. register int * Crrtab = cconvert->Cr_r_tab;
  168839. register int * Cbbtab = cconvert->Cb_b_tab;
  168840. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168841. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168842. SHIFT_TEMPS
  168843. while (--num_rows >= 0) {
  168844. inptr0 = input_buf[0][input_row];
  168845. inptr1 = input_buf[1][input_row];
  168846. inptr2 = input_buf[2][input_row];
  168847. input_row++;
  168848. outptr = *output_buf++;
  168849. for (col = 0; col < num_cols; col++) {
  168850. y = GETJSAMPLE(inptr0[col]);
  168851. cb = GETJSAMPLE(inptr1[col]);
  168852. cr = GETJSAMPLE(inptr2[col]);
  168853. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168854. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168855. outptr[RGB_GREEN] = range_limit[y +
  168856. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168857. SCALEBITS))];
  168858. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168859. outptr += RGB_PIXELSIZE;
  168860. }
  168861. }
  168862. }
  168863. /**************** Cases other than YCbCr -> RGB **************/
  168864. /*
  168865. * Color conversion for no colorspace change: just copy the data,
  168866. * converting from separate-planes to interleaved representation.
  168867. */
  168868. METHODDEF(void)
  168869. null_convert2 (j_decompress_ptr cinfo,
  168870. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168871. JSAMPARRAY output_buf, int num_rows)
  168872. {
  168873. register JSAMPROW inptr, outptr;
  168874. register JDIMENSION count;
  168875. register int num_components = cinfo->num_components;
  168876. JDIMENSION num_cols = cinfo->output_width;
  168877. int ci;
  168878. while (--num_rows >= 0) {
  168879. for (ci = 0; ci < num_components; ci++) {
  168880. inptr = input_buf[ci][input_row];
  168881. outptr = output_buf[0] + ci;
  168882. for (count = num_cols; count > 0; count--) {
  168883. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168884. outptr += num_components;
  168885. }
  168886. }
  168887. input_row++;
  168888. output_buf++;
  168889. }
  168890. }
  168891. /*
  168892. * Color conversion for grayscale: just copy the data.
  168893. * This also works for YCbCr -> grayscale conversion, in which
  168894. * we just copy the Y (luminance) component and ignore chrominance.
  168895. */
  168896. METHODDEF(void)
  168897. grayscale_convert2 (j_decompress_ptr cinfo,
  168898. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168899. JSAMPARRAY output_buf, int num_rows)
  168900. {
  168901. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168902. num_rows, cinfo->output_width);
  168903. }
  168904. /*
  168905. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168906. * This is provided to support applications that don't want to cope
  168907. * with grayscale as a separate case.
  168908. */
  168909. METHODDEF(void)
  168910. gray_rgb_convert (j_decompress_ptr cinfo,
  168911. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168912. JSAMPARRAY output_buf, int num_rows)
  168913. {
  168914. register JSAMPROW inptr, outptr;
  168915. register JDIMENSION col;
  168916. JDIMENSION num_cols = cinfo->output_width;
  168917. while (--num_rows >= 0) {
  168918. inptr = input_buf[0][input_row++];
  168919. outptr = *output_buf++;
  168920. for (col = 0; col < num_cols; col++) {
  168921. /* We can dispense with GETJSAMPLE() here */
  168922. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168923. outptr += RGB_PIXELSIZE;
  168924. }
  168925. }
  168926. }
  168927. /*
  168928. * Adobe-style YCCK->CMYK conversion.
  168929. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168930. * conversion as above, while passing K (black) unchanged.
  168931. * We assume build_ycc_rgb_table has been called.
  168932. */
  168933. METHODDEF(void)
  168934. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168935. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168936. JSAMPARRAY output_buf, int num_rows)
  168937. {
  168938. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168939. register int y, cb, cr;
  168940. register JSAMPROW outptr;
  168941. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168942. register JDIMENSION col;
  168943. JDIMENSION num_cols = cinfo->output_width;
  168944. /* copy these pointers into registers if possible */
  168945. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168946. register int * Crrtab = cconvert->Cr_r_tab;
  168947. register int * Cbbtab = cconvert->Cb_b_tab;
  168948. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168949. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168950. SHIFT_TEMPS
  168951. while (--num_rows >= 0) {
  168952. inptr0 = input_buf[0][input_row];
  168953. inptr1 = input_buf[1][input_row];
  168954. inptr2 = input_buf[2][input_row];
  168955. inptr3 = input_buf[3][input_row];
  168956. input_row++;
  168957. outptr = *output_buf++;
  168958. for (col = 0; col < num_cols; col++) {
  168959. y = GETJSAMPLE(inptr0[col]);
  168960. cb = GETJSAMPLE(inptr1[col]);
  168961. cr = GETJSAMPLE(inptr2[col]);
  168962. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168963. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168964. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168965. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168966. SCALEBITS)))];
  168967. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168968. /* K passes through unchanged */
  168969. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168970. outptr += 4;
  168971. }
  168972. }
  168973. }
  168974. /*
  168975. * Empty method for start_pass.
  168976. */
  168977. METHODDEF(void)
  168978. start_pass_dcolor (j_decompress_ptr)
  168979. {
  168980. /* no work needed */
  168981. }
  168982. /*
  168983. * Module initialization routine for output colorspace conversion.
  168984. */
  168985. GLOBAL(void)
  168986. jinit_color_deconverter (j_decompress_ptr cinfo)
  168987. {
  168988. my_cconvert_ptr2 cconvert;
  168989. int ci;
  168990. cconvert = (my_cconvert_ptr2)
  168991. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168992. SIZEOF(my_color_deconverter2));
  168993. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168994. cconvert->pub.start_pass = start_pass_dcolor;
  168995. /* Make sure num_components agrees with jpeg_color_space */
  168996. switch (cinfo->jpeg_color_space) {
  168997. case JCS_GRAYSCALE:
  168998. if (cinfo->num_components != 1)
  168999. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169000. break;
  169001. case JCS_RGB:
  169002. case JCS_YCbCr:
  169003. if (cinfo->num_components != 3)
  169004. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169005. break;
  169006. case JCS_CMYK:
  169007. case JCS_YCCK:
  169008. if (cinfo->num_components != 4)
  169009. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169010. break;
  169011. default: /* JCS_UNKNOWN can be anything */
  169012. if (cinfo->num_components < 1)
  169013. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169014. break;
  169015. }
  169016. /* Set out_color_components and conversion method based on requested space.
  169017. * Also clear the component_needed flags for any unused components,
  169018. * so that earlier pipeline stages can avoid useless computation.
  169019. */
  169020. switch (cinfo->out_color_space) {
  169021. case JCS_GRAYSCALE:
  169022. cinfo->out_color_components = 1;
  169023. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169024. cinfo->jpeg_color_space == JCS_YCbCr) {
  169025. cconvert->pub.color_convert = grayscale_convert2;
  169026. /* For color->grayscale conversion, only the Y (0) component is needed */
  169027. for (ci = 1; ci < cinfo->num_components; ci++)
  169028. cinfo->comp_info[ci].component_needed = FALSE;
  169029. } else
  169030. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169031. break;
  169032. case JCS_RGB:
  169033. cinfo->out_color_components = RGB_PIXELSIZE;
  169034. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169035. cconvert->pub.color_convert = ycc_rgb_convert;
  169036. build_ycc_rgb_table(cinfo);
  169037. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169038. cconvert->pub.color_convert = gray_rgb_convert;
  169039. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169040. cconvert->pub.color_convert = null_convert2;
  169041. } else
  169042. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169043. break;
  169044. case JCS_CMYK:
  169045. cinfo->out_color_components = 4;
  169046. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169047. cconvert->pub.color_convert = ycck_cmyk_convert;
  169048. build_ycc_rgb_table(cinfo);
  169049. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169050. cconvert->pub.color_convert = null_convert2;
  169051. } else
  169052. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169053. break;
  169054. default:
  169055. /* Permit null conversion to same output space */
  169056. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169057. cinfo->out_color_components = cinfo->num_components;
  169058. cconvert->pub.color_convert = null_convert2;
  169059. } else /* unsupported non-null conversion */
  169060. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169061. break;
  169062. }
  169063. if (cinfo->quantize_colors)
  169064. cinfo->output_components = 1; /* single colormapped output component */
  169065. else
  169066. cinfo->output_components = cinfo->out_color_components;
  169067. }
  169068. /*** End of inlined file: jdcolor.c ***/
  169069. #undef FIX
  169070. /*** Start of inlined file: jddctmgr.c ***/
  169071. #define JPEG_INTERNALS
  169072. /*
  169073. * The decompressor input side (jdinput.c) saves away the appropriate
  169074. * quantization table for each component at the start of the first scan
  169075. * involving that component. (This is necessary in order to correctly
  169076. * decode files that reuse Q-table slots.)
  169077. * When we are ready to make an output pass, the saved Q-table is converted
  169078. * to a multiplier table that will actually be used by the IDCT routine.
  169079. * The multiplier table contents are IDCT-method-dependent. To support
  169080. * application changes in IDCT method between scans, we can remake the
  169081. * multiplier tables if necessary.
  169082. * In buffered-image mode, the first output pass may occur before any data
  169083. * has been seen for some components, and thus before their Q-tables have
  169084. * been saved away. To handle this case, multiplier tables are preset
  169085. * to zeroes; the result of the IDCT will be a neutral gray level.
  169086. */
  169087. /* Private subobject for this module */
  169088. typedef struct {
  169089. struct jpeg_inverse_dct pub; /* public fields */
  169090. /* This array contains the IDCT method code that each multiplier table
  169091. * is currently set up for, or -1 if it's not yet set up.
  169092. * The actual multiplier tables are pointed to by dct_table in the
  169093. * per-component comp_info structures.
  169094. */
  169095. int cur_method[MAX_COMPONENTS];
  169096. } my_idct_controller;
  169097. typedef my_idct_controller * my_idct_ptr;
  169098. /* Allocated multiplier tables: big enough for any supported variant */
  169099. typedef union {
  169100. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169101. #ifdef DCT_IFAST_SUPPORTED
  169102. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169103. #endif
  169104. #ifdef DCT_FLOAT_SUPPORTED
  169105. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169106. #endif
  169107. } multiplier_table;
  169108. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169109. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169110. */
  169111. #ifdef DCT_ISLOW_SUPPORTED
  169112. #define PROVIDE_ISLOW_TABLES
  169113. #else
  169114. #ifdef IDCT_SCALING_SUPPORTED
  169115. #define PROVIDE_ISLOW_TABLES
  169116. #endif
  169117. #endif
  169118. /*
  169119. * Prepare for an output pass.
  169120. * Here we select the proper IDCT routine for each component and build
  169121. * a matching multiplier table.
  169122. */
  169123. METHODDEF(void)
  169124. start_pass (j_decompress_ptr cinfo)
  169125. {
  169126. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169127. int ci, i;
  169128. jpeg_component_info *compptr;
  169129. int method = 0;
  169130. inverse_DCT_method_ptr method_ptr = NULL;
  169131. JQUANT_TBL * qtbl;
  169132. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169133. ci++, compptr++) {
  169134. /* Select the proper IDCT routine for this component's scaling */
  169135. switch (compptr->DCT_scaled_size) {
  169136. #ifdef IDCT_SCALING_SUPPORTED
  169137. case 1:
  169138. method_ptr = jpeg_idct_1x1;
  169139. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169140. break;
  169141. case 2:
  169142. method_ptr = jpeg_idct_2x2;
  169143. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169144. break;
  169145. case 4:
  169146. method_ptr = jpeg_idct_4x4;
  169147. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169148. break;
  169149. #endif
  169150. case DCTSIZE:
  169151. switch (cinfo->dct_method) {
  169152. #ifdef DCT_ISLOW_SUPPORTED
  169153. case JDCT_ISLOW:
  169154. method_ptr = jpeg_idct_islow;
  169155. method = JDCT_ISLOW;
  169156. break;
  169157. #endif
  169158. #ifdef DCT_IFAST_SUPPORTED
  169159. case JDCT_IFAST:
  169160. method_ptr = jpeg_idct_ifast;
  169161. method = JDCT_IFAST;
  169162. break;
  169163. #endif
  169164. #ifdef DCT_FLOAT_SUPPORTED
  169165. case JDCT_FLOAT:
  169166. method_ptr = jpeg_idct_float;
  169167. method = JDCT_FLOAT;
  169168. break;
  169169. #endif
  169170. default:
  169171. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169172. break;
  169173. }
  169174. break;
  169175. default:
  169176. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169177. break;
  169178. }
  169179. idct->pub.inverse_DCT[ci] = method_ptr;
  169180. /* Create multiplier table from quant table.
  169181. * However, we can skip this if the component is uninteresting
  169182. * or if we already built the table. Also, if no quant table
  169183. * has yet been saved for the component, we leave the
  169184. * multiplier table all-zero; we'll be reading zeroes from the
  169185. * coefficient controller's buffer anyway.
  169186. */
  169187. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169188. continue;
  169189. qtbl = compptr->quant_table;
  169190. if (qtbl == NULL) /* happens if no data yet for component */
  169191. continue;
  169192. idct->cur_method[ci] = method;
  169193. switch (method) {
  169194. #ifdef PROVIDE_ISLOW_TABLES
  169195. case JDCT_ISLOW:
  169196. {
  169197. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169198. * coefficients, but are stored as ints to ensure access efficiency.
  169199. */
  169200. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169201. for (i = 0; i < DCTSIZE2; i++) {
  169202. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169203. }
  169204. }
  169205. break;
  169206. #endif
  169207. #ifdef DCT_IFAST_SUPPORTED
  169208. case JDCT_IFAST:
  169209. {
  169210. /* For AA&N IDCT method, multipliers are equal to quantization
  169211. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169212. * scalefactor[0] = 1
  169213. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169214. * For integer operation, the multiplier table is to be scaled by
  169215. * IFAST_SCALE_BITS.
  169216. */
  169217. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169218. #define CONST_BITS 14
  169219. static const INT16 aanscales[DCTSIZE2] = {
  169220. /* precomputed values scaled up by 14 bits */
  169221. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169222. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169223. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169224. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169225. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169226. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169227. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169228. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169229. };
  169230. SHIFT_TEMPS
  169231. for (i = 0; i < DCTSIZE2; i++) {
  169232. ifmtbl[i] = (IFAST_MULT_TYPE)
  169233. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169234. (INT32) aanscales[i]),
  169235. CONST_BITS-IFAST_SCALE_BITS);
  169236. }
  169237. }
  169238. break;
  169239. #endif
  169240. #ifdef DCT_FLOAT_SUPPORTED
  169241. case JDCT_FLOAT:
  169242. {
  169243. /* For float AA&N IDCT method, multipliers are equal to quantization
  169244. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169245. * scalefactor[0] = 1
  169246. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169247. */
  169248. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169249. int row, col;
  169250. static const double aanscalefactor[DCTSIZE] = {
  169251. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169252. 1.0, 0.785694958, 0.541196100, 0.275899379
  169253. };
  169254. i = 0;
  169255. for (row = 0; row < DCTSIZE; row++) {
  169256. for (col = 0; col < DCTSIZE; col++) {
  169257. fmtbl[i] = (FLOAT_MULT_TYPE)
  169258. ((double) qtbl->quantval[i] *
  169259. aanscalefactor[row] * aanscalefactor[col]);
  169260. i++;
  169261. }
  169262. }
  169263. }
  169264. break;
  169265. #endif
  169266. default:
  169267. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169268. break;
  169269. }
  169270. }
  169271. }
  169272. /*
  169273. * Initialize IDCT manager.
  169274. */
  169275. GLOBAL(void)
  169276. jinit_inverse_dct (j_decompress_ptr cinfo)
  169277. {
  169278. my_idct_ptr idct;
  169279. int ci;
  169280. jpeg_component_info *compptr;
  169281. idct = (my_idct_ptr)
  169282. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169283. SIZEOF(my_idct_controller));
  169284. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169285. idct->pub.start_pass = start_pass;
  169286. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169287. ci++, compptr++) {
  169288. /* Allocate and pre-zero a multiplier table for each component */
  169289. compptr->dct_table =
  169290. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169291. SIZEOF(multiplier_table));
  169292. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169293. /* Mark multiplier table not yet set up for any method */
  169294. idct->cur_method[ci] = -1;
  169295. }
  169296. }
  169297. /*** End of inlined file: jddctmgr.c ***/
  169298. #undef CONST_BITS
  169299. #undef ASSIGN_STATE
  169300. /*** Start of inlined file: jdhuff.c ***/
  169301. #define JPEG_INTERNALS
  169302. /*** Start of inlined file: jdhuff.h ***/
  169303. /* Short forms of external names for systems with brain-damaged linkers. */
  169304. #ifndef __jdhuff_h__
  169305. #define __jdhuff_h__
  169306. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169307. #define jpeg_make_d_derived_tbl jMkDDerived
  169308. #define jpeg_fill_bit_buffer jFilBitBuf
  169309. #define jpeg_huff_decode jHufDecode
  169310. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169311. /* Derived data constructed for each Huffman table */
  169312. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169313. typedef struct {
  169314. /* Basic tables: (element [0] of each array is unused) */
  169315. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169316. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169317. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169318. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169319. * the smallest code of length k; so given a code of length k, the
  169320. * corresponding symbol is huffval[code + valoffset[k]]
  169321. */
  169322. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169323. JHUFF_TBL *pub;
  169324. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169325. * the input data stream. If the next Huffman code is no more
  169326. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169327. * the corresponding symbol directly from these tables.
  169328. */
  169329. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169330. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169331. } d_derived_tbl;
  169332. /* Expand a Huffman table definition into the derived format */
  169333. EXTERN(void) jpeg_make_d_derived_tbl
  169334. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169335. d_derived_tbl ** pdtbl));
  169336. /*
  169337. * Fetching the next N bits from the input stream is a time-critical operation
  169338. * for the Huffman decoders. We implement it with a combination of inline
  169339. * macros and out-of-line subroutines. Note that N (the number of bits
  169340. * demanded at one time) never exceeds 15 for JPEG use.
  169341. *
  169342. * We read source bytes into get_buffer and dole out bits as needed.
  169343. * If get_buffer already contains enough bits, they are fetched in-line
  169344. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169345. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169346. * as full as possible (not just to the number of bits needed; this
  169347. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169348. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169349. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169350. * at least the requested number of bits --- dummy zeroes are inserted if
  169351. * necessary.
  169352. */
  169353. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169354. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169355. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169356. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169357. * appropriately should be a win. Unfortunately we can't define the size
  169358. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169359. * because not all machines measure sizeof in 8-bit bytes.
  169360. */
  169361. typedef struct { /* Bitreading state saved across MCUs */
  169362. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169363. int bits_left; /* # of unused bits in it */
  169364. } bitread_perm_state;
  169365. typedef struct { /* Bitreading working state within an MCU */
  169366. /* Current data source location */
  169367. /* We need a copy, rather than munging the original, in case of suspension */
  169368. const JOCTET * next_input_byte; /* => next byte to read from source */
  169369. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169370. /* Bit input buffer --- note these values are kept in register variables,
  169371. * not in this struct, inside the inner loops.
  169372. */
  169373. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169374. int bits_left; /* # of unused bits in it */
  169375. /* Pointer needed by jpeg_fill_bit_buffer. */
  169376. j_decompress_ptr cinfo; /* back link to decompress master record */
  169377. } bitread_working_state;
  169378. /* Macros to declare and load/save bitread local variables. */
  169379. #define BITREAD_STATE_VARS \
  169380. register bit_buf_type get_buffer; \
  169381. register int bits_left; \
  169382. bitread_working_state br_state
  169383. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169384. br_state.cinfo = cinfop; \
  169385. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169386. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169387. get_buffer = permstate.get_buffer; \
  169388. bits_left = permstate.bits_left;
  169389. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169390. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169391. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169392. permstate.get_buffer = get_buffer; \
  169393. permstate.bits_left = bits_left
  169394. /*
  169395. * These macros provide the in-line portion of bit fetching.
  169396. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169397. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169398. * The variables get_buffer and bits_left are assumed to be locals,
  169399. * but the state struct might not be (jpeg_huff_decode needs this).
  169400. * CHECK_BIT_BUFFER(state,n,action);
  169401. * Ensure there are N bits in get_buffer; if suspend, take action.
  169402. * val = GET_BITS(n);
  169403. * Fetch next N bits.
  169404. * val = PEEK_BITS(n);
  169405. * Fetch next N bits without removing them from the buffer.
  169406. * DROP_BITS(n);
  169407. * Discard next N bits.
  169408. * The value N should be a simple variable, not an expression, because it
  169409. * is evaluated multiple times.
  169410. */
  169411. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169412. { if (bits_left < (nbits)) { \
  169413. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169414. { action; } \
  169415. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169416. #define GET_BITS(nbits) \
  169417. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169418. #define PEEK_BITS(nbits) \
  169419. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169420. #define DROP_BITS(nbits) \
  169421. (bits_left -= (nbits))
  169422. /* Load up the bit buffer to a depth of at least nbits */
  169423. EXTERN(boolean) jpeg_fill_bit_buffer
  169424. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169425. register int bits_left, int nbits));
  169426. /*
  169427. * Code for extracting next Huffman-coded symbol from input bit stream.
  169428. * Again, this is time-critical and we make the main paths be macros.
  169429. *
  169430. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169431. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169432. * or fewer bits long. The few overlength codes are handled with a loop,
  169433. * which need not be inline code.
  169434. *
  169435. * Notes about the HUFF_DECODE macro:
  169436. * 1. Near the end of the data segment, we may fail to get enough bits
  169437. * for a lookahead. In that case, we do it the hard way.
  169438. * 2. If the lookahead table contains no entry, the next code must be
  169439. * more than HUFF_LOOKAHEAD bits long.
  169440. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169441. */
  169442. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169443. { register int nb, look; \
  169444. if (bits_left < HUFF_LOOKAHEAD) { \
  169445. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169446. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169447. if (bits_left < HUFF_LOOKAHEAD) { \
  169448. nb = 1; goto slowlabel; \
  169449. } \
  169450. } \
  169451. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169452. if ((nb = htbl->look_nbits[look]) != 0) { \
  169453. DROP_BITS(nb); \
  169454. result = htbl->look_sym[look]; \
  169455. } else { \
  169456. nb = HUFF_LOOKAHEAD+1; \
  169457. slowlabel: \
  169458. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169459. { failaction; } \
  169460. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169461. } \
  169462. }
  169463. /* Out-of-line case for Huffman code fetching */
  169464. EXTERN(int) jpeg_huff_decode
  169465. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169466. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169467. #endif
  169468. /*** End of inlined file: jdhuff.h ***/
  169469. /* Declarations shared with jdphuff.c */
  169470. /*
  169471. * Expanded entropy decoder object for Huffman decoding.
  169472. *
  169473. * The savable_state subrecord contains fields that change within an MCU,
  169474. * but must not be updated permanently until we complete the MCU.
  169475. */
  169476. typedef struct {
  169477. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169478. } savable_state2;
  169479. /* This macro is to work around compilers with missing or broken
  169480. * structure assignment. You'll need to fix this code if you have
  169481. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169482. */
  169483. #ifndef NO_STRUCT_ASSIGN
  169484. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169485. #else
  169486. #if MAX_COMPS_IN_SCAN == 4
  169487. #define ASSIGN_STATE(dest,src) \
  169488. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169489. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169490. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169491. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169492. #endif
  169493. #endif
  169494. typedef struct {
  169495. struct jpeg_entropy_decoder pub; /* public fields */
  169496. /* These fields are loaded into local variables at start of each MCU.
  169497. * In case of suspension, we exit WITHOUT updating them.
  169498. */
  169499. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169500. savable_state2 saved; /* Other state at start of MCU */
  169501. /* These fields are NOT loaded into local working state. */
  169502. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169503. /* Pointers to derived tables (these workspaces have image lifespan) */
  169504. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169505. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169506. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169507. /* Pointers to derived tables to be used for each block within an MCU */
  169508. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169509. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169510. /* Whether we care about the DC and AC coefficient values for each block */
  169511. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169512. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169513. } huff_entropy_decoder2;
  169514. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169515. /*
  169516. * Initialize for a Huffman-compressed scan.
  169517. */
  169518. METHODDEF(void)
  169519. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169520. {
  169521. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169522. int ci, blkn, dctbl, actbl;
  169523. jpeg_component_info * compptr;
  169524. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169525. * This ought to be an error condition, but we make it a warning because
  169526. * there are some baseline files out there with all zeroes in these bytes.
  169527. */
  169528. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169529. cinfo->Ah != 0 || cinfo->Al != 0)
  169530. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169531. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169532. compptr = cinfo->cur_comp_info[ci];
  169533. dctbl = compptr->dc_tbl_no;
  169534. actbl = compptr->ac_tbl_no;
  169535. /* Compute derived values for Huffman tables */
  169536. /* We may do this more than once for a table, but it's not expensive */
  169537. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169538. & entropy->dc_derived_tbls[dctbl]);
  169539. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169540. & entropy->ac_derived_tbls[actbl]);
  169541. /* Initialize DC predictions to 0 */
  169542. entropy->saved.last_dc_val[ci] = 0;
  169543. }
  169544. /* Precalculate decoding info for each block in an MCU of this scan */
  169545. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169546. ci = cinfo->MCU_membership[blkn];
  169547. compptr = cinfo->cur_comp_info[ci];
  169548. /* Precalculate which table to use for each block */
  169549. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169550. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169551. /* Decide whether we really care about the coefficient values */
  169552. if (compptr->component_needed) {
  169553. entropy->dc_needed[blkn] = TRUE;
  169554. /* we don't need the ACs if producing a 1/8th-size image */
  169555. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169556. } else {
  169557. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169558. }
  169559. }
  169560. /* Initialize bitread state variables */
  169561. entropy->bitstate.bits_left = 0;
  169562. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169563. entropy->pub.insufficient_data = FALSE;
  169564. /* Initialize restart counter */
  169565. entropy->restarts_to_go = cinfo->restart_interval;
  169566. }
  169567. /*
  169568. * Compute the derived values for a Huffman table.
  169569. * This routine also performs some validation checks on the table.
  169570. *
  169571. * Note this is also used by jdphuff.c.
  169572. */
  169573. GLOBAL(void)
  169574. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169575. d_derived_tbl ** pdtbl)
  169576. {
  169577. JHUFF_TBL *htbl;
  169578. d_derived_tbl *dtbl;
  169579. int p, i, l, si, numsymbols;
  169580. int lookbits, ctr;
  169581. char huffsize[257];
  169582. unsigned int huffcode[257];
  169583. unsigned int code;
  169584. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169585. * paralleling the order of the symbols themselves in htbl->huffval[].
  169586. */
  169587. /* Find the input Huffman table */
  169588. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169589. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169590. htbl =
  169591. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169592. if (htbl == NULL)
  169593. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169594. /* Allocate a workspace if we haven't already done so. */
  169595. if (*pdtbl == NULL)
  169596. *pdtbl = (d_derived_tbl *)
  169597. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169598. SIZEOF(d_derived_tbl));
  169599. dtbl = *pdtbl;
  169600. dtbl->pub = htbl; /* fill in back link */
  169601. /* Figure C.1: make table of Huffman code length for each symbol */
  169602. p = 0;
  169603. for (l = 1; l <= 16; l++) {
  169604. i = (int) htbl->bits[l];
  169605. if (i < 0 || p + i > 256) /* protect against table overrun */
  169606. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169607. while (i--)
  169608. huffsize[p++] = (char) l;
  169609. }
  169610. huffsize[p] = 0;
  169611. numsymbols = p;
  169612. /* Figure C.2: generate the codes themselves */
  169613. /* We also validate that the counts represent a legal Huffman code tree. */
  169614. code = 0;
  169615. si = huffsize[0];
  169616. p = 0;
  169617. while (huffsize[p]) {
  169618. while (((int) huffsize[p]) == si) {
  169619. huffcode[p++] = code;
  169620. code++;
  169621. }
  169622. /* code is now 1 more than the last code used for codelength si; but
  169623. * it must still fit in si bits, since no code is allowed to be all ones.
  169624. */
  169625. if (((INT32) code) >= (((INT32) 1) << si))
  169626. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169627. code <<= 1;
  169628. si++;
  169629. }
  169630. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169631. p = 0;
  169632. for (l = 1; l <= 16; l++) {
  169633. if (htbl->bits[l]) {
  169634. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169635. * minus the minimum code of length l
  169636. */
  169637. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169638. p += htbl->bits[l];
  169639. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169640. } else {
  169641. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169642. }
  169643. }
  169644. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169645. /* Compute lookahead tables to speed up decoding.
  169646. * First we set all the table entries to 0, indicating "too long";
  169647. * then we iterate through the Huffman codes that are short enough and
  169648. * fill in all the entries that correspond to bit sequences starting
  169649. * with that code.
  169650. */
  169651. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169652. p = 0;
  169653. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169654. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169655. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169656. /* Generate left-justified code followed by all possible bit sequences */
  169657. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169658. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169659. dtbl->look_nbits[lookbits] = l;
  169660. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169661. lookbits++;
  169662. }
  169663. }
  169664. }
  169665. /* Validate symbols as being reasonable.
  169666. * For AC tables, we make no check, but accept all byte values 0..255.
  169667. * For DC tables, we require the symbols to be in range 0..15.
  169668. * (Tighter bounds could be applied depending on the data depth and mode,
  169669. * but this is sufficient to ensure safe decoding.)
  169670. */
  169671. if (isDC) {
  169672. for (i = 0; i < numsymbols; i++) {
  169673. int sym = htbl->huffval[i];
  169674. if (sym < 0 || sym > 15)
  169675. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169676. }
  169677. }
  169678. }
  169679. /*
  169680. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169681. * See jdhuff.h for info about usage.
  169682. * Note: current values of get_buffer and bits_left are passed as parameters,
  169683. * but are returned in the corresponding fields of the state struct.
  169684. *
  169685. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169686. * of get_buffer to be used. (On machines with wider words, an even larger
  169687. * buffer could be used.) However, on some machines 32-bit shifts are
  169688. * quite slow and take time proportional to the number of places shifted.
  169689. * (This is true with most PC compilers, for instance.) In this case it may
  169690. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169691. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169692. */
  169693. #ifdef SLOW_SHIFT_32
  169694. #define MIN_GET_BITS 15 /* minimum allowable value */
  169695. #else
  169696. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169697. #endif
  169698. GLOBAL(boolean)
  169699. jpeg_fill_bit_buffer (bitread_working_state * state,
  169700. register bit_buf_type get_buffer, register int bits_left,
  169701. int nbits)
  169702. /* Load up the bit buffer to a depth of at least nbits */
  169703. {
  169704. /* Copy heavily used state fields into locals (hopefully registers) */
  169705. register const JOCTET * next_input_byte = state->next_input_byte;
  169706. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169707. j_decompress_ptr cinfo = state->cinfo;
  169708. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169709. /* (It is assumed that no request will be for more than that many bits.) */
  169710. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169711. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169712. while (bits_left < MIN_GET_BITS) {
  169713. register int c;
  169714. /* Attempt to read a byte */
  169715. if (bytes_in_buffer == 0) {
  169716. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169717. return FALSE;
  169718. next_input_byte = cinfo->src->next_input_byte;
  169719. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169720. }
  169721. bytes_in_buffer--;
  169722. c = GETJOCTET(*next_input_byte++);
  169723. /* If it's 0xFF, check and discard stuffed zero byte */
  169724. if (c == 0xFF) {
  169725. /* Loop here to discard any padding FF's on terminating marker,
  169726. * so that we can save a valid unread_marker value. NOTE: we will
  169727. * accept multiple FF's followed by a 0 as meaning a single FF data
  169728. * byte. This data pattern is not valid according to the standard.
  169729. */
  169730. do {
  169731. if (bytes_in_buffer == 0) {
  169732. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169733. return FALSE;
  169734. next_input_byte = cinfo->src->next_input_byte;
  169735. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169736. }
  169737. bytes_in_buffer--;
  169738. c = GETJOCTET(*next_input_byte++);
  169739. } while (c == 0xFF);
  169740. if (c == 0) {
  169741. /* Found FF/00, which represents an FF data byte */
  169742. c = 0xFF;
  169743. } else {
  169744. /* Oops, it's actually a marker indicating end of compressed data.
  169745. * Save the marker code for later use.
  169746. * Fine point: it might appear that we should save the marker into
  169747. * bitread working state, not straight into permanent state. But
  169748. * once we have hit a marker, we cannot need to suspend within the
  169749. * current MCU, because we will read no more bytes from the data
  169750. * source. So it is OK to update permanent state right away.
  169751. */
  169752. cinfo->unread_marker = c;
  169753. /* See if we need to insert some fake zero bits. */
  169754. goto no_more_bytes;
  169755. }
  169756. }
  169757. /* OK, load c into get_buffer */
  169758. get_buffer = (get_buffer << 8) | c;
  169759. bits_left += 8;
  169760. } /* end while */
  169761. } else {
  169762. no_more_bytes:
  169763. /* We get here if we've read the marker that terminates the compressed
  169764. * data segment. There should be enough bits in the buffer register
  169765. * to satisfy the request; if so, no problem.
  169766. */
  169767. if (nbits > bits_left) {
  169768. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169769. * the data stream, so that we can produce some kind of image.
  169770. * We use a nonvolatile flag to ensure that only one warning message
  169771. * appears per data segment.
  169772. */
  169773. if (! cinfo->entropy->insufficient_data) {
  169774. WARNMS(cinfo, JWRN_HIT_MARKER);
  169775. cinfo->entropy->insufficient_data = TRUE;
  169776. }
  169777. /* Fill the buffer with zero bits */
  169778. get_buffer <<= MIN_GET_BITS - bits_left;
  169779. bits_left = MIN_GET_BITS;
  169780. }
  169781. }
  169782. /* Unload the local registers */
  169783. state->next_input_byte = next_input_byte;
  169784. state->bytes_in_buffer = bytes_in_buffer;
  169785. state->get_buffer = get_buffer;
  169786. state->bits_left = bits_left;
  169787. return TRUE;
  169788. }
  169789. /*
  169790. * Out-of-line code for Huffman code decoding.
  169791. * See jdhuff.h for info about usage.
  169792. */
  169793. GLOBAL(int)
  169794. jpeg_huff_decode (bitread_working_state * state,
  169795. register bit_buf_type get_buffer, register int bits_left,
  169796. d_derived_tbl * htbl, int min_bits)
  169797. {
  169798. register int l = min_bits;
  169799. register INT32 code;
  169800. /* HUFF_DECODE has determined that the code is at least min_bits */
  169801. /* bits long, so fetch that many bits in one swoop. */
  169802. CHECK_BIT_BUFFER(*state, l, return -1);
  169803. code = GET_BITS(l);
  169804. /* Collect the rest of the Huffman code one bit at a time. */
  169805. /* This is per Figure F.16 in the JPEG spec. */
  169806. while (code > htbl->maxcode[l]) {
  169807. code <<= 1;
  169808. CHECK_BIT_BUFFER(*state, 1, return -1);
  169809. code |= GET_BITS(1);
  169810. l++;
  169811. }
  169812. /* Unload the local registers */
  169813. state->get_buffer = get_buffer;
  169814. state->bits_left = bits_left;
  169815. /* With garbage input we may reach the sentinel value l = 17. */
  169816. if (l > 16) {
  169817. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169818. return 0; /* fake a zero as the safest result */
  169819. }
  169820. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169821. }
  169822. /*
  169823. * Check for a restart marker & resynchronize decoder.
  169824. * Returns FALSE if must suspend.
  169825. */
  169826. LOCAL(boolean)
  169827. process_restart (j_decompress_ptr cinfo)
  169828. {
  169829. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169830. int ci;
  169831. /* Throw away any unused bits remaining in bit buffer; */
  169832. /* include any full bytes in next_marker's count of discarded bytes */
  169833. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169834. entropy->bitstate.bits_left = 0;
  169835. /* Advance past the RSTn marker */
  169836. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169837. return FALSE;
  169838. /* Re-initialize DC predictions to 0 */
  169839. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169840. entropy->saved.last_dc_val[ci] = 0;
  169841. /* Reset restart counter */
  169842. entropy->restarts_to_go = cinfo->restart_interval;
  169843. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169844. * against a marker. In that case we will end up treating the next data
  169845. * segment as empty, and we can avoid producing bogus output pixels by
  169846. * leaving the flag set.
  169847. */
  169848. if (cinfo->unread_marker == 0)
  169849. entropy->pub.insufficient_data = FALSE;
  169850. return TRUE;
  169851. }
  169852. /*
  169853. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169854. * The coefficients are reordered from zigzag order into natural array order,
  169855. * but are not dequantized.
  169856. *
  169857. * The i'th block of the MCU is stored into the block pointed to by
  169858. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169859. * (Wholesale zeroing is usually a little faster than retail...)
  169860. *
  169861. * Returns FALSE if data source requested suspension. In that case no
  169862. * changes have been made to permanent state. (Exception: some output
  169863. * coefficients may already have been assigned. This is harmless for
  169864. * this module, since we'll just re-assign them on the next call.)
  169865. */
  169866. METHODDEF(boolean)
  169867. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169868. {
  169869. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169870. int blkn;
  169871. BITREAD_STATE_VARS;
  169872. savable_state2 state;
  169873. /* Process restart marker if needed; may have to suspend */
  169874. if (cinfo->restart_interval) {
  169875. if (entropy->restarts_to_go == 0)
  169876. if (! process_restart(cinfo))
  169877. return FALSE;
  169878. }
  169879. /* If we've run out of data, just leave the MCU set to zeroes.
  169880. * This way, we return uniform gray for the remainder of the segment.
  169881. */
  169882. if (! entropy->pub.insufficient_data) {
  169883. /* Load up working state */
  169884. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169885. ASSIGN_STATE(state, entropy->saved);
  169886. /* Outer loop handles each block in the MCU */
  169887. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169888. JBLOCKROW block = MCU_data[blkn];
  169889. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169890. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169891. register int s, k, r;
  169892. /* Decode a single block's worth of coefficients */
  169893. /* Section F.2.2.1: decode the DC coefficient difference */
  169894. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169895. if (s) {
  169896. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169897. r = GET_BITS(s);
  169898. s = HUFF_EXTEND(r, s);
  169899. }
  169900. if (entropy->dc_needed[blkn]) {
  169901. /* Convert DC difference to actual value, update last_dc_val */
  169902. int ci = cinfo->MCU_membership[blkn];
  169903. s += state.last_dc_val[ci];
  169904. state.last_dc_val[ci] = s;
  169905. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169906. (*block)[0] = (JCOEF) s;
  169907. }
  169908. if (entropy->ac_needed[blkn]) {
  169909. /* Section F.2.2.2: decode the AC coefficients */
  169910. /* Since zeroes are skipped, output area must be cleared beforehand */
  169911. for (k = 1; k < DCTSIZE2; k++) {
  169912. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169913. r = s >> 4;
  169914. s &= 15;
  169915. if (s) {
  169916. k += r;
  169917. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169918. r = GET_BITS(s);
  169919. s = HUFF_EXTEND(r, s);
  169920. /* Output coefficient in natural (dezigzagged) order.
  169921. * Note: the extra entries in jpeg_natural_order[] will save us
  169922. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169923. */
  169924. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169925. } else {
  169926. if (r != 15)
  169927. break;
  169928. k += 15;
  169929. }
  169930. }
  169931. } else {
  169932. /* Section F.2.2.2: decode the AC coefficients */
  169933. /* In this path we just discard the values */
  169934. for (k = 1; k < DCTSIZE2; k++) {
  169935. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169936. r = s >> 4;
  169937. s &= 15;
  169938. if (s) {
  169939. k += r;
  169940. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169941. DROP_BITS(s);
  169942. } else {
  169943. if (r != 15)
  169944. break;
  169945. k += 15;
  169946. }
  169947. }
  169948. }
  169949. }
  169950. /* Completed MCU, so update state */
  169951. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169952. ASSIGN_STATE(entropy->saved, state);
  169953. }
  169954. /* Account for restart interval (no-op if not using restarts) */
  169955. entropy->restarts_to_go--;
  169956. return TRUE;
  169957. }
  169958. /*
  169959. * Module initialization routine for Huffman entropy decoding.
  169960. */
  169961. GLOBAL(void)
  169962. jinit_huff_decoder (j_decompress_ptr cinfo)
  169963. {
  169964. huff_entropy_ptr2 entropy;
  169965. int i;
  169966. entropy = (huff_entropy_ptr2)
  169967. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169968. SIZEOF(huff_entropy_decoder2));
  169969. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169970. entropy->pub.start_pass = start_pass_huff_decoder;
  169971. entropy->pub.decode_mcu = decode_mcu;
  169972. /* Mark tables unallocated */
  169973. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169974. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169975. }
  169976. }
  169977. /*** End of inlined file: jdhuff.c ***/
  169978. /*** Start of inlined file: jdinput.c ***/
  169979. #define JPEG_INTERNALS
  169980. /* Private state */
  169981. typedef struct {
  169982. struct jpeg_input_controller pub; /* public fields */
  169983. boolean inheaders; /* TRUE until first SOS is reached */
  169984. } my_input_controller;
  169985. typedef my_input_controller * my_inputctl_ptr;
  169986. /* Forward declarations */
  169987. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169988. /*
  169989. * Routines to calculate various quantities related to the size of the image.
  169990. */
  169991. LOCAL(void)
  169992. initial_setup2 (j_decompress_ptr cinfo)
  169993. /* Called once, when first SOS marker is reached */
  169994. {
  169995. int ci;
  169996. jpeg_component_info *compptr;
  169997. /* Make sure image isn't bigger than I can handle */
  169998. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169999. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170000. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170001. /* For now, precision must match compiled-in value... */
  170002. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170003. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170004. /* Check that number of components won't exceed internal array sizes */
  170005. if (cinfo->num_components > MAX_COMPONENTS)
  170006. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170007. MAX_COMPONENTS);
  170008. /* Compute maximum sampling factors; check factor validity */
  170009. cinfo->max_h_samp_factor = 1;
  170010. cinfo->max_v_samp_factor = 1;
  170011. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170012. ci++, compptr++) {
  170013. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170014. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170015. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170016. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170017. compptr->h_samp_factor);
  170018. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170019. compptr->v_samp_factor);
  170020. }
  170021. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170022. * In the full decompressor, this will be overridden by jdmaster.c;
  170023. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170024. */
  170025. cinfo->min_DCT_scaled_size = DCTSIZE;
  170026. /* Compute dimensions of components */
  170027. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170028. ci++, compptr++) {
  170029. compptr->DCT_scaled_size = DCTSIZE;
  170030. /* Size in DCT blocks */
  170031. compptr->width_in_blocks = (JDIMENSION)
  170032. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170033. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170034. compptr->height_in_blocks = (JDIMENSION)
  170035. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170036. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170037. /* downsampled_width and downsampled_height will also be overridden by
  170038. * jdmaster.c if we are doing full decompression. The transcoder library
  170039. * doesn't use these values, but the calling application might.
  170040. */
  170041. /* Size in samples */
  170042. compptr->downsampled_width = (JDIMENSION)
  170043. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170044. (long) cinfo->max_h_samp_factor);
  170045. compptr->downsampled_height = (JDIMENSION)
  170046. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170047. (long) cinfo->max_v_samp_factor);
  170048. /* Mark component needed, until color conversion says otherwise */
  170049. compptr->component_needed = TRUE;
  170050. /* Mark no quantization table yet saved for component */
  170051. compptr->quant_table = NULL;
  170052. }
  170053. /* Compute number of fully interleaved MCU rows. */
  170054. cinfo->total_iMCU_rows = (JDIMENSION)
  170055. jdiv_round_up((long) cinfo->image_height,
  170056. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170057. /* Decide whether file contains multiple scans */
  170058. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170059. cinfo->inputctl->has_multiple_scans = TRUE;
  170060. else
  170061. cinfo->inputctl->has_multiple_scans = FALSE;
  170062. }
  170063. LOCAL(void)
  170064. per_scan_setup2 (j_decompress_ptr cinfo)
  170065. /* Do computations that are needed before processing a JPEG scan */
  170066. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170067. {
  170068. int ci, mcublks, tmp;
  170069. jpeg_component_info *compptr;
  170070. if (cinfo->comps_in_scan == 1) {
  170071. /* Noninterleaved (single-component) scan */
  170072. compptr = cinfo->cur_comp_info[0];
  170073. /* Overall image size in MCUs */
  170074. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170075. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170076. /* For noninterleaved scan, always one block per MCU */
  170077. compptr->MCU_width = 1;
  170078. compptr->MCU_height = 1;
  170079. compptr->MCU_blocks = 1;
  170080. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170081. compptr->last_col_width = 1;
  170082. /* For noninterleaved scans, it is convenient to define last_row_height
  170083. * as the number of block rows present in the last iMCU row.
  170084. */
  170085. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170086. if (tmp == 0) tmp = compptr->v_samp_factor;
  170087. compptr->last_row_height = tmp;
  170088. /* Prepare array describing MCU composition */
  170089. cinfo->blocks_in_MCU = 1;
  170090. cinfo->MCU_membership[0] = 0;
  170091. } else {
  170092. /* Interleaved (multi-component) scan */
  170093. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170094. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170095. MAX_COMPS_IN_SCAN);
  170096. /* Overall image size in MCUs */
  170097. cinfo->MCUs_per_row = (JDIMENSION)
  170098. jdiv_round_up((long) cinfo->image_width,
  170099. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170100. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170101. jdiv_round_up((long) cinfo->image_height,
  170102. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170103. cinfo->blocks_in_MCU = 0;
  170104. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170105. compptr = cinfo->cur_comp_info[ci];
  170106. /* Sampling factors give # of blocks of component in each MCU */
  170107. compptr->MCU_width = compptr->h_samp_factor;
  170108. compptr->MCU_height = compptr->v_samp_factor;
  170109. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170110. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170111. /* Figure number of non-dummy blocks in last MCU column & row */
  170112. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170113. if (tmp == 0) tmp = compptr->MCU_width;
  170114. compptr->last_col_width = tmp;
  170115. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170116. if (tmp == 0) tmp = compptr->MCU_height;
  170117. compptr->last_row_height = tmp;
  170118. /* Prepare array describing MCU composition */
  170119. mcublks = compptr->MCU_blocks;
  170120. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170121. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170122. while (mcublks-- > 0) {
  170123. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170124. }
  170125. }
  170126. }
  170127. }
  170128. /*
  170129. * Save away a copy of the Q-table referenced by each component present
  170130. * in the current scan, unless already saved during a prior scan.
  170131. *
  170132. * In a multiple-scan JPEG file, the encoder could assign different components
  170133. * the same Q-table slot number, but change table definitions between scans
  170134. * so that each component uses a different Q-table. (The IJG encoder is not
  170135. * currently capable of doing this, but other encoders might.) Since we want
  170136. * to be able to dequantize all the components at the end of the file, this
  170137. * means that we have to save away the table actually used for each component.
  170138. * We do this by copying the table at the start of the first scan containing
  170139. * the component.
  170140. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170141. * slot between scans of a component using that slot. If the encoder does so
  170142. * anyway, this decoder will simply use the Q-table values that were current
  170143. * at the start of the first scan for the component.
  170144. *
  170145. * The decompressor output side looks only at the saved quant tables,
  170146. * not at the current Q-table slots.
  170147. */
  170148. LOCAL(void)
  170149. latch_quant_tables (j_decompress_ptr cinfo)
  170150. {
  170151. int ci, qtblno;
  170152. jpeg_component_info *compptr;
  170153. JQUANT_TBL * qtbl;
  170154. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170155. compptr = cinfo->cur_comp_info[ci];
  170156. /* No work if we already saved Q-table for this component */
  170157. if (compptr->quant_table != NULL)
  170158. continue;
  170159. /* Make sure specified quantization table is present */
  170160. qtblno = compptr->quant_tbl_no;
  170161. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170162. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170163. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170164. /* OK, save away the quantization table */
  170165. qtbl = (JQUANT_TBL *)
  170166. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170167. SIZEOF(JQUANT_TBL));
  170168. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170169. compptr->quant_table = qtbl;
  170170. }
  170171. }
  170172. /*
  170173. * Initialize the input modules to read a scan of compressed data.
  170174. * The first call to this is done by jdmaster.c after initializing
  170175. * the entire decompressor (during jpeg_start_decompress).
  170176. * Subsequent calls come from consume_markers, below.
  170177. */
  170178. METHODDEF(void)
  170179. start_input_pass2 (j_decompress_ptr cinfo)
  170180. {
  170181. per_scan_setup2(cinfo);
  170182. latch_quant_tables(cinfo);
  170183. (*cinfo->entropy->start_pass) (cinfo);
  170184. (*cinfo->coef->start_input_pass) (cinfo);
  170185. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170186. }
  170187. /*
  170188. * Finish up after inputting a compressed-data scan.
  170189. * This is called by the coefficient controller after it's read all
  170190. * the expected data of the scan.
  170191. */
  170192. METHODDEF(void)
  170193. finish_input_pass (j_decompress_ptr cinfo)
  170194. {
  170195. cinfo->inputctl->consume_input = consume_markers;
  170196. }
  170197. /*
  170198. * Read JPEG markers before, between, or after compressed-data scans.
  170199. * Change state as necessary when a new scan is reached.
  170200. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170201. *
  170202. * The consume_input method pointer points either here or to the
  170203. * coefficient controller's consume_data routine, depending on whether
  170204. * we are reading a compressed data segment or inter-segment markers.
  170205. */
  170206. METHODDEF(int)
  170207. consume_markers (j_decompress_ptr cinfo)
  170208. {
  170209. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170210. int val;
  170211. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170212. return JPEG_REACHED_EOI;
  170213. val = (*cinfo->marker->read_markers) (cinfo);
  170214. switch (val) {
  170215. case JPEG_REACHED_SOS: /* Found SOS */
  170216. if (inputctl->inheaders) { /* 1st SOS */
  170217. initial_setup2(cinfo);
  170218. inputctl->inheaders = FALSE;
  170219. /* Note: start_input_pass must be called by jdmaster.c
  170220. * before any more input can be consumed. jdapimin.c is
  170221. * responsible for enforcing this sequencing.
  170222. */
  170223. } else { /* 2nd or later SOS marker */
  170224. if (! inputctl->pub.has_multiple_scans)
  170225. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170226. start_input_pass2(cinfo);
  170227. }
  170228. break;
  170229. case JPEG_REACHED_EOI: /* Found EOI */
  170230. inputctl->pub.eoi_reached = TRUE;
  170231. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170232. if (cinfo->marker->saw_SOF)
  170233. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170234. } else {
  170235. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170236. * if user set output_scan_number larger than number of scans.
  170237. */
  170238. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170239. cinfo->output_scan_number = cinfo->input_scan_number;
  170240. }
  170241. break;
  170242. case JPEG_SUSPENDED:
  170243. break;
  170244. }
  170245. return val;
  170246. }
  170247. /*
  170248. * Reset state to begin a fresh datastream.
  170249. */
  170250. METHODDEF(void)
  170251. reset_input_controller (j_decompress_ptr cinfo)
  170252. {
  170253. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170254. inputctl->pub.consume_input = consume_markers;
  170255. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170256. inputctl->pub.eoi_reached = FALSE;
  170257. inputctl->inheaders = TRUE;
  170258. /* Reset other modules */
  170259. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170260. (*cinfo->marker->reset_marker_reader) (cinfo);
  170261. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170262. cinfo->coef_bits = NULL;
  170263. }
  170264. /*
  170265. * Initialize the input controller module.
  170266. * This is called only once, when the decompression object is created.
  170267. */
  170268. GLOBAL(void)
  170269. jinit_input_controller (j_decompress_ptr cinfo)
  170270. {
  170271. my_inputctl_ptr inputctl;
  170272. /* Create subobject in permanent pool */
  170273. inputctl = (my_inputctl_ptr)
  170274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170275. SIZEOF(my_input_controller));
  170276. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170277. /* Initialize method pointers */
  170278. inputctl->pub.consume_input = consume_markers;
  170279. inputctl->pub.reset_input_controller = reset_input_controller;
  170280. inputctl->pub.start_input_pass = start_input_pass2;
  170281. inputctl->pub.finish_input_pass = finish_input_pass;
  170282. /* Initialize state: can't use reset_input_controller since we don't
  170283. * want to try to reset other modules yet.
  170284. */
  170285. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170286. inputctl->pub.eoi_reached = FALSE;
  170287. inputctl->inheaders = TRUE;
  170288. }
  170289. /*** End of inlined file: jdinput.c ***/
  170290. /*** Start of inlined file: jdmainct.c ***/
  170291. #define JPEG_INTERNALS
  170292. /*
  170293. * In the current system design, the main buffer need never be a full-image
  170294. * buffer; any full-height buffers will be found inside the coefficient or
  170295. * postprocessing controllers. Nonetheless, the main controller is not
  170296. * trivial. Its responsibility is to provide context rows for upsampling/
  170297. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170298. *
  170299. * Postprocessor input data is counted in "row groups". A row group
  170300. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170301. * sample rows of each component. (We require DCT_scaled_size values to be
  170302. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170303. * values will likely be powers of two, so we actually have the stronger
  170304. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170305. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170306. * row group (times any additional scale factor that the upsampler is
  170307. * applying).
  170308. *
  170309. * The coefficient controller will deliver data to us one iMCU row at a time;
  170310. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170311. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170312. * to one row of MCUs when the image is fully interleaved.) Note that the
  170313. * number of sample rows varies across components, but the number of row
  170314. * groups does not. Some garbage sample rows may be included in the last iMCU
  170315. * row at the bottom of the image.
  170316. *
  170317. * Depending on the vertical scaling algorithm used, the upsampler may need
  170318. * access to the sample row(s) above and below its current input row group.
  170319. * The upsampler is required to set need_context_rows TRUE at global selection
  170320. * time if so. When need_context_rows is FALSE, this controller can simply
  170321. * obtain one iMCU row at a time from the coefficient controller and dole it
  170322. * out as row groups to the postprocessor.
  170323. *
  170324. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170325. * passed to postprocessing contains at least one row group's worth of samples
  170326. * above and below the row group(s) being processed. Note that the context
  170327. * rows "above" the first passed row group appear at negative row offsets in
  170328. * the passed buffer. At the top and bottom of the image, the required
  170329. * context rows are manufactured by duplicating the first or last real sample
  170330. * row; this avoids having special cases in the upsampling inner loops.
  170331. *
  170332. * The amount of context is fixed at one row group just because that's a
  170333. * convenient number for this controller to work with. The existing
  170334. * upsamplers really only need one sample row of context. An upsampler
  170335. * supporting arbitrary output rescaling might wish for more than one row
  170336. * group of context when shrinking the image; tough, we don't handle that.
  170337. * (This is justified by the assumption that downsizing will be handled mostly
  170338. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170339. * the upsample step needn't be much less than one.)
  170340. *
  170341. * To provide the desired context, we have to retain the last two row groups
  170342. * of one iMCU row while reading in the next iMCU row. (The last row group
  170343. * can't be processed until we have another row group for its below-context,
  170344. * and so we have to save the next-to-last group too for its above-context.)
  170345. * We could do this most simply by copying data around in our buffer, but
  170346. * that'd be very slow. We can avoid copying any data by creating a rather
  170347. * strange pointer structure. Here's how it works. We allocate a workspace
  170348. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170349. * of row groups per iMCU row). We create two sets of redundant pointers to
  170350. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170351. * pointer lists look like this:
  170352. * M+1 M-1
  170353. * master pointer --> 0 master pointer --> 0
  170354. * 1 1
  170355. * ... ...
  170356. * M-3 M-3
  170357. * M-2 M
  170358. * M-1 M+1
  170359. * M M-2
  170360. * M+1 M-1
  170361. * 0 0
  170362. * We read alternate iMCU rows using each master pointer; thus the last two
  170363. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170364. * The pointer lists are set up so that the required context rows appear to
  170365. * be adjacent to the proper places when we pass the pointer lists to the
  170366. * upsampler.
  170367. *
  170368. * The above pictures describe the normal state of the pointer lists.
  170369. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170370. * the first or last sample row as necessary (this is cheaper than copying
  170371. * sample rows around).
  170372. *
  170373. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170374. * situation each iMCU row provides only one row group so the buffering logic
  170375. * must be different (eg, we must read two iMCU rows before we can emit the
  170376. * first row group). For now, we simply do not support providing context
  170377. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170378. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170379. * want it quick and dirty, so a context-free upsampler is sufficient.
  170380. */
  170381. /* Private buffer controller object */
  170382. typedef struct {
  170383. struct jpeg_d_main_controller pub; /* public fields */
  170384. /* Pointer to allocated workspace (M or M+2 row groups). */
  170385. JSAMPARRAY buffer[MAX_COMPONENTS];
  170386. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170387. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170388. /* Remaining fields are only used in the context case. */
  170389. /* These are the master pointers to the funny-order pointer lists. */
  170390. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170391. int whichptr; /* indicates which pointer set is now in use */
  170392. int context_state; /* process_data state machine status */
  170393. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170394. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170395. } my_main_controller4;
  170396. typedef my_main_controller4 * my_main_ptr4;
  170397. /* context_state values: */
  170398. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170399. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170400. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170401. /* Forward declarations */
  170402. METHODDEF(void) process_data_simple_main2
  170403. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170404. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170405. METHODDEF(void) process_data_context_main
  170406. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170407. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170408. #ifdef QUANT_2PASS_SUPPORTED
  170409. METHODDEF(void) process_data_crank_post
  170410. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170411. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170412. #endif
  170413. LOCAL(void)
  170414. alloc_funny_pointers (j_decompress_ptr cinfo)
  170415. /* Allocate space for the funny pointer lists.
  170416. * This is done only once, not once per pass.
  170417. */
  170418. {
  170419. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170420. int ci, rgroup;
  170421. int M = cinfo->min_DCT_scaled_size;
  170422. jpeg_component_info *compptr;
  170423. JSAMPARRAY xbuf;
  170424. /* Get top-level space for component array pointers.
  170425. * We alloc both arrays with one call to save a few cycles.
  170426. */
  170427. main_->xbuffer[0] = (JSAMPIMAGE)
  170428. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170429. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170430. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170432. ci++, compptr++) {
  170433. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170434. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170435. /* Get space for pointer lists --- M+4 row groups in each list.
  170436. * We alloc both pointer lists with one call to save a few cycles.
  170437. */
  170438. xbuf = (JSAMPARRAY)
  170439. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170440. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170441. xbuf += rgroup; /* want one row group at negative offsets */
  170442. main_->xbuffer[0][ci] = xbuf;
  170443. xbuf += rgroup * (M + 4);
  170444. main_->xbuffer[1][ci] = xbuf;
  170445. }
  170446. }
  170447. LOCAL(void)
  170448. make_funny_pointers (j_decompress_ptr cinfo)
  170449. /* Create the funny pointer lists discussed in the comments above.
  170450. * The actual workspace is already allocated (in main->buffer),
  170451. * and the space for the pointer lists is allocated too.
  170452. * This routine just fills in the curiously ordered lists.
  170453. * This will be repeated at the beginning of each pass.
  170454. */
  170455. {
  170456. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170457. int ci, i, rgroup;
  170458. int M = cinfo->min_DCT_scaled_size;
  170459. jpeg_component_info *compptr;
  170460. JSAMPARRAY buf, xbuf0, xbuf1;
  170461. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170462. ci++, compptr++) {
  170463. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170464. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170465. xbuf0 = main_->xbuffer[0][ci];
  170466. xbuf1 = main_->xbuffer[1][ci];
  170467. /* First copy the workspace pointers as-is */
  170468. buf = main_->buffer[ci];
  170469. for (i = 0; i < rgroup * (M + 2); i++) {
  170470. xbuf0[i] = xbuf1[i] = buf[i];
  170471. }
  170472. /* In the second list, put the last four row groups in swapped order */
  170473. for (i = 0; i < rgroup * 2; i++) {
  170474. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170475. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170476. }
  170477. /* The wraparound pointers at top and bottom will be filled later
  170478. * (see set_wraparound_pointers, below). Initially we want the "above"
  170479. * pointers to duplicate the first actual data line. This only needs
  170480. * to happen in xbuffer[0].
  170481. */
  170482. for (i = 0; i < rgroup; i++) {
  170483. xbuf0[i - rgroup] = xbuf0[0];
  170484. }
  170485. }
  170486. }
  170487. LOCAL(void)
  170488. set_wraparound_pointers (j_decompress_ptr cinfo)
  170489. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170490. * This changes the pointer list state from top-of-image to the normal state.
  170491. */
  170492. {
  170493. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170494. int ci, i, rgroup;
  170495. int M = cinfo->min_DCT_scaled_size;
  170496. jpeg_component_info *compptr;
  170497. JSAMPARRAY xbuf0, xbuf1;
  170498. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170499. ci++, compptr++) {
  170500. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170501. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170502. xbuf0 = main_->xbuffer[0][ci];
  170503. xbuf1 = main_->xbuffer[1][ci];
  170504. for (i = 0; i < rgroup; i++) {
  170505. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170506. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170507. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170508. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170509. }
  170510. }
  170511. }
  170512. LOCAL(void)
  170513. set_bottom_pointers (j_decompress_ptr cinfo)
  170514. /* Change the pointer lists to duplicate the last sample row at the bottom
  170515. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170516. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170517. */
  170518. {
  170519. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170520. int ci, i, rgroup, iMCUheight, rows_left;
  170521. jpeg_component_info *compptr;
  170522. JSAMPARRAY xbuf;
  170523. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170524. ci++, compptr++) {
  170525. /* Count sample rows in one iMCU row and in one row group */
  170526. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170527. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170528. /* Count nondummy sample rows remaining for this component */
  170529. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170530. if (rows_left == 0) rows_left = iMCUheight;
  170531. /* Count nondummy row groups. Should get same answer for each component,
  170532. * so we need only do it once.
  170533. */
  170534. if (ci == 0) {
  170535. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170536. }
  170537. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170538. * last partial rowgroup and ensures at least one full rowgroup of context.
  170539. */
  170540. xbuf = main_->xbuffer[main_->whichptr][ci];
  170541. for (i = 0; i < rgroup * 2; i++) {
  170542. xbuf[rows_left + i] = xbuf[rows_left-1];
  170543. }
  170544. }
  170545. }
  170546. /*
  170547. * Initialize for a processing pass.
  170548. */
  170549. METHODDEF(void)
  170550. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170551. {
  170552. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170553. switch (pass_mode) {
  170554. case JBUF_PASS_THRU:
  170555. if (cinfo->upsample->need_context_rows) {
  170556. main_->pub.process_data = process_data_context_main;
  170557. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170558. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170559. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170560. main_->iMCU_row_ctr = 0;
  170561. } else {
  170562. /* Simple case with no context needed */
  170563. main_->pub.process_data = process_data_simple_main2;
  170564. }
  170565. main_->buffer_full = FALSE; /* Mark buffer empty */
  170566. main_->rowgroup_ctr = 0;
  170567. break;
  170568. #ifdef QUANT_2PASS_SUPPORTED
  170569. case JBUF_CRANK_DEST:
  170570. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170571. main_->pub.process_data = process_data_crank_post;
  170572. break;
  170573. #endif
  170574. default:
  170575. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170576. break;
  170577. }
  170578. }
  170579. /*
  170580. * Process some data.
  170581. * This handles the simple case where no context is required.
  170582. */
  170583. METHODDEF(void)
  170584. process_data_simple_main2 (j_decompress_ptr cinfo,
  170585. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170586. JDIMENSION out_rows_avail)
  170587. {
  170588. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170589. JDIMENSION rowgroups_avail;
  170590. /* Read input data if we haven't filled the main buffer yet */
  170591. if (! main_->buffer_full) {
  170592. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170593. return; /* suspension forced, can do nothing more */
  170594. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170595. }
  170596. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170597. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170598. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170599. * to the postprocessor. The postprocessor has to check for bottom
  170600. * of image anyway (at row resolution), so no point in us doing it too.
  170601. */
  170602. /* Feed the postprocessor */
  170603. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170604. &main_->rowgroup_ctr, rowgroups_avail,
  170605. output_buf, out_row_ctr, out_rows_avail);
  170606. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170607. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170608. main_->buffer_full = FALSE;
  170609. main_->rowgroup_ctr = 0;
  170610. }
  170611. }
  170612. /*
  170613. * Process some data.
  170614. * This handles the case where context rows must be provided.
  170615. */
  170616. METHODDEF(void)
  170617. process_data_context_main (j_decompress_ptr cinfo,
  170618. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170619. JDIMENSION out_rows_avail)
  170620. {
  170621. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170622. /* Read input data if we haven't filled the main buffer yet */
  170623. if (! main_->buffer_full) {
  170624. if (! (*cinfo->coef->decompress_data) (cinfo,
  170625. main_->xbuffer[main_->whichptr]))
  170626. return; /* suspension forced, can do nothing more */
  170627. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170628. main_->iMCU_row_ctr++; /* count rows received */
  170629. }
  170630. /* Postprocessor typically will not swallow all the input data it is handed
  170631. * in one call (due to filling the output buffer first). Must be prepared
  170632. * to exit and restart. This switch lets us keep track of how far we got.
  170633. * Note that each case falls through to the next on successful completion.
  170634. */
  170635. switch (main_->context_state) {
  170636. case CTX_POSTPONED_ROW:
  170637. /* Call postprocessor using previously set pointers for postponed row */
  170638. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170639. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170640. output_buf, out_row_ctr, out_rows_avail);
  170641. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170642. return; /* Need to suspend */
  170643. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170644. if (*out_row_ctr >= out_rows_avail)
  170645. return; /* Postprocessor exactly filled output buf */
  170646. /*FALLTHROUGH*/
  170647. case CTX_PREPARE_FOR_IMCU:
  170648. /* Prepare to process first M-1 row groups of this iMCU row */
  170649. main_->rowgroup_ctr = 0;
  170650. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170651. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170652. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170653. */
  170654. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170655. set_bottom_pointers(cinfo);
  170656. main_->context_state = CTX_PROCESS_IMCU;
  170657. /*FALLTHROUGH*/
  170658. case CTX_PROCESS_IMCU:
  170659. /* Call postprocessor using previously set pointers */
  170660. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170661. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170662. output_buf, out_row_ctr, out_rows_avail);
  170663. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170664. return; /* Need to suspend */
  170665. /* After the first iMCU, change wraparound pointers to normal state */
  170666. if (main_->iMCU_row_ctr == 1)
  170667. set_wraparound_pointers(cinfo);
  170668. /* Prepare to load new iMCU row using other xbuffer list */
  170669. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170670. main_->buffer_full = FALSE;
  170671. /* Still need to process last row group of this iMCU row, */
  170672. /* which is saved at index M+1 of the other xbuffer */
  170673. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170674. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170675. main_->context_state = CTX_POSTPONED_ROW;
  170676. }
  170677. }
  170678. /*
  170679. * Process some data.
  170680. * Final pass of two-pass quantization: just call the postprocessor.
  170681. * Source data will be the postprocessor controller's internal buffer.
  170682. */
  170683. #ifdef QUANT_2PASS_SUPPORTED
  170684. METHODDEF(void)
  170685. process_data_crank_post (j_decompress_ptr cinfo,
  170686. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170687. JDIMENSION out_rows_avail)
  170688. {
  170689. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170690. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170691. output_buf, out_row_ctr, out_rows_avail);
  170692. }
  170693. #endif /* QUANT_2PASS_SUPPORTED */
  170694. /*
  170695. * Initialize main buffer controller.
  170696. */
  170697. GLOBAL(void)
  170698. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170699. {
  170700. my_main_ptr4 main_;
  170701. int ci, rgroup, ngroups;
  170702. jpeg_component_info *compptr;
  170703. main_ = (my_main_ptr4)
  170704. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170705. SIZEOF(my_main_controller4));
  170706. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170707. main_->pub.start_pass = start_pass_main2;
  170708. if (need_full_buffer) /* shouldn't happen */
  170709. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170710. /* Allocate the workspace.
  170711. * ngroups is the number of row groups we need.
  170712. */
  170713. if (cinfo->upsample->need_context_rows) {
  170714. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170715. ERREXIT(cinfo, JERR_NOTIMPL);
  170716. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170717. ngroups = cinfo->min_DCT_scaled_size + 2;
  170718. } else {
  170719. ngroups = cinfo->min_DCT_scaled_size;
  170720. }
  170721. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170722. ci++, compptr++) {
  170723. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170724. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170725. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170726. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170727. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170728. (JDIMENSION) (rgroup * ngroups));
  170729. }
  170730. }
  170731. /*** End of inlined file: jdmainct.c ***/
  170732. /*** Start of inlined file: jdmarker.c ***/
  170733. #define JPEG_INTERNALS
  170734. /* Private state */
  170735. typedef struct {
  170736. struct jpeg_marker_reader pub; /* public fields */
  170737. /* Application-overridable marker processing methods */
  170738. jpeg_marker_parser_method process_COM;
  170739. jpeg_marker_parser_method process_APPn[16];
  170740. /* Limit on marker data length to save for each marker type */
  170741. unsigned int length_limit_COM;
  170742. unsigned int length_limit_APPn[16];
  170743. /* Status of COM/APPn marker saving */
  170744. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170745. unsigned int bytes_read; /* data bytes read so far in marker */
  170746. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170747. } my_marker_reader;
  170748. typedef my_marker_reader * my_marker_ptr2;
  170749. /*
  170750. * Macros for fetching data from the data source module.
  170751. *
  170752. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170753. * the current restart point; we update them only when we have reached a
  170754. * suitable place to restart if a suspension occurs.
  170755. */
  170756. /* Declare and initialize local copies of input pointer/count */
  170757. #define INPUT_VARS(cinfo) \
  170758. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170759. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170760. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170761. /* Unload the local copies --- do this only at a restart boundary */
  170762. #define INPUT_SYNC(cinfo) \
  170763. ( datasrc->next_input_byte = next_input_byte, \
  170764. datasrc->bytes_in_buffer = bytes_in_buffer )
  170765. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170766. #define INPUT_RELOAD(cinfo) \
  170767. ( next_input_byte = datasrc->next_input_byte, \
  170768. bytes_in_buffer = datasrc->bytes_in_buffer )
  170769. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170770. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170771. * but we must reload the local copies after a successful fill.
  170772. */
  170773. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170774. if (bytes_in_buffer == 0) { \
  170775. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170776. { action; } \
  170777. INPUT_RELOAD(cinfo); \
  170778. }
  170779. /* Read a byte into variable V.
  170780. * If must suspend, take the specified action (typically "return FALSE").
  170781. */
  170782. #define INPUT_BYTE(cinfo,V,action) \
  170783. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170784. bytes_in_buffer--; \
  170785. V = GETJOCTET(*next_input_byte++); )
  170786. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170787. * V should be declared unsigned int or perhaps INT32.
  170788. */
  170789. #define INPUT_2BYTES(cinfo,V,action) \
  170790. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170791. bytes_in_buffer--; \
  170792. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170793. MAKE_BYTE_AVAIL(cinfo,action); \
  170794. bytes_in_buffer--; \
  170795. V += GETJOCTET(*next_input_byte++); )
  170796. /*
  170797. * Routines to process JPEG markers.
  170798. *
  170799. * Entry condition: JPEG marker itself has been read and its code saved
  170800. * in cinfo->unread_marker; input restart point is just after the marker.
  170801. *
  170802. * Exit: if return TRUE, have read and processed any parameters, and have
  170803. * updated the restart point to point after the parameters.
  170804. * If return FALSE, was forced to suspend before reaching end of
  170805. * marker parameters; restart point has not been moved. Same routine
  170806. * will be called again after application supplies more input data.
  170807. *
  170808. * This approach to suspension assumes that all of a marker's parameters
  170809. * can fit into a single input bufferload. This should hold for "normal"
  170810. * markers. Some COM/APPn markers might have large parameter segments
  170811. * that might not fit. If we are simply dropping such a marker, we use
  170812. * skip_input_data to get past it, and thereby put the problem on the
  170813. * source manager's shoulders. If we are saving the marker's contents
  170814. * into memory, we use a slightly different convention: when forced to
  170815. * suspend, the marker processor updates the restart point to the end of
  170816. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170817. * On resumption, cinfo->unread_marker still contains the marker code,
  170818. * but the data source will point to the next chunk of marker data.
  170819. * The marker processor must retain internal state to deal with this.
  170820. *
  170821. * Note that we don't bother to avoid duplicate trace messages if a
  170822. * suspension occurs within marker parameters. Other side effects
  170823. * require more care.
  170824. */
  170825. LOCAL(boolean)
  170826. get_soi (j_decompress_ptr cinfo)
  170827. /* Process an SOI marker */
  170828. {
  170829. int i;
  170830. TRACEMS(cinfo, 1, JTRC_SOI);
  170831. if (cinfo->marker->saw_SOI)
  170832. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170833. /* Reset all parameters that are defined to be reset by SOI */
  170834. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170835. cinfo->arith_dc_L[i] = 0;
  170836. cinfo->arith_dc_U[i] = 1;
  170837. cinfo->arith_ac_K[i] = 5;
  170838. }
  170839. cinfo->restart_interval = 0;
  170840. /* Set initial assumptions for colorspace etc */
  170841. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170842. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170843. cinfo->saw_JFIF_marker = FALSE;
  170844. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170845. cinfo->JFIF_minor_version = 1;
  170846. cinfo->density_unit = 0;
  170847. cinfo->X_density = 1;
  170848. cinfo->Y_density = 1;
  170849. cinfo->saw_Adobe_marker = FALSE;
  170850. cinfo->Adobe_transform = 0;
  170851. cinfo->marker->saw_SOI = TRUE;
  170852. return TRUE;
  170853. }
  170854. LOCAL(boolean)
  170855. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170856. /* Process a SOFn marker */
  170857. {
  170858. INT32 length;
  170859. int c, ci;
  170860. jpeg_component_info * compptr;
  170861. INPUT_VARS(cinfo);
  170862. cinfo->progressive_mode = is_prog;
  170863. cinfo->arith_code = is_arith;
  170864. INPUT_2BYTES(cinfo, length, return FALSE);
  170865. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170866. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170867. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170868. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170869. length -= 8;
  170870. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170871. (int) cinfo->image_width, (int) cinfo->image_height,
  170872. cinfo->num_components);
  170873. if (cinfo->marker->saw_SOF)
  170874. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170875. /* We don't support files in which the image height is initially specified */
  170876. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170877. /* might as well have a general sanity check. */
  170878. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170879. || cinfo->num_components <= 0)
  170880. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170881. if (length != (cinfo->num_components * 3))
  170882. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170883. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170884. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170885. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170886. cinfo->num_components * SIZEOF(jpeg_component_info));
  170887. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170888. ci++, compptr++) {
  170889. compptr->component_index = ci;
  170890. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170891. INPUT_BYTE(cinfo, c, return FALSE);
  170892. compptr->h_samp_factor = (c >> 4) & 15;
  170893. compptr->v_samp_factor = (c ) & 15;
  170894. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170895. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170896. compptr->component_id, compptr->h_samp_factor,
  170897. compptr->v_samp_factor, compptr->quant_tbl_no);
  170898. }
  170899. cinfo->marker->saw_SOF = TRUE;
  170900. INPUT_SYNC(cinfo);
  170901. return TRUE;
  170902. }
  170903. LOCAL(boolean)
  170904. get_sos (j_decompress_ptr cinfo)
  170905. /* Process a SOS marker */
  170906. {
  170907. INT32 length;
  170908. int i, ci, n, c, cc;
  170909. jpeg_component_info * compptr;
  170910. INPUT_VARS(cinfo);
  170911. if (! cinfo->marker->saw_SOF)
  170912. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170913. INPUT_2BYTES(cinfo, length, return FALSE);
  170914. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170915. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170916. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170917. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170918. cinfo->comps_in_scan = n;
  170919. /* Collect the component-spec parameters */
  170920. for (i = 0; i < n; i++) {
  170921. INPUT_BYTE(cinfo, cc, return FALSE);
  170922. INPUT_BYTE(cinfo, c, return FALSE);
  170923. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170924. ci++, compptr++) {
  170925. if (cc == compptr->component_id)
  170926. goto id_found;
  170927. }
  170928. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170929. id_found:
  170930. cinfo->cur_comp_info[i] = compptr;
  170931. compptr->dc_tbl_no = (c >> 4) & 15;
  170932. compptr->ac_tbl_no = (c ) & 15;
  170933. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170934. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170935. }
  170936. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170937. INPUT_BYTE(cinfo, c, return FALSE);
  170938. cinfo->Ss = c;
  170939. INPUT_BYTE(cinfo, c, return FALSE);
  170940. cinfo->Se = c;
  170941. INPUT_BYTE(cinfo, c, return FALSE);
  170942. cinfo->Ah = (c >> 4) & 15;
  170943. cinfo->Al = (c ) & 15;
  170944. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170945. cinfo->Ah, cinfo->Al);
  170946. /* Prepare to scan data & restart markers */
  170947. cinfo->marker->next_restart_num = 0;
  170948. /* Count another SOS marker */
  170949. cinfo->input_scan_number++;
  170950. INPUT_SYNC(cinfo);
  170951. return TRUE;
  170952. }
  170953. #ifdef D_ARITH_CODING_SUPPORTED
  170954. LOCAL(boolean)
  170955. get_dac (j_decompress_ptr cinfo)
  170956. /* Process a DAC marker */
  170957. {
  170958. INT32 length;
  170959. int index, val;
  170960. INPUT_VARS(cinfo);
  170961. INPUT_2BYTES(cinfo, length, return FALSE);
  170962. length -= 2;
  170963. while (length > 0) {
  170964. INPUT_BYTE(cinfo, index, return FALSE);
  170965. INPUT_BYTE(cinfo, val, return FALSE);
  170966. length -= 2;
  170967. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170968. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170969. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170970. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170971. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170972. } else { /* define DC table */
  170973. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170974. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170975. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170976. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170977. }
  170978. }
  170979. if (length != 0)
  170980. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170981. INPUT_SYNC(cinfo);
  170982. return TRUE;
  170983. }
  170984. #else /* ! D_ARITH_CODING_SUPPORTED */
  170985. #define get_dac(cinfo) skip_variable(cinfo)
  170986. #endif /* D_ARITH_CODING_SUPPORTED */
  170987. LOCAL(boolean)
  170988. get_dht (j_decompress_ptr cinfo)
  170989. /* Process a DHT marker */
  170990. {
  170991. INT32 length;
  170992. UINT8 bits[17];
  170993. UINT8 huffval[256];
  170994. int i, index, count;
  170995. JHUFF_TBL **htblptr;
  170996. INPUT_VARS(cinfo);
  170997. INPUT_2BYTES(cinfo, length, return FALSE);
  170998. length -= 2;
  170999. while (length > 16) {
  171000. INPUT_BYTE(cinfo, index, return FALSE);
  171001. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171002. bits[0] = 0;
  171003. count = 0;
  171004. for (i = 1; i <= 16; i++) {
  171005. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171006. count += bits[i];
  171007. }
  171008. length -= 1 + 16;
  171009. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171010. bits[1], bits[2], bits[3], bits[4],
  171011. bits[5], bits[6], bits[7], bits[8]);
  171012. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171013. bits[9], bits[10], bits[11], bits[12],
  171014. bits[13], bits[14], bits[15], bits[16]);
  171015. /* Here we just do minimal validation of the counts to avoid walking
  171016. * off the end of our table space. jdhuff.c will check more carefully.
  171017. */
  171018. if (count > 256 || ((INT32) count) > length)
  171019. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171020. for (i = 0; i < count; i++)
  171021. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171022. length -= count;
  171023. if (index & 0x10) { /* AC table definition */
  171024. index -= 0x10;
  171025. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171026. } else { /* DC table definition */
  171027. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171028. }
  171029. if (index < 0 || index >= NUM_HUFF_TBLS)
  171030. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171031. if (*htblptr == NULL)
  171032. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171033. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171034. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171035. }
  171036. if (length != 0)
  171037. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171038. INPUT_SYNC(cinfo);
  171039. return TRUE;
  171040. }
  171041. LOCAL(boolean)
  171042. get_dqt (j_decompress_ptr cinfo)
  171043. /* Process a DQT marker */
  171044. {
  171045. INT32 length;
  171046. int n, i, prec;
  171047. unsigned int tmp;
  171048. JQUANT_TBL *quant_ptr;
  171049. INPUT_VARS(cinfo);
  171050. INPUT_2BYTES(cinfo, length, return FALSE);
  171051. length -= 2;
  171052. while (length > 0) {
  171053. INPUT_BYTE(cinfo, n, return FALSE);
  171054. prec = n >> 4;
  171055. n &= 0x0F;
  171056. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171057. if (n >= NUM_QUANT_TBLS)
  171058. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171059. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171060. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171061. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171062. for (i = 0; i < DCTSIZE2; i++) {
  171063. if (prec)
  171064. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171065. else
  171066. INPUT_BYTE(cinfo, tmp, return FALSE);
  171067. /* We convert the zigzag-order table to natural array order. */
  171068. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171069. }
  171070. if (cinfo->err->trace_level >= 2) {
  171071. for (i = 0; i < DCTSIZE2; i += 8) {
  171072. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171073. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171074. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171075. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171076. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171077. }
  171078. }
  171079. length -= DCTSIZE2+1;
  171080. if (prec) length -= DCTSIZE2;
  171081. }
  171082. if (length != 0)
  171083. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171084. INPUT_SYNC(cinfo);
  171085. return TRUE;
  171086. }
  171087. LOCAL(boolean)
  171088. get_dri (j_decompress_ptr cinfo)
  171089. /* Process a DRI marker */
  171090. {
  171091. INT32 length;
  171092. unsigned int tmp;
  171093. INPUT_VARS(cinfo);
  171094. INPUT_2BYTES(cinfo, length, return FALSE);
  171095. if (length != 4)
  171096. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171097. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171098. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171099. cinfo->restart_interval = tmp;
  171100. INPUT_SYNC(cinfo);
  171101. return TRUE;
  171102. }
  171103. /*
  171104. * Routines for processing APPn and COM markers.
  171105. * These are either saved in memory or discarded, per application request.
  171106. * APP0 and APP14 are specially checked to see if they are
  171107. * JFIF and Adobe markers, respectively.
  171108. */
  171109. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171110. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171111. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171112. LOCAL(void)
  171113. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171114. unsigned int datalen, INT32 remaining)
  171115. /* Examine first few bytes from an APP0.
  171116. * Take appropriate action if it is a JFIF marker.
  171117. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171118. */
  171119. {
  171120. INT32 totallen = (INT32) datalen + remaining;
  171121. if (datalen >= APP0_DATA_LEN &&
  171122. GETJOCTET(data[0]) == 0x4A &&
  171123. GETJOCTET(data[1]) == 0x46 &&
  171124. GETJOCTET(data[2]) == 0x49 &&
  171125. GETJOCTET(data[3]) == 0x46 &&
  171126. GETJOCTET(data[4]) == 0) {
  171127. /* Found JFIF APP0 marker: save info */
  171128. cinfo->saw_JFIF_marker = TRUE;
  171129. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171130. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171131. cinfo->density_unit = GETJOCTET(data[7]);
  171132. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171133. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171134. /* Check version.
  171135. * Major version must be 1, anything else signals an incompatible change.
  171136. * (We used to treat this as an error, but now it's a nonfatal warning,
  171137. * because some bozo at Hijaak couldn't read the spec.)
  171138. * Minor version should be 0..2, but process anyway if newer.
  171139. */
  171140. if (cinfo->JFIF_major_version != 1)
  171141. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171142. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171143. /* Generate trace messages */
  171144. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171145. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171146. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171147. /* Validate thumbnail dimensions and issue appropriate messages */
  171148. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171149. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171150. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171151. totallen -= APP0_DATA_LEN;
  171152. if (totallen !=
  171153. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171154. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171155. } else if (datalen >= 6 &&
  171156. GETJOCTET(data[0]) == 0x4A &&
  171157. GETJOCTET(data[1]) == 0x46 &&
  171158. GETJOCTET(data[2]) == 0x58 &&
  171159. GETJOCTET(data[3]) == 0x58 &&
  171160. GETJOCTET(data[4]) == 0) {
  171161. /* Found JFIF "JFXX" extension APP0 marker */
  171162. /* The library doesn't actually do anything with these,
  171163. * but we try to produce a helpful trace message.
  171164. */
  171165. switch (GETJOCTET(data[5])) {
  171166. case 0x10:
  171167. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171168. break;
  171169. case 0x11:
  171170. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171171. break;
  171172. case 0x13:
  171173. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171174. break;
  171175. default:
  171176. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171177. GETJOCTET(data[5]), (int) totallen);
  171178. break;
  171179. }
  171180. } else {
  171181. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171182. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171183. }
  171184. }
  171185. LOCAL(void)
  171186. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171187. unsigned int datalen, INT32 remaining)
  171188. /* Examine first few bytes from an APP14.
  171189. * Take appropriate action if it is an Adobe marker.
  171190. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171191. */
  171192. {
  171193. unsigned int version, flags0, flags1, transform;
  171194. if (datalen >= APP14_DATA_LEN &&
  171195. GETJOCTET(data[0]) == 0x41 &&
  171196. GETJOCTET(data[1]) == 0x64 &&
  171197. GETJOCTET(data[2]) == 0x6F &&
  171198. GETJOCTET(data[3]) == 0x62 &&
  171199. GETJOCTET(data[4]) == 0x65) {
  171200. /* Found Adobe APP14 marker */
  171201. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171202. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171203. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171204. transform = GETJOCTET(data[11]);
  171205. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171206. cinfo->saw_Adobe_marker = TRUE;
  171207. cinfo->Adobe_transform = (UINT8) transform;
  171208. } else {
  171209. /* Start of APP14 does not match "Adobe", or too short */
  171210. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171211. }
  171212. }
  171213. METHODDEF(boolean)
  171214. get_interesting_appn (j_decompress_ptr cinfo)
  171215. /* Process an APP0 or APP14 marker without saving it */
  171216. {
  171217. INT32 length;
  171218. JOCTET b[APPN_DATA_LEN];
  171219. unsigned int i, numtoread;
  171220. INPUT_VARS(cinfo);
  171221. INPUT_2BYTES(cinfo, length, return FALSE);
  171222. length -= 2;
  171223. /* get the interesting part of the marker data */
  171224. if (length >= APPN_DATA_LEN)
  171225. numtoread = APPN_DATA_LEN;
  171226. else if (length > 0)
  171227. numtoread = (unsigned int) length;
  171228. else
  171229. numtoread = 0;
  171230. for (i = 0; i < numtoread; i++)
  171231. INPUT_BYTE(cinfo, b[i], return FALSE);
  171232. length -= numtoread;
  171233. /* process it */
  171234. switch (cinfo->unread_marker) {
  171235. case M_APP0:
  171236. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171237. break;
  171238. case M_APP14:
  171239. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171240. break;
  171241. default:
  171242. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171243. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171244. break;
  171245. }
  171246. /* skip any remaining data -- could be lots */
  171247. INPUT_SYNC(cinfo);
  171248. if (length > 0)
  171249. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171250. return TRUE;
  171251. }
  171252. #ifdef SAVE_MARKERS_SUPPORTED
  171253. METHODDEF(boolean)
  171254. save_marker (j_decompress_ptr cinfo)
  171255. /* Save an APPn or COM marker into the marker list */
  171256. {
  171257. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171258. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171259. unsigned int bytes_read, data_length;
  171260. JOCTET FAR * data;
  171261. INT32 length = 0;
  171262. INPUT_VARS(cinfo);
  171263. if (cur_marker == NULL) {
  171264. /* begin reading a marker */
  171265. INPUT_2BYTES(cinfo, length, return FALSE);
  171266. length -= 2;
  171267. if (length >= 0) { /* watch out for bogus length word */
  171268. /* figure out how much we want to save */
  171269. unsigned int limit;
  171270. if (cinfo->unread_marker == (int) M_COM)
  171271. limit = marker->length_limit_COM;
  171272. else
  171273. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171274. if ((unsigned int) length < limit)
  171275. limit = (unsigned int) length;
  171276. /* allocate and initialize the marker item */
  171277. cur_marker = (jpeg_saved_marker_ptr)
  171278. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171279. SIZEOF(struct jpeg_marker_struct) + limit);
  171280. cur_marker->next = NULL;
  171281. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171282. cur_marker->original_length = (unsigned int) length;
  171283. cur_marker->data_length = limit;
  171284. /* data area is just beyond the jpeg_marker_struct */
  171285. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171286. marker->cur_marker = cur_marker;
  171287. marker->bytes_read = 0;
  171288. bytes_read = 0;
  171289. data_length = limit;
  171290. } else {
  171291. /* deal with bogus length word */
  171292. bytes_read = data_length = 0;
  171293. data = NULL;
  171294. }
  171295. } else {
  171296. /* resume reading a marker */
  171297. bytes_read = marker->bytes_read;
  171298. data_length = cur_marker->data_length;
  171299. data = cur_marker->data + bytes_read;
  171300. }
  171301. while (bytes_read < data_length) {
  171302. INPUT_SYNC(cinfo); /* move the restart point to here */
  171303. marker->bytes_read = bytes_read;
  171304. /* If there's not at least one byte in buffer, suspend */
  171305. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171306. /* Copy bytes with reasonable rapidity */
  171307. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171308. *data++ = *next_input_byte++;
  171309. bytes_in_buffer--;
  171310. bytes_read++;
  171311. }
  171312. }
  171313. /* Done reading what we want to read */
  171314. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171315. /* Add new marker to end of list */
  171316. if (cinfo->marker_list == NULL) {
  171317. cinfo->marker_list = cur_marker;
  171318. } else {
  171319. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171320. while (prev->next != NULL)
  171321. prev = prev->next;
  171322. prev->next = cur_marker;
  171323. }
  171324. /* Reset pointer & calc remaining data length */
  171325. data = cur_marker->data;
  171326. length = cur_marker->original_length - data_length;
  171327. }
  171328. /* Reset to initial state for next marker */
  171329. marker->cur_marker = NULL;
  171330. /* Process the marker if interesting; else just make a generic trace msg */
  171331. switch (cinfo->unread_marker) {
  171332. case M_APP0:
  171333. examine_app0(cinfo, data, data_length, length);
  171334. break;
  171335. case M_APP14:
  171336. examine_app14(cinfo, data, data_length, length);
  171337. break;
  171338. default:
  171339. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171340. (int) (data_length + length));
  171341. break;
  171342. }
  171343. /* skip any remaining data -- could be lots */
  171344. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171345. if (length > 0)
  171346. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171347. return TRUE;
  171348. }
  171349. #endif /* SAVE_MARKERS_SUPPORTED */
  171350. METHODDEF(boolean)
  171351. skip_variable (j_decompress_ptr cinfo)
  171352. /* Skip over an unknown or uninteresting variable-length marker */
  171353. {
  171354. INT32 length;
  171355. INPUT_VARS(cinfo);
  171356. INPUT_2BYTES(cinfo, length, return FALSE);
  171357. length -= 2;
  171358. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171359. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171360. if (length > 0)
  171361. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171362. return TRUE;
  171363. }
  171364. /*
  171365. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171366. * Returns FALSE if had to suspend before reaching a marker;
  171367. * in that case cinfo->unread_marker is unchanged.
  171368. *
  171369. * Note that the result might not be a valid marker code,
  171370. * but it will never be 0 or FF.
  171371. */
  171372. LOCAL(boolean)
  171373. next_marker (j_decompress_ptr cinfo)
  171374. {
  171375. int c;
  171376. INPUT_VARS(cinfo);
  171377. for (;;) {
  171378. INPUT_BYTE(cinfo, c, return FALSE);
  171379. /* Skip any non-FF bytes.
  171380. * This may look a bit inefficient, but it will not occur in a valid file.
  171381. * We sync after each discarded byte so that a suspending data source
  171382. * can discard the byte from its buffer.
  171383. */
  171384. while (c != 0xFF) {
  171385. cinfo->marker->discarded_bytes++;
  171386. INPUT_SYNC(cinfo);
  171387. INPUT_BYTE(cinfo, c, return FALSE);
  171388. }
  171389. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171390. * pad bytes, so don't count them in discarded_bytes. We assume there
  171391. * will not be so many consecutive FF bytes as to overflow a suspending
  171392. * data source's input buffer.
  171393. */
  171394. do {
  171395. INPUT_BYTE(cinfo, c, return FALSE);
  171396. } while (c == 0xFF);
  171397. if (c != 0)
  171398. break; /* found a valid marker, exit loop */
  171399. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171400. * Discard it and loop back to try again.
  171401. */
  171402. cinfo->marker->discarded_bytes += 2;
  171403. INPUT_SYNC(cinfo);
  171404. }
  171405. if (cinfo->marker->discarded_bytes != 0) {
  171406. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171407. cinfo->marker->discarded_bytes = 0;
  171408. }
  171409. cinfo->unread_marker = c;
  171410. INPUT_SYNC(cinfo);
  171411. return TRUE;
  171412. }
  171413. LOCAL(boolean)
  171414. first_marker (j_decompress_ptr cinfo)
  171415. /* Like next_marker, but used to obtain the initial SOI marker. */
  171416. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171417. * we might well scan an entire input file before realizing it ain't JPEG.
  171418. * If an application wants to process non-JFIF files, it must seek to the
  171419. * SOI before calling the JPEG library.
  171420. */
  171421. {
  171422. int c, c2;
  171423. INPUT_VARS(cinfo);
  171424. INPUT_BYTE(cinfo, c, return FALSE);
  171425. INPUT_BYTE(cinfo, c2, return FALSE);
  171426. if (c != 0xFF || c2 != (int) M_SOI)
  171427. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171428. cinfo->unread_marker = c2;
  171429. INPUT_SYNC(cinfo);
  171430. return TRUE;
  171431. }
  171432. /*
  171433. * Read markers until SOS or EOI.
  171434. *
  171435. * Returns same codes as are defined for jpeg_consume_input:
  171436. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171437. */
  171438. METHODDEF(int)
  171439. read_markers (j_decompress_ptr cinfo)
  171440. {
  171441. /* Outer loop repeats once for each marker. */
  171442. for (;;) {
  171443. /* Collect the marker proper, unless we already did. */
  171444. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171445. if (cinfo->unread_marker == 0) {
  171446. if (! cinfo->marker->saw_SOI) {
  171447. if (! first_marker(cinfo))
  171448. return JPEG_SUSPENDED;
  171449. } else {
  171450. if (! next_marker(cinfo))
  171451. return JPEG_SUSPENDED;
  171452. }
  171453. }
  171454. /* At this point cinfo->unread_marker contains the marker code and the
  171455. * input point is just past the marker proper, but before any parameters.
  171456. * A suspension will cause us to return with this state still true.
  171457. */
  171458. switch (cinfo->unread_marker) {
  171459. case M_SOI:
  171460. if (! get_soi(cinfo))
  171461. return JPEG_SUSPENDED;
  171462. break;
  171463. case M_SOF0: /* Baseline */
  171464. case M_SOF1: /* Extended sequential, Huffman */
  171465. if (! get_sof(cinfo, FALSE, FALSE))
  171466. return JPEG_SUSPENDED;
  171467. break;
  171468. case M_SOF2: /* Progressive, Huffman */
  171469. if (! get_sof(cinfo, TRUE, FALSE))
  171470. return JPEG_SUSPENDED;
  171471. break;
  171472. case M_SOF9: /* Extended sequential, arithmetic */
  171473. if (! get_sof(cinfo, FALSE, TRUE))
  171474. return JPEG_SUSPENDED;
  171475. break;
  171476. case M_SOF10: /* Progressive, arithmetic */
  171477. if (! get_sof(cinfo, TRUE, TRUE))
  171478. return JPEG_SUSPENDED;
  171479. break;
  171480. /* Currently unsupported SOFn types */
  171481. case M_SOF3: /* Lossless, Huffman */
  171482. case M_SOF5: /* Differential sequential, Huffman */
  171483. case M_SOF6: /* Differential progressive, Huffman */
  171484. case M_SOF7: /* Differential lossless, Huffman */
  171485. case M_JPG: /* Reserved for JPEG extensions */
  171486. case M_SOF11: /* Lossless, arithmetic */
  171487. case M_SOF13: /* Differential sequential, arithmetic */
  171488. case M_SOF14: /* Differential progressive, arithmetic */
  171489. case M_SOF15: /* Differential lossless, arithmetic */
  171490. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171491. break;
  171492. case M_SOS:
  171493. if (! get_sos(cinfo))
  171494. return JPEG_SUSPENDED;
  171495. cinfo->unread_marker = 0; /* processed the marker */
  171496. return JPEG_REACHED_SOS;
  171497. case M_EOI:
  171498. TRACEMS(cinfo, 1, JTRC_EOI);
  171499. cinfo->unread_marker = 0; /* processed the marker */
  171500. return JPEG_REACHED_EOI;
  171501. case M_DAC:
  171502. if (! get_dac(cinfo))
  171503. return JPEG_SUSPENDED;
  171504. break;
  171505. case M_DHT:
  171506. if (! get_dht(cinfo))
  171507. return JPEG_SUSPENDED;
  171508. break;
  171509. case M_DQT:
  171510. if (! get_dqt(cinfo))
  171511. return JPEG_SUSPENDED;
  171512. break;
  171513. case M_DRI:
  171514. if (! get_dri(cinfo))
  171515. return JPEG_SUSPENDED;
  171516. break;
  171517. case M_APP0:
  171518. case M_APP1:
  171519. case M_APP2:
  171520. case M_APP3:
  171521. case M_APP4:
  171522. case M_APP5:
  171523. case M_APP6:
  171524. case M_APP7:
  171525. case M_APP8:
  171526. case M_APP9:
  171527. case M_APP10:
  171528. case M_APP11:
  171529. case M_APP12:
  171530. case M_APP13:
  171531. case M_APP14:
  171532. case M_APP15:
  171533. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171534. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171535. return JPEG_SUSPENDED;
  171536. break;
  171537. case M_COM:
  171538. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171539. return JPEG_SUSPENDED;
  171540. break;
  171541. case M_RST0: /* these are all parameterless */
  171542. case M_RST1:
  171543. case M_RST2:
  171544. case M_RST3:
  171545. case M_RST4:
  171546. case M_RST5:
  171547. case M_RST6:
  171548. case M_RST7:
  171549. case M_TEM:
  171550. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171551. break;
  171552. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171553. if (! skip_variable(cinfo))
  171554. return JPEG_SUSPENDED;
  171555. break;
  171556. default: /* must be DHP, EXP, JPGn, or RESn */
  171557. /* For now, we treat the reserved markers as fatal errors since they are
  171558. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171559. * Once the JPEG 3 version-number marker is well defined, this code
  171560. * ought to change!
  171561. */
  171562. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171563. break;
  171564. }
  171565. /* Successfully processed marker, so reset state variable */
  171566. cinfo->unread_marker = 0;
  171567. } /* end loop */
  171568. }
  171569. /*
  171570. * Read a restart marker, which is expected to appear next in the datastream;
  171571. * if the marker is not there, take appropriate recovery action.
  171572. * Returns FALSE if suspension is required.
  171573. *
  171574. * This is called by the entropy decoder after it has read an appropriate
  171575. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171576. * has already read a marker from the data source. Under normal conditions
  171577. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171578. * it holds a marker which the decoder will be unable to read past.
  171579. */
  171580. METHODDEF(boolean)
  171581. read_restart_marker (j_decompress_ptr cinfo)
  171582. {
  171583. /* Obtain a marker unless we already did. */
  171584. /* Note that next_marker will complain if it skips any data. */
  171585. if (cinfo->unread_marker == 0) {
  171586. if (! next_marker(cinfo))
  171587. return FALSE;
  171588. }
  171589. if (cinfo->unread_marker ==
  171590. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171591. /* Normal case --- swallow the marker and let entropy decoder continue */
  171592. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171593. cinfo->unread_marker = 0;
  171594. } else {
  171595. /* Uh-oh, the restart markers have been messed up. */
  171596. /* Let the data source manager determine how to resync. */
  171597. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171598. cinfo->marker->next_restart_num))
  171599. return FALSE;
  171600. }
  171601. /* Update next-restart state */
  171602. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171603. return TRUE;
  171604. }
  171605. /*
  171606. * This is the default resync_to_restart method for data source managers
  171607. * to use if they don't have any better approach. Some data source managers
  171608. * may be able to back up, or may have additional knowledge about the data
  171609. * which permits a more intelligent recovery strategy; such managers would
  171610. * presumably supply their own resync method.
  171611. *
  171612. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171613. * the restart marker it was expecting. (This code is *not* used unless
  171614. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171615. * the marker code actually found (might be anything, except 0 or FF).
  171616. * The desired restart marker number (0..7) is passed as a parameter.
  171617. * This routine is supposed to apply whatever error recovery strategy seems
  171618. * appropriate in order to position the input stream to the next data segment.
  171619. * Note that cinfo->unread_marker is treated as a marker appearing before
  171620. * the current data-source input point; usually it should be reset to zero
  171621. * before returning.
  171622. * Returns FALSE if suspension is required.
  171623. *
  171624. * This implementation is substantially constrained by wanting to treat the
  171625. * input as a data stream; this means we can't back up. Therefore, we have
  171626. * only the following actions to work with:
  171627. * 1. Simply discard the marker and let the entropy decoder resume at next
  171628. * byte of file.
  171629. * 2. Read forward until we find another marker, discarding intervening
  171630. * data. (In theory we could look ahead within the current bufferload,
  171631. * without having to discard data if we don't find the desired marker.
  171632. * This idea is not implemented here, in part because it makes behavior
  171633. * dependent on buffer size and chance buffer-boundary positions.)
  171634. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171635. * This will cause the entropy decoder to process an empty data segment,
  171636. * inserting dummy zeroes, and then we will reprocess the marker.
  171637. *
  171638. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171639. * appropriate if the found marker is a future restart marker (indicating
  171640. * that we have missed the desired restart marker, probably because it got
  171641. * corrupted).
  171642. * We apply #2 or #3 if the found marker is a restart marker no more than
  171643. * two counts behind or ahead of the expected one. We also apply #2 if the
  171644. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171645. * If the found marker is a restart marker more than 2 counts away, we do #1
  171646. * (too much risk that the marker is erroneous; with luck we will be able to
  171647. * resync at some future point).
  171648. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171649. * overrunning the end of a scan. An implementation limited to single-scan
  171650. * files might find it better to apply #2 for markers other than EOI, since
  171651. * any other marker would have to be bogus data in that case.
  171652. */
  171653. GLOBAL(boolean)
  171654. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171655. {
  171656. int marker = cinfo->unread_marker;
  171657. int action = 1;
  171658. /* Always put up a warning. */
  171659. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171660. /* Outer loop handles repeated decision after scanning forward. */
  171661. for (;;) {
  171662. if (marker < (int) M_SOF0)
  171663. action = 2; /* invalid marker */
  171664. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171665. action = 3; /* valid non-restart marker */
  171666. else {
  171667. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171668. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171669. action = 3; /* one of the next two expected restarts */
  171670. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171671. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171672. action = 2; /* a prior restart, so advance */
  171673. else
  171674. action = 1; /* desired restart or too far away */
  171675. }
  171676. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171677. switch (action) {
  171678. case 1:
  171679. /* Discard marker and let entropy decoder resume processing. */
  171680. cinfo->unread_marker = 0;
  171681. return TRUE;
  171682. case 2:
  171683. /* Scan to the next marker, and repeat the decision loop. */
  171684. if (! next_marker(cinfo))
  171685. return FALSE;
  171686. marker = cinfo->unread_marker;
  171687. break;
  171688. case 3:
  171689. /* Return without advancing past this marker. */
  171690. /* Entropy decoder will be forced to process an empty segment. */
  171691. return TRUE;
  171692. }
  171693. } /* end loop */
  171694. }
  171695. /*
  171696. * Reset marker processing state to begin a fresh datastream.
  171697. */
  171698. METHODDEF(void)
  171699. reset_marker_reader (j_decompress_ptr cinfo)
  171700. {
  171701. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171702. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171703. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171704. cinfo->unread_marker = 0; /* no pending marker */
  171705. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171706. marker->pub.saw_SOF = FALSE;
  171707. marker->pub.discarded_bytes = 0;
  171708. marker->cur_marker = NULL;
  171709. }
  171710. /*
  171711. * Initialize the marker reader module.
  171712. * This is called only once, when the decompression object is created.
  171713. */
  171714. GLOBAL(void)
  171715. jinit_marker_reader (j_decompress_ptr cinfo)
  171716. {
  171717. my_marker_ptr2 marker;
  171718. int i;
  171719. /* Create subobject in permanent pool */
  171720. marker = (my_marker_ptr2)
  171721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171722. SIZEOF(my_marker_reader));
  171723. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171724. /* Initialize public method pointers */
  171725. marker->pub.reset_marker_reader = reset_marker_reader;
  171726. marker->pub.read_markers = read_markers;
  171727. marker->pub.read_restart_marker = read_restart_marker;
  171728. /* Initialize COM/APPn processing.
  171729. * By default, we examine and then discard APP0 and APP14,
  171730. * but simply discard COM and all other APPn.
  171731. */
  171732. marker->process_COM = skip_variable;
  171733. marker->length_limit_COM = 0;
  171734. for (i = 0; i < 16; i++) {
  171735. marker->process_APPn[i] = skip_variable;
  171736. marker->length_limit_APPn[i] = 0;
  171737. }
  171738. marker->process_APPn[0] = get_interesting_appn;
  171739. marker->process_APPn[14] = get_interesting_appn;
  171740. /* Reset marker processing state */
  171741. reset_marker_reader(cinfo);
  171742. }
  171743. /*
  171744. * Control saving of COM and APPn markers into marker_list.
  171745. */
  171746. #ifdef SAVE_MARKERS_SUPPORTED
  171747. GLOBAL(void)
  171748. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171749. unsigned int length_limit)
  171750. {
  171751. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171752. long maxlength;
  171753. jpeg_marker_parser_method processor;
  171754. /* Length limit mustn't be larger than what we can allocate
  171755. * (should only be a concern in a 16-bit environment).
  171756. */
  171757. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171758. if (((long) length_limit) > maxlength)
  171759. length_limit = (unsigned int) maxlength;
  171760. /* Choose processor routine to use.
  171761. * APP0/APP14 have special requirements.
  171762. */
  171763. if (length_limit) {
  171764. processor = save_marker;
  171765. /* If saving APP0/APP14, save at least enough for our internal use. */
  171766. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171767. length_limit = APP0_DATA_LEN;
  171768. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171769. length_limit = APP14_DATA_LEN;
  171770. } else {
  171771. processor = skip_variable;
  171772. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171773. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171774. processor = get_interesting_appn;
  171775. }
  171776. if (marker_code == (int) M_COM) {
  171777. marker->process_COM = processor;
  171778. marker->length_limit_COM = length_limit;
  171779. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171780. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171781. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171782. } else
  171783. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171784. }
  171785. #endif /* SAVE_MARKERS_SUPPORTED */
  171786. /*
  171787. * Install a special processing method for COM or APPn markers.
  171788. */
  171789. GLOBAL(void)
  171790. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171791. jpeg_marker_parser_method routine)
  171792. {
  171793. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171794. if (marker_code == (int) M_COM)
  171795. marker->process_COM = routine;
  171796. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171797. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171798. else
  171799. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171800. }
  171801. /*** End of inlined file: jdmarker.c ***/
  171802. /*** Start of inlined file: jdmaster.c ***/
  171803. #define JPEG_INTERNALS
  171804. /* Private state */
  171805. typedef struct {
  171806. struct jpeg_decomp_master pub; /* public fields */
  171807. int pass_number; /* # of passes completed */
  171808. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171809. /* Saved references to initialized quantizer modules,
  171810. * in case we need to switch modes.
  171811. */
  171812. struct jpeg_color_quantizer * quantizer_1pass;
  171813. struct jpeg_color_quantizer * quantizer_2pass;
  171814. } my_decomp_master;
  171815. typedef my_decomp_master * my_master_ptr6;
  171816. /*
  171817. * Determine whether merged upsample/color conversion should be used.
  171818. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171819. */
  171820. LOCAL(boolean)
  171821. use_merged_upsample (j_decompress_ptr cinfo)
  171822. {
  171823. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171824. /* Merging is the equivalent of plain box-filter upsampling */
  171825. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171826. return FALSE;
  171827. /* jdmerge.c only supports YCC=>RGB color conversion */
  171828. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171829. cinfo->out_color_space != JCS_RGB ||
  171830. cinfo->out_color_components != RGB_PIXELSIZE)
  171831. return FALSE;
  171832. /* and it only handles 2h1v or 2h2v sampling ratios */
  171833. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171834. cinfo->comp_info[1].h_samp_factor != 1 ||
  171835. cinfo->comp_info[2].h_samp_factor != 1 ||
  171836. cinfo->comp_info[0].v_samp_factor > 2 ||
  171837. cinfo->comp_info[1].v_samp_factor != 1 ||
  171838. cinfo->comp_info[2].v_samp_factor != 1)
  171839. return FALSE;
  171840. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171841. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171842. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171843. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171844. return FALSE;
  171845. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171846. return TRUE; /* by golly, it'll work... */
  171847. #else
  171848. return FALSE;
  171849. #endif
  171850. }
  171851. /*
  171852. * Compute output image dimensions and related values.
  171853. * NOTE: this is exported for possible use by application.
  171854. * Hence it mustn't do anything that can't be done twice.
  171855. * Also note that it may be called before the master module is initialized!
  171856. */
  171857. GLOBAL(void)
  171858. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171859. /* Do computations that are needed before master selection phase */
  171860. {
  171861. #ifdef IDCT_SCALING_SUPPORTED
  171862. int ci;
  171863. jpeg_component_info *compptr;
  171864. #endif
  171865. /* Prevent application from calling me at wrong times */
  171866. if (cinfo->global_state != DSTATE_READY)
  171867. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171868. #ifdef IDCT_SCALING_SUPPORTED
  171869. /* Compute actual output image dimensions and DCT scaling choices. */
  171870. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171871. /* Provide 1/8 scaling */
  171872. cinfo->output_width = (JDIMENSION)
  171873. jdiv_round_up((long) cinfo->image_width, 8L);
  171874. cinfo->output_height = (JDIMENSION)
  171875. jdiv_round_up((long) cinfo->image_height, 8L);
  171876. cinfo->min_DCT_scaled_size = 1;
  171877. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171878. /* Provide 1/4 scaling */
  171879. cinfo->output_width = (JDIMENSION)
  171880. jdiv_round_up((long) cinfo->image_width, 4L);
  171881. cinfo->output_height = (JDIMENSION)
  171882. jdiv_round_up((long) cinfo->image_height, 4L);
  171883. cinfo->min_DCT_scaled_size = 2;
  171884. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171885. /* Provide 1/2 scaling */
  171886. cinfo->output_width = (JDIMENSION)
  171887. jdiv_round_up((long) cinfo->image_width, 2L);
  171888. cinfo->output_height = (JDIMENSION)
  171889. jdiv_round_up((long) cinfo->image_height, 2L);
  171890. cinfo->min_DCT_scaled_size = 4;
  171891. } else {
  171892. /* Provide 1/1 scaling */
  171893. cinfo->output_width = cinfo->image_width;
  171894. cinfo->output_height = cinfo->image_height;
  171895. cinfo->min_DCT_scaled_size = DCTSIZE;
  171896. }
  171897. /* In selecting the actual DCT scaling for each component, we try to
  171898. * scale up the chroma components via IDCT scaling rather than upsampling.
  171899. * This saves time if the upsampler gets to use 1:1 scaling.
  171900. * Note this code assumes that the supported DCT scalings are powers of 2.
  171901. */
  171902. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171903. ci++, compptr++) {
  171904. int ssize = cinfo->min_DCT_scaled_size;
  171905. while (ssize < DCTSIZE &&
  171906. (compptr->h_samp_factor * ssize * 2 <=
  171907. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171908. (compptr->v_samp_factor * ssize * 2 <=
  171909. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171910. ssize = ssize * 2;
  171911. }
  171912. compptr->DCT_scaled_size = ssize;
  171913. }
  171914. /* Recompute downsampled dimensions of components;
  171915. * application needs to know these if using raw downsampled data.
  171916. */
  171917. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171918. ci++, compptr++) {
  171919. /* Size in samples, after IDCT scaling */
  171920. compptr->downsampled_width = (JDIMENSION)
  171921. jdiv_round_up((long) cinfo->image_width *
  171922. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171923. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171924. compptr->downsampled_height = (JDIMENSION)
  171925. jdiv_round_up((long) cinfo->image_height *
  171926. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171927. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171928. }
  171929. #else /* !IDCT_SCALING_SUPPORTED */
  171930. /* Hardwire it to "no scaling" */
  171931. cinfo->output_width = cinfo->image_width;
  171932. cinfo->output_height = cinfo->image_height;
  171933. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171934. * and has computed unscaled downsampled_width and downsampled_height.
  171935. */
  171936. #endif /* IDCT_SCALING_SUPPORTED */
  171937. /* Report number of components in selected colorspace. */
  171938. /* Probably this should be in the color conversion module... */
  171939. switch (cinfo->out_color_space) {
  171940. case JCS_GRAYSCALE:
  171941. cinfo->out_color_components = 1;
  171942. break;
  171943. case JCS_RGB:
  171944. #if RGB_PIXELSIZE != 3
  171945. cinfo->out_color_components = RGB_PIXELSIZE;
  171946. break;
  171947. #endif /* else share code with YCbCr */
  171948. case JCS_YCbCr:
  171949. cinfo->out_color_components = 3;
  171950. break;
  171951. case JCS_CMYK:
  171952. case JCS_YCCK:
  171953. cinfo->out_color_components = 4;
  171954. break;
  171955. default: /* else must be same colorspace as in file */
  171956. cinfo->out_color_components = cinfo->num_components;
  171957. break;
  171958. }
  171959. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171960. cinfo->out_color_components);
  171961. /* See if upsampler will want to emit more than one row at a time */
  171962. if (use_merged_upsample(cinfo))
  171963. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171964. else
  171965. cinfo->rec_outbuf_height = 1;
  171966. }
  171967. /*
  171968. * Several decompression processes need to range-limit values to the range
  171969. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171970. * due to noise introduced by quantization, roundoff error, etc. These
  171971. * processes are inner loops and need to be as fast as possible. On most
  171972. * machines, particularly CPUs with pipelines or instruction prefetch,
  171973. * a (subscript-check-less) C table lookup
  171974. * x = sample_range_limit[x];
  171975. * is faster than explicit tests
  171976. * if (x < 0) x = 0;
  171977. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171978. * These processes all use a common table prepared by the routine below.
  171979. *
  171980. * For most steps we can mathematically guarantee that the initial value
  171981. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171982. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171983. * limiting step (just after the IDCT), a wildly out-of-range value is
  171984. * possible if the input data is corrupt. To avoid any chance of indexing
  171985. * off the end of memory and getting a bad-pointer trap, we perform the
  171986. * post-IDCT limiting thus:
  171987. * x = range_limit[x & MASK];
  171988. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171989. * samples. Under normal circumstances this is more than enough range and
  171990. * a correct output will be generated; with bogus input data the mask will
  171991. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171992. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171993. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171994. * So the post-IDCT limiting table ends up looking like this:
  171995. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171996. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171997. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171998. * 0,1,...,CENTERJSAMPLE-1
  171999. * Negative inputs select values from the upper half of the table after
  172000. * masking.
  172001. *
  172002. * We can save some space by overlapping the start of the post-IDCT table
  172003. * with the simpler range limiting table. The post-IDCT table begins at
  172004. * sample_range_limit + CENTERJSAMPLE.
  172005. *
  172006. * Note that the table is allocated in near data space on PCs; it's small
  172007. * enough and used often enough to justify this.
  172008. */
  172009. LOCAL(void)
  172010. prepare_range_limit_table (j_decompress_ptr cinfo)
  172011. /* Allocate and fill in the sample_range_limit table */
  172012. {
  172013. JSAMPLE * table;
  172014. int i;
  172015. table = (JSAMPLE *)
  172016. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172017. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172018. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172019. cinfo->sample_range_limit = table;
  172020. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172021. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172022. /* Main part of "simple" table: limit[x] = x */
  172023. for (i = 0; i <= MAXJSAMPLE; i++)
  172024. table[i] = (JSAMPLE) i;
  172025. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172026. /* End of simple table, rest of first half of post-IDCT table */
  172027. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172028. table[i] = MAXJSAMPLE;
  172029. /* Second half of post-IDCT table */
  172030. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172031. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172032. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172033. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172034. }
  172035. /*
  172036. * Master selection of decompression modules.
  172037. * This is done once at jpeg_start_decompress time. We determine
  172038. * which modules will be used and give them appropriate initialization calls.
  172039. * We also initialize the decompressor input side to begin consuming data.
  172040. *
  172041. * Since jpeg_read_header has finished, we know what is in the SOF
  172042. * and (first) SOS markers. We also have all the application parameter
  172043. * settings.
  172044. */
  172045. LOCAL(void)
  172046. master_selection (j_decompress_ptr cinfo)
  172047. {
  172048. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172049. boolean use_c_buffer;
  172050. long samplesperrow;
  172051. JDIMENSION jd_samplesperrow;
  172052. /* Initialize dimensions and other stuff */
  172053. jpeg_calc_output_dimensions(cinfo);
  172054. prepare_range_limit_table(cinfo);
  172055. /* Width of an output scanline must be representable as JDIMENSION. */
  172056. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172057. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172058. if ((long) jd_samplesperrow != samplesperrow)
  172059. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172060. /* Initialize my private state */
  172061. master->pass_number = 0;
  172062. master->using_merged_upsample = use_merged_upsample(cinfo);
  172063. /* Color quantizer selection */
  172064. master->quantizer_1pass = NULL;
  172065. master->quantizer_2pass = NULL;
  172066. /* No mode changes if not using buffered-image mode. */
  172067. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172068. cinfo->enable_1pass_quant = FALSE;
  172069. cinfo->enable_external_quant = FALSE;
  172070. cinfo->enable_2pass_quant = FALSE;
  172071. }
  172072. if (cinfo->quantize_colors) {
  172073. if (cinfo->raw_data_out)
  172074. ERREXIT(cinfo, JERR_NOTIMPL);
  172075. /* 2-pass quantizer only works in 3-component color space. */
  172076. if (cinfo->out_color_components != 3) {
  172077. cinfo->enable_1pass_quant = TRUE;
  172078. cinfo->enable_external_quant = FALSE;
  172079. cinfo->enable_2pass_quant = FALSE;
  172080. cinfo->colormap = NULL;
  172081. } else if (cinfo->colormap != NULL) {
  172082. cinfo->enable_external_quant = TRUE;
  172083. } else if (cinfo->two_pass_quantize) {
  172084. cinfo->enable_2pass_quant = TRUE;
  172085. } else {
  172086. cinfo->enable_1pass_quant = TRUE;
  172087. }
  172088. if (cinfo->enable_1pass_quant) {
  172089. #ifdef QUANT_1PASS_SUPPORTED
  172090. jinit_1pass_quantizer(cinfo);
  172091. master->quantizer_1pass = cinfo->cquantize;
  172092. #else
  172093. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172094. #endif
  172095. }
  172096. /* We use the 2-pass code to map to external colormaps. */
  172097. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172098. #ifdef QUANT_2PASS_SUPPORTED
  172099. jinit_2pass_quantizer(cinfo);
  172100. master->quantizer_2pass = cinfo->cquantize;
  172101. #else
  172102. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172103. #endif
  172104. }
  172105. /* If both quantizers are initialized, the 2-pass one is left active;
  172106. * this is necessary for starting with quantization to an external map.
  172107. */
  172108. }
  172109. /* Post-processing: in particular, color conversion first */
  172110. if (! cinfo->raw_data_out) {
  172111. if (master->using_merged_upsample) {
  172112. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172113. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172114. #else
  172115. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172116. #endif
  172117. } else {
  172118. jinit_color_deconverter(cinfo);
  172119. jinit_upsampler(cinfo);
  172120. }
  172121. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172122. }
  172123. /* Inverse DCT */
  172124. jinit_inverse_dct(cinfo);
  172125. /* Entropy decoding: either Huffman or arithmetic coding. */
  172126. if (cinfo->arith_code) {
  172127. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172128. } else {
  172129. if (cinfo->progressive_mode) {
  172130. #ifdef D_PROGRESSIVE_SUPPORTED
  172131. jinit_phuff_decoder(cinfo);
  172132. #else
  172133. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172134. #endif
  172135. } else
  172136. jinit_huff_decoder(cinfo);
  172137. }
  172138. /* Initialize principal buffer controllers. */
  172139. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172140. jinit_d_coef_controller(cinfo, use_c_buffer);
  172141. if (! cinfo->raw_data_out)
  172142. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172143. /* We can now tell the memory manager to allocate virtual arrays. */
  172144. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172145. /* Initialize input side of decompressor to consume first scan. */
  172146. (*cinfo->inputctl->start_input_pass) (cinfo);
  172147. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172148. /* If jpeg_start_decompress will read the whole file, initialize
  172149. * progress monitoring appropriately. The input step is counted
  172150. * as one pass.
  172151. */
  172152. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172153. cinfo->inputctl->has_multiple_scans) {
  172154. int nscans;
  172155. /* Estimate number of scans to set pass_limit. */
  172156. if (cinfo->progressive_mode) {
  172157. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172158. nscans = 2 + 3 * cinfo->num_components;
  172159. } else {
  172160. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172161. nscans = cinfo->num_components;
  172162. }
  172163. cinfo->progress->pass_counter = 0L;
  172164. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172165. cinfo->progress->completed_passes = 0;
  172166. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172167. /* Count the input pass as done */
  172168. master->pass_number++;
  172169. }
  172170. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172171. }
  172172. /*
  172173. * Per-pass setup.
  172174. * This is called at the beginning of each output pass. We determine which
  172175. * modules will be active during this pass and give them appropriate
  172176. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172177. * is a "real" output pass or a dummy pass for color quantization.
  172178. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172179. */
  172180. METHODDEF(void)
  172181. prepare_for_output_pass (j_decompress_ptr cinfo)
  172182. {
  172183. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172184. if (master->pub.is_dummy_pass) {
  172185. #ifdef QUANT_2PASS_SUPPORTED
  172186. /* Final pass of 2-pass quantization */
  172187. master->pub.is_dummy_pass = FALSE;
  172188. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172189. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172190. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172191. #else
  172192. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172193. #endif /* QUANT_2PASS_SUPPORTED */
  172194. } else {
  172195. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172196. /* Select new quantization method */
  172197. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172198. cinfo->cquantize = master->quantizer_2pass;
  172199. master->pub.is_dummy_pass = TRUE;
  172200. } else if (cinfo->enable_1pass_quant) {
  172201. cinfo->cquantize = master->quantizer_1pass;
  172202. } else {
  172203. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172204. }
  172205. }
  172206. (*cinfo->idct->start_pass) (cinfo);
  172207. (*cinfo->coef->start_output_pass) (cinfo);
  172208. if (! cinfo->raw_data_out) {
  172209. if (! master->using_merged_upsample)
  172210. (*cinfo->cconvert->start_pass) (cinfo);
  172211. (*cinfo->upsample->start_pass) (cinfo);
  172212. if (cinfo->quantize_colors)
  172213. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172214. (*cinfo->post->start_pass) (cinfo,
  172215. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172216. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172217. }
  172218. }
  172219. /* Set up progress monitor's pass info if present */
  172220. if (cinfo->progress != NULL) {
  172221. cinfo->progress->completed_passes = master->pass_number;
  172222. cinfo->progress->total_passes = master->pass_number +
  172223. (master->pub.is_dummy_pass ? 2 : 1);
  172224. /* In buffered-image mode, we assume one more output pass if EOI not
  172225. * yet reached, but no more passes if EOI has been reached.
  172226. */
  172227. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172228. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172229. }
  172230. }
  172231. }
  172232. /*
  172233. * Finish up at end of an output pass.
  172234. */
  172235. METHODDEF(void)
  172236. finish_output_pass (j_decompress_ptr cinfo)
  172237. {
  172238. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172239. if (cinfo->quantize_colors)
  172240. (*cinfo->cquantize->finish_pass) (cinfo);
  172241. master->pass_number++;
  172242. }
  172243. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172244. /*
  172245. * Switch to a new external colormap between output passes.
  172246. */
  172247. GLOBAL(void)
  172248. jpeg_new_colormap (j_decompress_ptr cinfo)
  172249. {
  172250. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172251. /* Prevent application from calling me at wrong times */
  172252. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172253. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172254. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172255. cinfo->colormap != NULL) {
  172256. /* Select 2-pass quantizer for external colormap use */
  172257. cinfo->cquantize = master->quantizer_2pass;
  172258. /* Notify quantizer of colormap change */
  172259. (*cinfo->cquantize->new_color_map) (cinfo);
  172260. master->pub.is_dummy_pass = FALSE; /* just in case */
  172261. } else
  172262. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172263. }
  172264. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172265. /*
  172266. * Initialize master decompression control and select active modules.
  172267. * This is performed at the start of jpeg_start_decompress.
  172268. */
  172269. GLOBAL(void)
  172270. jinit_master_decompress (j_decompress_ptr cinfo)
  172271. {
  172272. my_master_ptr6 master;
  172273. master = (my_master_ptr6)
  172274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172275. SIZEOF(my_decomp_master));
  172276. cinfo->master = (struct jpeg_decomp_master *) master;
  172277. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172278. master->pub.finish_output_pass = finish_output_pass;
  172279. master->pub.is_dummy_pass = FALSE;
  172280. master_selection(cinfo);
  172281. }
  172282. /*** End of inlined file: jdmaster.c ***/
  172283. #undef FIX
  172284. /*** Start of inlined file: jdmerge.c ***/
  172285. #define JPEG_INTERNALS
  172286. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172287. /* Private subobject */
  172288. typedef struct {
  172289. struct jpeg_upsampler pub; /* public fields */
  172290. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172291. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172292. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172293. JSAMPARRAY output_buf));
  172294. /* Private state for YCC->RGB conversion */
  172295. int * Cr_r_tab; /* => table for Cr to R conversion */
  172296. int * Cb_b_tab; /* => table for Cb to B conversion */
  172297. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172298. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172299. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172300. * We need a "spare" row buffer to hold the second output row if the
  172301. * application provides just a one-row buffer; we also use the spare
  172302. * to discard the dummy last row if the image height is odd.
  172303. */
  172304. JSAMPROW spare_row;
  172305. boolean spare_full; /* T if spare buffer is occupied */
  172306. JDIMENSION out_row_width; /* samples per output row */
  172307. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172308. } my_upsampler;
  172309. typedef my_upsampler * my_upsample_ptr;
  172310. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172311. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172312. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172313. /*
  172314. * Initialize tables for YCC->RGB colorspace conversion.
  172315. * This is taken directly from jdcolor.c; see that file for more info.
  172316. */
  172317. LOCAL(void)
  172318. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172319. {
  172320. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172321. int i;
  172322. INT32 x;
  172323. SHIFT_TEMPS
  172324. upsample->Cr_r_tab = (int *)
  172325. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172326. (MAXJSAMPLE+1) * SIZEOF(int));
  172327. upsample->Cb_b_tab = (int *)
  172328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172329. (MAXJSAMPLE+1) * SIZEOF(int));
  172330. upsample->Cr_g_tab = (INT32 *)
  172331. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172332. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172333. upsample->Cb_g_tab = (INT32 *)
  172334. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172335. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172336. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172337. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172338. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172339. /* Cr=>R value is nearest int to 1.40200 * x */
  172340. upsample->Cr_r_tab[i] = (int)
  172341. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172342. /* Cb=>B value is nearest int to 1.77200 * x */
  172343. upsample->Cb_b_tab[i] = (int)
  172344. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172345. /* Cr=>G value is scaled-up -0.71414 * x */
  172346. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172347. /* Cb=>G value is scaled-up -0.34414 * x */
  172348. /* We also add in ONE_HALF so that need not do it in inner loop */
  172349. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172350. }
  172351. }
  172352. /*
  172353. * Initialize for an upsampling pass.
  172354. */
  172355. METHODDEF(void)
  172356. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172357. {
  172358. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172359. /* Mark the spare buffer empty */
  172360. upsample->spare_full = FALSE;
  172361. /* Initialize total-height counter for detecting bottom of image */
  172362. upsample->rows_to_go = cinfo->output_height;
  172363. }
  172364. /*
  172365. * Control routine to do upsampling (and color conversion).
  172366. *
  172367. * The control routine just handles the row buffering considerations.
  172368. */
  172369. METHODDEF(void)
  172370. merged_2v_upsample (j_decompress_ptr cinfo,
  172371. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172372. JDIMENSION,
  172373. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172374. JDIMENSION out_rows_avail)
  172375. /* 2:1 vertical sampling case: may need a spare row. */
  172376. {
  172377. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172378. JSAMPROW work_ptrs[2];
  172379. JDIMENSION num_rows; /* number of rows returned to caller */
  172380. if (upsample->spare_full) {
  172381. /* If we have a spare row saved from a previous cycle, just return it. */
  172382. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172383. 1, upsample->out_row_width);
  172384. num_rows = 1;
  172385. upsample->spare_full = FALSE;
  172386. } else {
  172387. /* Figure number of rows to return to caller. */
  172388. num_rows = 2;
  172389. /* Not more than the distance to the end of the image. */
  172390. if (num_rows > upsample->rows_to_go)
  172391. num_rows = upsample->rows_to_go;
  172392. /* And not more than what the client can accept: */
  172393. out_rows_avail -= *out_row_ctr;
  172394. if (num_rows > out_rows_avail)
  172395. num_rows = out_rows_avail;
  172396. /* Create output pointer array for upsampler. */
  172397. work_ptrs[0] = output_buf[*out_row_ctr];
  172398. if (num_rows > 1) {
  172399. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172400. } else {
  172401. work_ptrs[1] = upsample->spare_row;
  172402. upsample->spare_full = TRUE;
  172403. }
  172404. /* Now do the upsampling. */
  172405. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172406. }
  172407. /* Adjust counts */
  172408. *out_row_ctr += num_rows;
  172409. upsample->rows_to_go -= num_rows;
  172410. /* When the buffer is emptied, declare this input row group consumed */
  172411. if (! upsample->spare_full)
  172412. (*in_row_group_ctr)++;
  172413. }
  172414. METHODDEF(void)
  172415. merged_1v_upsample (j_decompress_ptr cinfo,
  172416. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172417. JDIMENSION,
  172418. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172419. JDIMENSION)
  172420. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172421. {
  172422. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172423. /* Just do the upsampling. */
  172424. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172425. output_buf + *out_row_ctr);
  172426. /* Adjust counts */
  172427. (*out_row_ctr)++;
  172428. (*in_row_group_ctr)++;
  172429. }
  172430. /*
  172431. * These are the routines invoked by the control routines to do
  172432. * the actual upsampling/conversion. One row group is processed per call.
  172433. *
  172434. * Note: since we may be writing directly into application-supplied buffers,
  172435. * we have to be honest about the output width; we can't assume the buffer
  172436. * has been rounded up to an even width.
  172437. */
  172438. /*
  172439. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172440. */
  172441. METHODDEF(void)
  172442. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172443. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172444. JSAMPARRAY output_buf)
  172445. {
  172446. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172447. register int y, cred, cgreen, cblue;
  172448. int cb, cr;
  172449. register JSAMPROW outptr;
  172450. JSAMPROW inptr0, inptr1, inptr2;
  172451. JDIMENSION col;
  172452. /* copy these pointers into registers if possible */
  172453. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172454. int * Crrtab = upsample->Cr_r_tab;
  172455. int * Cbbtab = upsample->Cb_b_tab;
  172456. INT32 * Crgtab = upsample->Cr_g_tab;
  172457. INT32 * Cbgtab = upsample->Cb_g_tab;
  172458. SHIFT_TEMPS
  172459. inptr0 = input_buf[0][in_row_group_ctr];
  172460. inptr1 = input_buf[1][in_row_group_ctr];
  172461. inptr2 = input_buf[2][in_row_group_ctr];
  172462. outptr = output_buf[0];
  172463. /* Loop for each pair of output pixels */
  172464. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172465. /* Do the chroma part of the calculation */
  172466. cb = GETJSAMPLE(*inptr1++);
  172467. cr = GETJSAMPLE(*inptr2++);
  172468. cred = Crrtab[cr];
  172469. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172470. cblue = Cbbtab[cb];
  172471. /* Fetch 2 Y values and emit 2 pixels */
  172472. y = GETJSAMPLE(*inptr0++);
  172473. outptr[RGB_RED] = range_limit[y + cred];
  172474. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172475. outptr[RGB_BLUE] = range_limit[y + cblue];
  172476. outptr += RGB_PIXELSIZE;
  172477. y = GETJSAMPLE(*inptr0++);
  172478. outptr[RGB_RED] = range_limit[y + cred];
  172479. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172480. outptr[RGB_BLUE] = range_limit[y + cblue];
  172481. outptr += RGB_PIXELSIZE;
  172482. }
  172483. /* If image width is odd, do the last output column separately */
  172484. if (cinfo->output_width & 1) {
  172485. cb = GETJSAMPLE(*inptr1);
  172486. cr = GETJSAMPLE(*inptr2);
  172487. cred = Crrtab[cr];
  172488. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172489. cblue = Cbbtab[cb];
  172490. y = GETJSAMPLE(*inptr0);
  172491. outptr[RGB_RED] = range_limit[y + cred];
  172492. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172493. outptr[RGB_BLUE] = range_limit[y + cblue];
  172494. }
  172495. }
  172496. /*
  172497. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172498. */
  172499. METHODDEF(void)
  172500. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172501. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172502. JSAMPARRAY output_buf)
  172503. {
  172504. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172505. register int y, cred, cgreen, cblue;
  172506. int cb, cr;
  172507. register JSAMPROW outptr0, outptr1;
  172508. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172509. JDIMENSION col;
  172510. /* copy these pointers into registers if possible */
  172511. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172512. int * Crrtab = upsample->Cr_r_tab;
  172513. int * Cbbtab = upsample->Cb_b_tab;
  172514. INT32 * Crgtab = upsample->Cr_g_tab;
  172515. INT32 * Cbgtab = upsample->Cb_g_tab;
  172516. SHIFT_TEMPS
  172517. inptr00 = input_buf[0][in_row_group_ctr*2];
  172518. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172519. inptr1 = input_buf[1][in_row_group_ctr];
  172520. inptr2 = input_buf[2][in_row_group_ctr];
  172521. outptr0 = output_buf[0];
  172522. outptr1 = output_buf[1];
  172523. /* Loop for each group of output pixels */
  172524. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172525. /* Do the chroma part of the calculation */
  172526. cb = GETJSAMPLE(*inptr1++);
  172527. cr = GETJSAMPLE(*inptr2++);
  172528. cred = Crrtab[cr];
  172529. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172530. cblue = Cbbtab[cb];
  172531. /* Fetch 4 Y values and emit 4 pixels */
  172532. y = GETJSAMPLE(*inptr00++);
  172533. outptr0[RGB_RED] = range_limit[y + cred];
  172534. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172535. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172536. outptr0 += RGB_PIXELSIZE;
  172537. y = GETJSAMPLE(*inptr00++);
  172538. outptr0[RGB_RED] = range_limit[y + cred];
  172539. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172540. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172541. outptr0 += RGB_PIXELSIZE;
  172542. y = GETJSAMPLE(*inptr01++);
  172543. outptr1[RGB_RED] = range_limit[y + cred];
  172544. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172545. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172546. outptr1 += RGB_PIXELSIZE;
  172547. y = GETJSAMPLE(*inptr01++);
  172548. outptr1[RGB_RED] = range_limit[y + cred];
  172549. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172550. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172551. outptr1 += RGB_PIXELSIZE;
  172552. }
  172553. /* If image width is odd, do the last output column separately */
  172554. if (cinfo->output_width & 1) {
  172555. cb = GETJSAMPLE(*inptr1);
  172556. cr = GETJSAMPLE(*inptr2);
  172557. cred = Crrtab[cr];
  172558. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172559. cblue = Cbbtab[cb];
  172560. y = GETJSAMPLE(*inptr00);
  172561. outptr0[RGB_RED] = range_limit[y + cred];
  172562. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172563. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172564. y = GETJSAMPLE(*inptr01);
  172565. outptr1[RGB_RED] = range_limit[y + cred];
  172566. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172567. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172568. }
  172569. }
  172570. /*
  172571. * Module initialization routine for merged upsampling/color conversion.
  172572. *
  172573. * NB: this is called under the conditions determined by use_merged_upsample()
  172574. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172575. * of this module; no safety checks are made here.
  172576. */
  172577. GLOBAL(void)
  172578. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172579. {
  172580. my_upsample_ptr upsample;
  172581. upsample = (my_upsample_ptr)
  172582. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172583. SIZEOF(my_upsampler));
  172584. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172585. upsample->pub.start_pass = start_pass_merged_upsample;
  172586. upsample->pub.need_context_rows = FALSE;
  172587. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172588. if (cinfo->max_v_samp_factor == 2) {
  172589. upsample->pub.upsample = merged_2v_upsample;
  172590. upsample->upmethod = h2v2_merged_upsample;
  172591. /* Allocate a spare row buffer */
  172592. upsample->spare_row = (JSAMPROW)
  172593. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172594. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172595. } else {
  172596. upsample->pub.upsample = merged_1v_upsample;
  172597. upsample->upmethod = h2v1_merged_upsample;
  172598. /* No spare row needed */
  172599. upsample->spare_row = NULL;
  172600. }
  172601. build_ycc_rgb_table2(cinfo);
  172602. }
  172603. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172604. /*** End of inlined file: jdmerge.c ***/
  172605. #undef ASSIGN_STATE
  172606. /*** Start of inlined file: jdphuff.c ***/
  172607. #define JPEG_INTERNALS
  172608. #ifdef D_PROGRESSIVE_SUPPORTED
  172609. /*
  172610. * Expanded entropy decoder object for progressive Huffman decoding.
  172611. *
  172612. * The savable_state subrecord contains fields that change within an MCU,
  172613. * but must not be updated permanently until we complete the MCU.
  172614. */
  172615. typedef struct {
  172616. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172617. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172618. } savable_state3;
  172619. /* This macro is to work around compilers with missing or broken
  172620. * structure assignment. You'll need to fix this code if you have
  172621. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172622. */
  172623. #ifndef NO_STRUCT_ASSIGN
  172624. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172625. #else
  172626. #if MAX_COMPS_IN_SCAN == 4
  172627. #define ASSIGN_STATE(dest,src) \
  172628. ((dest).EOBRUN = (src).EOBRUN, \
  172629. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172630. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172631. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172632. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172633. #endif
  172634. #endif
  172635. typedef struct {
  172636. struct jpeg_entropy_decoder pub; /* public fields */
  172637. /* These fields are loaded into local variables at start of each MCU.
  172638. * In case of suspension, we exit WITHOUT updating them.
  172639. */
  172640. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172641. savable_state3 saved; /* Other state at start of MCU */
  172642. /* These fields are NOT loaded into local working state. */
  172643. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172644. /* Pointers to derived tables (these workspaces have image lifespan) */
  172645. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172646. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172647. } phuff_entropy_decoder;
  172648. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172649. /* Forward declarations */
  172650. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172651. JBLOCKROW *MCU_data));
  172652. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172653. JBLOCKROW *MCU_data));
  172654. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172655. JBLOCKROW *MCU_data));
  172656. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172657. JBLOCKROW *MCU_data));
  172658. /*
  172659. * Initialize for a Huffman-compressed scan.
  172660. */
  172661. METHODDEF(void)
  172662. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172663. {
  172664. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172665. boolean is_DC_band, bad;
  172666. int ci, coefi, tbl;
  172667. int *coef_bit_ptr;
  172668. jpeg_component_info * compptr;
  172669. is_DC_band = (cinfo->Ss == 0);
  172670. /* Validate scan parameters */
  172671. bad = FALSE;
  172672. if (is_DC_band) {
  172673. if (cinfo->Se != 0)
  172674. bad = TRUE;
  172675. } else {
  172676. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172677. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172678. bad = TRUE;
  172679. /* AC scans may have only one component */
  172680. if (cinfo->comps_in_scan != 1)
  172681. bad = TRUE;
  172682. }
  172683. if (cinfo->Ah != 0) {
  172684. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172685. if (cinfo->Al != cinfo->Ah-1)
  172686. bad = TRUE;
  172687. }
  172688. if (cinfo->Al > 13) /* need not check for < 0 */
  172689. bad = TRUE;
  172690. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172691. * but the spec doesn't say so, and we try to be liberal about what we
  172692. * accept. Note: large Al values could result in out-of-range DC
  172693. * coefficients during early scans, leading to bizarre displays due to
  172694. * overflows in the IDCT math. But we won't crash.
  172695. */
  172696. if (bad)
  172697. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172698. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172699. /* Update progression status, and verify that scan order is legal.
  172700. * Note that inter-scan inconsistencies are treated as warnings
  172701. * not fatal errors ... not clear if this is right way to behave.
  172702. */
  172703. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172704. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172705. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172706. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172707. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172708. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172709. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172710. if (cinfo->Ah != expected)
  172711. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172712. coef_bit_ptr[coefi] = cinfo->Al;
  172713. }
  172714. }
  172715. /* Select MCU decoding routine */
  172716. if (cinfo->Ah == 0) {
  172717. if (is_DC_band)
  172718. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172719. else
  172720. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172721. } else {
  172722. if (is_DC_band)
  172723. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172724. else
  172725. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172726. }
  172727. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172728. compptr = cinfo->cur_comp_info[ci];
  172729. /* Make sure requested tables are present, and compute derived tables.
  172730. * We may build same derived table more than once, but it's not expensive.
  172731. */
  172732. if (is_DC_band) {
  172733. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172734. tbl = compptr->dc_tbl_no;
  172735. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172736. & entropy->derived_tbls[tbl]);
  172737. }
  172738. } else {
  172739. tbl = compptr->ac_tbl_no;
  172740. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172741. & entropy->derived_tbls[tbl]);
  172742. /* remember the single active table */
  172743. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172744. }
  172745. /* Initialize DC predictions to 0 */
  172746. entropy->saved.last_dc_val[ci] = 0;
  172747. }
  172748. /* Initialize bitread state variables */
  172749. entropy->bitstate.bits_left = 0;
  172750. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172751. entropy->pub.insufficient_data = FALSE;
  172752. /* Initialize private state variables */
  172753. entropy->saved.EOBRUN = 0;
  172754. /* Initialize restart counter */
  172755. entropy->restarts_to_go = cinfo->restart_interval;
  172756. }
  172757. /*
  172758. * Check for a restart marker & resynchronize decoder.
  172759. * Returns FALSE if must suspend.
  172760. */
  172761. LOCAL(boolean)
  172762. process_restartp (j_decompress_ptr cinfo)
  172763. {
  172764. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172765. int ci;
  172766. /* Throw away any unused bits remaining in bit buffer; */
  172767. /* include any full bytes in next_marker's count of discarded bytes */
  172768. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172769. entropy->bitstate.bits_left = 0;
  172770. /* Advance past the RSTn marker */
  172771. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172772. return FALSE;
  172773. /* Re-initialize DC predictions to 0 */
  172774. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172775. entropy->saved.last_dc_val[ci] = 0;
  172776. /* Re-init EOB run count, too */
  172777. entropy->saved.EOBRUN = 0;
  172778. /* Reset restart counter */
  172779. entropy->restarts_to_go = cinfo->restart_interval;
  172780. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172781. * against a marker. In that case we will end up treating the next data
  172782. * segment as empty, and we can avoid producing bogus output pixels by
  172783. * leaving the flag set.
  172784. */
  172785. if (cinfo->unread_marker == 0)
  172786. entropy->pub.insufficient_data = FALSE;
  172787. return TRUE;
  172788. }
  172789. /*
  172790. * Huffman MCU decoding.
  172791. * Each of these routines decodes and returns one MCU's worth of
  172792. * Huffman-compressed coefficients.
  172793. * The coefficients are reordered from zigzag order into natural array order,
  172794. * but are not dequantized.
  172795. *
  172796. * The i'th block of the MCU is stored into the block pointed to by
  172797. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172798. *
  172799. * We return FALSE if data source requested suspension. In that case no
  172800. * changes have been made to permanent state. (Exception: some output
  172801. * coefficients may already have been assigned. This is harmless for
  172802. * spectral selection, since we'll just re-assign them on the next call.
  172803. * Successive approximation AC refinement has to be more careful, however.)
  172804. */
  172805. /*
  172806. * MCU decoding for DC initial scan (either spectral selection,
  172807. * or first pass of successive approximation).
  172808. */
  172809. METHODDEF(boolean)
  172810. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172811. {
  172812. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172813. int Al = cinfo->Al;
  172814. register int s, r;
  172815. int blkn, ci;
  172816. JBLOCKROW block;
  172817. BITREAD_STATE_VARS;
  172818. savable_state3 state;
  172819. d_derived_tbl * tbl;
  172820. jpeg_component_info * compptr;
  172821. /* Process restart marker if needed; may have to suspend */
  172822. if (cinfo->restart_interval) {
  172823. if (entropy->restarts_to_go == 0)
  172824. if (! process_restartp(cinfo))
  172825. return FALSE;
  172826. }
  172827. /* If we've run out of data, just leave the MCU set to zeroes.
  172828. * This way, we return uniform gray for the remainder of the segment.
  172829. */
  172830. if (! entropy->pub.insufficient_data) {
  172831. /* Load up working state */
  172832. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172833. ASSIGN_STATE(state, entropy->saved);
  172834. /* Outer loop handles each block in the MCU */
  172835. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172836. block = MCU_data[blkn];
  172837. ci = cinfo->MCU_membership[blkn];
  172838. compptr = cinfo->cur_comp_info[ci];
  172839. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172840. /* Decode a single block's worth of coefficients */
  172841. /* Section F.2.2.1: decode the DC coefficient difference */
  172842. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172843. if (s) {
  172844. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172845. r = GET_BITS(s);
  172846. s = HUFF_EXTEND(r, s);
  172847. }
  172848. /* Convert DC difference to actual value, update last_dc_val */
  172849. s += state.last_dc_val[ci];
  172850. state.last_dc_val[ci] = s;
  172851. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172852. (*block)[0] = (JCOEF) (s << Al);
  172853. }
  172854. /* Completed MCU, so update state */
  172855. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172856. ASSIGN_STATE(entropy->saved, state);
  172857. }
  172858. /* Account for restart interval (no-op if not using restarts) */
  172859. entropy->restarts_to_go--;
  172860. return TRUE;
  172861. }
  172862. /*
  172863. * MCU decoding for AC initial scan (either spectral selection,
  172864. * or first pass of successive approximation).
  172865. */
  172866. METHODDEF(boolean)
  172867. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172868. {
  172869. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172870. int Se = cinfo->Se;
  172871. int Al = cinfo->Al;
  172872. register int s, k, r;
  172873. unsigned int EOBRUN;
  172874. JBLOCKROW block;
  172875. BITREAD_STATE_VARS;
  172876. d_derived_tbl * tbl;
  172877. /* Process restart marker if needed; may have to suspend */
  172878. if (cinfo->restart_interval) {
  172879. if (entropy->restarts_to_go == 0)
  172880. if (! process_restartp(cinfo))
  172881. return FALSE;
  172882. }
  172883. /* If we've run out of data, just leave the MCU set to zeroes.
  172884. * This way, we return uniform gray for the remainder of the segment.
  172885. */
  172886. if (! entropy->pub.insufficient_data) {
  172887. /* Load up working state.
  172888. * We can avoid loading/saving bitread state if in an EOB run.
  172889. */
  172890. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172891. /* There is always only one block per MCU */
  172892. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172893. EOBRUN--; /* ...process it now (we do nothing) */
  172894. else {
  172895. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172896. block = MCU_data[0];
  172897. tbl = entropy->ac_derived_tbl;
  172898. for (k = cinfo->Ss; k <= Se; k++) {
  172899. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172900. r = s >> 4;
  172901. s &= 15;
  172902. if (s) {
  172903. k += r;
  172904. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172905. r = GET_BITS(s);
  172906. s = HUFF_EXTEND(r, s);
  172907. /* Scale and output coefficient in natural (dezigzagged) order */
  172908. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172909. } else {
  172910. if (r == 15) { /* ZRL */
  172911. k += 15; /* skip 15 zeroes in band */
  172912. } else { /* EOBr, run length is 2^r + appended bits */
  172913. EOBRUN = 1 << r;
  172914. if (r) { /* EOBr, r > 0 */
  172915. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172916. r = GET_BITS(r);
  172917. EOBRUN += r;
  172918. }
  172919. EOBRUN--; /* this band is processed at this moment */
  172920. break; /* force end-of-band */
  172921. }
  172922. }
  172923. }
  172924. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172925. }
  172926. /* Completed MCU, so update state */
  172927. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172928. }
  172929. /* Account for restart interval (no-op if not using restarts) */
  172930. entropy->restarts_to_go--;
  172931. return TRUE;
  172932. }
  172933. /*
  172934. * MCU decoding for DC successive approximation refinement scan.
  172935. * Note: we assume such scans can be multi-component, although the spec
  172936. * is not very clear on the point.
  172937. */
  172938. METHODDEF(boolean)
  172939. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172940. {
  172941. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172942. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172943. int blkn;
  172944. JBLOCKROW block;
  172945. BITREAD_STATE_VARS;
  172946. /* Process restart marker if needed; may have to suspend */
  172947. if (cinfo->restart_interval) {
  172948. if (entropy->restarts_to_go == 0)
  172949. if (! process_restartp(cinfo))
  172950. return FALSE;
  172951. }
  172952. /* Not worth the cycles to check insufficient_data here,
  172953. * since we will not change the data anyway if we read zeroes.
  172954. */
  172955. /* Load up working state */
  172956. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172957. /* Outer loop handles each block in the MCU */
  172958. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172959. block = MCU_data[blkn];
  172960. /* Encoded data is simply the next bit of the two's-complement DC value */
  172961. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172962. if (GET_BITS(1))
  172963. (*block)[0] |= p1;
  172964. /* Note: since we use |=, repeating the assignment later is safe */
  172965. }
  172966. /* Completed MCU, so update state */
  172967. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172968. /* Account for restart interval (no-op if not using restarts) */
  172969. entropy->restarts_to_go--;
  172970. return TRUE;
  172971. }
  172972. /*
  172973. * MCU decoding for AC successive approximation refinement scan.
  172974. */
  172975. METHODDEF(boolean)
  172976. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172977. {
  172978. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172979. int Se = cinfo->Se;
  172980. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172981. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172982. register int s, k, r;
  172983. unsigned int EOBRUN;
  172984. JBLOCKROW block;
  172985. JCOEFPTR thiscoef;
  172986. BITREAD_STATE_VARS;
  172987. d_derived_tbl * tbl;
  172988. int num_newnz;
  172989. int newnz_pos[DCTSIZE2];
  172990. /* Process restart marker if needed; may have to suspend */
  172991. if (cinfo->restart_interval) {
  172992. if (entropy->restarts_to_go == 0)
  172993. if (! process_restartp(cinfo))
  172994. return FALSE;
  172995. }
  172996. /* If we've run out of data, don't modify the MCU.
  172997. */
  172998. if (! entropy->pub.insufficient_data) {
  172999. /* Load up working state */
  173000. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173001. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173002. /* There is always only one block per MCU */
  173003. block = MCU_data[0];
  173004. tbl = entropy->ac_derived_tbl;
  173005. /* If we are forced to suspend, we must undo the assignments to any newly
  173006. * nonzero coefficients in the block, because otherwise we'd get confused
  173007. * next time about which coefficients were already nonzero.
  173008. * But we need not undo addition of bits to already-nonzero coefficients;
  173009. * instead, we can test the current bit to see if we already did it.
  173010. */
  173011. num_newnz = 0;
  173012. /* initialize coefficient loop counter to start of band */
  173013. k = cinfo->Ss;
  173014. if (EOBRUN == 0) {
  173015. for (; k <= Se; k++) {
  173016. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173017. r = s >> 4;
  173018. s &= 15;
  173019. if (s) {
  173020. if (s != 1) /* size of new coef should always be 1 */
  173021. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173022. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173023. if (GET_BITS(1))
  173024. s = p1; /* newly nonzero coef is positive */
  173025. else
  173026. s = m1; /* newly nonzero coef is negative */
  173027. } else {
  173028. if (r != 15) {
  173029. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173030. if (r) {
  173031. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173032. r = GET_BITS(r);
  173033. EOBRUN += r;
  173034. }
  173035. break; /* rest of block is handled by EOB logic */
  173036. }
  173037. /* note s = 0 for processing ZRL */
  173038. }
  173039. /* Advance over already-nonzero coefs and r still-zero coefs,
  173040. * appending correction bits to the nonzeroes. A correction bit is 1
  173041. * if the absolute value of the coefficient must be increased.
  173042. */
  173043. do {
  173044. thiscoef = *block + jpeg_natural_order[k];
  173045. if (*thiscoef != 0) {
  173046. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173047. if (GET_BITS(1)) {
  173048. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173049. if (*thiscoef >= 0)
  173050. *thiscoef += p1;
  173051. else
  173052. *thiscoef += m1;
  173053. }
  173054. }
  173055. } else {
  173056. if (--r < 0)
  173057. break; /* reached target zero coefficient */
  173058. }
  173059. k++;
  173060. } while (k <= Se);
  173061. if (s) {
  173062. int pos = jpeg_natural_order[k];
  173063. /* Output newly nonzero coefficient */
  173064. (*block)[pos] = (JCOEF) s;
  173065. /* Remember its position in case we have to suspend */
  173066. newnz_pos[num_newnz++] = pos;
  173067. }
  173068. }
  173069. }
  173070. if (EOBRUN > 0) {
  173071. /* Scan any remaining coefficient positions after the end-of-band
  173072. * (the last newly nonzero coefficient, if any). Append a correction
  173073. * bit to each already-nonzero coefficient. A correction bit is 1
  173074. * if the absolute value of the coefficient must be increased.
  173075. */
  173076. for (; k <= Se; k++) {
  173077. thiscoef = *block + jpeg_natural_order[k];
  173078. if (*thiscoef != 0) {
  173079. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173080. if (GET_BITS(1)) {
  173081. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173082. if (*thiscoef >= 0)
  173083. *thiscoef += p1;
  173084. else
  173085. *thiscoef += m1;
  173086. }
  173087. }
  173088. }
  173089. }
  173090. /* Count one block completed in EOB run */
  173091. EOBRUN--;
  173092. }
  173093. /* Completed MCU, so update state */
  173094. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173095. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173096. }
  173097. /* Account for restart interval (no-op if not using restarts) */
  173098. entropy->restarts_to_go--;
  173099. return TRUE;
  173100. undoit:
  173101. /* Re-zero any output coefficients that we made newly nonzero */
  173102. while (num_newnz > 0)
  173103. (*block)[newnz_pos[--num_newnz]] = 0;
  173104. return FALSE;
  173105. }
  173106. /*
  173107. * Module initialization routine for progressive Huffman entropy decoding.
  173108. */
  173109. GLOBAL(void)
  173110. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173111. {
  173112. phuff_entropy_ptr2 entropy;
  173113. int *coef_bit_ptr;
  173114. int ci, i;
  173115. entropy = (phuff_entropy_ptr2)
  173116. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173117. SIZEOF(phuff_entropy_decoder));
  173118. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173119. entropy->pub.start_pass = start_pass_phuff_decoder;
  173120. /* Mark derived tables unallocated */
  173121. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173122. entropy->derived_tbls[i] = NULL;
  173123. }
  173124. /* Create progression status table */
  173125. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173126. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173127. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173128. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173129. for (ci = 0; ci < cinfo->num_components; ci++)
  173130. for (i = 0; i < DCTSIZE2; i++)
  173131. *coef_bit_ptr++ = -1;
  173132. }
  173133. #endif /* D_PROGRESSIVE_SUPPORTED */
  173134. /*** End of inlined file: jdphuff.c ***/
  173135. /*** Start of inlined file: jdpostct.c ***/
  173136. #define JPEG_INTERNALS
  173137. /* Private buffer controller object */
  173138. typedef struct {
  173139. struct jpeg_d_post_controller pub; /* public fields */
  173140. /* Color quantization source buffer: this holds output data from
  173141. * the upsample/color conversion step to be passed to the quantizer.
  173142. * For two-pass color quantization, we need a full-image buffer;
  173143. * for one-pass operation, a strip buffer is sufficient.
  173144. */
  173145. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173146. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173147. JDIMENSION strip_height; /* buffer size in rows */
  173148. /* for two-pass mode only: */
  173149. JDIMENSION starting_row; /* row # of first row in current strip */
  173150. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173151. } my_post_controller;
  173152. typedef my_post_controller * my_post_ptr;
  173153. /* Forward declarations */
  173154. METHODDEF(void) post_process_1pass
  173155. JPP((j_decompress_ptr cinfo,
  173156. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173157. JDIMENSION in_row_groups_avail,
  173158. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173159. JDIMENSION out_rows_avail));
  173160. #ifdef QUANT_2PASS_SUPPORTED
  173161. METHODDEF(void) post_process_prepass
  173162. JPP((j_decompress_ptr cinfo,
  173163. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173164. JDIMENSION in_row_groups_avail,
  173165. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173166. JDIMENSION out_rows_avail));
  173167. METHODDEF(void) post_process_2pass
  173168. JPP((j_decompress_ptr cinfo,
  173169. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173170. JDIMENSION in_row_groups_avail,
  173171. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173172. JDIMENSION out_rows_avail));
  173173. #endif
  173174. /*
  173175. * Initialize for a processing pass.
  173176. */
  173177. METHODDEF(void)
  173178. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173179. {
  173180. my_post_ptr post = (my_post_ptr) cinfo->post;
  173181. switch (pass_mode) {
  173182. case JBUF_PASS_THRU:
  173183. if (cinfo->quantize_colors) {
  173184. /* Single-pass processing with color quantization. */
  173185. post->pub.post_process_data = post_process_1pass;
  173186. /* We could be doing buffered-image output before starting a 2-pass
  173187. * color quantization; in that case, jinit_d_post_controller did not
  173188. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173189. */
  173190. if (post->buffer == NULL) {
  173191. post->buffer = (*cinfo->mem->access_virt_sarray)
  173192. ((j_common_ptr) cinfo, post->whole_image,
  173193. (JDIMENSION) 0, post->strip_height, TRUE);
  173194. }
  173195. } else {
  173196. /* For single-pass processing without color quantization,
  173197. * I have no work to do; just call the upsampler directly.
  173198. */
  173199. post->pub.post_process_data = cinfo->upsample->upsample;
  173200. }
  173201. break;
  173202. #ifdef QUANT_2PASS_SUPPORTED
  173203. case JBUF_SAVE_AND_PASS:
  173204. /* First pass of 2-pass quantization */
  173205. if (post->whole_image == NULL)
  173206. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173207. post->pub.post_process_data = post_process_prepass;
  173208. break;
  173209. case JBUF_CRANK_DEST:
  173210. /* Second pass of 2-pass quantization */
  173211. if (post->whole_image == NULL)
  173212. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173213. post->pub.post_process_data = post_process_2pass;
  173214. break;
  173215. #endif /* QUANT_2PASS_SUPPORTED */
  173216. default:
  173217. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173218. break;
  173219. }
  173220. post->starting_row = post->next_row = 0;
  173221. }
  173222. /*
  173223. * Process some data in the one-pass (strip buffer) case.
  173224. * This is used for color precision reduction as well as one-pass quantization.
  173225. */
  173226. METHODDEF(void)
  173227. post_process_1pass (j_decompress_ptr cinfo,
  173228. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173229. JDIMENSION in_row_groups_avail,
  173230. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173231. JDIMENSION out_rows_avail)
  173232. {
  173233. my_post_ptr post = (my_post_ptr) cinfo->post;
  173234. JDIMENSION num_rows, max_rows;
  173235. /* Fill the buffer, but not more than what we can dump out in one go. */
  173236. /* Note we rely on the upsampler to detect bottom of image. */
  173237. max_rows = out_rows_avail - *out_row_ctr;
  173238. if (max_rows > post->strip_height)
  173239. max_rows = post->strip_height;
  173240. num_rows = 0;
  173241. (*cinfo->upsample->upsample) (cinfo,
  173242. input_buf, in_row_group_ctr, in_row_groups_avail,
  173243. post->buffer, &num_rows, max_rows);
  173244. /* Quantize and emit data. */
  173245. (*cinfo->cquantize->color_quantize) (cinfo,
  173246. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173247. *out_row_ctr += num_rows;
  173248. }
  173249. #ifdef QUANT_2PASS_SUPPORTED
  173250. /*
  173251. * Process some data in the first pass of 2-pass quantization.
  173252. */
  173253. METHODDEF(void)
  173254. post_process_prepass (j_decompress_ptr cinfo,
  173255. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173256. JDIMENSION in_row_groups_avail,
  173257. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173258. JDIMENSION)
  173259. {
  173260. my_post_ptr post = (my_post_ptr) cinfo->post;
  173261. JDIMENSION old_next_row, num_rows;
  173262. /* Reposition virtual buffer if at start of strip. */
  173263. if (post->next_row == 0) {
  173264. post->buffer = (*cinfo->mem->access_virt_sarray)
  173265. ((j_common_ptr) cinfo, post->whole_image,
  173266. post->starting_row, post->strip_height, TRUE);
  173267. }
  173268. /* Upsample some data (up to a strip height's worth). */
  173269. old_next_row = post->next_row;
  173270. (*cinfo->upsample->upsample) (cinfo,
  173271. input_buf, in_row_group_ctr, in_row_groups_avail,
  173272. post->buffer, &post->next_row, post->strip_height);
  173273. /* Allow quantizer to scan new data. No data is emitted, */
  173274. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173275. if (post->next_row > old_next_row) {
  173276. num_rows = post->next_row - old_next_row;
  173277. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173278. (JSAMPARRAY) NULL, (int) num_rows);
  173279. *out_row_ctr += num_rows;
  173280. }
  173281. /* Advance if we filled the strip. */
  173282. if (post->next_row >= post->strip_height) {
  173283. post->starting_row += post->strip_height;
  173284. post->next_row = 0;
  173285. }
  173286. }
  173287. /*
  173288. * Process some data in the second pass of 2-pass quantization.
  173289. */
  173290. METHODDEF(void)
  173291. post_process_2pass (j_decompress_ptr cinfo,
  173292. JSAMPIMAGE, JDIMENSION *,
  173293. JDIMENSION,
  173294. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173295. JDIMENSION out_rows_avail)
  173296. {
  173297. my_post_ptr post = (my_post_ptr) cinfo->post;
  173298. JDIMENSION num_rows, max_rows;
  173299. /* Reposition virtual buffer if at start of strip. */
  173300. if (post->next_row == 0) {
  173301. post->buffer = (*cinfo->mem->access_virt_sarray)
  173302. ((j_common_ptr) cinfo, post->whole_image,
  173303. post->starting_row, post->strip_height, FALSE);
  173304. }
  173305. /* Determine number of rows to emit. */
  173306. num_rows = post->strip_height - post->next_row; /* available in strip */
  173307. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173308. if (num_rows > max_rows)
  173309. num_rows = max_rows;
  173310. /* We have to check bottom of image here, can't depend on upsampler. */
  173311. max_rows = cinfo->output_height - post->starting_row;
  173312. if (num_rows > max_rows)
  173313. num_rows = max_rows;
  173314. /* Quantize and emit data. */
  173315. (*cinfo->cquantize->color_quantize) (cinfo,
  173316. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173317. (int) num_rows);
  173318. *out_row_ctr += num_rows;
  173319. /* Advance if we filled the strip. */
  173320. post->next_row += num_rows;
  173321. if (post->next_row >= post->strip_height) {
  173322. post->starting_row += post->strip_height;
  173323. post->next_row = 0;
  173324. }
  173325. }
  173326. #endif /* QUANT_2PASS_SUPPORTED */
  173327. /*
  173328. * Initialize postprocessing controller.
  173329. */
  173330. GLOBAL(void)
  173331. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173332. {
  173333. my_post_ptr post;
  173334. post = (my_post_ptr)
  173335. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173336. SIZEOF(my_post_controller));
  173337. cinfo->post = (struct jpeg_d_post_controller *) post;
  173338. post->pub.start_pass = start_pass_dpost;
  173339. post->whole_image = NULL; /* flag for no virtual arrays */
  173340. post->buffer = NULL; /* flag for no strip buffer */
  173341. /* Create the quantization buffer, if needed */
  173342. if (cinfo->quantize_colors) {
  173343. /* The buffer strip height is max_v_samp_factor, which is typically
  173344. * an efficient number of rows for upsampling to return.
  173345. * (In the presence of output rescaling, we might want to be smarter?)
  173346. */
  173347. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173348. if (need_full_buffer) {
  173349. /* Two-pass color quantization: need full-image storage. */
  173350. /* We round up the number of rows to a multiple of the strip height. */
  173351. #ifdef QUANT_2PASS_SUPPORTED
  173352. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173353. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173354. cinfo->output_width * cinfo->out_color_components,
  173355. (JDIMENSION) jround_up((long) cinfo->output_height,
  173356. (long) post->strip_height),
  173357. post->strip_height);
  173358. #else
  173359. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173360. #endif /* QUANT_2PASS_SUPPORTED */
  173361. } else {
  173362. /* One-pass color quantization: just make a strip buffer. */
  173363. post->buffer = (*cinfo->mem->alloc_sarray)
  173364. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173365. cinfo->output_width * cinfo->out_color_components,
  173366. post->strip_height);
  173367. }
  173368. }
  173369. }
  173370. /*** End of inlined file: jdpostct.c ***/
  173371. #undef FIX
  173372. /*** Start of inlined file: jdsample.c ***/
  173373. #define JPEG_INTERNALS
  173374. /* Pointer to routine to upsample a single component */
  173375. typedef JMETHOD(void, upsample1_ptr,
  173376. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173377. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173378. /* Private subobject */
  173379. typedef struct {
  173380. struct jpeg_upsampler pub; /* public fields */
  173381. /* Color conversion buffer. When using separate upsampling and color
  173382. * conversion steps, this buffer holds one upsampled row group until it
  173383. * has been color converted and output.
  173384. * Note: we do not allocate any storage for component(s) which are full-size,
  173385. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173386. * simply set to point to the input data array, thereby avoiding copying.
  173387. */
  173388. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173389. /* Per-component upsampling method pointers */
  173390. upsample1_ptr methods[MAX_COMPONENTS];
  173391. int next_row_out; /* counts rows emitted from color_buf */
  173392. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173393. /* Height of an input row group for each component. */
  173394. int rowgroup_height[MAX_COMPONENTS];
  173395. /* These arrays save pixel expansion factors so that int_expand need not
  173396. * recompute them each time. They are unused for other upsampling methods.
  173397. */
  173398. UINT8 h_expand[MAX_COMPONENTS];
  173399. UINT8 v_expand[MAX_COMPONENTS];
  173400. } my_upsampler2;
  173401. typedef my_upsampler2 * my_upsample_ptr2;
  173402. /*
  173403. * Initialize for an upsampling pass.
  173404. */
  173405. METHODDEF(void)
  173406. start_pass_upsample (j_decompress_ptr cinfo)
  173407. {
  173408. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173409. /* Mark the conversion buffer empty */
  173410. upsample->next_row_out = cinfo->max_v_samp_factor;
  173411. /* Initialize total-height counter for detecting bottom of image */
  173412. upsample->rows_to_go = cinfo->output_height;
  173413. }
  173414. /*
  173415. * Control routine to do upsampling (and color conversion).
  173416. *
  173417. * In this version we upsample each component independently.
  173418. * We upsample one row group into the conversion buffer, then apply
  173419. * color conversion a row at a time.
  173420. */
  173421. METHODDEF(void)
  173422. sep_upsample (j_decompress_ptr cinfo,
  173423. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173424. JDIMENSION,
  173425. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173426. JDIMENSION out_rows_avail)
  173427. {
  173428. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173429. int ci;
  173430. jpeg_component_info * compptr;
  173431. JDIMENSION num_rows;
  173432. /* Fill the conversion buffer, if it's empty */
  173433. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173434. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173435. ci++, compptr++) {
  173436. /* Invoke per-component upsample method. Notice we pass a POINTER
  173437. * to color_buf[ci], so that fullsize_upsample can change it.
  173438. */
  173439. (*upsample->methods[ci]) (cinfo, compptr,
  173440. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173441. upsample->color_buf + ci);
  173442. }
  173443. upsample->next_row_out = 0;
  173444. }
  173445. /* Color-convert and emit rows */
  173446. /* How many we have in the buffer: */
  173447. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173448. /* Not more than the distance to the end of the image. Need this test
  173449. * in case the image height is not a multiple of max_v_samp_factor:
  173450. */
  173451. if (num_rows > upsample->rows_to_go)
  173452. num_rows = upsample->rows_to_go;
  173453. /* And not more than what the client can accept: */
  173454. out_rows_avail -= *out_row_ctr;
  173455. if (num_rows > out_rows_avail)
  173456. num_rows = out_rows_avail;
  173457. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173458. (JDIMENSION) upsample->next_row_out,
  173459. output_buf + *out_row_ctr,
  173460. (int) num_rows);
  173461. /* Adjust counts */
  173462. *out_row_ctr += num_rows;
  173463. upsample->rows_to_go -= num_rows;
  173464. upsample->next_row_out += num_rows;
  173465. /* When the buffer is emptied, declare this input row group consumed */
  173466. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173467. (*in_row_group_ctr)++;
  173468. }
  173469. /*
  173470. * These are the routines invoked by sep_upsample to upsample pixel values
  173471. * of a single component. One row group is processed per call.
  173472. */
  173473. /*
  173474. * For full-size components, we just make color_buf[ci] point at the
  173475. * input buffer, and thus avoid copying any data. Note that this is
  173476. * safe only because sep_upsample doesn't declare the input row group
  173477. * "consumed" until we are done color converting and emitting it.
  173478. */
  173479. METHODDEF(void)
  173480. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173481. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173482. {
  173483. *output_data_ptr = input_data;
  173484. }
  173485. /*
  173486. * This is a no-op version used for "uninteresting" components.
  173487. * These components will not be referenced by color conversion.
  173488. */
  173489. METHODDEF(void)
  173490. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173491. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173492. {
  173493. *output_data_ptr = NULL; /* safety check */
  173494. }
  173495. /*
  173496. * This version handles any integral sampling ratios.
  173497. * This is not used for typical JPEG files, so it need not be fast.
  173498. * Nor, for that matter, is it particularly accurate: the algorithm is
  173499. * simple replication of the input pixel onto the corresponding output
  173500. * pixels. The hi-falutin sampling literature refers to this as a
  173501. * "box filter". A box filter tends to introduce visible artifacts,
  173502. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173503. * you would be well advised to improve this code.
  173504. */
  173505. METHODDEF(void)
  173506. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173507. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173508. {
  173509. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173510. JSAMPARRAY output_data = *output_data_ptr;
  173511. register JSAMPROW inptr, outptr;
  173512. register JSAMPLE invalue;
  173513. register int h;
  173514. JSAMPROW outend;
  173515. int h_expand, v_expand;
  173516. int inrow, outrow;
  173517. h_expand = upsample->h_expand[compptr->component_index];
  173518. v_expand = upsample->v_expand[compptr->component_index];
  173519. inrow = outrow = 0;
  173520. while (outrow < cinfo->max_v_samp_factor) {
  173521. /* Generate one output row with proper horizontal expansion */
  173522. inptr = input_data[inrow];
  173523. outptr = output_data[outrow];
  173524. outend = outptr + cinfo->output_width;
  173525. while (outptr < outend) {
  173526. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173527. for (h = h_expand; h > 0; h--) {
  173528. *outptr++ = invalue;
  173529. }
  173530. }
  173531. /* Generate any additional output rows by duplicating the first one */
  173532. if (v_expand > 1) {
  173533. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173534. v_expand-1, cinfo->output_width);
  173535. }
  173536. inrow++;
  173537. outrow += v_expand;
  173538. }
  173539. }
  173540. /*
  173541. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173542. * It's still a box filter.
  173543. */
  173544. METHODDEF(void)
  173545. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173546. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173547. {
  173548. JSAMPARRAY output_data = *output_data_ptr;
  173549. register JSAMPROW inptr, outptr;
  173550. register JSAMPLE invalue;
  173551. JSAMPROW outend;
  173552. int inrow;
  173553. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173554. inptr = input_data[inrow];
  173555. outptr = output_data[inrow];
  173556. outend = outptr + cinfo->output_width;
  173557. while (outptr < outend) {
  173558. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173559. *outptr++ = invalue;
  173560. *outptr++ = invalue;
  173561. }
  173562. }
  173563. }
  173564. /*
  173565. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173566. * It's still a box filter.
  173567. */
  173568. METHODDEF(void)
  173569. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173570. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173571. {
  173572. JSAMPARRAY output_data = *output_data_ptr;
  173573. register JSAMPROW inptr, outptr;
  173574. register JSAMPLE invalue;
  173575. JSAMPROW outend;
  173576. int inrow, outrow;
  173577. inrow = outrow = 0;
  173578. while (outrow < cinfo->max_v_samp_factor) {
  173579. inptr = input_data[inrow];
  173580. outptr = output_data[outrow];
  173581. outend = outptr + cinfo->output_width;
  173582. while (outptr < outend) {
  173583. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173584. *outptr++ = invalue;
  173585. *outptr++ = invalue;
  173586. }
  173587. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173588. 1, cinfo->output_width);
  173589. inrow++;
  173590. outrow += 2;
  173591. }
  173592. }
  173593. /*
  173594. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173595. *
  173596. * The upsampling algorithm is linear interpolation between pixel centers,
  173597. * also known as a "triangle filter". This is a good compromise between
  173598. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173599. * of the way between input pixel centers.
  173600. *
  173601. * A note about the "bias" calculations: when rounding fractional values to
  173602. * integer, we do not want to always round 0.5 up to the next integer.
  173603. * If we did that, we'd introduce a noticeable bias towards larger values.
  173604. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173605. * alternate pixel locations (a simple ordered dither pattern).
  173606. */
  173607. METHODDEF(void)
  173608. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173609. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173610. {
  173611. JSAMPARRAY output_data = *output_data_ptr;
  173612. register JSAMPROW inptr, outptr;
  173613. register int invalue;
  173614. register JDIMENSION colctr;
  173615. int inrow;
  173616. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173617. inptr = input_data[inrow];
  173618. outptr = output_data[inrow];
  173619. /* Special case for first column */
  173620. invalue = GETJSAMPLE(*inptr++);
  173621. *outptr++ = (JSAMPLE) invalue;
  173622. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173623. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173624. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173625. invalue = GETJSAMPLE(*inptr++) * 3;
  173626. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173627. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173628. }
  173629. /* Special case for last column */
  173630. invalue = GETJSAMPLE(*inptr);
  173631. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173632. *outptr++ = (JSAMPLE) invalue;
  173633. }
  173634. }
  173635. /*
  173636. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173637. * Again a triangle filter; see comments for h2v1 case, above.
  173638. *
  173639. * It is OK for us to reference the adjacent input rows because we demanded
  173640. * context from the main buffer controller (see initialization code).
  173641. */
  173642. METHODDEF(void)
  173643. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173644. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173645. {
  173646. JSAMPARRAY output_data = *output_data_ptr;
  173647. register JSAMPROW inptr0, inptr1, outptr;
  173648. #if BITS_IN_JSAMPLE == 8
  173649. register int thiscolsum, lastcolsum, nextcolsum;
  173650. #else
  173651. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173652. #endif
  173653. register JDIMENSION colctr;
  173654. int inrow, outrow, v;
  173655. inrow = outrow = 0;
  173656. while (outrow < cinfo->max_v_samp_factor) {
  173657. for (v = 0; v < 2; v++) {
  173658. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173659. inptr0 = input_data[inrow];
  173660. if (v == 0) /* next nearest is row above */
  173661. inptr1 = input_data[inrow-1];
  173662. else /* next nearest is row below */
  173663. inptr1 = input_data[inrow+1];
  173664. outptr = output_data[outrow++];
  173665. /* Special case for first column */
  173666. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173667. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173668. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173669. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173670. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173671. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173672. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173673. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173674. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173675. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173676. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173677. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173678. }
  173679. /* Special case for last column */
  173680. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173681. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173682. }
  173683. inrow++;
  173684. }
  173685. }
  173686. /*
  173687. * Module initialization routine for upsampling.
  173688. */
  173689. GLOBAL(void)
  173690. jinit_upsampler (j_decompress_ptr cinfo)
  173691. {
  173692. my_upsample_ptr2 upsample;
  173693. int ci;
  173694. jpeg_component_info * compptr;
  173695. boolean need_buffer, do_fancy;
  173696. int h_in_group, v_in_group, h_out_group, v_out_group;
  173697. upsample = (my_upsample_ptr2)
  173698. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173699. SIZEOF(my_upsampler2));
  173700. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173701. upsample->pub.start_pass = start_pass_upsample;
  173702. upsample->pub.upsample = sep_upsample;
  173703. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173704. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173705. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173706. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173707. * so don't ask for it.
  173708. */
  173709. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173710. /* Verify we can handle the sampling factors, select per-component methods,
  173711. * and create storage as needed.
  173712. */
  173713. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173714. ci++, compptr++) {
  173715. /* Compute size of an "input group" after IDCT scaling. This many samples
  173716. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173717. */
  173718. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173719. cinfo->min_DCT_scaled_size;
  173720. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173721. cinfo->min_DCT_scaled_size;
  173722. h_out_group = cinfo->max_h_samp_factor;
  173723. v_out_group = cinfo->max_v_samp_factor;
  173724. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173725. need_buffer = TRUE;
  173726. if (! compptr->component_needed) {
  173727. /* Don't bother to upsample an uninteresting component. */
  173728. upsample->methods[ci] = noop_upsample;
  173729. need_buffer = FALSE;
  173730. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173731. /* Fullsize components can be processed without any work. */
  173732. upsample->methods[ci] = fullsize_upsample;
  173733. need_buffer = FALSE;
  173734. } else if (h_in_group * 2 == h_out_group &&
  173735. v_in_group == v_out_group) {
  173736. /* Special cases for 2h1v upsampling */
  173737. if (do_fancy && compptr->downsampled_width > 2)
  173738. upsample->methods[ci] = h2v1_fancy_upsample;
  173739. else
  173740. upsample->methods[ci] = h2v1_upsample;
  173741. } else if (h_in_group * 2 == h_out_group &&
  173742. v_in_group * 2 == v_out_group) {
  173743. /* Special cases for 2h2v upsampling */
  173744. if (do_fancy && compptr->downsampled_width > 2) {
  173745. upsample->methods[ci] = h2v2_fancy_upsample;
  173746. upsample->pub.need_context_rows = TRUE;
  173747. } else
  173748. upsample->methods[ci] = h2v2_upsample;
  173749. } else if ((h_out_group % h_in_group) == 0 &&
  173750. (v_out_group % v_in_group) == 0) {
  173751. /* Generic integral-factors upsampling method */
  173752. upsample->methods[ci] = int_upsample;
  173753. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173754. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173755. } else
  173756. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173757. if (need_buffer) {
  173758. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173759. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173760. (JDIMENSION) jround_up((long) cinfo->output_width,
  173761. (long) cinfo->max_h_samp_factor),
  173762. (JDIMENSION) cinfo->max_v_samp_factor);
  173763. }
  173764. }
  173765. }
  173766. /*** End of inlined file: jdsample.c ***/
  173767. /*** Start of inlined file: jdtrans.c ***/
  173768. #define JPEG_INTERNALS
  173769. /* Forward declarations */
  173770. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173771. /*
  173772. * Read the coefficient arrays from a JPEG file.
  173773. * jpeg_read_header must be completed before calling this.
  173774. *
  173775. * The entire image is read into a set of virtual coefficient-block arrays,
  173776. * one per component. The return value is a pointer to the array of
  173777. * virtual-array descriptors. These can be manipulated directly via the
  173778. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173779. * To release the memory occupied by the virtual arrays, call
  173780. * jpeg_finish_decompress() when done with the data.
  173781. *
  173782. * An alternative usage is to simply obtain access to the coefficient arrays
  173783. * during a buffered-image-mode decompression operation. This is allowed
  173784. * after any jpeg_finish_output() call. The arrays can be accessed until
  173785. * jpeg_finish_decompress() is called. (Note that any call to the library
  173786. * may reposition the arrays, so don't rely on access_virt_barray() results
  173787. * to stay valid across library calls.)
  173788. *
  173789. * Returns NULL if suspended. This case need be checked only if
  173790. * a suspending data source is used.
  173791. */
  173792. GLOBAL(jvirt_barray_ptr *)
  173793. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173794. {
  173795. if (cinfo->global_state == DSTATE_READY) {
  173796. /* First call: initialize active modules */
  173797. transdecode_master_selection(cinfo);
  173798. cinfo->global_state = DSTATE_RDCOEFS;
  173799. }
  173800. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173801. /* Absorb whole file into the coef buffer */
  173802. for (;;) {
  173803. int retcode;
  173804. /* Call progress monitor hook if present */
  173805. if (cinfo->progress != NULL)
  173806. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173807. /* Absorb some more input */
  173808. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173809. if (retcode == JPEG_SUSPENDED)
  173810. return NULL;
  173811. if (retcode == JPEG_REACHED_EOI)
  173812. break;
  173813. /* Advance progress counter if appropriate */
  173814. if (cinfo->progress != NULL &&
  173815. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173816. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173817. /* startup underestimated number of scans; ratchet up one scan */
  173818. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173819. }
  173820. }
  173821. }
  173822. /* Set state so that jpeg_finish_decompress does the right thing */
  173823. cinfo->global_state = DSTATE_STOPPING;
  173824. }
  173825. /* At this point we should be in state DSTATE_STOPPING if being used
  173826. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173827. * to the coefficients during a full buffered-image-mode decompression.
  173828. */
  173829. if ((cinfo->global_state == DSTATE_STOPPING ||
  173830. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173831. return cinfo->coef->coef_arrays;
  173832. }
  173833. /* Oops, improper usage */
  173834. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173835. return NULL; /* keep compiler happy */
  173836. }
  173837. /*
  173838. * Master selection of decompression modules for transcoding.
  173839. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173840. */
  173841. LOCAL(void)
  173842. transdecode_master_selection (j_decompress_ptr cinfo)
  173843. {
  173844. /* This is effectively a buffered-image operation. */
  173845. cinfo->buffered_image = TRUE;
  173846. /* Entropy decoding: either Huffman or arithmetic coding. */
  173847. if (cinfo->arith_code) {
  173848. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173849. } else {
  173850. if (cinfo->progressive_mode) {
  173851. #ifdef D_PROGRESSIVE_SUPPORTED
  173852. jinit_phuff_decoder(cinfo);
  173853. #else
  173854. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173855. #endif
  173856. } else
  173857. jinit_huff_decoder(cinfo);
  173858. }
  173859. /* Always get a full-image coefficient buffer. */
  173860. jinit_d_coef_controller(cinfo, TRUE);
  173861. /* We can now tell the memory manager to allocate virtual arrays. */
  173862. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173863. /* Initialize input side of decompressor to consume first scan. */
  173864. (*cinfo->inputctl->start_input_pass) (cinfo);
  173865. /* Initialize progress monitoring. */
  173866. if (cinfo->progress != NULL) {
  173867. int nscans;
  173868. /* Estimate number of scans to set pass_limit. */
  173869. if (cinfo->progressive_mode) {
  173870. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173871. nscans = 2 + 3 * cinfo->num_components;
  173872. } else if (cinfo->inputctl->has_multiple_scans) {
  173873. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173874. nscans = cinfo->num_components;
  173875. } else {
  173876. nscans = 1;
  173877. }
  173878. cinfo->progress->pass_counter = 0L;
  173879. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173880. cinfo->progress->completed_passes = 0;
  173881. cinfo->progress->total_passes = 1;
  173882. }
  173883. }
  173884. /*** End of inlined file: jdtrans.c ***/
  173885. /*** Start of inlined file: jfdctflt.c ***/
  173886. #define JPEG_INTERNALS
  173887. #ifdef DCT_FLOAT_SUPPORTED
  173888. /*
  173889. * This module is specialized to the case DCTSIZE = 8.
  173890. */
  173891. #if DCTSIZE != 8
  173892. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173893. #endif
  173894. /*
  173895. * Perform the forward DCT on one block of samples.
  173896. */
  173897. GLOBAL(void)
  173898. jpeg_fdct_float (FAST_FLOAT * data)
  173899. {
  173900. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173901. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173902. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173903. FAST_FLOAT *dataptr;
  173904. int ctr;
  173905. /* Pass 1: process rows. */
  173906. dataptr = data;
  173907. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173908. tmp0 = dataptr[0] + dataptr[7];
  173909. tmp7 = dataptr[0] - dataptr[7];
  173910. tmp1 = dataptr[1] + dataptr[6];
  173911. tmp6 = dataptr[1] - dataptr[6];
  173912. tmp2 = dataptr[2] + dataptr[5];
  173913. tmp5 = dataptr[2] - dataptr[5];
  173914. tmp3 = dataptr[3] + dataptr[4];
  173915. tmp4 = dataptr[3] - dataptr[4];
  173916. /* Even part */
  173917. tmp10 = tmp0 + tmp3; /* phase 2 */
  173918. tmp13 = tmp0 - tmp3;
  173919. tmp11 = tmp1 + tmp2;
  173920. tmp12 = tmp1 - tmp2;
  173921. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173922. dataptr[4] = tmp10 - tmp11;
  173923. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173924. dataptr[2] = tmp13 + z1; /* phase 5 */
  173925. dataptr[6] = tmp13 - z1;
  173926. /* Odd part */
  173927. tmp10 = tmp4 + tmp5; /* phase 2 */
  173928. tmp11 = tmp5 + tmp6;
  173929. tmp12 = tmp6 + tmp7;
  173930. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173931. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173932. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173933. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173934. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173935. z11 = tmp7 + z3; /* phase 5 */
  173936. z13 = tmp7 - z3;
  173937. dataptr[5] = z13 + z2; /* phase 6 */
  173938. dataptr[3] = z13 - z2;
  173939. dataptr[1] = z11 + z4;
  173940. dataptr[7] = z11 - z4;
  173941. dataptr += DCTSIZE; /* advance pointer to next row */
  173942. }
  173943. /* Pass 2: process columns. */
  173944. dataptr = data;
  173945. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173946. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173947. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173948. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173949. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173950. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173951. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173952. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173953. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173954. /* Even part */
  173955. tmp10 = tmp0 + tmp3; /* phase 2 */
  173956. tmp13 = tmp0 - tmp3;
  173957. tmp11 = tmp1 + tmp2;
  173958. tmp12 = tmp1 - tmp2;
  173959. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173960. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173961. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173962. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173963. dataptr[DCTSIZE*6] = tmp13 - z1;
  173964. /* Odd part */
  173965. tmp10 = tmp4 + tmp5; /* phase 2 */
  173966. tmp11 = tmp5 + tmp6;
  173967. tmp12 = tmp6 + tmp7;
  173968. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173969. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173970. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173971. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173972. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173973. z11 = tmp7 + z3; /* phase 5 */
  173974. z13 = tmp7 - z3;
  173975. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173976. dataptr[DCTSIZE*3] = z13 - z2;
  173977. dataptr[DCTSIZE*1] = z11 + z4;
  173978. dataptr[DCTSIZE*7] = z11 - z4;
  173979. dataptr++; /* advance pointer to next column */
  173980. }
  173981. }
  173982. #endif /* DCT_FLOAT_SUPPORTED */
  173983. /*** End of inlined file: jfdctflt.c ***/
  173984. /*** Start of inlined file: jfdctint.c ***/
  173985. #define JPEG_INTERNALS
  173986. #ifdef DCT_ISLOW_SUPPORTED
  173987. /*
  173988. * This module is specialized to the case DCTSIZE = 8.
  173989. */
  173990. #if DCTSIZE != 8
  173991. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173992. #endif
  173993. /*
  173994. * The poop on this scaling stuff is as follows:
  173995. *
  173996. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173997. * larger than the true DCT outputs. The final outputs are therefore
  173998. * a factor of N larger than desired; since N=8 this can be cured by
  173999. * a simple right shift at the end of the algorithm. The advantage of
  174000. * this arrangement is that we save two multiplications per 1-D DCT,
  174001. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174002. * In the IJG code, this factor of 8 is removed by the quantization step
  174003. * (in jcdctmgr.c), NOT in this module.
  174004. *
  174005. * We have to do addition and subtraction of the integer inputs, which
  174006. * is no problem, and multiplication by fractional constants, which is
  174007. * a problem to do in integer arithmetic. We multiply all the constants
  174008. * by CONST_SCALE and convert them to integer constants (thus retaining
  174009. * CONST_BITS bits of precision in the constants). After doing a
  174010. * multiplication we have to divide the product by CONST_SCALE, with proper
  174011. * rounding, to produce the correct output. This division can be done
  174012. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174013. * as long as possible so that partial sums can be added together with
  174014. * full fractional precision.
  174015. *
  174016. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174017. * they are represented to better-than-integral precision. These outputs
  174018. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174019. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174020. * array is INT32 anyway.)
  174021. *
  174022. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174023. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174024. * shows that the values given below are the most effective.
  174025. */
  174026. #if BITS_IN_JSAMPLE == 8
  174027. #define CONST_BITS 13
  174028. #define PASS1_BITS 2
  174029. #else
  174030. #define CONST_BITS 13
  174031. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174032. #endif
  174033. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174034. * causing a lot of useless floating-point operations at run time.
  174035. * To get around this we use the following pre-calculated constants.
  174036. * If you change CONST_BITS you may want to add appropriate values.
  174037. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174038. */
  174039. #if CONST_BITS == 13
  174040. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174041. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174042. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174043. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174044. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174045. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174046. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174047. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174048. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174049. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174050. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174051. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174052. #else
  174053. #define FIX_0_298631336 FIX(0.298631336)
  174054. #define FIX_0_390180644 FIX(0.390180644)
  174055. #define FIX_0_541196100 FIX(0.541196100)
  174056. #define FIX_0_765366865 FIX(0.765366865)
  174057. #define FIX_0_899976223 FIX(0.899976223)
  174058. #define FIX_1_175875602 FIX(1.175875602)
  174059. #define FIX_1_501321110 FIX(1.501321110)
  174060. #define FIX_1_847759065 FIX(1.847759065)
  174061. #define FIX_1_961570560 FIX(1.961570560)
  174062. #define FIX_2_053119869 FIX(2.053119869)
  174063. #define FIX_2_562915447 FIX(2.562915447)
  174064. #define FIX_3_072711026 FIX(3.072711026)
  174065. #endif
  174066. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174067. * For 8-bit samples with the recommended scaling, all the variable
  174068. * and constant values involved are no more than 16 bits wide, so a
  174069. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174070. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174071. */
  174072. #if BITS_IN_JSAMPLE == 8
  174073. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174074. #else
  174075. #define MULTIPLY(var,const) ((var) * (const))
  174076. #endif
  174077. /*
  174078. * Perform the forward DCT on one block of samples.
  174079. */
  174080. GLOBAL(void)
  174081. jpeg_fdct_islow (DCTELEM * data)
  174082. {
  174083. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174084. INT32 tmp10, tmp11, tmp12, tmp13;
  174085. INT32 z1, z2, z3, z4, z5;
  174086. DCTELEM *dataptr;
  174087. int ctr;
  174088. SHIFT_TEMPS
  174089. /* Pass 1: process rows. */
  174090. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174091. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174092. dataptr = data;
  174093. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174094. tmp0 = dataptr[0] + dataptr[7];
  174095. tmp7 = dataptr[0] - dataptr[7];
  174096. tmp1 = dataptr[1] + dataptr[6];
  174097. tmp6 = dataptr[1] - dataptr[6];
  174098. tmp2 = dataptr[2] + dataptr[5];
  174099. tmp5 = dataptr[2] - dataptr[5];
  174100. tmp3 = dataptr[3] + dataptr[4];
  174101. tmp4 = dataptr[3] - dataptr[4];
  174102. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174103. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174104. */
  174105. tmp10 = tmp0 + tmp3;
  174106. tmp13 = tmp0 - tmp3;
  174107. tmp11 = tmp1 + tmp2;
  174108. tmp12 = tmp1 - tmp2;
  174109. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174110. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174111. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174112. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174113. CONST_BITS-PASS1_BITS);
  174114. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174115. CONST_BITS-PASS1_BITS);
  174116. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174117. * cK represents cos(K*pi/16).
  174118. * i0..i3 in the paper are tmp4..tmp7 here.
  174119. */
  174120. z1 = tmp4 + tmp7;
  174121. z2 = tmp5 + tmp6;
  174122. z3 = tmp4 + tmp6;
  174123. z4 = tmp5 + tmp7;
  174124. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174125. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174126. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174127. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174128. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174129. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174130. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174131. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174132. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174133. z3 += z5;
  174134. z4 += z5;
  174135. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174136. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174137. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174138. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174139. dataptr += DCTSIZE; /* advance pointer to next row */
  174140. }
  174141. /* Pass 2: process columns.
  174142. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174143. * by an overall factor of 8.
  174144. */
  174145. dataptr = data;
  174146. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174147. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174148. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174149. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174150. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174151. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174152. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174153. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174154. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174155. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174156. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174157. */
  174158. tmp10 = tmp0 + tmp3;
  174159. tmp13 = tmp0 - tmp3;
  174160. tmp11 = tmp1 + tmp2;
  174161. tmp12 = tmp1 - tmp2;
  174162. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174163. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174164. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174165. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174166. CONST_BITS+PASS1_BITS);
  174167. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174168. CONST_BITS+PASS1_BITS);
  174169. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174170. * cK represents cos(K*pi/16).
  174171. * i0..i3 in the paper are tmp4..tmp7 here.
  174172. */
  174173. z1 = tmp4 + tmp7;
  174174. z2 = tmp5 + tmp6;
  174175. z3 = tmp4 + tmp6;
  174176. z4 = tmp5 + tmp7;
  174177. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174178. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174179. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174180. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174181. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174182. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174183. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174184. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174185. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174186. z3 += z5;
  174187. z4 += z5;
  174188. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174189. CONST_BITS+PASS1_BITS);
  174190. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174191. CONST_BITS+PASS1_BITS);
  174192. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174193. CONST_BITS+PASS1_BITS);
  174194. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174195. CONST_BITS+PASS1_BITS);
  174196. dataptr++; /* advance pointer to next column */
  174197. }
  174198. }
  174199. #endif /* DCT_ISLOW_SUPPORTED */
  174200. /*** End of inlined file: jfdctint.c ***/
  174201. #undef CONST_BITS
  174202. #undef MULTIPLY
  174203. #undef FIX_0_541196100
  174204. /*** Start of inlined file: jfdctfst.c ***/
  174205. #define JPEG_INTERNALS
  174206. #ifdef DCT_IFAST_SUPPORTED
  174207. /*
  174208. * This module is specialized to the case DCTSIZE = 8.
  174209. */
  174210. #if DCTSIZE != 8
  174211. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174212. #endif
  174213. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174214. * see jfdctint.c for more details. However, we choose to descale
  174215. * (right shift) multiplication products as soon as they are formed,
  174216. * rather than carrying additional fractional bits into subsequent additions.
  174217. * This compromises accuracy slightly, but it lets us save a few shifts.
  174218. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174219. * everywhere except in the multiplications proper; this saves a good deal
  174220. * of work on 16-bit-int machines.
  174221. *
  174222. * Again to save a few shifts, the intermediate results between pass 1 and
  174223. * pass 2 are not upscaled, but are represented only to integral precision.
  174224. *
  174225. * A final compromise is to represent the multiplicative constants to only
  174226. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174227. * machines, and may also reduce the cost of multiplication (since there
  174228. * are fewer one-bits in the constants).
  174229. */
  174230. #define CONST_BITS 8
  174231. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174232. * causing a lot of useless floating-point operations at run time.
  174233. * To get around this we use the following pre-calculated constants.
  174234. * If you change CONST_BITS you may want to add appropriate values.
  174235. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174236. */
  174237. #if CONST_BITS == 8
  174238. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174239. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174240. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174241. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174242. #else
  174243. #define FIX_0_382683433 FIX(0.382683433)
  174244. #define FIX_0_541196100 FIX(0.541196100)
  174245. #define FIX_0_707106781 FIX(0.707106781)
  174246. #define FIX_1_306562965 FIX(1.306562965)
  174247. #endif
  174248. /* We can gain a little more speed, with a further compromise in accuracy,
  174249. * by omitting the addition in a descaling shift. This yields an incorrectly
  174250. * rounded result half the time...
  174251. */
  174252. #ifndef USE_ACCURATE_ROUNDING
  174253. #undef DESCALE
  174254. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174255. #endif
  174256. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174257. * descale to yield a DCTELEM result.
  174258. */
  174259. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174260. /*
  174261. * Perform the forward DCT on one block of samples.
  174262. */
  174263. GLOBAL(void)
  174264. jpeg_fdct_ifast (DCTELEM * data)
  174265. {
  174266. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174267. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174268. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174269. DCTELEM *dataptr;
  174270. int ctr;
  174271. SHIFT_TEMPS
  174272. /* Pass 1: process rows. */
  174273. dataptr = data;
  174274. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174275. tmp0 = dataptr[0] + dataptr[7];
  174276. tmp7 = dataptr[0] - dataptr[7];
  174277. tmp1 = dataptr[1] + dataptr[6];
  174278. tmp6 = dataptr[1] - dataptr[6];
  174279. tmp2 = dataptr[2] + dataptr[5];
  174280. tmp5 = dataptr[2] - dataptr[5];
  174281. tmp3 = dataptr[3] + dataptr[4];
  174282. tmp4 = dataptr[3] - dataptr[4];
  174283. /* Even part */
  174284. tmp10 = tmp0 + tmp3; /* phase 2 */
  174285. tmp13 = tmp0 - tmp3;
  174286. tmp11 = tmp1 + tmp2;
  174287. tmp12 = tmp1 - tmp2;
  174288. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174289. dataptr[4] = tmp10 - tmp11;
  174290. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174291. dataptr[2] = tmp13 + z1; /* phase 5 */
  174292. dataptr[6] = tmp13 - z1;
  174293. /* Odd part */
  174294. tmp10 = tmp4 + tmp5; /* phase 2 */
  174295. tmp11 = tmp5 + tmp6;
  174296. tmp12 = tmp6 + tmp7;
  174297. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174298. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174299. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174300. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174301. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174302. z11 = tmp7 + z3; /* phase 5 */
  174303. z13 = tmp7 - z3;
  174304. dataptr[5] = z13 + z2; /* phase 6 */
  174305. dataptr[3] = z13 - z2;
  174306. dataptr[1] = z11 + z4;
  174307. dataptr[7] = z11 - z4;
  174308. dataptr += DCTSIZE; /* advance pointer to next row */
  174309. }
  174310. /* Pass 2: process columns. */
  174311. dataptr = data;
  174312. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174313. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174314. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174315. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174316. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174317. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174318. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174319. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174320. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174321. /* Even part */
  174322. tmp10 = tmp0 + tmp3; /* phase 2 */
  174323. tmp13 = tmp0 - tmp3;
  174324. tmp11 = tmp1 + tmp2;
  174325. tmp12 = tmp1 - tmp2;
  174326. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174327. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174328. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174329. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174330. dataptr[DCTSIZE*6] = tmp13 - z1;
  174331. /* Odd part */
  174332. tmp10 = tmp4 + tmp5; /* phase 2 */
  174333. tmp11 = tmp5 + tmp6;
  174334. tmp12 = tmp6 + tmp7;
  174335. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174336. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174337. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174338. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174339. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174340. z11 = tmp7 + z3; /* phase 5 */
  174341. z13 = tmp7 - z3;
  174342. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174343. dataptr[DCTSIZE*3] = z13 - z2;
  174344. dataptr[DCTSIZE*1] = z11 + z4;
  174345. dataptr[DCTSIZE*7] = z11 - z4;
  174346. dataptr++; /* advance pointer to next column */
  174347. }
  174348. }
  174349. #endif /* DCT_IFAST_SUPPORTED */
  174350. /*** End of inlined file: jfdctfst.c ***/
  174351. #undef FIX_0_541196100
  174352. /*** Start of inlined file: jidctflt.c ***/
  174353. #define JPEG_INTERNALS
  174354. #ifdef DCT_FLOAT_SUPPORTED
  174355. /*
  174356. * This module is specialized to the case DCTSIZE = 8.
  174357. */
  174358. #if DCTSIZE != 8
  174359. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174360. #endif
  174361. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174362. * entry; produce a float result.
  174363. */
  174364. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174365. /*
  174366. * Perform dequantization and inverse DCT on one block of coefficients.
  174367. */
  174368. GLOBAL(void)
  174369. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174370. JCOEFPTR coef_block,
  174371. JSAMPARRAY output_buf, JDIMENSION output_col)
  174372. {
  174373. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174374. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174375. FAST_FLOAT z5, z10, z11, z12, z13;
  174376. JCOEFPTR inptr;
  174377. FLOAT_MULT_TYPE * quantptr;
  174378. FAST_FLOAT * wsptr;
  174379. JSAMPROW outptr;
  174380. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174381. int ctr;
  174382. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174383. SHIFT_TEMPS
  174384. /* Pass 1: process columns from input, store into work array. */
  174385. inptr = coef_block;
  174386. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174387. wsptr = workspace;
  174388. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174389. /* Due to quantization, we will usually find that many of the input
  174390. * coefficients are zero, especially the AC terms. We can exploit this
  174391. * by short-circuiting the IDCT calculation for any column in which all
  174392. * the AC terms are zero. In that case each output is equal to the
  174393. * DC coefficient (with scale factor as needed).
  174394. * With typical images and quantization tables, half or more of the
  174395. * column DCT calculations can be simplified this way.
  174396. */
  174397. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174398. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174399. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174400. inptr[DCTSIZE*7] == 0) {
  174401. /* AC terms all zero */
  174402. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174403. wsptr[DCTSIZE*0] = dcval;
  174404. wsptr[DCTSIZE*1] = dcval;
  174405. wsptr[DCTSIZE*2] = dcval;
  174406. wsptr[DCTSIZE*3] = dcval;
  174407. wsptr[DCTSIZE*4] = dcval;
  174408. wsptr[DCTSIZE*5] = dcval;
  174409. wsptr[DCTSIZE*6] = dcval;
  174410. wsptr[DCTSIZE*7] = dcval;
  174411. inptr++; /* advance pointers to next column */
  174412. quantptr++;
  174413. wsptr++;
  174414. continue;
  174415. }
  174416. /* Even part */
  174417. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174418. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174419. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174420. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174421. tmp10 = tmp0 + tmp2; /* phase 3 */
  174422. tmp11 = tmp0 - tmp2;
  174423. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174424. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174425. tmp0 = tmp10 + tmp13; /* phase 2 */
  174426. tmp3 = tmp10 - tmp13;
  174427. tmp1 = tmp11 + tmp12;
  174428. tmp2 = tmp11 - tmp12;
  174429. /* Odd part */
  174430. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174431. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174432. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174433. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174434. z13 = tmp6 + tmp5; /* phase 6 */
  174435. z10 = tmp6 - tmp5;
  174436. z11 = tmp4 + tmp7;
  174437. z12 = tmp4 - tmp7;
  174438. tmp7 = z11 + z13; /* phase 5 */
  174439. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174440. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174441. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174442. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174443. tmp6 = tmp12 - tmp7; /* phase 2 */
  174444. tmp5 = tmp11 - tmp6;
  174445. tmp4 = tmp10 + tmp5;
  174446. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174447. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174448. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174449. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174450. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174451. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174452. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174453. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174454. inptr++; /* advance pointers to next column */
  174455. quantptr++;
  174456. wsptr++;
  174457. }
  174458. /* Pass 2: process rows from work array, store into output array. */
  174459. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174460. wsptr = workspace;
  174461. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174462. outptr = output_buf[ctr] + output_col;
  174463. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174464. * However, the column calculation has created many nonzero AC terms, so
  174465. * the simplification applies less often (typically 5% to 10% of the time).
  174466. * And testing floats for zero is relatively expensive, so we don't bother.
  174467. */
  174468. /* Even part */
  174469. tmp10 = wsptr[0] + wsptr[4];
  174470. tmp11 = wsptr[0] - wsptr[4];
  174471. tmp13 = wsptr[2] + wsptr[6];
  174472. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174473. tmp0 = tmp10 + tmp13;
  174474. tmp3 = tmp10 - tmp13;
  174475. tmp1 = tmp11 + tmp12;
  174476. tmp2 = tmp11 - tmp12;
  174477. /* Odd part */
  174478. z13 = wsptr[5] + wsptr[3];
  174479. z10 = wsptr[5] - wsptr[3];
  174480. z11 = wsptr[1] + wsptr[7];
  174481. z12 = wsptr[1] - wsptr[7];
  174482. tmp7 = z11 + z13;
  174483. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174484. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174485. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174486. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174487. tmp6 = tmp12 - tmp7;
  174488. tmp5 = tmp11 - tmp6;
  174489. tmp4 = tmp10 + tmp5;
  174490. /* Final output stage: scale down by a factor of 8 and range-limit */
  174491. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174492. & RANGE_MASK];
  174493. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174494. & RANGE_MASK];
  174495. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174496. & RANGE_MASK];
  174497. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174498. & RANGE_MASK];
  174499. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174500. & RANGE_MASK];
  174501. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174502. & RANGE_MASK];
  174503. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174504. & RANGE_MASK];
  174505. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174506. & RANGE_MASK];
  174507. wsptr += DCTSIZE; /* advance pointer to next row */
  174508. }
  174509. }
  174510. #endif /* DCT_FLOAT_SUPPORTED */
  174511. /*** End of inlined file: jidctflt.c ***/
  174512. #undef CONST_BITS
  174513. #undef FIX_1_847759065
  174514. #undef MULTIPLY
  174515. #undef DEQUANTIZE
  174516. #undef DESCALE
  174517. /*** Start of inlined file: jidctfst.c ***/
  174518. #define JPEG_INTERNALS
  174519. #ifdef DCT_IFAST_SUPPORTED
  174520. /*
  174521. * This module is specialized to the case DCTSIZE = 8.
  174522. */
  174523. #if DCTSIZE != 8
  174524. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174525. #endif
  174526. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174527. * see jidctint.c for more details. However, we choose to descale
  174528. * (right shift) multiplication products as soon as they are formed,
  174529. * rather than carrying additional fractional bits into subsequent additions.
  174530. * This compromises accuracy slightly, but it lets us save a few shifts.
  174531. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174532. * everywhere except in the multiplications proper; this saves a good deal
  174533. * of work on 16-bit-int machines.
  174534. *
  174535. * The dequantized coefficients are not integers because the AA&N scaling
  174536. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174537. * so that the first and second IDCT rounds have the same input scaling.
  174538. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174539. * avoid a descaling shift; this compromises accuracy rather drastically
  174540. * for small quantization table entries, but it saves a lot of shifts.
  174541. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174542. * so we use a much larger scaling factor to preserve accuracy.
  174543. *
  174544. * A final compromise is to represent the multiplicative constants to only
  174545. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174546. * machines, and may also reduce the cost of multiplication (since there
  174547. * are fewer one-bits in the constants).
  174548. */
  174549. #if BITS_IN_JSAMPLE == 8
  174550. #define CONST_BITS 8
  174551. #define PASS1_BITS 2
  174552. #else
  174553. #define CONST_BITS 8
  174554. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174555. #endif
  174556. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174557. * causing a lot of useless floating-point operations at run time.
  174558. * To get around this we use the following pre-calculated constants.
  174559. * If you change CONST_BITS you may want to add appropriate values.
  174560. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174561. */
  174562. #if CONST_BITS == 8
  174563. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174564. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174565. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174566. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174567. #else
  174568. #define FIX_1_082392200 FIX(1.082392200)
  174569. #define FIX_1_414213562 FIX(1.414213562)
  174570. #define FIX_1_847759065 FIX(1.847759065)
  174571. #define FIX_2_613125930 FIX(2.613125930)
  174572. #endif
  174573. /* We can gain a little more speed, with a further compromise in accuracy,
  174574. * by omitting the addition in a descaling shift. This yields an incorrectly
  174575. * rounded result half the time...
  174576. */
  174577. #ifndef USE_ACCURATE_ROUNDING
  174578. #undef DESCALE
  174579. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174580. #endif
  174581. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174582. * descale to yield a DCTELEM result.
  174583. */
  174584. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174585. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174586. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174587. * multiplication will do. For 12-bit data, the multiplier table is
  174588. * declared INT32, so a 32-bit multiply will be used.
  174589. */
  174590. #if BITS_IN_JSAMPLE == 8
  174591. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174592. #else
  174593. #define DEQUANTIZE(coef,quantval) \
  174594. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174595. #endif
  174596. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174597. * We assume that int right shift is unsigned if INT32 right shift is.
  174598. */
  174599. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174600. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174601. #if BITS_IN_JSAMPLE == 8
  174602. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174603. #else
  174604. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174605. #endif
  174606. #define IRIGHT_SHIFT(x,shft) \
  174607. ((ishift_temp = (x)) < 0 ? \
  174608. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174609. (ishift_temp >> (shft)))
  174610. #else
  174611. #define ISHIFT_TEMPS
  174612. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174613. #endif
  174614. #ifdef USE_ACCURATE_ROUNDING
  174615. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174616. #else
  174617. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174618. #endif
  174619. /*
  174620. * Perform dequantization and inverse DCT on one block of coefficients.
  174621. */
  174622. GLOBAL(void)
  174623. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174624. JCOEFPTR coef_block,
  174625. JSAMPARRAY output_buf, JDIMENSION output_col)
  174626. {
  174627. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174628. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174629. DCTELEM z5, z10, z11, z12, z13;
  174630. JCOEFPTR inptr;
  174631. IFAST_MULT_TYPE * quantptr;
  174632. int * wsptr;
  174633. JSAMPROW outptr;
  174634. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174635. int ctr;
  174636. int workspace[DCTSIZE2]; /* buffers data between passes */
  174637. SHIFT_TEMPS /* for DESCALE */
  174638. ISHIFT_TEMPS /* for IDESCALE */
  174639. /* Pass 1: process columns from input, store into work array. */
  174640. inptr = coef_block;
  174641. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174642. wsptr = workspace;
  174643. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174644. /* Due to quantization, we will usually find that many of the input
  174645. * coefficients are zero, especially the AC terms. We can exploit this
  174646. * by short-circuiting the IDCT calculation for any column in which all
  174647. * the AC terms are zero. In that case each output is equal to the
  174648. * DC coefficient (with scale factor as needed).
  174649. * With typical images and quantization tables, half or more of the
  174650. * column DCT calculations can be simplified this way.
  174651. */
  174652. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174653. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174654. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174655. inptr[DCTSIZE*7] == 0) {
  174656. /* AC terms all zero */
  174657. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174658. wsptr[DCTSIZE*0] = dcval;
  174659. wsptr[DCTSIZE*1] = dcval;
  174660. wsptr[DCTSIZE*2] = dcval;
  174661. wsptr[DCTSIZE*3] = dcval;
  174662. wsptr[DCTSIZE*4] = dcval;
  174663. wsptr[DCTSIZE*5] = dcval;
  174664. wsptr[DCTSIZE*6] = dcval;
  174665. wsptr[DCTSIZE*7] = dcval;
  174666. inptr++; /* advance pointers to next column */
  174667. quantptr++;
  174668. wsptr++;
  174669. continue;
  174670. }
  174671. /* Even part */
  174672. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174673. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174674. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174675. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174676. tmp10 = tmp0 + tmp2; /* phase 3 */
  174677. tmp11 = tmp0 - tmp2;
  174678. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174679. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174680. tmp0 = tmp10 + tmp13; /* phase 2 */
  174681. tmp3 = tmp10 - tmp13;
  174682. tmp1 = tmp11 + tmp12;
  174683. tmp2 = tmp11 - tmp12;
  174684. /* Odd part */
  174685. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174686. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174687. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174688. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174689. z13 = tmp6 + tmp5; /* phase 6 */
  174690. z10 = tmp6 - tmp5;
  174691. z11 = tmp4 + tmp7;
  174692. z12 = tmp4 - tmp7;
  174693. tmp7 = z11 + z13; /* phase 5 */
  174694. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174695. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174696. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174697. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174698. tmp6 = tmp12 - tmp7; /* phase 2 */
  174699. tmp5 = tmp11 - tmp6;
  174700. tmp4 = tmp10 + tmp5;
  174701. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174702. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174703. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174704. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174705. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174706. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174707. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174708. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174709. inptr++; /* advance pointers to next column */
  174710. quantptr++;
  174711. wsptr++;
  174712. }
  174713. /* Pass 2: process rows from work array, store into output array. */
  174714. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174715. /* and also undo the PASS1_BITS scaling. */
  174716. wsptr = workspace;
  174717. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174718. outptr = output_buf[ctr] + output_col;
  174719. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174720. * However, the column calculation has created many nonzero AC terms, so
  174721. * the simplification applies less often (typically 5% to 10% of the time).
  174722. * On machines with very fast multiplication, it's possible that the
  174723. * test takes more time than it's worth. In that case this section
  174724. * may be commented out.
  174725. */
  174726. #ifndef NO_ZERO_ROW_TEST
  174727. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174728. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174729. /* AC terms all zero */
  174730. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174731. & RANGE_MASK];
  174732. outptr[0] = dcval;
  174733. outptr[1] = dcval;
  174734. outptr[2] = dcval;
  174735. outptr[3] = dcval;
  174736. outptr[4] = dcval;
  174737. outptr[5] = dcval;
  174738. outptr[6] = dcval;
  174739. outptr[7] = dcval;
  174740. wsptr += DCTSIZE; /* advance pointer to next row */
  174741. continue;
  174742. }
  174743. #endif
  174744. /* Even part */
  174745. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174746. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174747. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174748. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174749. - tmp13;
  174750. tmp0 = tmp10 + tmp13;
  174751. tmp3 = tmp10 - tmp13;
  174752. tmp1 = tmp11 + tmp12;
  174753. tmp2 = tmp11 - tmp12;
  174754. /* Odd part */
  174755. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174756. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174757. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174758. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174759. tmp7 = z11 + z13; /* phase 5 */
  174760. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174761. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174762. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174763. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174764. tmp6 = tmp12 - tmp7; /* phase 2 */
  174765. tmp5 = tmp11 - tmp6;
  174766. tmp4 = tmp10 + tmp5;
  174767. /* Final output stage: scale down by a factor of 8 and range-limit */
  174768. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174769. & RANGE_MASK];
  174770. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174771. & RANGE_MASK];
  174772. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174773. & RANGE_MASK];
  174774. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174775. & RANGE_MASK];
  174776. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174777. & RANGE_MASK];
  174778. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174779. & RANGE_MASK];
  174780. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174781. & RANGE_MASK];
  174782. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174783. & RANGE_MASK];
  174784. wsptr += DCTSIZE; /* advance pointer to next row */
  174785. }
  174786. }
  174787. #endif /* DCT_IFAST_SUPPORTED */
  174788. /*** End of inlined file: jidctfst.c ***/
  174789. #undef CONST_BITS
  174790. #undef FIX_1_847759065
  174791. #undef MULTIPLY
  174792. #undef DEQUANTIZE
  174793. /*** Start of inlined file: jidctint.c ***/
  174794. #define JPEG_INTERNALS
  174795. #ifdef DCT_ISLOW_SUPPORTED
  174796. /*
  174797. * This module is specialized to the case DCTSIZE = 8.
  174798. */
  174799. #if DCTSIZE != 8
  174800. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174801. #endif
  174802. /*
  174803. * The poop on this scaling stuff is as follows:
  174804. *
  174805. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174806. * larger than the true IDCT outputs. The final outputs are therefore
  174807. * a factor of N larger than desired; since N=8 this can be cured by
  174808. * a simple right shift at the end of the algorithm. The advantage of
  174809. * this arrangement is that we save two multiplications per 1-D IDCT,
  174810. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174811. *
  174812. * We have to do addition and subtraction of the integer inputs, which
  174813. * is no problem, and multiplication by fractional constants, which is
  174814. * a problem to do in integer arithmetic. We multiply all the constants
  174815. * by CONST_SCALE and convert them to integer constants (thus retaining
  174816. * CONST_BITS bits of precision in the constants). After doing a
  174817. * multiplication we have to divide the product by CONST_SCALE, with proper
  174818. * rounding, to produce the correct output. This division can be done
  174819. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174820. * as long as possible so that partial sums can be added together with
  174821. * full fractional precision.
  174822. *
  174823. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174824. * they are represented to better-than-integral precision. These outputs
  174825. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174826. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174827. * intermediate INT32 array would be needed.)
  174828. *
  174829. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174830. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174831. * shows that the values given below are the most effective.
  174832. */
  174833. #if BITS_IN_JSAMPLE == 8
  174834. #define CONST_BITS 13
  174835. #define PASS1_BITS 2
  174836. #else
  174837. #define CONST_BITS 13
  174838. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174839. #endif
  174840. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174841. * causing a lot of useless floating-point operations at run time.
  174842. * To get around this we use the following pre-calculated constants.
  174843. * If you change CONST_BITS you may want to add appropriate values.
  174844. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174845. */
  174846. #if CONST_BITS == 13
  174847. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174848. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174849. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174850. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174851. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174852. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174853. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174854. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174855. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174856. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174857. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174858. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174859. #else
  174860. #define FIX_0_298631336 FIX(0.298631336)
  174861. #define FIX_0_390180644 FIX(0.390180644)
  174862. #define FIX_0_541196100 FIX(0.541196100)
  174863. #define FIX_0_765366865 FIX(0.765366865)
  174864. #define FIX_0_899976223 FIX(0.899976223)
  174865. #define FIX_1_175875602 FIX(1.175875602)
  174866. #define FIX_1_501321110 FIX(1.501321110)
  174867. #define FIX_1_847759065 FIX(1.847759065)
  174868. #define FIX_1_961570560 FIX(1.961570560)
  174869. #define FIX_2_053119869 FIX(2.053119869)
  174870. #define FIX_2_562915447 FIX(2.562915447)
  174871. #define FIX_3_072711026 FIX(3.072711026)
  174872. #endif
  174873. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174874. * For 8-bit samples with the recommended scaling, all the variable
  174875. * and constant values involved are no more than 16 bits wide, so a
  174876. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174877. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174878. */
  174879. #if BITS_IN_JSAMPLE == 8
  174880. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174881. #else
  174882. #define MULTIPLY(var,const) ((var) * (const))
  174883. #endif
  174884. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174885. * entry; produce an int result. In this module, both inputs and result
  174886. * are 16 bits or less, so either int or short multiply will work.
  174887. */
  174888. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174889. /*
  174890. * Perform dequantization and inverse DCT on one block of coefficients.
  174891. */
  174892. GLOBAL(void)
  174893. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174894. JCOEFPTR coef_block,
  174895. JSAMPARRAY output_buf, JDIMENSION output_col)
  174896. {
  174897. INT32 tmp0, tmp1, tmp2, tmp3;
  174898. INT32 tmp10, tmp11, tmp12, tmp13;
  174899. INT32 z1, z2, z3, z4, z5;
  174900. JCOEFPTR inptr;
  174901. ISLOW_MULT_TYPE * quantptr;
  174902. int * wsptr;
  174903. JSAMPROW outptr;
  174904. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174905. int ctr;
  174906. int workspace[DCTSIZE2]; /* buffers data between passes */
  174907. SHIFT_TEMPS
  174908. /* Pass 1: process columns from input, store into work array. */
  174909. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174910. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174911. inptr = coef_block;
  174912. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174913. wsptr = workspace;
  174914. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174915. /* Due to quantization, we will usually find that many of the input
  174916. * coefficients are zero, especially the AC terms. We can exploit this
  174917. * by short-circuiting the IDCT calculation for any column in which all
  174918. * the AC terms are zero. In that case each output is equal to the
  174919. * DC coefficient (with scale factor as needed).
  174920. * With typical images and quantization tables, half or more of the
  174921. * column DCT calculations can be simplified this way.
  174922. */
  174923. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174924. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174925. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174926. inptr[DCTSIZE*7] == 0) {
  174927. /* AC terms all zero */
  174928. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174929. wsptr[DCTSIZE*0] = dcval;
  174930. wsptr[DCTSIZE*1] = dcval;
  174931. wsptr[DCTSIZE*2] = dcval;
  174932. wsptr[DCTSIZE*3] = dcval;
  174933. wsptr[DCTSIZE*4] = dcval;
  174934. wsptr[DCTSIZE*5] = dcval;
  174935. wsptr[DCTSIZE*6] = dcval;
  174936. wsptr[DCTSIZE*7] = dcval;
  174937. inptr++; /* advance pointers to next column */
  174938. quantptr++;
  174939. wsptr++;
  174940. continue;
  174941. }
  174942. /* Even part: reverse the even part of the forward DCT. */
  174943. /* The rotator is sqrt(2)*c(-6). */
  174944. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174945. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174946. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174947. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174948. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174949. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174950. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174951. tmp0 = (z2 + z3) << CONST_BITS;
  174952. tmp1 = (z2 - z3) << CONST_BITS;
  174953. tmp10 = tmp0 + tmp3;
  174954. tmp13 = tmp0 - tmp3;
  174955. tmp11 = tmp1 + tmp2;
  174956. tmp12 = tmp1 - tmp2;
  174957. /* Odd part per figure 8; the matrix is unitary and hence its
  174958. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174959. */
  174960. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174961. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174962. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174963. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174964. z1 = tmp0 + tmp3;
  174965. z2 = tmp1 + tmp2;
  174966. z3 = tmp0 + tmp2;
  174967. z4 = tmp1 + tmp3;
  174968. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174969. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174970. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174971. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174972. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174973. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174974. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174975. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174976. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174977. z3 += z5;
  174978. z4 += z5;
  174979. tmp0 += z1 + z3;
  174980. tmp1 += z2 + z4;
  174981. tmp2 += z2 + z3;
  174982. tmp3 += z1 + z4;
  174983. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174984. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174985. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174986. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174987. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174988. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174989. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174990. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174991. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174992. inptr++; /* advance pointers to next column */
  174993. quantptr++;
  174994. wsptr++;
  174995. }
  174996. /* Pass 2: process rows from work array, store into output array. */
  174997. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174998. /* and also undo the PASS1_BITS scaling. */
  174999. wsptr = workspace;
  175000. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175001. outptr = output_buf[ctr] + output_col;
  175002. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175003. * However, the column calculation has created many nonzero AC terms, so
  175004. * the simplification applies less often (typically 5% to 10% of the time).
  175005. * On machines with very fast multiplication, it's possible that the
  175006. * test takes more time than it's worth. In that case this section
  175007. * may be commented out.
  175008. */
  175009. #ifndef NO_ZERO_ROW_TEST
  175010. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175011. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175012. /* AC terms all zero */
  175013. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175014. & RANGE_MASK];
  175015. outptr[0] = dcval;
  175016. outptr[1] = dcval;
  175017. outptr[2] = dcval;
  175018. outptr[3] = dcval;
  175019. outptr[4] = dcval;
  175020. outptr[5] = dcval;
  175021. outptr[6] = dcval;
  175022. outptr[7] = dcval;
  175023. wsptr += DCTSIZE; /* advance pointer to next row */
  175024. continue;
  175025. }
  175026. #endif
  175027. /* Even part: reverse the even part of the forward DCT. */
  175028. /* The rotator is sqrt(2)*c(-6). */
  175029. z2 = (INT32) wsptr[2];
  175030. z3 = (INT32) wsptr[6];
  175031. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175032. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175033. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175034. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175035. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175036. tmp10 = tmp0 + tmp3;
  175037. tmp13 = tmp0 - tmp3;
  175038. tmp11 = tmp1 + tmp2;
  175039. tmp12 = tmp1 - tmp2;
  175040. /* Odd part per figure 8; the matrix is unitary and hence its
  175041. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175042. */
  175043. tmp0 = (INT32) wsptr[7];
  175044. tmp1 = (INT32) wsptr[5];
  175045. tmp2 = (INT32) wsptr[3];
  175046. tmp3 = (INT32) wsptr[1];
  175047. z1 = tmp0 + tmp3;
  175048. z2 = tmp1 + tmp2;
  175049. z3 = tmp0 + tmp2;
  175050. z4 = tmp1 + tmp3;
  175051. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175052. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175053. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175054. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175055. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175056. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175057. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175058. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175059. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175060. z3 += z5;
  175061. z4 += z5;
  175062. tmp0 += z1 + z3;
  175063. tmp1 += z2 + z4;
  175064. tmp2 += z2 + z3;
  175065. tmp3 += z1 + z4;
  175066. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175067. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175068. CONST_BITS+PASS1_BITS+3)
  175069. & RANGE_MASK];
  175070. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175071. CONST_BITS+PASS1_BITS+3)
  175072. & RANGE_MASK];
  175073. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175074. CONST_BITS+PASS1_BITS+3)
  175075. & RANGE_MASK];
  175076. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175077. CONST_BITS+PASS1_BITS+3)
  175078. & RANGE_MASK];
  175079. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175080. CONST_BITS+PASS1_BITS+3)
  175081. & RANGE_MASK];
  175082. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175083. CONST_BITS+PASS1_BITS+3)
  175084. & RANGE_MASK];
  175085. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175086. CONST_BITS+PASS1_BITS+3)
  175087. & RANGE_MASK];
  175088. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175089. CONST_BITS+PASS1_BITS+3)
  175090. & RANGE_MASK];
  175091. wsptr += DCTSIZE; /* advance pointer to next row */
  175092. }
  175093. }
  175094. #endif /* DCT_ISLOW_SUPPORTED */
  175095. /*** End of inlined file: jidctint.c ***/
  175096. /*** Start of inlined file: jidctred.c ***/
  175097. #define JPEG_INTERNALS
  175098. #ifdef IDCT_SCALING_SUPPORTED
  175099. /*
  175100. * This module is specialized to the case DCTSIZE = 8.
  175101. */
  175102. #if DCTSIZE != 8
  175103. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175104. #endif
  175105. /* Scaling is the same as in jidctint.c. */
  175106. #if BITS_IN_JSAMPLE == 8
  175107. #define CONST_BITS 13
  175108. #define PASS1_BITS 2
  175109. #else
  175110. #define CONST_BITS 13
  175111. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175112. #endif
  175113. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175114. * causing a lot of useless floating-point operations at run time.
  175115. * To get around this we use the following pre-calculated constants.
  175116. * If you change CONST_BITS you may want to add appropriate values.
  175117. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175118. */
  175119. #if CONST_BITS == 13
  175120. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175121. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175122. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175123. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175124. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175125. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175126. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175127. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175128. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175129. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175130. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175131. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175132. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175133. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175134. #else
  175135. #define FIX_0_211164243 FIX(0.211164243)
  175136. #define FIX_0_509795579 FIX(0.509795579)
  175137. #define FIX_0_601344887 FIX(0.601344887)
  175138. #define FIX_0_720959822 FIX(0.720959822)
  175139. #define FIX_0_765366865 FIX(0.765366865)
  175140. #define FIX_0_850430095 FIX(0.850430095)
  175141. #define FIX_0_899976223 FIX(0.899976223)
  175142. #define FIX_1_061594337 FIX(1.061594337)
  175143. #define FIX_1_272758580 FIX(1.272758580)
  175144. #define FIX_1_451774981 FIX(1.451774981)
  175145. #define FIX_1_847759065 FIX(1.847759065)
  175146. #define FIX_2_172734803 FIX(2.172734803)
  175147. #define FIX_2_562915447 FIX(2.562915447)
  175148. #define FIX_3_624509785 FIX(3.624509785)
  175149. #endif
  175150. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175151. * For 8-bit samples with the recommended scaling, all the variable
  175152. * and constant values involved are no more than 16 bits wide, so a
  175153. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175154. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175155. */
  175156. #if BITS_IN_JSAMPLE == 8
  175157. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175158. #else
  175159. #define MULTIPLY(var,const) ((var) * (const))
  175160. #endif
  175161. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175162. * entry; produce an int result. In this module, both inputs and result
  175163. * are 16 bits or less, so either int or short multiply will work.
  175164. */
  175165. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175166. /*
  175167. * Perform dequantization and inverse DCT on one block of coefficients,
  175168. * producing a reduced-size 4x4 output block.
  175169. */
  175170. GLOBAL(void)
  175171. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175172. JCOEFPTR coef_block,
  175173. JSAMPARRAY output_buf, JDIMENSION output_col)
  175174. {
  175175. INT32 tmp0, tmp2, tmp10, tmp12;
  175176. INT32 z1, z2, z3, z4;
  175177. JCOEFPTR inptr;
  175178. ISLOW_MULT_TYPE * quantptr;
  175179. int * wsptr;
  175180. JSAMPROW outptr;
  175181. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175182. int ctr;
  175183. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175184. SHIFT_TEMPS
  175185. /* Pass 1: process columns from input, store into work array. */
  175186. inptr = coef_block;
  175187. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175188. wsptr = workspace;
  175189. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175190. /* Don't bother to process column 4, because second pass won't use it */
  175191. if (ctr == DCTSIZE-4)
  175192. continue;
  175193. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175194. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175195. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175196. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175197. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175198. wsptr[DCTSIZE*0] = dcval;
  175199. wsptr[DCTSIZE*1] = dcval;
  175200. wsptr[DCTSIZE*2] = dcval;
  175201. wsptr[DCTSIZE*3] = dcval;
  175202. continue;
  175203. }
  175204. /* Even part */
  175205. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175206. tmp0 <<= (CONST_BITS+1);
  175207. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175208. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175209. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175210. tmp10 = tmp0 + tmp2;
  175211. tmp12 = tmp0 - tmp2;
  175212. /* Odd part */
  175213. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175214. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175215. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175216. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175217. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175218. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175219. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175220. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175221. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175222. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175223. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175224. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175225. /* Final output stage */
  175226. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175227. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175228. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175229. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175230. }
  175231. /* Pass 2: process 4 rows from work array, store into output array. */
  175232. wsptr = workspace;
  175233. for (ctr = 0; ctr < 4; ctr++) {
  175234. outptr = output_buf[ctr] + output_col;
  175235. /* It's not clear whether a zero row test is worthwhile here ... */
  175236. #ifndef NO_ZERO_ROW_TEST
  175237. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175238. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175239. /* AC terms all zero */
  175240. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175241. & RANGE_MASK];
  175242. outptr[0] = dcval;
  175243. outptr[1] = dcval;
  175244. outptr[2] = dcval;
  175245. outptr[3] = dcval;
  175246. wsptr += DCTSIZE; /* advance pointer to next row */
  175247. continue;
  175248. }
  175249. #endif
  175250. /* Even part */
  175251. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175252. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175253. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175254. tmp10 = tmp0 + tmp2;
  175255. tmp12 = tmp0 - tmp2;
  175256. /* Odd part */
  175257. z1 = (INT32) wsptr[7];
  175258. z2 = (INT32) wsptr[5];
  175259. z3 = (INT32) wsptr[3];
  175260. z4 = (INT32) wsptr[1];
  175261. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175262. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175263. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175264. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175265. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175266. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175267. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175268. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175269. /* Final output stage */
  175270. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175271. CONST_BITS+PASS1_BITS+3+1)
  175272. & RANGE_MASK];
  175273. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175274. CONST_BITS+PASS1_BITS+3+1)
  175275. & RANGE_MASK];
  175276. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175277. CONST_BITS+PASS1_BITS+3+1)
  175278. & RANGE_MASK];
  175279. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175280. CONST_BITS+PASS1_BITS+3+1)
  175281. & RANGE_MASK];
  175282. wsptr += DCTSIZE; /* advance pointer to next row */
  175283. }
  175284. }
  175285. /*
  175286. * Perform dequantization and inverse DCT on one block of coefficients,
  175287. * producing a reduced-size 2x2 output block.
  175288. */
  175289. GLOBAL(void)
  175290. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175291. JCOEFPTR coef_block,
  175292. JSAMPARRAY output_buf, JDIMENSION output_col)
  175293. {
  175294. INT32 tmp0, tmp10, z1;
  175295. JCOEFPTR inptr;
  175296. ISLOW_MULT_TYPE * quantptr;
  175297. int * wsptr;
  175298. JSAMPROW outptr;
  175299. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175300. int ctr;
  175301. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175302. SHIFT_TEMPS
  175303. /* Pass 1: process columns from input, store into work array. */
  175304. inptr = coef_block;
  175305. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175306. wsptr = workspace;
  175307. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175308. /* Don't bother to process columns 2,4,6 */
  175309. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175310. continue;
  175311. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175312. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175313. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175314. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175315. wsptr[DCTSIZE*0] = dcval;
  175316. wsptr[DCTSIZE*1] = dcval;
  175317. continue;
  175318. }
  175319. /* Even part */
  175320. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175321. tmp10 = z1 << (CONST_BITS+2);
  175322. /* Odd part */
  175323. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175324. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175325. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175326. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175327. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175328. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175329. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175330. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175331. /* Final output stage */
  175332. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175333. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175334. }
  175335. /* Pass 2: process 2 rows from work array, store into output array. */
  175336. wsptr = workspace;
  175337. for (ctr = 0; ctr < 2; ctr++) {
  175338. outptr = output_buf[ctr] + output_col;
  175339. /* It's not clear whether a zero row test is worthwhile here ... */
  175340. #ifndef NO_ZERO_ROW_TEST
  175341. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175342. /* AC terms all zero */
  175343. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175344. & RANGE_MASK];
  175345. outptr[0] = dcval;
  175346. outptr[1] = dcval;
  175347. wsptr += DCTSIZE; /* advance pointer to next row */
  175348. continue;
  175349. }
  175350. #endif
  175351. /* Even part */
  175352. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175353. /* Odd part */
  175354. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175355. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175356. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175357. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175358. /* Final output stage */
  175359. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175360. CONST_BITS+PASS1_BITS+3+2)
  175361. & RANGE_MASK];
  175362. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175363. CONST_BITS+PASS1_BITS+3+2)
  175364. & RANGE_MASK];
  175365. wsptr += DCTSIZE; /* advance pointer to next row */
  175366. }
  175367. }
  175368. /*
  175369. * Perform dequantization and inverse DCT on one block of coefficients,
  175370. * producing a reduced-size 1x1 output block.
  175371. */
  175372. GLOBAL(void)
  175373. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175374. JCOEFPTR coef_block,
  175375. JSAMPARRAY output_buf, JDIMENSION output_col)
  175376. {
  175377. int dcval;
  175378. ISLOW_MULT_TYPE * quantptr;
  175379. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175380. SHIFT_TEMPS
  175381. /* We hardly need an inverse DCT routine for this: just take the
  175382. * average pixel value, which is one-eighth of the DC coefficient.
  175383. */
  175384. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175385. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175386. dcval = (int) DESCALE((INT32) dcval, 3);
  175387. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175388. }
  175389. #endif /* IDCT_SCALING_SUPPORTED */
  175390. /*** End of inlined file: jidctred.c ***/
  175391. /*** Start of inlined file: jmemmgr.c ***/
  175392. #define JPEG_INTERNALS
  175393. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175394. /*** Start of inlined file: jmemsys.h ***/
  175395. #ifndef __jmemsys_h__
  175396. #define __jmemsys_h__
  175397. /* Short forms of external names for systems with brain-damaged linkers. */
  175398. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175399. #define jpeg_get_small jGetSmall
  175400. #define jpeg_free_small jFreeSmall
  175401. #define jpeg_get_large jGetLarge
  175402. #define jpeg_free_large jFreeLarge
  175403. #define jpeg_mem_available jMemAvail
  175404. #define jpeg_open_backing_store jOpenBackStore
  175405. #define jpeg_mem_init jMemInit
  175406. #define jpeg_mem_term jMemTerm
  175407. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175408. /*
  175409. * These two functions are used to allocate and release small chunks of
  175410. * memory. (Typically the total amount requested through jpeg_get_small is
  175411. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175412. * Behavior should be the same as for the standard library functions malloc
  175413. * and free; in particular, jpeg_get_small must return NULL on failure.
  175414. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175415. * size of the object being freed, just in case it's needed.
  175416. * On an 80x86 machine using small-data memory model, these manage near heap.
  175417. */
  175418. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175419. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175420. size_t sizeofobject));
  175421. /*
  175422. * These two functions are used to allocate and release large chunks of
  175423. * memory (up to the total free space designated by jpeg_mem_available).
  175424. * The interface is the same as above, except that on an 80x86 machine,
  175425. * far pointers are used. On most other machines these are identical to
  175426. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175427. * in case a different allocation strategy is desirable for large chunks.
  175428. */
  175429. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175430. size_t sizeofobject));
  175431. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175432. size_t sizeofobject));
  175433. /*
  175434. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175435. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175436. * matter, but that case should never come into play). This macro is needed
  175437. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175438. * On those machines, we expect that jconfig.h will provide a proper value.
  175439. * On machines with 32-bit flat address spaces, any large constant may be used.
  175440. *
  175441. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175442. * size_t and will be a multiple of sizeof(align_type).
  175443. */
  175444. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175445. #define MAX_ALLOC_CHUNK 1000000000L
  175446. #endif
  175447. /*
  175448. * This routine computes the total space still available for allocation by
  175449. * jpeg_get_large. If more space than this is needed, backing store will be
  175450. * used. NOTE: any memory already allocated must not be counted.
  175451. *
  175452. * There is a minimum space requirement, corresponding to the minimum
  175453. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175454. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175455. * all working storage in memory, is also passed in case it is useful.
  175456. * Finally, the total space already allocated is passed. If no better
  175457. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175458. * is often a suitable calculation.
  175459. *
  175460. * It is OK for jpeg_mem_available to underestimate the space available
  175461. * (that'll just lead to more backing-store access than is really necessary).
  175462. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175463. * a slop factor from the true available space. 5% should be enough.
  175464. *
  175465. * On machines with lots of virtual memory, any large constant may be returned.
  175466. * Conversely, zero may be returned to always use the minimum amount of memory.
  175467. */
  175468. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175469. long min_bytes_needed,
  175470. long max_bytes_needed,
  175471. long already_allocated));
  175472. /*
  175473. * This structure holds whatever state is needed to access a single
  175474. * backing-store object. The read/write/close method pointers are called
  175475. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175476. * are private to the system-dependent backing store routines.
  175477. */
  175478. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175479. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175480. typedef unsigned short XMSH; /* type of extended-memory handles */
  175481. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175482. typedef union {
  175483. short file_handle; /* DOS file handle if it's a temp file */
  175484. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175485. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175486. } handle_union;
  175487. #endif /* USE_MSDOS_MEMMGR */
  175488. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175489. #include <Files.h>
  175490. #endif /* USE_MAC_MEMMGR */
  175491. //typedef struct backing_store_struct * backing_store_ptr;
  175492. typedef struct backing_store_struct {
  175493. /* Methods for reading/writing/closing this backing-store object */
  175494. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175495. struct backing_store_struct *info,
  175496. void FAR * buffer_address,
  175497. long file_offset, long byte_count));
  175498. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175499. struct backing_store_struct *info,
  175500. void FAR * buffer_address,
  175501. long file_offset, long byte_count));
  175502. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175503. struct backing_store_struct *info));
  175504. /* Private fields for system-dependent backing-store management */
  175505. #ifdef USE_MSDOS_MEMMGR
  175506. /* For the MS-DOS manager (jmemdos.c), we need: */
  175507. handle_union handle; /* reference to backing-store storage object */
  175508. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175509. #else
  175510. #ifdef USE_MAC_MEMMGR
  175511. /* For the Mac manager (jmemmac.c), we need: */
  175512. short temp_file; /* file reference number to temp file */
  175513. FSSpec tempSpec; /* the FSSpec for the temp file */
  175514. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175515. #else
  175516. /* For a typical implementation with temp files, we need: */
  175517. FILE * temp_file; /* stdio reference to temp file */
  175518. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175519. #endif
  175520. #endif
  175521. } backing_store_info;
  175522. /*
  175523. * Initial opening of a backing-store object. This must fill in the
  175524. * read/write/close pointers in the object. The read/write routines
  175525. * may take an error exit if the specified maximum file size is exceeded.
  175526. * (If jpeg_mem_available always returns a large value, this routine can
  175527. * just take an error exit.)
  175528. */
  175529. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175530. struct backing_store_struct *info,
  175531. long total_bytes_needed));
  175532. /*
  175533. * These routines take care of any system-dependent initialization and
  175534. * cleanup required. jpeg_mem_init will be called before anything is
  175535. * allocated (and, therefore, nothing in cinfo is of use except the error
  175536. * manager pointer). It should return a suitable default value for
  175537. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175538. * application. (Note that max_memory_to_use is only important if
  175539. * jpeg_mem_available chooses to consult it ... no one else will.)
  175540. * jpeg_mem_term may assume that all requested memory has been freed and that
  175541. * all opened backing-store objects have been closed.
  175542. */
  175543. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175544. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175545. #endif
  175546. /*** End of inlined file: jmemsys.h ***/
  175547. /* import the system-dependent declarations */
  175548. #ifndef NO_GETENV
  175549. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175550. extern char * getenv JPP((const char * name));
  175551. #endif
  175552. #endif
  175553. /*
  175554. * Some important notes:
  175555. * The allocation routines provided here must never return NULL.
  175556. * They should exit to error_exit if unsuccessful.
  175557. *
  175558. * It's not a good idea to try to merge the sarray and barray routines,
  175559. * even though they are textually almost the same, because samples are
  175560. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175561. * in machines where byte pointers have a different representation from
  175562. * word pointers, the resulting machine code could not be the same.
  175563. */
  175564. /*
  175565. * Many machines require storage alignment: longs must start on 4-byte
  175566. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175567. * always returns pointers that are multiples of the worst-case alignment
  175568. * requirement, and we had better do so too.
  175569. * There isn't any really portable way to determine the worst-case alignment
  175570. * requirement. This module assumes that the alignment requirement is
  175571. * multiples of sizeof(ALIGN_TYPE).
  175572. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175573. * workstations (where doubles really do need 8-byte alignment) and will work
  175574. * fine on nearly everything. If your machine has lesser alignment needs,
  175575. * you can save a few bytes by making ALIGN_TYPE smaller.
  175576. * The only place I know of where this will NOT work is certain Macintosh
  175577. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175578. * Doing 10-byte alignment is counterproductive because longwords won't be
  175579. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175580. * such a compiler.
  175581. */
  175582. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175583. #define ALIGN_TYPE double
  175584. #endif
  175585. /*
  175586. * We allocate objects from "pools", where each pool is gotten with a single
  175587. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175588. * overhead within a pool, except for alignment padding. Each pool has a
  175589. * header with a link to the next pool of the same class.
  175590. * Small and large pool headers are identical except that the latter's
  175591. * link pointer must be FAR on 80x86 machines.
  175592. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175593. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175594. * of the alignment requirement of ALIGN_TYPE.
  175595. */
  175596. typedef union small_pool_struct * small_pool_ptr;
  175597. typedef union small_pool_struct {
  175598. struct {
  175599. small_pool_ptr next; /* next in list of pools */
  175600. size_t bytes_used; /* how many bytes already used within pool */
  175601. size_t bytes_left; /* bytes still available in this pool */
  175602. } hdr;
  175603. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175604. } small_pool_hdr;
  175605. typedef union large_pool_struct FAR * large_pool_ptr;
  175606. typedef union large_pool_struct {
  175607. struct {
  175608. large_pool_ptr next; /* next in list of pools */
  175609. size_t bytes_used; /* how many bytes already used within pool */
  175610. size_t bytes_left; /* bytes still available in this pool */
  175611. } hdr;
  175612. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175613. } large_pool_hdr;
  175614. /*
  175615. * Here is the full definition of a memory manager object.
  175616. */
  175617. typedef struct {
  175618. struct jpeg_memory_mgr pub; /* public fields */
  175619. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175620. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175621. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175622. /* Since we only have one lifetime class of virtual arrays, only one
  175623. * linked list is necessary (for each datatype). Note that the virtual
  175624. * array control blocks being linked together are actually stored somewhere
  175625. * in the small-pool list.
  175626. */
  175627. jvirt_sarray_ptr virt_sarray_list;
  175628. jvirt_barray_ptr virt_barray_list;
  175629. /* This counts total space obtained from jpeg_get_small/large */
  175630. long total_space_allocated;
  175631. /* alloc_sarray and alloc_barray set this value for use by virtual
  175632. * array routines.
  175633. */
  175634. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175635. } my_memory_mgr;
  175636. typedef my_memory_mgr * my_mem_ptr;
  175637. /*
  175638. * The control blocks for virtual arrays.
  175639. * Note that these blocks are allocated in the "small" pool area.
  175640. * System-dependent info for the associated backing store (if any) is hidden
  175641. * inside the backing_store_info struct.
  175642. */
  175643. struct jvirt_sarray_control {
  175644. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175645. JDIMENSION rows_in_array; /* total virtual array height */
  175646. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175647. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175648. JDIMENSION rows_in_mem; /* height of memory buffer */
  175649. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175650. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175651. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175652. boolean pre_zero; /* pre-zero mode requested? */
  175653. boolean dirty; /* do current buffer contents need written? */
  175654. boolean b_s_open; /* is backing-store data valid? */
  175655. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175656. backing_store_info b_s_info; /* System-dependent control info */
  175657. };
  175658. struct jvirt_barray_control {
  175659. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175660. JDIMENSION rows_in_array; /* total virtual array height */
  175661. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175662. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175663. JDIMENSION rows_in_mem; /* height of memory buffer */
  175664. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175665. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175666. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175667. boolean pre_zero; /* pre-zero mode requested? */
  175668. boolean dirty; /* do current buffer contents need written? */
  175669. boolean b_s_open; /* is backing-store data valid? */
  175670. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175671. backing_store_info b_s_info; /* System-dependent control info */
  175672. };
  175673. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175674. LOCAL(void)
  175675. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175676. {
  175677. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175678. small_pool_ptr shdr_ptr;
  175679. large_pool_ptr lhdr_ptr;
  175680. /* Since this is only a debugging stub, we can cheat a little by using
  175681. * fprintf directly rather than going through the trace message code.
  175682. * This is helpful because message parm array can't handle longs.
  175683. */
  175684. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175685. pool_id, mem->total_space_allocated);
  175686. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175687. lhdr_ptr = lhdr_ptr->hdr.next) {
  175688. fprintf(stderr, " Large chunk used %ld\n",
  175689. (long) lhdr_ptr->hdr.bytes_used);
  175690. }
  175691. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175692. shdr_ptr = shdr_ptr->hdr.next) {
  175693. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175694. (long) shdr_ptr->hdr.bytes_used,
  175695. (long) shdr_ptr->hdr.bytes_left);
  175696. }
  175697. }
  175698. #endif /* MEM_STATS */
  175699. LOCAL(void)
  175700. out_of_memory (j_common_ptr cinfo, int which)
  175701. /* Report an out-of-memory error and stop execution */
  175702. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175703. {
  175704. #ifdef MEM_STATS
  175705. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175706. #endif
  175707. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175708. }
  175709. /*
  175710. * Allocation of "small" objects.
  175711. *
  175712. * For these, we use pooled storage. When a new pool must be created,
  175713. * we try to get enough space for the current request plus a "slop" factor,
  175714. * where the slop will be the amount of leftover space in the new pool.
  175715. * The speed vs. space tradeoff is largely determined by the slop values.
  175716. * A different slop value is provided for each pool class (lifetime),
  175717. * and we also distinguish the first pool of a class from later ones.
  175718. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175719. * machines, but may be too small if longs are 64 bits or more.
  175720. */
  175721. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175722. {
  175723. 1600, /* first PERMANENT pool */
  175724. 16000 /* first IMAGE pool */
  175725. };
  175726. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175727. {
  175728. 0, /* additional PERMANENT pools */
  175729. 5000 /* additional IMAGE pools */
  175730. };
  175731. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175732. METHODDEF(void *)
  175733. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175734. /* Allocate a "small" object */
  175735. {
  175736. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175737. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175738. char * data_ptr;
  175739. size_t odd_bytes, min_request, slop;
  175740. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175741. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175742. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175743. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175744. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175745. if (odd_bytes > 0)
  175746. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175747. /* See if space is available in any existing pool */
  175748. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175749. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175750. prev_hdr_ptr = NULL;
  175751. hdr_ptr = mem->small_list[pool_id];
  175752. while (hdr_ptr != NULL) {
  175753. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175754. break; /* found pool with enough space */
  175755. prev_hdr_ptr = hdr_ptr;
  175756. hdr_ptr = hdr_ptr->hdr.next;
  175757. }
  175758. /* Time to make a new pool? */
  175759. if (hdr_ptr == NULL) {
  175760. /* min_request is what we need now, slop is what will be leftover */
  175761. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175762. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175763. slop = first_pool_slop[pool_id];
  175764. else
  175765. slop = extra_pool_slop[pool_id];
  175766. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175767. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175768. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175769. /* Try to get space, if fail reduce slop and try again */
  175770. for (;;) {
  175771. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175772. if (hdr_ptr != NULL)
  175773. break;
  175774. slop /= 2;
  175775. if (slop < MIN_SLOP) /* give up when it gets real small */
  175776. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175777. }
  175778. mem->total_space_allocated += min_request + slop;
  175779. /* Success, initialize the new pool header and add to end of list */
  175780. hdr_ptr->hdr.next = NULL;
  175781. hdr_ptr->hdr.bytes_used = 0;
  175782. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175783. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175784. mem->small_list[pool_id] = hdr_ptr;
  175785. else
  175786. prev_hdr_ptr->hdr.next = hdr_ptr;
  175787. }
  175788. /* OK, allocate the object from the current pool */
  175789. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175790. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175791. hdr_ptr->hdr.bytes_used += sizeofobject;
  175792. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175793. return (void *) data_ptr;
  175794. }
  175795. /*
  175796. * Allocation of "large" objects.
  175797. *
  175798. * The external semantics of these are the same as "small" objects,
  175799. * except that FAR pointers are used on 80x86. However the pool
  175800. * management heuristics are quite different. We assume that each
  175801. * request is large enough that it may as well be passed directly to
  175802. * jpeg_get_large; the pool management just links everything together
  175803. * so that we can free it all on demand.
  175804. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175805. * structures. The routines that create these structures (see below)
  175806. * deliberately bunch rows together to ensure a large request size.
  175807. */
  175808. METHODDEF(void FAR *)
  175809. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175810. /* Allocate a "large" object */
  175811. {
  175812. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175813. large_pool_ptr hdr_ptr;
  175814. size_t odd_bytes;
  175815. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175816. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175817. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175818. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175819. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175820. if (odd_bytes > 0)
  175821. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175822. /* Always make a new pool */
  175823. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175824. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175825. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175826. SIZEOF(large_pool_hdr));
  175827. if (hdr_ptr == NULL)
  175828. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175829. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175830. /* Success, initialize the new pool header and add to list */
  175831. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175832. /* We maintain space counts in each pool header for statistical purposes,
  175833. * even though they are not needed for allocation.
  175834. */
  175835. hdr_ptr->hdr.bytes_used = sizeofobject;
  175836. hdr_ptr->hdr.bytes_left = 0;
  175837. mem->large_list[pool_id] = hdr_ptr;
  175838. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175839. }
  175840. /*
  175841. * Creation of 2-D sample arrays.
  175842. * The pointers are in near heap, the samples themselves in FAR heap.
  175843. *
  175844. * To minimize allocation overhead and to allow I/O of large contiguous
  175845. * blocks, we allocate the sample rows in groups of as many rows as possible
  175846. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175847. * NB: the virtual array control routines, later in this file, know about
  175848. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175849. * object so that it can be saved away if this sarray is the workspace for
  175850. * a virtual array.
  175851. */
  175852. METHODDEF(JSAMPARRAY)
  175853. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175854. JDIMENSION samplesperrow, JDIMENSION numrows)
  175855. /* Allocate a 2-D sample array */
  175856. {
  175857. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175858. JSAMPARRAY result;
  175859. JSAMPROW workspace;
  175860. JDIMENSION rowsperchunk, currow, i;
  175861. long ltemp;
  175862. /* Calculate max # of rows allowed in one allocation chunk */
  175863. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175864. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175865. if (ltemp <= 0)
  175866. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175867. if (ltemp < (long) numrows)
  175868. rowsperchunk = (JDIMENSION) ltemp;
  175869. else
  175870. rowsperchunk = numrows;
  175871. mem->last_rowsperchunk = rowsperchunk;
  175872. /* Get space for row pointers (small object) */
  175873. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175874. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175875. /* Get the rows themselves (large objects) */
  175876. currow = 0;
  175877. while (currow < numrows) {
  175878. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175879. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175880. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175881. * SIZEOF(JSAMPLE)));
  175882. for (i = rowsperchunk; i > 0; i--) {
  175883. result[currow++] = workspace;
  175884. workspace += samplesperrow;
  175885. }
  175886. }
  175887. return result;
  175888. }
  175889. /*
  175890. * Creation of 2-D coefficient-block arrays.
  175891. * This is essentially the same as the code for sample arrays, above.
  175892. */
  175893. METHODDEF(JBLOCKARRAY)
  175894. alloc_barray (j_common_ptr cinfo, int pool_id,
  175895. JDIMENSION blocksperrow, JDIMENSION numrows)
  175896. /* Allocate a 2-D coefficient-block array */
  175897. {
  175898. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175899. JBLOCKARRAY result;
  175900. JBLOCKROW workspace;
  175901. JDIMENSION rowsperchunk, currow, i;
  175902. long ltemp;
  175903. /* Calculate max # of rows allowed in one allocation chunk */
  175904. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175905. ((long) blocksperrow * SIZEOF(JBLOCK));
  175906. if (ltemp <= 0)
  175907. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175908. if (ltemp < (long) numrows)
  175909. rowsperchunk = (JDIMENSION) ltemp;
  175910. else
  175911. rowsperchunk = numrows;
  175912. mem->last_rowsperchunk = rowsperchunk;
  175913. /* Get space for row pointers (small object) */
  175914. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175915. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175916. /* Get the rows themselves (large objects) */
  175917. currow = 0;
  175918. while (currow < numrows) {
  175919. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175920. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175921. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175922. * SIZEOF(JBLOCK)));
  175923. for (i = rowsperchunk; i > 0; i--) {
  175924. result[currow++] = workspace;
  175925. workspace += blocksperrow;
  175926. }
  175927. }
  175928. return result;
  175929. }
  175930. /*
  175931. * About virtual array management:
  175932. *
  175933. * The above "normal" array routines are only used to allocate strip buffers
  175934. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175935. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175936. * time, but the memory manager must save the whole array for repeated
  175937. * accesses. The intended implementation is that there is a strip buffer in
  175938. * memory (as high as is possible given the desired memory limit), plus a
  175939. * backing file that holds the rest of the array.
  175940. *
  175941. * The request_virt_array routines are told the total size of the image and
  175942. * the maximum number of rows that will be accessed at once. The in-memory
  175943. * buffer must be at least as large as the maxaccess value.
  175944. *
  175945. * The request routines create control blocks but not the in-memory buffers.
  175946. * That is postponed until realize_virt_arrays is called. At that time the
  175947. * total amount of space needed is known (approximately, anyway), so free
  175948. * memory can be divided up fairly.
  175949. *
  175950. * The access_virt_array routines are responsible for making a specific strip
  175951. * area accessible (after reading or writing the backing file, if necessary).
  175952. * Note that the access routines are told whether the caller intends to modify
  175953. * the accessed strip; during a read-only pass this saves having to rewrite
  175954. * data to disk. The access routines are also responsible for pre-zeroing
  175955. * any newly accessed rows, if pre-zeroing was requested.
  175956. *
  175957. * In current usage, the access requests are usually for nonoverlapping
  175958. * strips; that is, successive access start_row numbers differ by exactly
  175959. * num_rows = maxaccess. This means we can get good performance with simple
  175960. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175961. * of the access height; then there will never be accesses across bufferload
  175962. * boundaries. The code will still work with overlapping access requests,
  175963. * but it doesn't handle bufferload overlaps very efficiently.
  175964. */
  175965. METHODDEF(jvirt_sarray_ptr)
  175966. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175967. JDIMENSION samplesperrow, JDIMENSION numrows,
  175968. JDIMENSION maxaccess)
  175969. /* Request a virtual 2-D sample array */
  175970. {
  175971. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175972. jvirt_sarray_ptr result;
  175973. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175974. if (pool_id != JPOOL_IMAGE)
  175975. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175976. /* get control block */
  175977. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175978. SIZEOF(struct jvirt_sarray_control));
  175979. result->mem_buffer = NULL; /* marks array not yet realized */
  175980. result->rows_in_array = numrows;
  175981. result->samplesperrow = samplesperrow;
  175982. result->maxaccess = maxaccess;
  175983. result->pre_zero = pre_zero;
  175984. result->b_s_open = FALSE; /* no associated backing-store object */
  175985. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175986. mem->virt_sarray_list = result;
  175987. return result;
  175988. }
  175989. METHODDEF(jvirt_barray_ptr)
  175990. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175991. JDIMENSION blocksperrow, JDIMENSION numrows,
  175992. JDIMENSION maxaccess)
  175993. /* Request a virtual 2-D coefficient-block array */
  175994. {
  175995. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175996. jvirt_barray_ptr result;
  175997. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175998. if (pool_id != JPOOL_IMAGE)
  175999. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176000. /* get control block */
  176001. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176002. SIZEOF(struct jvirt_barray_control));
  176003. result->mem_buffer = NULL; /* marks array not yet realized */
  176004. result->rows_in_array = numrows;
  176005. result->blocksperrow = blocksperrow;
  176006. result->maxaccess = maxaccess;
  176007. result->pre_zero = pre_zero;
  176008. result->b_s_open = FALSE; /* no associated backing-store object */
  176009. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176010. mem->virt_barray_list = result;
  176011. return result;
  176012. }
  176013. METHODDEF(void)
  176014. realize_virt_arrays (j_common_ptr cinfo)
  176015. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176016. {
  176017. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176018. long space_per_minheight, maximum_space, avail_mem;
  176019. long minheights, max_minheights;
  176020. jvirt_sarray_ptr sptr;
  176021. jvirt_barray_ptr bptr;
  176022. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176023. * and the maximum space needed (full image height in each buffer).
  176024. * These may be of use to the system-dependent jpeg_mem_available routine.
  176025. */
  176026. space_per_minheight = 0;
  176027. maximum_space = 0;
  176028. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176029. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176030. space_per_minheight += (long) sptr->maxaccess *
  176031. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176032. maximum_space += (long) sptr->rows_in_array *
  176033. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176034. }
  176035. }
  176036. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176037. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176038. space_per_minheight += (long) bptr->maxaccess *
  176039. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176040. maximum_space += (long) bptr->rows_in_array *
  176041. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176042. }
  176043. }
  176044. if (space_per_minheight <= 0)
  176045. return; /* no unrealized arrays, no work */
  176046. /* Determine amount of memory to actually use; this is system-dependent. */
  176047. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176048. mem->total_space_allocated);
  176049. /* If the maximum space needed is available, make all the buffers full
  176050. * height; otherwise parcel it out with the same number of minheights
  176051. * in each buffer.
  176052. */
  176053. if (avail_mem >= maximum_space)
  176054. max_minheights = 1000000000L;
  176055. else {
  176056. max_minheights = avail_mem / space_per_minheight;
  176057. /* If there doesn't seem to be enough space, try to get the minimum
  176058. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176059. */
  176060. if (max_minheights <= 0)
  176061. max_minheights = 1;
  176062. }
  176063. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176064. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176065. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176066. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176067. if (minheights <= max_minheights) {
  176068. /* This buffer fits in memory */
  176069. sptr->rows_in_mem = sptr->rows_in_array;
  176070. } else {
  176071. /* It doesn't fit in memory, create backing store. */
  176072. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176073. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176074. (long) sptr->rows_in_array *
  176075. (long) sptr->samplesperrow *
  176076. (long) SIZEOF(JSAMPLE));
  176077. sptr->b_s_open = TRUE;
  176078. }
  176079. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176080. sptr->samplesperrow, sptr->rows_in_mem);
  176081. sptr->rowsperchunk = mem->last_rowsperchunk;
  176082. sptr->cur_start_row = 0;
  176083. sptr->first_undef_row = 0;
  176084. sptr->dirty = FALSE;
  176085. }
  176086. }
  176087. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176088. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176089. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176090. if (minheights <= max_minheights) {
  176091. /* This buffer fits in memory */
  176092. bptr->rows_in_mem = bptr->rows_in_array;
  176093. } else {
  176094. /* It doesn't fit in memory, create backing store. */
  176095. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176096. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176097. (long) bptr->rows_in_array *
  176098. (long) bptr->blocksperrow *
  176099. (long) SIZEOF(JBLOCK));
  176100. bptr->b_s_open = TRUE;
  176101. }
  176102. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176103. bptr->blocksperrow, bptr->rows_in_mem);
  176104. bptr->rowsperchunk = mem->last_rowsperchunk;
  176105. bptr->cur_start_row = 0;
  176106. bptr->first_undef_row = 0;
  176107. bptr->dirty = FALSE;
  176108. }
  176109. }
  176110. }
  176111. LOCAL(void)
  176112. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176113. /* Do backing store read or write of a virtual sample array */
  176114. {
  176115. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176116. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176117. file_offset = ptr->cur_start_row * bytesperrow;
  176118. /* Loop to read or write each allocation chunk in mem_buffer */
  176119. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176120. /* One chunk, but check for short chunk at end of buffer */
  176121. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176122. /* Transfer no more than is currently defined */
  176123. thisrow = (long) ptr->cur_start_row + i;
  176124. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176125. /* Transfer no more than fits in file */
  176126. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176127. if (rows <= 0) /* this chunk might be past end of file! */
  176128. break;
  176129. byte_count = rows * bytesperrow;
  176130. if (writing)
  176131. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176132. (void FAR *) ptr->mem_buffer[i],
  176133. file_offset, byte_count);
  176134. else
  176135. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176136. (void FAR *) ptr->mem_buffer[i],
  176137. file_offset, byte_count);
  176138. file_offset += byte_count;
  176139. }
  176140. }
  176141. LOCAL(void)
  176142. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176143. /* Do backing store read or write of a virtual coefficient-block array */
  176144. {
  176145. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176146. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176147. file_offset = ptr->cur_start_row * bytesperrow;
  176148. /* Loop to read or write each allocation chunk in mem_buffer */
  176149. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176150. /* One chunk, but check for short chunk at end of buffer */
  176151. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176152. /* Transfer no more than is currently defined */
  176153. thisrow = (long) ptr->cur_start_row + i;
  176154. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176155. /* Transfer no more than fits in file */
  176156. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176157. if (rows <= 0) /* this chunk might be past end of file! */
  176158. break;
  176159. byte_count = rows * bytesperrow;
  176160. if (writing)
  176161. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176162. (void FAR *) ptr->mem_buffer[i],
  176163. file_offset, byte_count);
  176164. else
  176165. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176166. (void FAR *) ptr->mem_buffer[i],
  176167. file_offset, byte_count);
  176168. file_offset += byte_count;
  176169. }
  176170. }
  176171. METHODDEF(JSAMPARRAY)
  176172. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176173. JDIMENSION start_row, JDIMENSION num_rows,
  176174. boolean writable)
  176175. /* Access the part of a virtual sample array starting at start_row */
  176176. /* and extending for num_rows rows. writable is true if */
  176177. /* caller intends to modify the accessed area. */
  176178. {
  176179. JDIMENSION end_row = start_row + num_rows;
  176180. JDIMENSION undef_row;
  176181. /* debugging check */
  176182. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176183. ptr->mem_buffer == NULL)
  176184. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176185. /* Make the desired part of the virtual array accessible */
  176186. if (start_row < ptr->cur_start_row ||
  176187. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176188. if (! ptr->b_s_open)
  176189. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176190. /* Flush old buffer contents if necessary */
  176191. if (ptr->dirty) {
  176192. do_sarray_io(cinfo, ptr, TRUE);
  176193. ptr->dirty = FALSE;
  176194. }
  176195. /* Decide what part of virtual array to access.
  176196. * Algorithm: if target address > current window, assume forward scan,
  176197. * load starting at target address. If target address < current window,
  176198. * assume backward scan, load so that target area is top of window.
  176199. * Note that when switching from forward write to forward read, will have
  176200. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176201. */
  176202. if (start_row > ptr->cur_start_row) {
  176203. ptr->cur_start_row = start_row;
  176204. } else {
  176205. /* use long arithmetic here to avoid overflow & unsigned problems */
  176206. long ltemp;
  176207. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176208. if (ltemp < 0)
  176209. ltemp = 0; /* don't fall off front end of file */
  176210. ptr->cur_start_row = (JDIMENSION) ltemp;
  176211. }
  176212. /* Read in the selected part of the array.
  176213. * During the initial write pass, we will do no actual read
  176214. * because the selected part is all undefined.
  176215. */
  176216. do_sarray_io(cinfo, ptr, FALSE);
  176217. }
  176218. /* Ensure the accessed part of the array is defined; prezero if needed.
  176219. * To improve locality of access, we only prezero the part of the array
  176220. * that the caller is about to access, not the entire in-memory array.
  176221. */
  176222. if (ptr->first_undef_row < end_row) {
  176223. if (ptr->first_undef_row < start_row) {
  176224. if (writable) /* writer skipped over a section of array */
  176225. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176226. undef_row = start_row; /* but reader is allowed to read ahead */
  176227. } else {
  176228. undef_row = ptr->first_undef_row;
  176229. }
  176230. if (writable)
  176231. ptr->first_undef_row = end_row;
  176232. if (ptr->pre_zero) {
  176233. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176234. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176235. end_row -= ptr->cur_start_row;
  176236. while (undef_row < end_row) {
  176237. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176238. undef_row++;
  176239. }
  176240. } else {
  176241. if (! writable) /* reader looking at undefined data */
  176242. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176243. }
  176244. }
  176245. /* Flag the buffer dirty if caller will write in it */
  176246. if (writable)
  176247. ptr->dirty = TRUE;
  176248. /* Return address of proper part of the buffer */
  176249. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176250. }
  176251. METHODDEF(JBLOCKARRAY)
  176252. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176253. JDIMENSION start_row, JDIMENSION num_rows,
  176254. boolean writable)
  176255. /* Access the part of a virtual block array starting at start_row */
  176256. /* and extending for num_rows rows. writable is true if */
  176257. /* caller intends to modify the accessed area. */
  176258. {
  176259. JDIMENSION end_row = start_row + num_rows;
  176260. JDIMENSION undef_row;
  176261. /* debugging check */
  176262. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176263. ptr->mem_buffer == NULL)
  176264. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176265. /* Make the desired part of the virtual array accessible */
  176266. if (start_row < ptr->cur_start_row ||
  176267. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176268. if (! ptr->b_s_open)
  176269. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176270. /* Flush old buffer contents if necessary */
  176271. if (ptr->dirty) {
  176272. do_barray_io(cinfo, ptr, TRUE);
  176273. ptr->dirty = FALSE;
  176274. }
  176275. /* Decide what part of virtual array to access.
  176276. * Algorithm: if target address > current window, assume forward scan,
  176277. * load starting at target address. If target address < current window,
  176278. * assume backward scan, load so that target area is top of window.
  176279. * Note that when switching from forward write to forward read, will have
  176280. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176281. */
  176282. if (start_row > ptr->cur_start_row) {
  176283. ptr->cur_start_row = start_row;
  176284. } else {
  176285. /* use long arithmetic here to avoid overflow & unsigned problems */
  176286. long ltemp;
  176287. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176288. if (ltemp < 0)
  176289. ltemp = 0; /* don't fall off front end of file */
  176290. ptr->cur_start_row = (JDIMENSION) ltemp;
  176291. }
  176292. /* Read in the selected part of the array.
  176293. * During the initial write pass, we will do no actual read
  176294. * because the selected part is all undefined.
  176295. */
  176296. do_barray_io(cinfo, ptr, FALSE);
  176297. }
  176298. /* Ensure the accessed part of the array is defined; prezero if needed.
  176299. * To improve locality of access, we only prezero the part of the array
  176300. * that the caller is about to access, not the entire in-memory array.
  176301. */
  176302. if (ptr->first_undef_row < end_row) {
  176303. if (ptr->first_undef_row < start_row) {
  176304. if (writable) /* writer skipped over a section of array */
  176305. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176306. undef_row = start_row; /* but reader is allowed to read ahead */
  176307. } else {
  176308. undef_row = ptr->first_undef_row;
  176309. }
  176310. if (writable)
  176311. ptr->first_undef_row = end_row;
  176312. if (ptr->pre_zero) {
  176313. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176314. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176315. end_row -= ptr->cur_start_row;
  176316. while (undef_row < end_row) {
  176317. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176318. undef_row++;
  176319. }
  176320. } else {
  176321. if (! writable) /* reader looking at undefined data */
  176322. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176323. }
  176324. }
  176325. /* Flag the buffer dirty if caller will write in it */
  176326. if (writable)
  176327. ptr->dirty = TRUE;
  176328. /* Return address of proper part of the buffer */
  176329. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176330. }
  176331. /*
  176332. * Release all objects belonging to a specified pool.
  176333. */
  176334. METHODDEF(void)
  176335. free_pool (j_common_ptr cinfo, int pool_id)
  176336. {
  176337. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176338. small_pool_ptr shdr_ptr;
  176339. large_pool_ptr lhdr_ptr;
  176340. size_t space_freed;
  176341. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176342. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176343. #ifdef MEM_STATS
  176344. if (cinfo->err->trace_level > 1)
  176345. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176346. #endif
  176347. /* If freeing IMAGE pool, close any virtual arrays first */
  176348. if (pool_id == JPOOL_IMAGE) {
  176349. jvirt_sarray_ptr sptr;
  176350. jvirt_barray_ptr bptr;
  176351. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176352. if (sptr->b_s_open) { /* there may be no backing store */
  176353. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176354. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176355. }
  176356. }
  176357. mem->virt_sarray_list = NULL;
  176358. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176359. if (bptr->b_s_open) { /* there may be no backing store */
  176360. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176361. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176362. }
  176363. }
  176364. mem->virt_barray_list = NULL;
  176365. }
  176366. /* Release large objects */
  176367. lhdr_ptr = mem->large_list[pool_id];
  176368. mem->large_list[pool_id] = NULL;
  176369. while (lhdr_ptr != NULL) {
  176370. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176371. space_freed = lhdr_ptr->hdr.bytes_used +
  176372. lhdr_ptr->hdr.bytes_left +
  176373. SIZEOF(large_pool_hdr);
  176374. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176375. mem->total_space_allocated -= space_freed;
  176376. lhdr_ptr = next_lhdr_ptr;
  176377. }
  176378. /* Release small objects */
  176379. shdr_ptr = mem->small_list[pool_id];
  176380. mem->small_list[pool_id] = NULL;
  176381. while (shdr_ptr != NULL) {
  176382. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176383. space_freed = shdr_ptr->hdr.bytes_used +
  176384. shdr_ptr->hdr.bytes_left +
  176385. SIZEOF(small_pool_hdr);
  176386. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176387. mem->total_space_allocated -= space_freed;
  176388. shdr_ptr = next_shdr_ptr;
  176389. }
  176390. }
  176391. /*
  176392. * Close up shop entirely.
  176393. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176394. */
  176395. METHODDEF(void)
  176396. self_destruct (j_common_ptr cinfo)
  176397. {
  176398. int pool;
  176399. /* Close all backing store, release all memory.
  176400. * Releasing pools in reverse order might help avoid fragmentation
  176401. * with some (brain-damaged) malloc libraries.
  176402. */
  176403. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176404. free_pool(cinfo, pool);
  176405. }
  176406. /* Release the memory manager control block too. */
  176407. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176408. cinfo->mem = NULL; /* ensures I will be called only once */
  176409. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176410. }
  176411. /*
  176412. * Memory manager initialization.
  176413. * When this is called, only the error manager pointer is valid in cinfo!
  176414. */
  176415. GLOBAL(void)
  176416. jinit_memory_mgr (j_common_ptr cinfo)
  176417. {
  176418. my_mem_ptr mem;
  176419. long max_to_use;
  176420. int pool;
  176421. size_t test_mac;
  176422. cinfo->mem = NULL; /* for safety if init fails */
  176423. /* Check for configuration errors.
  176424. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176425. * doesn't reflect any real hardware alignment requirement.
  176426. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176427. * in common if and only if X is a power of 2, ie has only one one-bit.
  176428. * Some compilers may give an "unreachable code" warning here; ignore it.
  176429. */
  176430. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176431. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176432. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176433. * a multiple of SIZEOF(ALIGN_TYPE).
  176434. * Again, an "unreachable code" warning may be ignored here.
  176435. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176436. */
  176437. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176438. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176439. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176440. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176441. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176442. /* Attempt to allocate memory manager's control block */
  176443. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176444. if (mem == NULL) {
  176445. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176446. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176447. }
  176448. /* OK, fill in the method pointers */
  176449. mem->pub.alloc_small = alloc_small;
  176450. mem->pub.alloc_large = alloc_large;
  176451. mem->pub.alloc_sarray = alloc_sarray;
  176452. mem->pub.alloc_barray = alloc_barray;
  176453. mem->pub.request_virt_sarray = request_virt_sarray;
  176454. mem->pub.request_virt_barray = request_virt_barray;
  176455. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176456. mem->pub.access_virt_sarray = access_virt_sarray;
  176457. mem->pub.access_virt_barray = access_virt_barray;
  176458. mem->pub.free_pool = free_pool;
  176459. mem->pub.self_destruct = self_destruct;
  176460. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176461. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176462. /* Initialize working state */
  176463. mem->pub.max_memory_to_use = max_to_use;
  176464. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176465. mem->small_list[pool] = NULL;
  176466. mem->large_list[pool] = NULL;
  176467. }
  176468. mem->virt_sarray_list = NULL;
  176469. mem->virt_barray_list = NULL;
  176470. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176471. /* Declare ourselves open for business */
  176472. cinfo->mem = & mem->pub;
  176473. /* Check for an environment variable JPEGMEM; if found, override the
  176474. * default max_memory setting from jpeg_mem_init. Note that the
  176475. * surrounding application may again override this value.
  176476. * If your system doesn't support getenv(), define NO_GETENV to disable
  176477. * this feature.
  176478. */
  176479. #ifndef NO_GETENV
  176480. { char * memenv;
  176481. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176482. char ch = 'x';
  176483. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176484. if (ch == 'm' || ch == 'M')
  176485. max_to_use *= 1000L;
  176486. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176487. }
  176488. }
  176489. }
  176490. #endif
  176491. }
  176492. /*** End of inlined file: jmemmgr.c ***/
  176493. /*** Start of inlined file: jmemnobs.c ***/
  176494. #define JPEG_INTERNALS
  176495. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176496. extern void * malloc JPP((size_t size));
  176497. extern void free JPP((void *ptr));
  176498. #endif
  176499. /*
  176500. * Memory allocation and freeing are controlled by the regular library
  176501. * routines malloc() and free().
  176502. */
  176503. GLOBAL(void *)
  176504. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176505. {
  176506. return (void *) malloc(sizeofobject);
  176507. }
  176508. GLOBAL(void)
  176509. jpeg_free_small (j_common_ptr , void * object, size_t)
  176510. {
  176511. free(object);
  176512. }
  176513. /*
  176514. * "Large" objects are treated the same as "small" ones.
  176515. * NB: although we include FAR keywords in the routine declarations,
  176516. * this file won't actually work in 80x86 small/medium model; at least,
  176517. * you probably won't be able to process useful-size images in only 64KB.
  176518. */
  176519. GLOBAL(void FAR *)
  176520. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176521. {
  176522. return (void FAR *) malloc(sizeofobject);
  176523. }
  176524. GLOBAL(void)
  176525. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176526. {
  176527. free(object);
  176528. }
  176529. /*
  176530. * This routine computes the total memory space available for allocation.
  176531. * Here we always say, "we got all you want bud!"
  176532. */
  176533. GLOBAL(long)
  176534. jpeg_mem_available (j_common_ptr, long,
  176535. long max_bytes_needed, long)
  176536. {
  176537. return max_bytes_needed;
  176538. }
  176539. /*
  176540. * Backing store (temporary file) management.
  176541. * Since jpeg_mem_available always promised the moon,
  176542. * this should never be called and we can just error out.
  176543. */
  176544. GLOBAL(void)
  176545. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176546. long )
  176547. {
  176548. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176549. }
  176550. /*
  176551. * These routines take care of any system-dependent initialization and
  176552. * cleanup required. Here, there isn't any.
  176553. */
  176554. GLOBAL(long)
  176555. jpeg_mem_init (j_common_ptr)
  176556. {
  176557. return 0; /* just set max_memory_to_use to 0 */
  176558. }
  176559. GLOBAL(void)
  176560. jpeg_mem_term (j_common_ptr)
  176561. {
  176562. /* no work */
  176563. }
  176564. /*** End of inlined file: jmemnobs.c ***/
  176565. /*** Start of inlined file: jquant1.c ***/
  176566. #define JPEG_INTERNALS
  176567. #ifdef QUANT_1PASS_SUPPORTED
  176568. /*
  176569. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176570. * high quality, colormapped output capability. A 2-pass quantizer usually
  176571. * gives better visual quality; however, for quantized grayscale output this
  176572. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176573. * quantizer, though you can turn it off if you really want to.
  176574. *
  176575. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176576. * image. We use a map consisting of all combinations of Ncolors[i] color
  176577. * values for the i'th component. The Ncolors[] values are chosen so that
  176578. * their product, the total number of colors, is no more than that requested.
  176579. * (In most cases, the product will be somewhat less.)
  176580. *
  176581. * Since the colormap is orthogonal, the representative value for each color
  176582. * component can be determined without considering the other components;
  176583. * then these indexes can be combined into a colormap index by a standard
  176584. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176585. * can be precalculated and stored in the lookup table colorindex[].
  176586. * colorindex[i][j] maps pixel value j in component i to the nearest
  176587. * representative value (grid plane) for that component; this index is
  176588. * multiplied by the array stride for component i, so that the
  176589. * index of the colormap entry closest to a given pixel value is just
  176590. * sum( colorindex[component-number][pixel-component-value] )
  176591. * Aside from being fast, this scheme allows for variable spacing between
  176592. * representative values with no additional lookup cost.
  176593. *
  176594. * If gamma correction has been applied in color conversion, it might be wise
  176595. * to adjust the color grid spacing so that the representative colors are
  176596. * equidistant in linear space. At this writing, gamma correction is not
  176597. * implemented by jdcolor, so nothing is done here.
  176598. */
  176599. /* Declarations for ordered dithering.
  176600. *
  176601. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176602. * dithering is described in many references, for instance Dale Schumacher's
  176603. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176604. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176605. * "dither" value to the input pixel and then round the result to the nearest
  176606. * output value. The dither value is equivalent to (0.5 - threshold) times
  176607. * the distance between output values. For ordered dithering, we assume that
  176608. * the output colors are equally spaced; if not, results will probably be
  176609. * worse, since the dither may be too much or too little at a given point.
  176610. *
  176611. * The normal calculation would be to form pixel value + dither, range-limit
  176612. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176613. * We can skip the separate range-limiting step by extending the colorindex
  176614. * table in both directions.
  176615. */
  176616. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176617. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176618. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176619. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176620. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176621. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176622. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176623. /* Bayer's order-4 dither array. Generated by the code given in
  176624. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176625. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176626. */
  176627. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176628. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176629. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176630. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176631. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176632. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176633. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176634. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176635. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176636. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176637. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176638. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176639. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176640. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176641. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176642. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176643. };
  176644. /* Declarations for Floyd-Steinberg dithering.
  176645. *
  176646. * Errors are accumulated into the array fserrors[], at a resolution of
  176647. * 1/16th of a pixel count. The error at a given pixel is propagated
  176648. * to its not-yet-processed neighbors using the standard F-S fractions,
  176649. * ... (here) 7/16
  176650. * 3/16 5/16 1/16
  176651. * We work left-to-right on even rows, right-to-left on odd rows.
  176652. *
  176653. * We can get away with a single array (holding one row's worth of errors)
  176654. * by using it to store the current row's errors at pixel columns not yet
  176655. * processed, but the next row's errors at columns already processed. We
  176656. * need only a few extra variables to hold the errors immediately around the
  176657. * current column. (If we are lucky, those variables are in registers, but
  176658. * even if not, they're probably cheaper to access than array elements are.)
  176659. *
  176660. * The fserrors[] array is indexed [component#][position].
  176661. * We provide (#columns + 2) entries per component; the extra entry at each
  176662. * end saves us from special-casing the first and last pixels.
  176663. *
  176664. * Note: on a wide image, we might not have enough room in a PC's near data
  176665. * segment to hold the error array; so it is allocated with alloc_large.
  176666. */
  176667. #if BITS_IN_JSAMPLE == 8
  176668. typedef INT16 FSERROR; /* 16 bits should be enough */
  176669. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176670. #else
  176671. typedef INT32 FSERROR; /* may need more than 16 bits */
  176672. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176673. #endif
  176674. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176675. /* Private subobject */
  176676. #define MAX_Q_COMPS 4 /* max components I can handle */
  176677. typedef struct {
  176678. struct jpeg_color_quantizer pub; /* public fields */
  176679. /* Initially allocated colormap is saved here */
  176680. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176681. int sv_actual; /* number of entries in use */
  176682. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176683. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176684. * premultiplied as described above. Since colormap indexes must fit into
  176685. * JSAMPLEs, the entries of this array will too.
  176686. */
  176687. boolean is_padded; /* is the colorindex padded for odither? */
  176688. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176689. /* Variables for ordered dithering */
  176690. int row_index; /* cur row's vertical index in dither matrix */
  176691. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176692. /* Variables for Floyd-Steinberg dithering */
  176693. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176694. boolean on_odd_row; /* flag to remember which row we are on */
  176695. } my_cquantizer;
  176696. typedef my_cquantizer * my_cquantize_ptr;
  176697. /*
  176698. * Policy-making subroutines for create_colormap and create_colorindex.
  176699. * These routines determine the colormap to be used. The rest of the module
  176700. * only assumes that the colormap is orthogonal.
  176701. *
  176702. * * select_ncolors decides how to divvy up the available colors
  176703. * among the components.
  176704. * * output_value defines the set of representative values for a component.
  176705. * * largest_input_value defines the mapping from input values to
  176706. * representative values for a component.
  176707. * Note that the latter two routines may impose different policies for
  176708. * different components, though this is not currently done.
  176709. */
  176710. LOCAL(int)
  176711. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176712. /* Determine allocation of desired colors to components, */
  176713. /* and fill in Ncolors[] array to indicate choice. */
  176714. /* Return value is total number of colors (product of Ncolors[] values). */
  176715. {
  176716. int nc = cinfo->out_color_components; /* number of color components */
  176717. int max_colors = cinfo->desired_number_of_colors;
  176718. int total_colors, iroot, i, j;
  176719. boolean changed;
  176720. long temp;
  176721. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176722. /* We can allocate at least the nc'th root of max_colors per component. */
  176723. /* Compute floor(nc'th root of max_colors). */
  176724. iroot = 1;
  176725. do {
  176726. iroot++;
  176727. temp = iroot; /* set temp = iroot ** nc */
  176728. for (i = 1; i < nc; i++)
  176729. temp *= iroot;
  176730. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176731. iroot--; /* now iroot = floor(root) */
  176732. /* Must have at least 2 color values per component */
  176733. if (iroot < 2)
  176734. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176735. /* Initialize to iroot color values for each component */
  176736. total_colors = 1;
  176737. for (i = 0; i < nc; i++) {
  176738. Ncolors[i] = iroot;
  176739. total_colors *= iroot;
  176740. }
  176741. /* We may be able to increment the count for one or more components without
  176742. * exceeding max_colors, though we know not all can be incremented.
  176743. * Sometimes, the first component can be incremented more than once!
  176744. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176745. * In RGB colorspace, try to increment G first, then R, then B.
  176746. */
  176747. do {
  176748. changed = FALSE;
  176749. for (i = 0; i < nc; i++) {
  176750. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176751. /* calculate new total_colors if Ncolors[j] is incremented */
  176752. temp = total_colors / Ncolors[j];
  176753. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176754. if (temp > (long) max_colors)
  176755. break; /* won't fit, done with this pass */
  176756. Ncolors[j]++; /* OK, apply the increment */
  176757. total_colors = (int) temp;
  176758. changed = TRUE;
  176759. }
  176760. } while (changed);
  176761. return total_colors;
  176762. }
  176763. LOCAL(int)
  176764. output_value (j_decompress_ptr, int, int j, int maxj)
  176765. /* Return j'th output value, where j will range from 0 to maxj */
  176766. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176767. {
  176768. /* We always provide values 0 and MAXJSAMPLE for each component;
  176769. * any additional values are equally spaced between these limits.
  176770. * (Forcing the upper and lower values to the limits ensures that
  176771. * dithering can't produce a color outside the selected gamut.)
  176772. */
  176773. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176774. }
  176775. LOCAL(int)
  176776. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176777. /* Return largest input value that should map to j'th output value */
  176778. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176779. {
  176780. /* Breakpoints are halfway between values returned by output_value */
  176781. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176782. }
  176783. /*
  176784. * Create the colormap.
  176785. */
  176786. LOCAL(void)
  176787. create_colormap (j_decompress_ptr cinfo)
  176788. {
  176789. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176790. JSAMPARRAY colormap; /* Created colormap */
  176791. int total_colors; /* Number of distinct output colors */
  176792. int i,j,k, nci, blksize, blkdist, ptr, val;
  176793. /* Select number of colors for each component */
  176794. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176795. /* Report selected color counts */
  176796. if (cinfo->out_color_components == 3)
  176797. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176798. total_colors, cquantize->Ncolors[0],
  176799. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176800. else
  176801. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176802. /* Allocate and fill in the colormap. */
  176803. /* The colors are ordered in the map in standard row-major order, */
  176804. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176805. colormap = (*cinfo->mem->alloc_sarray)
  176806. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176807. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176808. /* blksize is number of adjacent repeated entries for a component */
  176809. /* blkdist is distance between groups of identical entries for a component */
  176810. blkdist = total_colors;
  176811. for (i = 0; i < cinfo->out_color_components; i++) {
  176812. /* fill in colormap entries for i'th color component */
  176813. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176814. blksize = blkdist / nci;
  176815. for (j = 0; j < nci; j++) {
  176816. /* Compute j'th output value (out of nci) for component */
  176817. val = output_value(cinfo, i, j, nci-1);
  176818. /* Fill in all colormap entries that have this value of this component */
  176819. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176820. /* fill in blksize entries beginning at ptr */
  176821. for (k = 0; k < blksize; k++)
  176822. colormap[i][ptr+k] = (JSAMPLE) val;
  176823. }
  176824. }
  176825. blkdist = blksize; /* blksize of this color is blkdist of next */
  176826. }
  176827. /* Save the colormap in private storage,
  176828. * where it will survive color quantization mode changes.
  176829. */
  176830. cquantize->sv_colormap = colormap;
  176831. cquantize->sv_actual = total_colors;
  176832. }
  176833. /*
  176834. * Create the color index table.
  176835. */
  176836. LOCAL(void)
  176837. create_colorindex (j_decompress_ptr cinfo)
  176838. {
  176839. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176840. JSAMPROW indexptr;
  176841. int i,j,k, nci, blksize, val, pad;
  176842. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176843. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176844. * This is not necessary in the other dithering modes. However, we
  176845. * flag whether it was done in case user changes dithering mode.
  176846. */
  176847. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176848. pad = MAXJSAMPLE*2;
  176849. cquantize->is_padded = TRUE;
  176850. } else {
  176851. pad = 0;
  176852. cquantize->is_padded = FALSE;
  176853. }
  176854. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176855. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176856. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176857. (JDIMENSION) cinfo->out_color_components);
  176858. /* blksize is number of adjacent repeated entries for a component */
  176859. blksize = cquantize->sv_actual;
  176860. for (i = 0; i < cinfo->out_color_components; i++) {
  176861. /* fill in colorindex entries for i'th color component */
  176862. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176863. blksize = blksize / nci;
  176864. /* adjust colorindex pointers to provide padding at negative indexes. */
  176865. if (pad)
  176866. cquantize->colorindex[i] += MAXJSAMPLE;
  176867. /* in loop, val = index of current output value, */
  176868. /* and k = largest j that maps to current val */
  176869. indexptr = cquantize->colorindex[i];
  176870. val = 0;
  176871. k = largest_input_value(cinfo, i, 0, nci-1);
  176872. for (j = 0; j <= MAXJSAMPLE; j++) {
  176873. while (j > k) /* advance val if past boundary */
  176874. k = largest_input_value(cinfo, i, ++val, nci-1);
  176875. /* premultiply so that no multiplication needed in main processing */
  176876. indexptr[j] = (JSAMPLE) (val * blksize);
  176877. }
  176878. /* Pad at both ends if necessary */
  176879. if (pad)
  176880. for (j = 1; j <= MAXJSAMPLE; j++) {
  176881. indexptr[-j] = indexptr[0];
  176882. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176883. }
  176884. }
  176885. }
  176886. /*
  176887. * Create an ordered-dither array for a component having ncolors
  176888. * distinct output values.
  176889. */
  176890. LOCAL(ODITHER_MATRIX_PTR)
  176891. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176892. {
  176893. ODITHER_MATRIX_PTR odither;
  176894. int j,k;
  176895. INT32 num,den;
  176896. odither = (ODITHER_MATRIX_PTR)
  176897. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176898. SIZEOF(ODITHER_MATRIX));
  176899. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176900. * Hence the dither value for the matrix cell with fill order f
  176901. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176902. * On 16-bit-int machine, be careful to avoid overflow.
  176903. */
  176904. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176905. for (j = 0; j < ODITHER_SIZE; j++) {
  176906. for (k = 0; k < ODITHER_SIZE; k++) {
  176907. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176908. * MAXJSAMPLE;
  176909. /* Ensure round towards zero despite C's lack of consistency
  176910. * about rounding negative values in integer division...
  176911. */
  176912. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176913. }
  176914. }
  176915. return odither;
  176916. }
  176917. /*
  176918. * Create the ordered-dither tables.
  176919. * Components having the same number of representative colors may
  176920. * share a dither table.
  176921. */
  176922. LOCAL(void)
  176923. create_odither_tables (j_decompress_ptr cinfo)
  176924. {
  176925. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176926. ODITHER_MATRIX_PTR odither;
  176927. int i, j, nci;
  176928. for (i = 0; i < cinfo->out_color_components; i++) {
  176929. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176930. odither = NULL; /* search for matching prior component */
  176931. for (j = 0; j < i; j++) {
  176932. if (nci == cquantize->Ncolors[j]) {
  176933. odither = cquantize->odither[j];
  176934. break;
  176935. }
  176936. }
  176937. if (odither == NULL) /* need a new table? */
  176938. odither = make_odither_array(cinfo, nci);
  176939. cquantize->odither[i] = odither;
  176940. }
  176941. }
  176942. /*
  176943. * Map some rows of pixels to the output colormapped representation.
  176944. */
  176945. METHODDEF(void)
  176946. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176947. JSAMPARRAY output_buf, int num_rows)
  176948. /* General case, no dithering */
  176949. {
  176950. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176951. JSAMPARRAY colorindex = cquantize->colorindex;
  176952. register int pixcode, ci;
  176953. register JSAMPROW ptrin, ptrout;
  176954. int row;
  176955. JDIMENSION col;
  176956. JDIMENSION width = cinfo->output_width;
  176957. register int nc = cinfo->out_color_components;
  176958. for (row = 0; row < num_rows; row++) {
  176959. ptrin = input_buf[row];
  176960. ptrout = output_buf[row];
  176961. for (col = width; col > 0; col--) {
  176962. pixcode = 0;
  176963. for (ci = 0; ci < nc; ci++) {
  176964. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176965. }
  176966. *ptrout++ = (JSAMPLE) pixcode;
  176967. }
  176968. }
  176969. }
  176970. METHODDEF(void)
  176971. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176972. JSAMPARRAY output_buf, int num_rows)
  176973. /* Fast path for out_color_components==3, no dithering */
  176974. {
  176975. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176976. register int pixcode;
  176977. register JSAMPROW ptrin, ptrout;
  176978. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176979. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176980. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176981. int row;
  176982. JDIMENSION col;
  176983. JDIMENSION width = cinfo->output_width;
  176984. for (row = 0; row < num_rows; row++) {
  176985. ptrin = input_buf[row];
  176986. ptrout = output_buf[row];
  176987. for (col = width; col > 0; col--) {
  176988. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176989. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176990. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176991. *ptrout++ = (JSAMPLE) pixcode;
  176992. }
  176993. }
  176994. }
  176995. METHODDEF(void)
  176996. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176997. JSAMPARRAY output_buf, int num_rows)
  176998. /* General case, with ordered dithering */
  176999. {
  177000. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177001. register JSAMPROW input_ptr;
  177002. register JSAMPROW output_ptr;
  177003. JSAMPROW colorindex_ci;
  177004. int * dither; /* points to active row of dither matrix */
  177005. int row_index, col_index; /* current indexes into dither matrix */
  177006. int nc = cinfo->out_color_components;
  177007. int ci;
  177008. int row;
  177009. JDIMENSION col;
  177010. JDIMENSION width = cinfo->output_width;
  177011. for (row = 0; row < num_rows; row++) {
  177012. /* Initialize output values to 0 so can process components separately */
  177013. jzero_far((void FAR *) output_buf[row],
  177014. (size_t) (width * SIZEOF(JSAMPLE)));
  177015. row_index = cquantize->row_index;
  177016. for (ci = 0; ci < nc; ci++) {
  177017. input_ptr = input_buf[row] + ci;
  177018. output_ptr = output_buf[row];
  177019. colorindex_ci = cquantize->colorindex[ci];
  177020. dither = cquantize->odither[ci][row_index];
  177021. col_index = 0;
  177022. for (col = width; col > 0; col--) {
  177023. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177024. * select output value, accumulate into output code for this pixel.
  177025. * Range-limiting need not be done explicitly, as we have extended
  177026. * the colorindex table to produce the right answers for out-of-range
  177027. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177028. * required amount of padding.
  177029. */
  177030. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177031. input_ptr += nc;
  177032. output_ptr++;
  177033. col_index = (col_index + 1) & ODITHER_MASK;
  177034. }
  177035. }
  177036. /* Advance row index for next row */
  177037. row_index = (row_index + 1) & ODITHER_MASK;
  177038. cquantize->row_index = row_index;
  177039. }
  177040. }
  177041. METHODDEF(void)
  177042. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177043. JSAMPARRAY output_buf, int num_rows)
  177044. /* Fast path for out_color_components==3, with ordered dithering */
  177045. {
  177046. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177047. register int pixcode;
  177048. register JSAMPROW input_ptr;
  177049. register JSAMPROW output_ptr;
  177050. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177051. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177052. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177053. int * dither0; /* points to active row of dither matrix */
  177054. int * dither1;
  177055. int * dither2;
  177056. int row_index, col_index; /* current indexes into dither matrix */
  177057. int row;
  177058. JDIMENSION col;
  177059. JDIMENSION width = cinfo->output_width;
  177060. for (row = 0; row < num_rows; row++) {
  177061. row_index = cquantize->row_index;
  177062. input_ptr = input_buf[row];
  177063. output_ptr = output_buf[row];
  177064. dither0 = cquantize->odither[0][row_index];
  177065. dither1 = cquantize->odither[1][row_index];
  177066. dither2 = cquantize->odither[2][row_index];
  177067. col_index = 0;
  177068. for (col = width; col > 0; col--) {
  177069. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177070. dither0[col_index]]);
  177071. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177072. dither1[col_index]]);
  177073. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177074. dither2[col_index]]);
  177075. *output_ptr++ = (JSAMPLE) pixcode;
  177076. col_index = (col_index + 1) & ODITHER_MASK;
  177077. }
  177078. row_index = (row_index + 1) & ODITHER_MASK;
  177079. cquantize->row_index = row_index;
  177080. }
  177081. }
  177082. METHODDEF(void)
  177083. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177084. JSAMPARRAY output_buf, int num_rows)
  177085. /* General case, with Floyd-Steinberg dithering */
  177086. {
  177087. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177088. register LOCFSERROR cur; /* current error or pixel value */
  177089. LOCFSERROR belowerr; /* error for pixel below cur */
  177090. LOCFSERROR bpreverr; /* error for below/prev col */
  177091. LOCFSERROR bnexterr; /* error for below/next col */
  177092. LOCFSERROR delta;
  177093. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177094. register JSAMPROW input_ptr;
  177095. register JSAMPROW output_ptr;
  177096. JSAMPROW colorindex_ci;
  177097. JSAMPROW colormap_ci;
  177098. int pixcode;
  177099. int nc = cinfo->out_color_components;
  177100. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177101. int dirnc; /* dir * nc */
  177102. int ci;
  177103. int row;
  177104. JDIMENSION col;
  177105. JDIMENSION width = cinfo->output_width;
  177106. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177107. SHIFT_TEMPS
  177108. for (row = 0; row < num_rows; row++) {
  177109. /* Initialize output values to 0 so can process components separately */
  177110. jzero_far((void FAR *) output_buf[row],
  177111. (size_t) (width * SIZEOF(JSAMPLE)));
  177112. for (ci = 0; ci < nc; ci++) {
  177113. input_ptr = input_buf[row] + ci;
  177114. output_ptr = output_buf[row];
  177115. if (cquantize->on_odd_row) {
  177116. /* work right to left in this row */
  177117. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177118. output_ptr += width-1;
  177119. dir = -1;
  177120. dirnc = -nc;
  177121. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177122. } else {
  177123. /* work left to right in this row */
  177124. dir = 1;
  177125. dirnc = nc;
  177126. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177127. }
  177128. colorindex_ci = cquantize->colorindex[ci];
  177129. colormap_ci = cquantize->sv_colormap[ci];
  177130. /* Preset error values: no error propagated to first pixel from left */
  177131. cur = 0;
  177132. /* and no error propagated to row below yet */
  177133. belowerr = bpreverr = 0;
  177134. for (col = width; col > 0; col--) {
  177135. /* cur holds the error propagated from the previous pixel on the
  177136. * current line. Add the error propagated from the previous line
  177137. * to form the complete error correction term for this pixel, and
  177138. * round the error term (which is expressed * 16) to an integer.
  177139. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177140. * for either sign of the error value.
  177141. * Note: errorptr points to *previous* column's array entry.
  177142. */
  177143. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177144. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177145. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177146. * of the range_limit array.
  177147. */
  177148. cur += GETJSAMPLE(*input_ptr);
  177149. cur = GETJSAMPLE(range_limit[cur]);
  177150. /* Select output value, accumulate into output code for this pixel */
  177151. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177152. *output_ptr += (JSAMPLE) pixcode;
  177153. /* Compute actual representation error at this pixel */
  177154. /* Note: we can do this even though we don't have the final */
  177155. /* pixel code, because the colormap is orthogonal. */
  177156. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177157. /* Compute error fractions to be propagated to adjacent pixels.
  177158. * Add these into the running sums, and simultaneously shift the
  177159. * next-line error sums left by 1 column.
  177160. */
  177161. bnexterr = cur;
  177162. delta = cur * 2;
  177163. cur += delta; /* form error * 3 */
  177164. errorptr[0] = (FSERROR) (bpreverr + cur);
  177165. cur += delta; /* form error * 5 */
  177166. bpreverr = belowerr + cur;
  177167. belowerr = bnexterr;
  177168. cur += delta; /* form error * 7 */
  177169. /* At this point cur contains the 7/16 error value to be propagated
  177170. * to the next pixel on the current line, and all the errors for the
  177171. * next line have been shifted over. We are therefore ready to move on.
  177172. */
  177173. input_ptr += dirnc; /* advance input ptr to next column */
  177174. output_ptr += dir; /* advance output ptr to next column */
  177175. errorptr += dir; /* advance errorptr to current column */
  177176. }
  177177. /* Post-loop cleanup: we must unload the final error value into the
  177178. * final fserrors[] entry. Note we need not unload belowerr because
  177179. * it is for the dummy column before or after the actual array.
  177180. */
  177181. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177182. }
  177183. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177184. }
  177185. }
  177186. /*
  177187. * Allocate workspace for Floyd-Steinberg errors.
  177188. */
  177189. LOCAL(void)
  177190. alloc_fs_workspace (j_decompress_ptr cinfo)
  177191. {
  177192. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177193. size_t arraysize;
  177194. int i;
  177195. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177196. for (i = 0; i < cinfo->out_color_components; i++) {
  177197. cquantize->fserrors[i] = (FSERRPTR)
  177198. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177199. }
  177200. }
  177201. /*
  177202. * Initialize for one-pass color quantization.
  177203. */
  177204. METHODDEF(void)
  177205. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177206. {
  177207. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177208. size_t arraysize;
  177209. int i;
  177210. /* Install my colormap. */
  177211. cinfo->colormap = cquantize->sv_colormap;
  177212. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177213. /* Initialize for desired dithering mode. */
  177214. switch (cinfo->dither_mode) {
  177215. case JDITHER_NONE:
  177216. if (cinfo->out_color_components == 3)
  177217. cquantize->pub.color_quantize = color_quantize3;
  177218. else
  177219. cquantize->pub.color_quantize = color_quantize;
  177220. break;
  177221. case JDITHER_ORDERED:
  177222. if (cinfo->out_color_components == 3)
  177223. cquantize->pub.color_quantize = quantize3_ord_dither;
  177224. else
  177225. cquantize->pub.color_quantize = quantize_ord_dither;
  177226. cquantize->row_index = 0; /* initialize state for ordered dither */
  177227. /* If user changed to ordered dither from another mode,
  177228. * we must recreate the color index table with padding.
  177229. * This will cost extra space, but probably isn't very likely.
  177230. */
  177231. if (! cquantize->is_padded)
  177232. create_colorindex(cinfo);
  177233. /* Create ordered-dither tables if we didn't already. */
  177234. if (cquantize->odither[0] == NULL)
  177235. create_odither_tables(cinfo);
  177236. break;
  177237. case JDITHER_FS:
  177238. cquantize->pub.color_quantize = quantize_fs_dither;
  177239. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177240. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177241. if (cquantize->fserrors[0] == NULL)
  177242. alloc_fs_workspace(cinfo);
  177243. /* Initialize the propagated errors to zero. */
  177244. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177245. for (i = 0; i < cinfo->out_color_components; i++)
  177246. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177247. break;
  177248. default:
  177249. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177250. break;
  177251. }
  177252. }
  177253. /*
  177254. * Finish up at the end of the pass.
  177255. */
  177256. METHODDEF(void)
  177257. finish_pass_1_quant (j_decompress_ptr)
  177258. {
  177259. /* no work in 1-pass case */
  177260. }
  177261. /*
  177262. * Switch to a new external colormap between output passes.
  177263. * Shouldn't get to this module!
  177264. */
  177265. METHODDEF(void)
  177266. new_color_map_1_quant (j_decompress_ptr cinfo)
  177267. {
  177268. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177269. }
  177270. /*
  177271. * Module initialization routine for 1-pass color quantization.
  177272. */
  177273. GLOBAL(void)
  177274. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177275. {
  177276. my_cquantize_ptr cquantize;
  177277. cquantize = (my_cquantize_ptr)
  177278. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177279. SIZEOF(my_cquantizer));
  177280. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177281. cquantize->pub.start_pass = start_pass_1_quant;
  177282. cquantize->pub.finish_pass = finish_pass_1_quant;
  177283. cquantize->pub.new_color_map = new_color_map_1_quant;
  177284. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177285. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177286. /* Make sure my internal arrays won't overflow */
  177287. if (cinfo->out_color_components > MAX_Q_COMPS)
  177288. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177289. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177290. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177291. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177292. /* Create the colormap and color index table. */
  177293. create_colormap(cinfo);
  177294. create_colorindex(cinfo);
  177295. /* Allocate Floyd-Steinberg workspace now if requested.
  177296. * We do this now since it is FAR storage and may affect the memory
  177297. * manager's space calculations. If the user changes to FS dither
  177298. * mode in a later pass, we will allocate the space then, and will
  177299. * possibly overrun the max_memory_to_use setting.
  177300. */
  177301. if (cinfo->dither_mode == JDITHER_FS)
  177302. alloc_fs_workspace(cinfo);
  177303. }
  177304. #endif /* QUANT_1PASS_SUPPORTED */
  177305. /*** End of inlined file: jquant1.c ***/
  177306. /*** Start of inlined file: jquant2.c ***/
  177307. #define JPEG_INTERNALS
  177308. #ifdef QUANT_2PASS_SUPPORTED
  177309. /*
  177310. * This module implements the well-known Heckbert paradigm for color
  177311. * quantization. Most of the ideas used here can be traced back to
  177312. * Heckbert's seminal paper
  177313. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177314. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177315. *
  177316. * In the first pass over the image, we accumulate a histogram showing the
  177317. * usage count of each possible color. To keep the histogram to a reasonable
  177318. * size, we reduce the precision of the input; typical practice is to retain
  177319. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177320. * in the same histogram cell.
  177321. *
  177322. * Next, the color-selection step begins with a box representing the whole
  177323. * color space, and repeatedly splits the "largest" remaining box until we
  177324. * have as many boxes as desired colors. Then the mean color in each
  177325. * remaining box becomes one of the possible output colors.
  177326. *
  177327. * The second pass over the image maps each input pixel to the closest output
  177328. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177329. * This mapping is logically trivial, but making it go fast enough requires
  177330. * considerable care.
  177331. *
  177332. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177333. * the "largest" box and deciding where to cut it. The particular policies
  177334. * used here have proved out well in experimental comparisons, but better ones
  177335. * may yet be found.
  177336. *
  177337. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177338. * space, processing the raw upsampled data without a color conversion step.
  177339. * This allowed the color conversion math to be done only once per colormap
  177340. * entry, not once per pixel. However, that optimization precluded other
  177341. * useful optimizations (such as merging color conversion with upsampling)
  177342. * and it also interfered with desired capabilities such as quantizing to an
  177343. * externally-supplied colormap. We have therefore abandoned that approach.
  177344. * The present code works in the post-conversion color space, typically RGB.
  177345. *
  177346. * To improve the visual quality of the results, we actually work in scaled
  177347. * RGB space, giving G distances more weight than R, and R in turn more than
  177348. * B. To do everything in integer math, we must use integer scale factors.
  177349. * The 2/3/1 scale factors used here correspond loosely to the relative
  177350. * weights of the colors in the NTSC grayscale equation.
  177351. * If you want to use this code to quantize a non-RGB color space, you'll
  177352. * probably need to change these scale factors.
  177353. */
  177354. #define R_SCALE 2 /* scale R distances by this much */
  177355. #define G_SCALE 3 /* scale G distances by this much */
  177356. #define B_SCALE 1 /* and B by this much */
  177357. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177358. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177359. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177360. * you'll get compile errors until you extend this logic. In that case
  177361. * you'll probably want to tweak the histogram sizes too.
  177362. */
  177363. #if RGB_RED == 0
  177364. #define C0_SCALE R_SCALE
  177365. #endif
  177366. #if RGB_BLUE == 0
  177367. #define C0_SCALE B_SCALE
  177368. #endif
  177369. #if RGB_GREEN == 1
  177370. #define C1_SCALE G_SCALE
  177371. #endif
  177372. #if RGB_RED == 2
  177373. #define C2_SCALE R_SCALE
  177374. #endif
  177375. #if RGB_BLUE == 2
  177376. #define C2_SCALE B_SCALE
  177377. #endif
  177378. /*
  177379. * First we have the histogram data structure and routines for creating it.
  177380. *
  177381. * The number of bits of precision can be adjusted by changing these symbols.
  177382. * We recommend keeping 6 bits for G and 5 each for R and B.
  177383. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177384. * better results; if you are short of memory, 5 bits all around will save
  177385. * some space but degrade the results.
  177386. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177387. * (preferably unsigned long) for each cell. In practice this is overkill;
  177388. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177389. * and clamping those that do overflow to the maximum value will give close-
  177390. * enough results. This reduces the recommended histogram size from 256Kb
  177391. * to 128Kb, which is a useful savings on PC-class machines.
  177392. * (In the second pass the histogram space is re-used for pixel mapping data;
  177393. * in that capacity, each cell must be able to store zero to the number of
  177394. * desired colors. 16 bits/cell is plenty for that too.)
  177395. * Since the JPEG code is intended to run in small memory model on 80x86
  177396. * machines, we can't just allocate the histogram in one chunk. Instead
  177397. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177398. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177399. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177400. * on 80x86 machines, the pointer row is in near memory but the actual
  177401. * arrays are in far memory (same arrangement as we use for image arrays).
  177402. */
  177403. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177404. /* These will do the right thing for either R,G,B or B,G,R color order,
  177405. * but you may not like the results for other color orders.
  177406. */
  177407. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177408. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177409. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177410. /* Number of elements along histogram axes. */
  177411. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177412. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177413. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177414. /* These are the amounts to shift an input value to get a histogram index. */
  177415. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177416. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177417. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177418. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177419. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177420. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177421. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177422. typedef hist2d * hist3d; /* type for top-level pointer */
  177423. /* Declarations for Floyd-Steinberg dithering.
  177424. *
  177425. * Errors are accumulated into the array fserrors[], at a resolution of
  177426. * 1/16th of a pixel count. The error at a given pixel is propagated
  177427. * to its not-yet-processed neighbors using the standard F-S fractions,
  177428. * ... (here) 7/16
  177429. * 3/16 5/16 1/16
  177430. * We work left-to-right on even rows, right-to-left on odd rows.
  177431. *
  177432. * We can get away with a single array (holding one row's worth of errors)
  177433. * by using it to store the current row's errors at pixel columns not yet
  177434. * processed, but the next row's errors at columns already processed. We
  177435. * need only a few extra variables to hold the errors immediately around the
  177436. * current column. (If we are lucky, those variables are in registers, but
  177437. * even if not, they're probably cheaper to access than array elements are.)
  177438. *
  177439. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177440. * each end saves us from special-casing the first and last pixels.
  177441. * Each entry is three values long, one value for each color component.
  177442. *
  177443. * Note: on a wide image, we might not have enough room in a PC's near data
  177444. * segment to hold the error array; so it is allocated with alloc_large.
  177445. */
  177446. #if BITS_IN_JSAMPLE == 8
  177447. typedef INT16 FSERROR; /* 16 bits should be enough */
  177448. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177449. #else
  177450. typedef INT32 FSERROR; /* may need more than 16 bits */
  177451. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177452. #endif
  177453. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177454. /* Private subobject */
  177455. typedef struct {
  177456. struct jpeg_color_quantizer pub; /* public fields */
  177457. /* Space for the eventually created colormap is stashed here */
  177458. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177459. int desired; /* desired # of colors = size of colormap */
  177460. /* Variables for accumulating image statistics */
  177461. hist3d histogram; /* pointer to the histogram */
  177462. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177463. /* Variables for Floyd-Steinberg dithering */
  177464. FSERRPTR fserrors; /* accumulated errors */
  177465. boolean on_odd_row; /* flag to remember which row we are on */
  177466. int * error_limiter; /* table for clamping the applied error */
  177467. } my_cquantizer2;
  177468. typedef my_cquantizer2 * my_cquantize_ptr2;
  177469. /*
  177470. * Prescan some rows of pixels.
  177471. * In this module the prescan simply updates the histogram, which has been
  177472. * initialized to zeroes by start_pass.
  177473. * An output_buf parameter is required by the method signature, but no data
  177474. * is actually output (in fact the buffer controller is probably passing a
  177475. * NULL pointer).
  177476. */
  177477. METHODDEF(void)
  177478. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177479. JSAMPARRAY, int num_rows)
  177480. {
  177481. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177482. register JSAMPROW ptr;
  177483. register histptr histp;
  177484. register hist3d histogram = cquantize->histogram;
  177485. int row;
  177486. JDIMENSION col;
  177487. JDIMENSION width = cinfo->output_width;
  177488. for (row = 0; row < num_rows; row++) {
  177489. ptr = input_buf[row];
  177490. for (col = width; col > 0; col--) {
  177491. /* get pixel value and index into the histogram */
  177492. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177493. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177494. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177495. /* increment, check for overflow and undo increment if so. */
  177496. if (++(*histp) <= 0)
  177497. (*histp)--;
  177498. ptr += 3;
  177499. }
  177500. }
  177501. }
  177502. /*
  177503. * Next we have the really interesting routines: selection of a colormap
  177504. * given the completed histogram.
  177505. * These routines work with a list of "boxes", each representing a rectangular
  177506. * subset of the input color space (to histogram precision).
  177507. */
  177508. typedef struct {
  177509. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177510. int c0min, c0max;
  177511. int c1min, c1max;
  177512. int c2min, c2max;
  177513. /* The volume (actually 2-norm) of the box */
  177514. INT32 volume;
  177515. /* The number of nonzero histogram cells within this box */
  177516. long colorcount;
  177517. } box;
  177518. typedef box * boxptr;
  177519. LOCAL(boxptr)
  177520. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177521. /* Find the splittable box with the largest color population */
  177522. /* Returns NULL if no splittable boxes remain */
  177523. {
  177524. register boxptr boxp;
  177525. register int i;
  177526. register long maxc = 0;
  177527. boxptr which = NULL;
  177528. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177529. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177530. which = boxp;
  177531. maxc = boxp->colorcount;
  177532. }
  177533. }
  177534. return which;
  177535. }
  177536. LOCAL(boxptr)
  177537. find_biggest_volume (boxptr boxlist, int numboxes)
  177538. /* Find the splittable box with the largest (scaled) volume */
  177539. /* Returns NULL if no splittable boxes remain */
  177540. {
  177541. register boxptr boxp;
  177542. register int i;
  177543. register INT32 maxv = 0;
  177544. boxptr which = NULL;
  177545. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177546. if (boxp->volume > maxv) {
  177547. which = boxp;
  177548. maxv = boxp->volume;
  177549. }
  177550. }
  177551. return which;
  177552. }
  177553. LOCAL(void)
  177554. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177555. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177556. /* and recompute its volume and population */
  177557. {
  177558. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177559. hist3d histogram = cquantize->histogram;
  177560. histptr histp;
  177561. int c0,c1,c2;
  177562. int c0min,c0max,c1min,c1max,c2min,c2max;
  177563. INT32 dist0,dist1,dist2;
  177564. long ccount;
  177565. c0min = boxp->c0min; c0max = boxp->c0max;
  177566. c1min = boxp->c1min; c1max = boxp->c1max;
  177567. c2min = boxp->c2min; c2max = boxp->c2max;
  177568. if (c0max > c0min)
  177569. for (c0 = c0min; c0 <= c0max; c0++)
  177570. for (c1 = c1min; c1 <= c1max; c1++) {
  177571. histp = & histogram[c0][c1][c2min];
  177572. for (c2 = c2min; c2 <= c2max; c2++)
  177573. if (*histp++ != 0) {
  177574. boxp->c0min = c0min = c0;
  177575. goto have_c0min;
  177576. }
  177577. }
  177578. have_c0min:
  177579. if (c0max > c0min)
  177580. for (c0 = c0max; c0 >= c0min; c0--)
  177581. for (c1 = c1min; c1 <= c1max; c1++) {
  177582. histp = & histogram[c0][c1][c2min];
  177583. for (c2 = c2min; c2 <= c2max; c2++)
  177584. if (*histp++ != 0) {
  177585. boxp->c0max = c0max = c0;
  177586. goto have_c0max;
  177587. }
  177588. }
  177589. have_c0max:
  177590. if (c1max > c1min)
  177591. for (c1 = c1min; c1 <= c1max; c1++)
  177592. for (c0 = c0min; c0 <= c0max; c0++) {
  177593. histp = & histogram[c0][c1][c2min];
  177594. for (c2 = c2min; c2 <= c2max; c2++)
  177595. if (*histp++ != 0) {
  177596. boxp->c1min = c1min = c1;
  177597. goto have_c1min;
  177598. }
  177599. }
  177600. have_c1min:
  177601. if (c1max > c1min)
  177602. for (c1 = c1max; c1 >= c1min; c1--)
  177603. for (c0 = c0min; c0 <= c0max; c0++) {
  177604. histp = & histogram[c0][c1][c2min];
  177605. for (c2 = c2min; c2 <= c2max; c2++)
  177606. if (*histp++ != 0) {
  177607. boxp->c1max = c1max = c1;
  177608. goto have_c1max;
  177609. }
  177610. }
  177611. have_c1max:
  177612. if (c2max > c2min)
  177613. for (c2 = c2min; c2 <= c2max; c2++)
  177614. for (c0 = c0min; c0 <= c0max; c0++) {
  177615. histp = & histogram[c0][c1min][c2];
  177616. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177617. if (*histp != 0) {
  177618. boxp->c2min = c2min = c2;
  177619. goto have_c2min;
  177620. }
  177621. }
  177622. have_c2min:
  177623. if (c2max > c2min)
  177624. for (c2 = c2max; c2 >= c2min; c2--)
  177625. for (c0 = c0min; c0 <= c0max; c0++) {
  177626. histp = & histogram[c0][c1min][c2];
  177627. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177628. if (*histp != 0) {
  177629. boxp->c2max = c2max = c2;
  177630. goto have_c2max;
  177631. }
  177632. }
  177633. have_c2max:
  177634. /* Update box volume.
  177635. * We use 2-norm rather than real volume here; this biases the method
  177636. * against making long narrow boxes, and it has the side benefit that
  177637. * a box is splittable iff norm > 0.
  177638. * Since the differences are expressed in histogram-cell units,
  177639. * we have to shift back to JSAMPLE units to get consistent distances;
  177640. * after which, we scale according to the selected distance scale factors.
  177641. */
  177642. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177643. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177644. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177645. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177646. /* Now scan remaining volume of box and compute population */
  177647. ccount = 0;
  177648. for (c0 = c0min; c0 <= c0max; c0++)
  177649. for (c1 = c1min; c1 <= c1max; c1++) {
  177650. histp = & histogram[c0][c1][c2min];
  177651. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177652. if (*histp != 0) {
  177653. ccount++;
  177654. }
  177655. }
  177656. boxp->colorcount = ccount;
  177657. }
  177658. LOCAL(int)
  177659. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177660. int desired_colors)
  177661. /* Repeatedly select and split the largest box until we have enough boxes */
  177662. {
  177663. int n,lb;
  177664. int c0,c1,c2,cmax;
  177665. register boxptr b1,b2;
  177666. while (numboxes < desired_colors) {
  177667. /* Select box to split.
  177668. * Current algorithm: by population for first half, then by volume.
  177669. */
  177670. if (numboxes*2 <= desired_colors) {
  177671. b1 = find_biggest_color_pop(boxlist, numboxes);
  177672. } else {
  177673. b1 = find_biggest_volume(boxlist, numboxes);
  177674. }
  177675. if (b1 == NULL) /* no splittable boxes left! */
  177676. break;
  177677. b2 = &boxlist[numboxes]; /* where new box will go */
  177678. /* Copy the color bounds to the new box. */
  177679. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177680. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177681. /* Choose which axis to split the box on.
  177682. * Current algorithm: longest scaled axis.
  177683. * See notes in update_box about scaling distances.
  177684. */
  177685. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177686. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177687. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177688. /* We want to break any ties in favor of green, then red, blue last.
  177689. * This code does the right thing for R,G,B or B,G,R color orders only.
  177690. */
  177691. #if RGB_RED == 0
  177692. cmax = c1; n = 1;
  177693. if (c0 > cmax) { cmax = c0; n = 0; }
  177694. if (c2 > cmax) { n = 2; }
  177695. #else
  177696. cmax = c1; n = 1;
  177697. if (c2 > cmax) { cmax = c2; n = 2; }
  177698. if (c0 > cmax) { n = 0; }
  177699. #endif
  177700. /* Choose split point along selected axis, and update box bounds.
  177701. * Current algorithm: split at halfway point.
  177702. * (Since the box has been shrunk to minimum volume,
  177703. * any split will produce two nonempty subboxes.)
  177704. * Note that lb value is max for lower box, so must be < old max.
  177705. */
  177706. switch (n) {
  177707. case 0:
  177708. lb = (b1->c0max + b1->c0min) / 2;
  177709. b1->c0max = lb;
  177710. b2->c0min = lb+1;
  177711. break;
  177712. case 1:
  177713. lb = (b1->c1max + b1->c1min) / 2;
  177714. b1->c1max = lb;
  177715. b2->c1min = lb+1;
  177716. break;
  177717. case 2:
  177718. lb = (b1->c2max + b1->c2min) / 2;
  177719. b1->c2max = lb;
  177720. b2->c2min = lb+1;
  177721. break;
  177722. }
  177723. /* Update stats for boxes */
  177724. update_box(cinfo, b1);
  177725. update_box(cinfo, b2);
  177726. numboxes++;
  177727. }
  177728. return numboxes;
  177729. }
  177730. LOCAL(void)
  177731. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177732. /* Compute representative color for a box, put it in colormap[icolor] */
  177733. {
  177734. /* Current algorithm: mean weighted by pixels (not colors) */
  177735. /* Note it is important to get the rounding correct! */
  177736. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177737. hist3d histogram = cquantize->histogram;
  177738. histptr histp;
  177739. int c0,c1,c2;
  177740. int c0min,c0max,c1min,c1max,c2min,c2max;
  177741. long count;
  177742. long total = 0;
  177743. long c0total = 0;
  177744. long c1total = 0;
  177745. long c2total = 0;
  177746. c0min = boxp->c0min; c0max = boxp->c0max;
  177747. c1min = boxp->c1min; c1max = boxp->c1max;
  177748. c2min = boxp->c2min; c2max = boxp->c2max;
  177749. for (c0 = c0min; c0 <= c0max; c0++)
  177750. for (c1 = c1min; c1 <= c1max; c1++) {
  177751. histp = & histogram[c0][c1][c2min];
  177752. for (c2 = c2min; c2 <= c2max; c2++) {
  177753. if ((count = *histp++) != 0) {
  177754. total += count;
  177755. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177756. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177757. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177758. }
  177759. }
  177760. }
  177761. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177762. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177763. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177764. }
  177765. LOCAL(void)
  177766. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177767. /* Master routine for color selection */
  177768. {
  177769. boxptr boxlist;
  177770. int numboxes;
  177771. int i;
  177772. /* Allocate workspace for box list */
  177773. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177774. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177775. /* Initialize one box containing whole space */
  177776. numboxes = 1;
  177777. boxlist[0].c0min = 0;
  177778. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177779. boxlist[0].c1min = 0;
  177780. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177781. boxlist[0].c2min = 0;
  177782. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177783. /* Shrink it to actually-used volume and set its statistics */
  177784. update_box(cinfo, & boxlist[0]);
  177785. /* Perform median-cut to produce final box list */
  177786. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177787. /* Compute the representative color for each box, fill colormap */
  177788. for (i = 0; i < numboxes; i++)
  177789. compute_color(cinfo, & boxlist[i], i);
  177790. cinfo->actual_number_of_colors = numboxes;
  177791. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177792. }
  177793. /*
  177794. * These routines are concerned with the time-critical task of mapping input
  177795. * colors to the nearest color in the selected colormap.
  177796. *
  177797. * We re-use the histogram space as an "inverse color map", essentially a
  177798. * cache for the results of nearest-color searches. All colors within a
  177799. * histogram cell will be mapped to the same colormap entry, namely the one
  177800. * closest to the cell's center. This may not be quite the closest entry to
  177801. * the actual input color, but it's almost as good. A zero in the cache
  177802. * indicates we haven't found the nearest color for that cell yet; the array
  177803. * is cleared to zeroes before starting the mapping pass. When we find the
  177804. * nearest color for a cell, its colormap index plus one is recorded in the
  177805. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177806. * when they need to use an unfilled entry in the cache.
  177807. *
  177808. * Our method of efficiently finding nearest colors is based on the "locally
  177809. * sorted search" idea described by Heckbert and on the incremental distance
  177810. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177811. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177812. * the distances from a given colormap entry to each cell of the histogram can
  177813. * be computed quickly using an incremental method: the differences between
  177814. * distances to adjacent cells themselves differ by a constant. This allows a
  177815. * fairly fast implementation of the "brute force" approach of computing the
  177816. * distance from every colormap entry to every histogram cell. Unfortunately,
  177817. * it needs a work array to hold the best-distance-so-far for each histogram
  177818. * cell (because the inner loop has to be over cells, not colormap entries).
  177819. * The work array elements have to be INT32s, so the work array would need
  177820. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177821. *
  177822. * To get around these problems, we apply Thomas' method to compute the
  177823. * nearest colors for only the cells within a small subbox of the histogram.
  177824. * The work array need be only as big as the subbox, so the memory usage
  177825. * problem is solved. Furthermore, we need not fill subboxes that are never
  177826. * referenced in pass2; many images use only part of the color gamut, so a
  177827. * fair amount of work is saved. An additional advantage of this
  177828. * approach is that we can apply Heckbert's locality criterion to quickly
  177829. * eliminate colormap entries that are far away from the subbox; typically
  177830. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177831. * and we need not compute their distances to individual cells in the subbox.
  177832. * The speed of this approach is heavily influenced by the subbox size: too
  177833. * small means too much overhead, too big loses because Heckbert's criterion
  177834. * can't eliminate as many colormap entries. Empirically the best subbox
  177835. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177836. *
  177837. * Thomas' article also describes a refined method which is asymptotically
  177838. * faster than the brute-force method, but it is also far more complex and
  177839. * cannot efficiently be applied to small subboxes. It is therefore not
  177840. * useful for programs intended to be portable to DOS machines. On machines
  177841. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177842. * refined method might be faster than the present code --- but then again,
  177843. * it might not be any faster, and it's certainly more complicated.
  177844. */
  177845. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177846. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177847. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177848. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177849. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177850. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177851. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177852. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177853. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177854. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177855. /*
  177856. * The next three routines implement inverse colormap filling. They could
  177857. * all be folded into one big routine, but splitting them up this way saves
  177858. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177859. * and may allow some compilers to produce better code by registerizing more
  177860. * inner-loop variables.
  177861. */
  177862. LOCAL(int)
  177863. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177864. JSAMPLE colorlist[])
  177865. /* Locate the colormap entries close enough to an update box to be candidates
  177866. * for the nearest entry to some cell(s) in the update box. The update box
  177867. * is specified by the center coordinates of its first cell. The number of
  177868. * candidate colormap entries is returned, and their colormap indexes are
  177869. * placed in colorlist[].
  177870. * This routine uses Heckbert's "locally sorted search" criterion to select
  177871. * the colors that need further consideration.
  177872. */
  177873. {
  177874. int numcolors = cinfo->actual_number_of_colors;
  177875. int maxc0, maxc1, maxc2;
  177876. int centerc0, centerc1, centerc2;
  177877. int i, x, ncolors;
  177878. INT32 minmaxdist, min_dist, max_dist, tdist;
  177879. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177880. /* Compute true coordinates of update box's upper corner and center.
  177881. * Actually we compute the coordinates of the center of the upper-corner
  177882. * histogram cell, which are the upper bounds of the volume we care about.
  177883. * Note that since ">>" rounds down, the "center" values may be closer to
  177884. * min than to max; hence comparisons to them must be "<=", not "<".
  177885. */
  177886. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177887. centerc0 = (minc0 + maxc0) >> 1;
  177888. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177889. centerc1 = (minc1 + maxc1) >> 1;
  177890. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177891. centerc2 = (minc2 + maxc2) >> 1;
  177892. /* For each color in colormap, find:
  177893. * 1. its minimum squared-distance to any point in the update box
  177894. * (zero if color is within update box);
  177895. * 2. its maximum squared-distance to any point in the update box.
  177896. * Both of these can be found by considering only the corners of the box.
  177897. * We save the minimum distance for each color in mindist[];
  177898. * only the smallest maximum distance is of interest.
  177899. */
  177900. minmaxdist = 0x7FFFFFFFL;
  177901. for (i = 0; i < numcolors; i++) {
  177902. /* We compute the squared-c0-distance term, then add in the other two. */
  177903. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177904. if (x < minc0) {
  177905. tdist = (x - minc0) * C0_SCALE;
  177906. min_dist = tdist*tdist;
  177907. tdist = (x - maxc0) * C0_SCALE;
  177908. max_dist = tdist*tdist;
  177909. } else if (x > maxc0) {
  177910. tdist = (x - maxc0) * C0_SCALE;
  177911. min_dist = tdist*tdist;
  177912. tdist = (x - minc0) * C0_SCALE;
  177913. max_dist = tdist*tdist;
  177914. } else {
  177915. /* within cell range so no contribution to min_dist */
  177916. min_dist = 0;
  177917. if (x <= centerc0) {
  177918. tdist = (x - maxc0) * C0_SCALE;
  177919. max_dist = tdist*tdist;
  177920. } else {
  177921. tdist = (x - minc0) * C0_SCALE;
  177922. max_dist = tdist*tdist;
  177923. }
  177924. }
  177925. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177926. if (x < minc1) {
  177927. tdist = (x - minc1) * C1_SCALE;
  177928. min_dist += tdist*tdist;
  177929. tdist = (x - maxc1) * C1_SCALE;
  177930. max_dist += tdist*tdist;
  177931. } else if (x > maxc1) {
  177932. tdist = (x - maxc1) * C1_SCALE;
  177933. min_dist += tdist*tdist;
  177934. tdist = (x - minc1) * C1_SCALE;
  177935. max_dist += tdist*tdist;
  177936. } else {
  177937. /* within cell range so no contribution to min_dist */
  177938. if (x <= centerc1) {
  177939. tdist = (x - maxc1) * C1_SCALE;
  177940. max_dist += tdist*tdist;
  177941. } else {
  177942. tdist = (x - minc1) * C1_SCALE;
  177943. max_dist += tdist*tdist;
  177944. }
  177945. }
  177946. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177947. if (x < minc2) {
  177948. tdist = (x - minc2) * C2_SCALE;
  177949. min_dist += tdist*tdist;
  177950. tdist = (x - maxc2) * C2_SCALE;
  177951. max_dist += tdist*tdist;
  177952. } else if (x > maxc2) {
  177953. tdist = (x - maxc2) * C2_SCALE;
  177954. min_dist += tdist*tdist;
  177955. tdist = (x - minc2) * C2_SCALE;
  177956. max_dist += tdist*tdist;
  177957. } else {
  177958. /* within cell range so no contribution to min_dist */
  177959. if (x <= centerc2) {
  177960. tdist = (x - maxc2) * C2_SCALE;
  177961. max_dist += tdist*tdist;
  177962. } else {
  177963. tdist = (x - minc2) * C2_SCALE;
  177964. max_dist += tdist*tdist;
  177965. }
  177966. }
  177967. mindist[i] = min_dist; /* save away the results */
  177968. if (max_dist < minmaxdist)
  177969. minmaxdist = max_dist;
  177970. }
  177971. /* Now we know that no cell in the update box is more than minmaxdist
  177972. * away from some colormap entry. Therefore, only colors that are
  177973. * within minmaxdist of some part of the box need be considered.
  177974. */
  177975. ncolors = 0;
  177976. for (i = 0; i < numcolors; i++) {
  177977. if (mindist[i] <= minmaxdist)
  177978. colorlist[ncolors++] = (JSAMPLE) i;
  177979. }
  177980. return ncolors;
  177981. }
  177982. LOCAL(void)
  177983. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177984. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177985. /* Find the closest colormap entry for each cell in the update box,
  177986. * given the list of candidate colors prepared by find_nearby_colors.
  177987. * Return the indexes of the closest entries in the bestcolor[] array.
  177988. * This routine uses Thomas' incremental distance calculation method to
  177989. * find the distance from a colormap entry to successive cells in the box.
  177990. */
  177991. {
  177992. int ic0, ic1, ic2;
  177993. int i, icolor;
  177994. register INT32 * bptr; /* pointer into bestdist[] array */
  177995. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177996. INT32 dist0, dist1; /* initial distance values */
  177997. register INT32 dist2; /* current distance in inner loop */
  177998. INT32 xx0, xx1; /* distance increments */
  177999. register INT32 xx2;
  178000. INT32 inc0, inc1, inc2; /* initial values for increments */
  178001. /* This array holds the distance to the nearest-so-far color for each cell */
  178002. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178003. /* Initialize best-distance for each cell of the update box */
  178004. bptr = bestdist;
  178005. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178006. *bptr++ = 0x7FFFFFFFL;
  178007. /* For each color selected by find_nearby_colors,
  178008. * compute its distance to the center of each cell in the box.
  178009. * If that's less than best-so-far, update best distance and color number.
  178010. */
  178011. /* Nominal steps between cell centers ("x" in Thomas article) */
  178012. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178013. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178014. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178015. for (i = 0; i < numcolors; i++) {
  178016. icolor = GETJSAMPLE(colorlist[i]);
  178017. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178018. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178019. dist0 = inc0*inc0;
  178020. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178021. dist0 += inc1*inc1;
  178022. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178023. dist0 += inc2*inc2;
  178024. /* Form the initial difference increments */
  178025. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178026. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178027. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178028. /* Now loop over all cells in box, updating distance per Thomas method */
  178029. bptr = bestdist;
  178030. cptr = bestcolor;
  178031. xx0 = inc0;
  178032. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178033. dist1 = dist0;
  178034. xx1 = inc1;
  178035. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178036. dist2 = dist1;
  178037. xx2 = inc2;
  178038. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178039. if (dist2 < *bptr) {
  178040. *bptr = dist2;
  178041. *cptr = (JSAMPLE) icolor;
  178042. }
  178043. dist2 += xx2;
  178044. xx2 += 2 * STEP_C2 * STEP_C2;
  178045. bptr++;
  178046. cptr++;
  178047. }
  178048. dist1 += xx1;
  178049. xx1 += 2 * STEP_C1 * STEP_C1;
  178050. }
  178051. dist0 += xx0;
  178052. xx0 += 2 * STEP_C0 * STEP_C0;
  178053. }
  178054. }
  178055. }
  178056. LOCAL(void)
  178057. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178058. /* Fill the inverse-colormap entries in the update box that contains */
  178059. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178060. /* we can fill as many others as we wish.) */
  178061. {
  178062. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178063. hist3d histogram = cquantize->histogram;
  178064. int minc0, minc1, minc2; /* lower left corner of update box */
  178065. int ic0, ic1, ic2;
  178066. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178067. register histptr cachep; /* pointer into main cache array */
  178068. /* This array lists the candidate colormap indexes. */
  178069. JSAMPLE colorlist[MAXNUMCOLORS];
  178070. int numcolors; /* number of candidate colors */
  178071. /* This array holds the actually closest colormap index for each cell. */
  178072. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178073. /* Convert cell coordinates to update box ID */
  178074. c0 >>= BOX_C0_LOG;
  178075. c1 >>= BOX_C1_LOG;
  178076. c2 >>= BOX_C2_LOG;
  178077. /* Compute true coordinates of update box's origin corner.
  178078. * Actually we compute the coordinates of the center of the corner
  178079. * histogram cell, which are the lower bounds of the volume we care about.
  178080. */
  178081. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178082. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178083. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178084. /* Determine which colormap entries are close enough to be candidates
  178085. * for the nearest entry to some cell in the update box.
  178086. */
  178087. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178088. /* Determine the actually nearest colors. */
  178089. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178090. bestcolor);
  178091. /* Save the best color numbers (plus 1) in the main cache array */
  178092. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178093. c1 <<= BOX_C1_LOG;
  178094. c2 <<= BOX_C2_LOG;
  178095. cptr = bestcolor;
  178096. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178097. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178098. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178099. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178100. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178101. }
  178102. }
  178103. }
  178104. }
  178105. /*
  178106. * Map some rows of pixels to the output colormapped representation.
  178107. */
  178108. METHODDEF(void)
  178109. pass2_no_dither (j_decompress_ptr cinfo,
  178110. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178111. /* This version performs no dithering */
  178112. {
  178113. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178114. hist3d histogram = cquantize->histogram;
  178115. register JSAMPROW inptr, outptr;
  178116. register histptr cachep;
  178117. register int c0, c1, c2;
  178118. int row;
  178119. JDIMENSION col;
  178120. JDIMENSION width = cinfo->output_width;
  178121. for (row = 0; row < num_rows; row++) {
  178122. inptr = input_buf[row];
  178123. outptr = output_buf[row];
  178124. for (col = width; col > 0; col--) {
  178125. /* get pixel value and index into the cache */
  178126. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178127. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178128. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178129. cachep = & histogram[c0][c1][c2];
  178130. /* If we have not seen this color before, find nearest colormap entry */
  178131. /* and update the cache */
  178132. if (*cachep == 0)
  178133. fill_inverse_cmap(cinfo, c0,c1,c2);
  178134. /* Now emit the colormap index for this cell */
  178135. *outptr++ = (JSAMPLE) (*cachep - 1);
  178136. }
  178137. }
  178138. }
  178139. METHODDEF(void)
  178140. pass2_fs_dither (j_decompress_ptr cinfo,
  178141. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178142. /* This version performs Floyd-Steinberg dithering */
  178143. {
  178144. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178145. hist3d histogram = cquantize->histogram;
  178146. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178147. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178148. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178149. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178150. JSAMPROW inptr; /* => current input pixel */
  178151. JSAMPROW outptr; /* => current output pixel */
  178152. histptr cachep;
  178153. int dir; /* +1 or -1 depending on direction */
  178154. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178155. int row;
  178156. JDIMENSION col;
  178157. JDIMENSION width = cinfo->output_width;
  178158. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178159. int *error_limit = cquantize->error_limiter;
  178160. JSAMPROW colormap0 = cinfo->colormap[0];
  178161. JSAMPROW colormap1 = cinfo->colormap[1];
  178162. JSAMPROW colormap2 = cinfo->colormap[2];
  178163. SHIFT_TEMPS
  178164. for (row = 0; row < num_rows; row++) {
  178165. inptr = input_buf[row];
  178166. outptr = output_buf[row];
  178167. if (cquantize->on_odd_row) {
  178168. /* work right to left in this row */
  178169. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178170. outptr += width-1;
  178171. dir = -1;
  178172. dir3 = -3;
  178173. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178174. cquantize->on_odd_row = FALSE; /* flip for next time */
  178175. } else {
  178176. /* work left to right in this row */
  178177. dir = 1;
  178178. dir3 = 3;
  178179. errorptr = cquantize->fserrors; /* => entry before first real column */
  178180. cquantize->on_odd_row = TRUE; /* flip for next time */
  178181. }
  178182. /* Preset error values: no error propagated to first pixel from left */
  178183. cur0 = cur1 = cur2 = 0;
  178184. /* and no error propagated to row below yet */
  178185. belowerr0 = belowerr1 = belowerr2 = 0;
  178186. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178187. for (col = width; col > 0; col--) {
  178188. /* curN holds the error propagated from the previous pixel on the
  178189. * current line. Add the error propagated from the previous line
  178190. * to form the complete error correction term for this pixel, and
  178191. * round the error term (which is expressed * 16) to an integer.
  178192. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178193. * for either sign of the error value.
  178194. * Note: errorptr points to *previous* column's array entry.
  178195. */
  178196. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178197. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178198. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178199. /* Limit the error using transfer function set by init_error_limit.
  178200. * See comments with init_error_limit for rationale.
  178201. */
  178202. cur0 = error_limit[cur0];
  178203. cur1 = error_limit[cur1];
  178204. cur2 = error_limit[cur2];
  178205. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178206. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178207. * this sets the required size of the range_limit array.
  178208. */
  178209. cur0 += GETJSAMPLE(inptr[0]);
  178210. cur1 += GETJSAMPLE(inptr[1]);
  178211. cur2 += GETJSAMPLE(inptr[2]);
  178212. cur0 = GETJSAMPLE(range_limit[cur0]);
  178213. cur1 = GETJSAMPLE(range_limit[cur1]);
  178214. cur2 = GETJSAMPLE(range_limit[cur2]);
  178215. /* Index into the cache with adjusted pixel value */
  178216. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178217. /* If we have not seen this color before, find nearest colormap */
  178218. /* entry and update the cache */
  178219. if (*cachep == 0)
  178220. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178221. /* Now emit the colormap index for this cell */
  178222. { register int pixcode = *cachep - 1;
  178223. *outptr = (JSAMPLE) pixcode;
  178224. /* Compute representation error for this pixel */
  178225. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178226. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178227. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178228. }
  178229. /* Compute error fractions to be propagated to adjacent pixels.
  178230. * Add these into the running sums, and simultaneously shift the
  178231. * next-line error sums left by 1 column.
  178232. */
  178233. { register LOCFSERROR bnexterr, delta;
  178234. bnexterr = cur0; /* Process component 0 */
  178235. delta = cur0 * 2;
  178236. cur0 += delta; /* form error * 3 */
  178237. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178238. cur0 += delta; /* form error * 5 */
  178239. bpreverr0 = belowerr0 + cur0;
  178240. belowerr0 = bnexterr;
  178241. cur0 += delta; /* form error * 7 */
  178242. bnexterr = cur1; /* Process component 1 */
  178243. delta = cur1 * 2;
  178244. cur1 += delta; /* form error * 3 */
  178245. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178246. cur1 += delta; /* form error * 5 */
  178247. bpreverr1 = belowerr1 + cur1;
  178248. belowerr1 = bnexterr;
  178249. cur1 += delta; /* form error * 7 */
  178250. bnexterr = cur2; /* Process component 2 */
  178251. delta = cur2 * 2;
  178252. cur2 += delta; /* form error * 3 */
  178253. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178254. cur2 += delta; /* form error * 5 */
  178255. bpreverr2 = belowerr2 + cur2;
  178256. belowerr2 = bnexterr;
  178257. cur2 += delta; /* form error * 7 */
  178258. }
  178259. /* At this point curN contains the 7/16 error value to be propagated
  178260. * to the next pixel on the current line, and all the errors for the
  178261. * next line have been shifted over. We are therefore ready to move on.
  178262. */
  178263. inptr += dir3; /* Advance pixel pointers to next column */
  178264. outptr += dir;
  178265. errorptr += dir3; /* advance errorptr to current column */
  178266. }
  178267. /* Post-loop cleanup: we must unload the final error values into the
  178268. * final fserrors[] entry. Note we need not unload belowerrN because
  178269. * it is for the dummy column before or after the actual array.
  178270. */
  178271. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178272. errorptr[1] = (FSERROR) bpreverr1;
  178273. errorptr[2] = (FSERROR) bpreverr2;
  178274. }
  178275. }
  178276. /*
  178277. * Initialize the error-limiting transfer function (lookup table).
  178278. * The raw F-S error computation can potentially compute error values of up to
  178279. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178280. * much less, otherwise obviously wrong pixels will be created. (Typical
  178281. * effects include weird fringes at color-area boundaries, isolated bright
  178282. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178283. * is to ensure that the "corners" of the color cube are allocated as output
  178284. * colors; then repeated errors in the same direction cannot cause cascading
  178285. * error buildup. However, that only prevents the error from getting
  178286. * completely out of hand; Aaron Giles reports that error limiting improves
  178287. * the results even with corner colors allocated.
  178288. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178289. * well, but the smoother transfer function used below is even better. Thanks
  178290. * to Aaron Giles for this idea.
  178291. */
  178292. LOCAL(void)
  178293. init_error_limit (j_decompress_ptr cinfo)
  178294. /* Allocate and fill in the error_limiter table */
  178295. {
  178296. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178297. int * table;
  178298. int in, out;
  178299. table = (int *) (*cinfo->mem->alloc_small)
  178300. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178301. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178302. cquantize->error_limiter = table;
  178303. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178304. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178305. out = 0;
  178306. for (in = 0; in < STEPSIZE; in++, out++) {
  178307. table[in] = out; table[-in] = -out;
  178308. }
  178309. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178310. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178311. table[in] = out; table[-in] = -out;
  178312. }
  178313. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178314. for (; in <= MAXJSAMPLE; in++) {
  178315. table[in] = out; table[-in] = -out;
  178316. }
  178317. #undef STEPSIZE
  178318. }
  178319. /*
  178320. * Finish up at the end of each pass.
  178321. */
  178322. METHODDEF(void)
  178323. finish_pass1 (j_decompress_ptr cinfo)
  178324. {
  178325. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178326. /* Select the representative colors and fill in cinfo->colormap */
  178327. cinfo->colormap = cquantize->sv_colormap;
  178328. select_colors(cinfo, cquantize->desired);
  178329. /* Force next pass to zero the color index table */
  178330. cquantize->needs_zeroed = TRUE;
  178331. }
  178332. METHODDEF(void)
  178333. finish_pass2 (j_decompress_ptr)
  178334. {
  178335. /* no work */
  178336. }
  178337. /*
  178338. * Initialize for each processing pass.
  178339. */
  178340. METHODDEF(void)
  178341. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178342. {
  178343. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178344. hist3d histogram = cquantize->histogram;
  178345. int i;
  178346. /* Only F-S dithering or no dithering is supported. */
  178347. /* If user asks for ordered dither, give him F-S. */
  178348. if (cinfo->dither_mode != JDITHER_NONE)
  178349. cinfo->dither_mode = JDITHER_FS;
  178350. if (is_pre_scan) {
  178351. /* Set up method pointers */
  178352. cquantize->pub.color_quantize = prescan_quantize;
  178353. cquantize->pub.finish_pass = finish_pass1;
  178354. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178355. } else {
  178356. /* Set up method pointers */
  178357. if (cinfo->dither_mode == JDITHER_FS)
  178358. cquantize->pub.color_quantize = pass2_fs_dither;
  178359. else
  178360. cquantize->pub.color_quantize = pass2_no_dither;
  178361. cquantize->pub.finish_pass = finish_pass2;
  178362. /* Make sure color count is acceptable */
  178363. i = cinfo->actual_number_of_colors;
  178364. if (i < 1)
  178365. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178366. if (i > MAXNUMCOLORS)
  178367. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178368. if (cinfo->dither_mode == JDITHER_FS) {
  178369. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178370. (3 * SIZEOF(FSERROR)));
  178371. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178372. if (cquantize->fserrors == NULL)
  178373. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178374. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178375. /* Initialize the propagated errors to zero. */
  178376. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178377. /* Make the error-limit table if we didn't already. */
  178378. if (cquantize->error_limiter == NULL)
  178379. init_error_limit(cinfo);
  178380. cquantize->on_odd_row = FALSE;
  178381. }
  178382. }
  178383. /* Zero the histogram or inverse color map, if necessary */
  178384. if (cquantize->needs_zeroed) {
  178385. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178386. jzero_far((void FAR *) histogram[i],
  178387. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178388. }
  178389. cquantize->needs_zeroed = FALSE;
  178390. }
  178391. }
  178392. /*
  178393. * Switch to a new external colormap between output passes.
  178394. */
  178395. METHODDEF(void)
  178396. new_color_map_2_quant (j_decompress_ptr cinfo)
  178397. {
  178398. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178399. /* Reset the inverse color map */
  178400. cquantize->needs_zeroed = TRUE;
  178401. }
  178402. /*
  178403. * Module initialization routine for 2-pass color quantization.
  178404. */
  178405. GLOBAL(void)
  178406. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178407. {
  178408. my_cquantize_ptr2 cquantize;
  178409. int i;
  178410. cquantize = (my_cquantize_ptr2)
  178411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178412. SIZEOF(my_cquantizer2));
  178413. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178414. cquantize->pub.start_pass = start_pass_2_quant;
  178415. cquantize->pub.new_color_map = new_color_map_2_quant;
  178416. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178417. cquantize->error_limiter = NULL;
  178418. /* Make sure jdmaster didn't give me a case I can't handle */
  178419. if (cinfo->out_color_components != 3)
  178420. ERREXIT(cinfo, JERR_NOTIMPL);
  178421. /* Allocate the histogram/inverse colormap storage */
  178422. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178423. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178424. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178425. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178426. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178427. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178428. }
  178429. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178430. /* Allocate storage for the completed colormap, if required.
  178431. * We do this now since it is FAR storage and may affect
  178432. * the memory manager's space calculations.
  178433. */
  178434. if (cinfo->enable_2pass_quant) {
  178435. /* Make sure color count is acceptable */
  178436. int desired = cinfo->desired_number_of_colors;
  178437. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178438. if (desired < 8)
  178439. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178440. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178441. if (desired > MAXNUMCOLORS)
  178442. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178443. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178444. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178445. cquantize->desired = desired;
  178446. } else
  178447. cquantize->sv_colormap = NULL;
  178448. /* Only F-S dithering or no dithering is supported. */
  178449. /* If user asks for ordered dither, give him F-S. */
  178450. if (cinfo->dither_mode != JDITHER_NONE)
  178451. cinfo->dither_mode = JDITHER_FS;
  178452. /* Allocate Floyd-Steinberg workspace if necessary.
  178453. * This isn't really needed until pass 2, but again it is FAR storage.
  178454. * Although we will cope with a later change in dither_mode,
  178455. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178456. */
  178457. if (cinfo->dither_mode == JDITHER_FS) {
  178458. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178459. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178460. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178461. /* Might as well create the error-limiting table too. */
  178462. init_error_limit(cinfo);
  178463. }
  178464. }
  178465. #endif /* QUANT_2PASS_SUPPORTED */
  178466. /*** End of inlined file: jquant2.c ***/
  178467. /*** Start of inlined file: jutils.c ***/
  178468. #define JPEG_INTERNALS
  178469. /*
  178470. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178471. * of a DCT block read in natural order (left to right, top to bottom).
  178472. */
  178473. #if 0 /* This table is not actually needed in v6a */
  178474. const int jpeg_zigzag_order[DCTSIZE2] = {
  178475. 0, 1, 5, 6, 14, 15, 27, 28,
  178476. 2, 4, 7, 13, 16, 26, 29, 42,
  178477. 3, 8, 12, 17, 25, 30, 41, 43,
  178478. 9, 11, 18, 24, 31, 40, 44, 53,
  178479. 10, 19, 23, 32, 39, 45, 52, 54,
  178480. 20, 22, 33, 38, 46, 51, 55, 60,
  178481. 21, 34, 37, 47, 50, 56, 59, 61,
  178482. 35, 36, 48, 49, 57, 58, 62, 63
  178483. };
  178484. #endif
  178485. /*
  178486. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178487. * of zigzag order.
  178488. *
  178489. * When reading corrupted data, the Huffman decoders could attempt
  178490. * to reference an entry beyond the end of this array (if the decoded
  178491. * zero run length reaches past the end of the block). To prevent
  178492. * wild stores without adding an inner-loop test, we put some extra
  178493. * "63"s after the real entries. This will cause the extra coefficient
  178494. * to be stored in location 63 of the block, not somewhere random.
  178495. * The worst case would be a run-length of 15, which means we need 16
  178496. * fake entries.
  178497. */
  178498. const int jpeg_natural_order[DCTSIZE2+16] = {
  178499. 0, 1, 8, 16, 9, 2, 3, 10,
  178500. 17, 24, 32, 25, 18, 11, 4, 5,
  178501. 12, 19, 26, 33, 40, 48, 41, 34,
  178502. 27, 20, 13, 6, 7, 14, 21, 28,
  178503. 35, 42, 49, 56, 57, 50, 43, 36,
  178504. 29, 22, 15, 23, 30, 37, 44, 51,
  178505. 58, 59, 52, 45, 38, 31, 39, 46,
  178506. 53, 60, 61, 54, 47, 55, 62, 63,
  178507. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178508. 63, 63, 63, 63, 63, 63, 63, 63
  178509. };
  178510. /*
  178511. * Arithmetic utilities
  178512. */
  178513. GLOBAL(long)
  178514. jdiv_round_up (long a, long b)
  178515. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178516. /* Assumes a >= 0, b > 0 */
  178517. {
  178518. return (a + b - 1L) / b;
  178519. }
  178520. GLOBAL(long)
  178521. jround_up (long a, long b)
  178522. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178523. /* Assumes a >= 0, b > 0 */
  178524. {
  178525. a += b - 1L;
  178526. return a - (a % b);
  178527. }
  178528. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178529. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178530. * are FAR and we're assuming a small-pointer memory model. However, some
  178531. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178532. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178533. * Otherwise, the routines below do it the hard way. (The performance cost
  178534. * is not all that great, because these routines aren't very heavily used.)
  178535. */
  178536. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178537. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178538. #define FMEMZERO(target,size) MEMZERO(target,size)
  178539. #else /* 80x86 case, define if we can */
  178540. #ifdef USE_FMEM
  178541. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178542. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178543. #endif
  178544. #endif
  178545. GLOBAL(void)
  178546. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178547. JSAMPARRAY output_array, int dest_row,
  178548. int num_rows, JDIMENSION num_cols)
  178549. /* Copy some rows of samples from one place to another.
  178550. * num_rows rows are copied from input_array[source_row++]
  178551. * to output_array[dest_row++]; these areas may overlap for duplication.
  178552. * The source and destination arrays must be at least as wide as num_cols.
  178553. */
  178554. {
  178555. register JSAMPROW inptr, outptr;
  178556. #ifdef FMEMCOPY
  178557. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178558. #else
  178559. register JDIMENSION count;
  178560. #endif
  178561. register int row;
  178562. input_array += source_row;
  178563. output_array += dest_row;
  178564. for (row = num_rows; row > 0; row--) {
  178565. inptr = *input_array++;
  178566. outptr = *output_array++;
  178567. #ifdef FMEMCOPY
  178568. FMEMCOPY(outptr, inptr, count);
  178569. #else
  178570. for (count = num_cols; count > 0; count--)
  178571. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178572. #endif
  178573. }
  178574. }
  178575. GLOBAL(void)
  178576. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178577. JDIMENSION num_blocks)
  178578. /* Copy a row of coefficient blocks from one place to another. */
  178579. {
  178580. #ifdef FMEMCOPY
  178581. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178582. #else
  178583. register JCOEFPTR inptr, outptr;
  178584. register long count;
  178585. inptr = (JCOEFPTR) input_row;
  178586. outptr = (JCOEFPTR) output_row;
  178587. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178588. *outptr++ = *inptr++;
  178589. }
  178590. #endif
  178591. }
  178592. GLOBAL(void)
  178593. jzero_far (void FAR * target, size_t bytestozero)
  178594. /* Zero out a chunk of FAR memory. */
  178595. /* This might be sample-array data, block-array data, or alloc_large data. */
  178596. {
  178597. #ifdef FMEMZERO
  178598. FMEMZERO(target, bytestozero);
  178599. #else
  178600. register char FAR * ptr = (char FAR *) target;
  178601. register size_t count;
  178602. for (count = bytestozero; count > 0; count--) {
  178603. *ptr++ = 0;
  178604. }
  178605. #endif
  178606. }
  178607. /*** End of inlined file: jutils.c ***/
  178608. /*** Start of inlined file: transupp.c ***/
  178609. /* Although this file really shouldn't have access to the library internals,
  178610. * it's helpful to let it call jround_up() and jcopy_block_row().
  178611. */
  178612. #define JPEG_INTERNALS
  178613. /*** Start of inlined file: transupp.h ***/
  178614. /* If you happen not to want the image transform support, disable it here */
  178615. #ifndef TRANSFORMS_SUPPORTED
  178616. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178617. #endif
  178618. /* Short forms of external names for systems with brain-damaged linkers. */
  178619. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178620. #define jtransform_request_workspace jTrRequest
  178621. #define jtransform_adjust_parameters jTrAdjust
  178622. #define jtransform_execute_transformation jTrExec
  178623. #define jcopy_markers_setup jCMrkSetup
  178624. #define jcopy_markers_execute jCMrkExec
  178625. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178626. /*
  178627. * Codes for supported types of image transformations.
  178628. */
  178629. typedef enum {
  178630. JXFORM_NONE, /* no transformation */
  178631. JXFORM_FLIP_H, /* horizontal flip */
  178632. JXFORM_FLIP_V, /* vertical flip */
  178633. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178634. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178635. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178636. JXFORM_ROT_180, /* 180-degree rotation */
  178637. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178638. } JXFORM_CODE;
  178639. /*
  178640. * Although rotating and flipping data expressed as DCT coefficients is not
  178641. * hard, there is an asymmetry in the JPEG format specification for images
  178642. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178643. * image edges are padded out to the next iMCU boundary with junk data; but
  178644. * no padding is possible at the top and left edges. If we were to flip
  178645. * the whole image including the pad data, then pad garbage would become
  178646. * visible at the top and/or left, and real pixels would disappear into the
  178647. * pad margins --- perhaps permanently, since encoders & decoders may not
  178648. * bother to preserve DCT blocks that appear to be completely outside the
  178649. * nominal image area. So, we have to exclude any partial iMCUs from the
  178650. * basic transformation.
  178651. *
  178652. * Transpose is the only transformation that can handle partial iMCUs at the
  178653. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178654. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178655. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178656. * The other transforms are defined as combinations of these basic transforms
  178657. * and process edge blocks in a way that preserves the equivalence.
  178658. *
  178659. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178660. * this is not strictly lossless, but it usually gives the best-looking
  178661. * result for odd-size images. Note that when this option is active,
  178662. * the expected mathematical equivalences between the transforms may not hold.
  178663. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178664. * followed by -rot 180 -trim trims both edges.)
  178665. *
  178666. * We also offer a "force to grayscale" option, which simply discards the
  178667. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178668. * the luminance channel is preserved exactly. It's not the same kind of
  178669. * thing as the rotate/flip transformations, but it's convenient to handle it
  178670. * as part of this package, mainly because the transformation routines have to
  178671. * be aware of the option to know how many components to work on.
  178672. */
  178673. typedef struct {
  178674. /* Options: set by caller */
  178675. JXFORM_CODE transform; /* image transform operator */
  178676. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178677. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178678. /* Internal workspace: caller should not touch these */
  178679. int num_components; /* # of components in workspace */
  178680. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178681. } jpeg_transform_info;
  178682. #if TRANSFORMS_SUPPORTED
  178683. /* Request any required workspace */
  178684. EXTERN(void) jtransform_request_workspace
  178685. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178686. /* Adjust output image parameters */
  178687. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178688. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178689. jvirt_barray_ptr *src_coef_arrays,
  178690. jpeg_transform_info *info));
  178691. /* Execute the actual transformation, if any */
  178692. EXTERN(void) jtransform_execute_transformation
  178693. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178694. jvirt_barray_ptr *src_coef_arrays,
  178695. jpeg_transform_info *info));
  178696. #endif /* TRANSFORMS_SUPPORTED */
  178697. /*
  178698. * Support for copying optional markers from source to destination file.
  178699. */
  178700. typedef enum {
  178701. JCOPYOPT_NONE, /* copy no optional markers */
  178702. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178703. JCOPYOPT_ALL /* copy all optional markers */
  178704. } JCOPY_OPTION;
  178705. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178706. /* Setup decompression object to save desired markers in memory */
  178707. EXTERN(void) jcopy_markers_setup
  178708. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178709. /* Copy markers saved in the given source object to the destination object */
  178710. EXTERN(void) jcopy_markers_execute
  178711. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178712. JCOPY_OPTION option));
  178713. /*** End of inlined file: transupp.h ***/
  178714. /* My own external interface */
  178715. #if TRANSFORMS_SUPPORTED
  178716. /*
  178717. * Lossless image transformation routines. These routines work on DCT
  178718. * coefficient arrays and thus do not require any lossy decompression
  178719. * or recompression of the image.
  178720. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178721. *
  178722. * Horizontal flipping is done in-place, using a single top-to-bottom
  178723. * pass through the virtual source array. It will thus be much the
  178724. * fastest option for images larger than main memory.
  178725. *
  178726. * The other routines require a set of destination virtual arrays, so they
  178727. * need twice as much memory as jpegtran normally does. The destination
  178728. * arrays are always written in normal scan order (top to bottom) because
  178729. * the virtual array manager expects this. The source arrays will be scanned
  178730. * in the corresponding order, which means multiple passes through the source
  178731. * arrays for most of the transforms. That could result in much thrashing
  178732. * if the image is larger than main memory.
  178733. *
  178734. * Some notes about the operating environment of the individual transform
  178735. * routines:
  178736. * 1. Both the source and destination virtual arrays are allocated from the
  178737. * source JPEG object, and therefore should be manipulated by calling the
  178738. * source's memory manager.
  178739. * 2. The destination's component count should be used. It may be smaller
  178740. * than the source's when forcing to grayscale.
  178741. * 3. Likewise the destination's sampling factors should be used. When
  178742. * forcing to grayscale the destination's sampling factors will be all 1,
  178743. * and we may as well take that as the effective iMCU size.
  178744. * 4. When "trim" is in effect, the destination's dimensions will be the
  178745. * trimmed values but the source's will be untrimmed.
  178746. * 5. All the routines assume that the source and destination buffers are
  178747. * padded out to a full iMCU boundary. This is true, although for the
  178748. * source buffer it is an undocumented property of jdcoefct.c.
  178749. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178750. * dimensions and ignore the source's.
  178751. */
  178752. LOCAL(void)
  178753. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178754. jvirt_barray_ptr *src_coef_arrays)
  178755. /* Horizontal flip; done in-place, so no separate dest array is required */
  178756. {
  178757. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178758. int ci, k, offset_y;
  178759. JBLOCKARRAY buffer;
  178760. JCOEFPTR ptr1, ptr2;
  178761. JCOEF temp1, temp2;
  178762. jpeg_component_info *compptr;
  178763. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178764. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178765. * mirroring by changing the signs of odd-numbered columns.
  178766. * Partial iMCUs at the right edge are left untouched.
  178767. */
  178768. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178769. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178770. compptr = dstinfo->comp_info + ci;
  178771. comp_width = MCU_cols * compptr->h_samp_factor;
  178772. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178773. blk_y += compptr->v_samp_factor) {
  178774. buffer = (*srcinfo->mem->access_virt_barray)
  178775. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178776. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178777. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178778. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178779. ptr1 = buffer[offset_y][blk_x];
  178780. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178781. /* this unrolled loop doesn't need to know which row it's on... */
  178782. for (k = 0; k < DCTSIZE2; k += 2) {
  178783. temp1 = *ptr1; /* swap even column */
  178784. temp2 = *ptr2;
  178785. *ptr1++ = temp2;
  178786. *ptr2++ = temp1;
  178787. temp1 = *ptr1; /* swap odd column with sign change */
  178788. temp2 = *ptr2;
  178789. *ptr1++ = -temp2;
  178790. *ptr2++ = -temp1;
  178791. }
  178792. }
  178793. }
  178794. }
  178795. }
  178796. }
  178797. LOCAL(void)
  178798. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178799. jvirt_barray_ptr *src_coef_arrays,
  178800. jvirt_barray_ptr *dst_coef_arrays)
  178801. /* Vertical flip */
  178802. {
  178803. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178804. int ci, i, j, offset_y;
  178805. JBLOCKARRAY src_buffer, dst_buffer;
  178806. JBLOCKROW src_row_ptr, dst_row_ptr;
  178807. JCOEFPTR src_ptr, dst_ptr;
  178808. jpeg_component_info *compptr;
  178809. /* We output into a separate array because we can't touch different
  178810. * rows of the source virtual array simultaneously. Otherwise, this
  178811. * is a pretty straightforward analog of horizontal flip.
  178812. * Within a DCT block, vertical mirroring is done by changing the signs
  178813. * of odd-numbered rows.
  178814. * Partial iMCUs at the bottom edge are copied verbatim.
  178815. */
  178816. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178817. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178818. compptr = dstinfo->comp_info + ci;
  178819. comp_height = MCU_rows * compptr->v_samp_factor;
  178820. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178821. dst_blk_y += compptr->v_samp_factor) {
  178822. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178823. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178824. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178825. if (dst_blk_y < comp_height) {
  178826. /* Row is within the mirrorable area. */
  178827. src_buffer = (*srcinfo->mem->access_virt_barray)
  178828. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178829. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178830. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178831. } else {
  178832. /* Bottom-edge blocks will be copied verbatim. */
  178833. src_buffer = (*srcinfo->mem->access_virt_barray)
  178834. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178835. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178836. }
  178837. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178838. if (dst_blk_y < comp_height) {
  178839. /* Row is within the mirrorable area. */
  178840. dst_row_ptr = dst_buffer[offset_y];
  178841. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178842. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178843. dst_blk_x++) {
  178844. dst_ptr = dst_row_ptr[dst_blk_x];
  178845. src_ptr = src_row_ptr[dst_blk_x];
  178846. for (i = 0; i < DCTSIZE; i += 2) {
  178847. /* copy even row */
  178848. for (j = 0; j < DCTSIZE; j++)
  178849. *dst_ptr++ = *src_ptr++;
  178850. /* copy odd row with sign change */
  178851. for (j = 0; j < DCTSIZE; j++)
  178852. *dst_ptr++ = - *src_ptr++;
  178853. }
  178854. }
  178855. } else {
  178856. /* Just copy row verbatim. */
  178857. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178858. compptr->width_in_blocks);
  178859. }
  178860. }
  178861. }
  178862. }
  178863. }
  178864. LOCAL(void)
  178865. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178866. jvirt_barray_ptr *src_coef_arrays,
  178867. jvirt_barray_ptr *dst_coef_arrays)
  178868. /* Transpose source into destination */
  178869. {
  178870. JDIMENSION dst_blk_x, dst_blk_y;
  178871. int ci, i, j, offset_x, offset_y;
  178872. JBLOCKARRAY src_buffer, dst_buffer;
  178873. JCOEFPTR src_ptr, dst_ptr;
  178874. jpeg_component_info *compptr;
  178875. /* Transposing pixels within a block just requires transposing the
  178876. * DCT coefficients.
  178877. * Partial iMCUs at the edges require no special treatment; we simply
  178878. * process all the available DCT blocks for every component.
  178879. */
  178880. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178881. compptr = dstinfo->comp_info + ci;
  178882. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178883. dst_blk_y += compptr->v_samp_factor) {
  178884. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178885. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178886. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178887. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178888. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178889. dst_blk_x += compptr->h_samp_factor) {
  178890. src_buffer = (*srcinfo->mem->access_virt_barray)
  178891. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178892. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178893. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178894. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178895. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178896. for (i = 0; i < DCTSIZE; i++)
  178897. for (j = 0; j < DCTSIZE; j++)
  178898. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178899. }
  178900. }
  178901. }
  178902. }
  178903. }
  178904. }
  178905. LOCAL(void)
  178906. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178907. jvirt_barray_ptr *src_coef_arrays,
  178908. jvirt_barray_ptr *dst_coef_arrays)
  178909. /* 90 degree rotation is equivalent to
  178910. * 1. Transposing the image;
  178911. * 2. Horizontal mirroring.
  178912. * These two steps are merged into a single processing routine.
  178913. */
  178914. {
  178915. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178916. int ci, i, j, offset_x, offset_y;
  178917. JBLOCKARRAY src_buffer, dst_buffer;
  178918. JCOEFPTR src_ptr, dst_ptr;
  178919. jpeg_component_info *compptr;
  178920. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178921. * at the (output) right edge properly. They just get transposed and
  178922. * not mirrored.
  178923. */
  178924. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178925. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178926. compptr = dstinfo->comp_info + ci;
  178927. comp_width = MCU_cols * compptr->h_samp_factor;
  178928. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178929. dst_blk_y += compptr->v_samp_factor) {
  178930. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178931. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178932. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178933. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178934. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178935. dst_blk_x += compptr->h_samp_factor) {
  178936. src_buffer = (*srcinfo->mem->access_virt_barray)
  178937. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178938. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178939. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178940. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178941. if (dst_blk_x < comp_width) {
  178942. /* Block is within the mirrorable area. */
  178943. dst_ptr = dst_buffer[offset_y]
  178944. [comp_width - dst_blk_x - offset_x - 1];
  178945. for (i = 0; i < DCTSIZE; i++) {
  178946. for (j = 0; j < DCTSIZE; j++)
  178947. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178948. i++;
  178949. for (j = 0; j < DCTSIZE; j++)
  178950. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178951. }
  178952. } else {
  178953. /* Edge blocks are transposed but not mirrored. */
  178954. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178955. for (i = 0; i < DCTSIZE; i++)
  178956. for (j = 0; j < DCTSIZE; j++)
  178957. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178958. }
  178959. }
  178960. }
  178961. }
  178962. }
  178963. }
  178964. }
  178965. LOCAL(void)
  178966. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178967. jvirt_barray_ptr *src_coef_arrays,
  178968. jvirt_barray_ptr *dst_coef_arrays)
  178969. /* 270 degree rotation is equivalent to
  178970. * 1. Horizontal mirroring;
  178971. * 2. Transposing the image.
  178972. * These two steps are merged into a single processing routine.
  178973. */
  178974. {
  178975. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178976. int ci, i, j, offset_x, offset_y;
  178977. JBLOCKARRAY src_buffer, dst_buffer;
  178978. JCOEFPTR src_ptr, dst_ptr;
  178979. jpeg_component_info *compptr;
  178980. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178981. * at the (output) bottom edge properly. They just get transposed and
  178982. * not mirrored.
  178983. */
  178984. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178985. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178986. compptr = dstinfo->comp_info + ci;
  178987. comp_height = MCU_rows * compptr->v_samp_factor;
  178988. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178989. dst_blk_y += compptr->v_samp_factor) {
  178990. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178991. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178992. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178993. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178994. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178995. dst_blk_x += compptr->h_samp_factor) {
  178996. src_buffer = (*srcinfo->mem->access_virt_barray)
  178997. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178998. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178999. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179000. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179001. if (dst_blk_y < comp_height) {
  179002. /* Block is within the mirrorable area. */
  179003. src_ptr = src_buffer[offset_x]
  179004. [comp_height - dst_blk_y - offset_y - 1];
  179005. for (i = 0; i < DCTSIZE; i++) {
  179006. for (j = 0; j < DCTSIZE; j++) {
  179007. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179008. j++;
  179009. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179010. }
  179011. }
  179012. } else {
  179013. /* Edge blocks are transposed but not mirrored. */
  179014. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179015. for (i = 0; i < DCTSIZE; i++)
  179016. for (j = 0; j < DCTSIZE; j++)
  179017. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179018. }
  179019. }
  179020. }
  179021. }
  179022. }
  179023. }
  179024. }
  179025. LOCAL(void)
  179026. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179027. jvirt_barray_ptr *src_coef_arrays,
  179028. jvirt_barray_ptr *dst_coef_arrays)
  179029. /* 180 degree rotation is equivalent to
  179030. * 1. Vertical mirroring;
  179031. * 2. Horizontal mirroring.
  179032. * These two steps are merged into a single processing routine.
  179033. */
  179034. {
  179035. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179036. int ci, i, j, offset_y;
  179037. JBLOCKARRAY src_buffer, dst_buffer;
  179038. JBLOCKROW src_row_ptr, dst_row_ptr;
  179039. JCOEFPTR src_ptr, dst_ptr;
  179040. jpeg_component_info *compptr;
  179041. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179042. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179043. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179044. compptr = dstinfo->comp_info + ci;
  179045. comp_width = MCU_cols * compptr->h_samp_factor;
  179046. comp_height = MCU_rows * compptr->v_samp_factor;
  179047. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179048. dst_blk_y += compptr->v_samp_factor) {
  179049. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179050. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179051. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179052. if (dst_blk_y < comp_height) {
  179053. /* Row is within the vertically mirrorable area. */
  179054. src_buffer = (*srcinfo->mem->access_virt_barray)
  179055. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179056. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179057. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179058. } else {
  179059. /* Bottom-edge rows are only mirrored horizontally. */
  179060. src_buffer = (*srcinfo->mem->access_virt_barray)
  179061. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179062. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179063. }
  179064. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179065. if (dst_blk_y < comp_height) {
  179066. /* Row is within the mirrorable area. */
  179067. dst_row_ptr = dst_buffer[offset_y];
  179068. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179069. /* Process the blocks that can be mirrored both ways. */
  179070. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179071. dst_ptr = dst_row_ptr[dst_blk_x];
  179072. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179073. for (i = 0; i < DCTSIZE; i += 2) {
  179074. /* For even row, negate every odd column. */
  179075. for (j = 0; j < DCTSIZE; j += 2) {
  179076. *dst_ptr++ = *src_ptr++;
  179077. *dst_ptr++ = - *src_ptr++;
  179078. }
  179079. /* For odd row, negate every even column. */
  179080. for (j = 0; j < DCTSIZE; j += 2) {
  179081. *dst_ptr++ = - *src_ptr++;
  179082. *dst_ptr++ = *src_ptr++;
  179083. }
  179084. }
  179085. }
  179086. /* Any remaining right-edge blocks are only mirrored vertically. */
  179087. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179088. dst_ptr = dst_row_ptr[dst_blk_x];
  179089. src_ptr = src_row_ptr[dst_blk_x];
  179090. for (i = 0; i < DCTSIZE; i += 2) {
  179091. for (j = 0; j < DCTSIZE; j++)
  179092. *dst_ptr++ = *src_ptr++;
  179093. for (j = 0; j < DCTSIZE; j++)
  179094. *dst_ptr++ = - *src_ptr++;
  179095. }
  179096. }
  179097. } else {
  179098. /* Remaining rows are just mirrored horizontally. */
  179099. dst_row_ptr = dst_buffer[offset_y];
  179100. src_row_ptr = src_buffer[offset_y];
  179101. /* Process the blocks that can be mirrored. */
  179102. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179103. dst_ptr = dst_row_ptr[dst_blk_x];
  179104. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179105. for (i = 0; i < DCTSIZE2; i += 2) {
  179106. *dst_ptr++ = *src_ptr++;
  179107. *dst_ptr++ = - *src_ptr++;
  179108. }
  179109. }
  179110. /* Any remaining right-edge blocks are only copied. */
  179111. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179112. dst_ptr = dst_row_ptr[dst_blk_x];
  179113. src_ptr = src_row_ptr[dst_blk_x];
  179114. for (i = 0; i < DCTSIZE2; i++)
  179115. *dst_ptr++ = *src_ptr++;
  179116. }
  179117. }
  179118. }
  179119. }
  179120. }
  179121. }
  179122. LOCAL(void)
  179123. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179124. jvirt_barray_ptr *src_coef_arrays,
  179125. jvirt_barray_ptr *dst_coef_arrays)
  179126. /* Transverse transpose is equivalent to
  179127. * 1. 180 degree rotation;
  179128. * 2. Transposition;
  179129. * or
  179130. * 1. Horizontal mirroring;
  179131. * 2. Transposition;
  179132. * 3. Horizontal mirroring.
  179133. * These steps are merged into a single processing routine.
  179134. */
  179135. {
  179136. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179137. int ci, i, j, offset_x, offset_y;
  179138. JBLOCKARRAY src_buffer, dst_buffer;
  179139. JCOEFPTR src_ptr, dst_ptr;
  179140. jpeg_component_info *compptr;
  179141. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179142. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179143. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179144. compptr = dstinfo->comp_info + ci;
  179145. comp_width = MCU_cols * compptr->h_samp_factor;
  179146. comp_height = MCU_rows * compptr->v_samp_factor;
  179147. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179148. dst_blk_y += compptr->v_samp_factor) {
  179149. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179150. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179151. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179152. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179153. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179154. dst_blk_x += compptr->h_samp_factor) {
  179155. src_buffer = (*srcinfo->mem->access_virt_barray)
  179156. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179157. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179158. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179159. if (dst_blk_y < comp_height) {
  179160. src_ptr = src_buffer[offset_x]
  179161. [comp_height - dst_blk_y - offset_y - 1];
  179162. if (dst_blk_x < comp_width) {
  179163. /* Block is within the mirrorable area. */
  179164. dst_ptr = dst_buffer[offset_y]
  179165. [comp_width - dst_blk_x - offset_x - 1];
  179166. for (i = 0; i < DCTSIZE; i++) {
  179167. for (j = 0; j < DCTSIZE; j++) {
  179168. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179169. j++;
  179170. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179171. }
  179172. i++;
  179173. for (j = 0; j < DCTSIZE; j++) {
  179174. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179175. j++;
  179176. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179177. }
  179178. }
  179179. } else {
  179180. /* Right-edge blocks are mirrored in y only */
  179181. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179182. for (i = 0; i < DCTSIZE; i++) {
  179183. for (j = 0; j < DCTSIZE; j++) {
  179184. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179185. j++;
  179186. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179187. }
  179188. }
  179189. }
  179190. } else {
  179191. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179192. if (dst_blk_x < comp_width) {
  179193. /* Bottom-edge blocks are mirrored in x only */
  179194. dst_ptr = dst_buffer[offset_y]
  179195. [comp_width - dst_blk_x - offset_x - 1];
  179196. for (i = 0; i < DCTSIZE; i++) {
  179197. for (j = 0; j < DCTSIZE; j++)
  179198. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179199. i++;
  179200. for (j = 0; j < DCTSIZE; j++)
  179201. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179202. }
  179203. } else {
  179204. /* At lower right corner, just transpose, no mirroring */
  179205. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179206. for (i = 0; i < DCTSIZE; i++)
  179207. for (j = 0; j < DCTSIZE; j++)
  179208. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179209. }
  179210. }
  179211. }
  179212. }
  179213. }
  179214. }
  179215. }
  179216. }
  179217. /* Request any required workspace.
  179218. *
  179219. * We allocate the workspace virtual arrays from the source decompression
  179220. * object, so that all the arrays (both the original data and the workspace)
  179221. * will be taken into account while making memory management decisions.
  179222. * Hence, this routine must be called after jpeg_read_header (which reads
  179223. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179224. * the source's virtual arrays).
  179225. */
  179226. GLOBAL(void)
  179227. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179228. jpeg_transform_info *info)
  179229. {
  179230. jvirt_barray_ptr *coef_arrays = NULL;
  179231. jpeg_component_info *compptr;
  179232. int ci;
  179233. if (info->force_grayscale &&
  179234. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179235. srcinfo->num_components == 3) {
  179236. /* We'll only process the first component */
  179237. info->num_components = 1;
  179238. } else {
  179239. /* Process all the components */
  179240. info->num_components = srcinfo->num_components;
  179241. }
  179242. switch (info->transform) {
  179243. case JXFORM_NONE:
  179244. case JXFORM_FLIP_H:
  179245. /* Don't need a workspace array */
  179246. break;
  179247. case JXFORM_FLIP_V:
  179248. case JXFORM_ROT_180:
  179249. /* Need workspace arrays having same dimensions as source image.
  179250. * Note that we allocate arrays padded out to the next iMCU boundary,
  179251. * so that transform routines need not worry about missing edge blocks.
  179252. */
  179253. coef_arrays = (jvirt_barray_ptr *)
  179254. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179255. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179256. for (ci = 0; ci < info->num_components; ci++) {
  179257. compptr = srcinfo->comp_info + ci;
  179258. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179259. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179260. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179261. (long) compptr->h_samp_factor),
  179262. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179263. (long) compptr->v_samp_factor),
  179264. (JDIMENSION) compptr->v_samp_factor);
  179265. }
  179266. break;
  179267. case JXFORM_TRANSPOSE:
  179268. case JXFORM_TRANSVERSE:
  179269. case JXFORM_ROT_90:
  179270. case JXFORM_ROT_270:
  179271. /* Need workspace arrays having transposed dimensions.
  179272. * Note that we allocate arrays padded out to the next iMCU boundary,
  179273. * so that transform routines need not worry about missing edge blocks.
  179274. */
  179275. coef_arrays = (jvirt_barray_ptr *)
  179276. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179277. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179278. for (ci = 0; ci < info->num_components; ci++) {
  179279. compptr = srcinfo->comp_info + ci;
  179280. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179281. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179282. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179283. (long) compptr->v_samp_factor),
  179284. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179285. (long) compptr->h_samp_factor),
  179286. (JDIMENSION) compptr->h_samp_factor);
  179287. }
  179288. break;
  179289. }
  179290. info->workspace_coef_arrays = coef_arrays;
  179291. }
  179292. /* Transpose destination image parameters */
  179293. LOCAL(void)
  179294. transpose_critical_parameters (j_compress_ptr dstinfo)
  179295. {
  179296. int tblno, i, j, ci, itemp;
  179297. jpeg_component_info *compptr;
  179298. JQUANT_TBL *qtblptr;
  179299. JDIMENSION dtemp;
  179300. UINT16 qtemp;
  179301. /* Transpose basic image dimensions */
  179302. dtemp = dstinfo->image_width;
  179303. dstinfo->image_width = dstinfo->image_height;
  179304. dstinfo->image_height = dtemp;
  179305. /* Transpose sampling factors */
  179306. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179307. compptr = dstinfo->comp_info + ci;
  179308. itemp = compptr->h_samp_factor;
  179309. compptr->h_samp_factor = compptr->v_samp_factor;
  179310. compptr->v_samp_factor = itemp;
  179311. }
  179312. /* Transpose quantization tables */
  179313. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179314. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179315. if (qtblptr != NULL) {
  179316. for (i = 0; i < DCTSIZE; i++) {
  179317. for (j = 0; j < i; j++) {
  179318. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179319. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179320. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179321. }
  179322. }
  179323. }
  179324. }
  179325. }
  179326. /* Trim off any partial iMCUs on the indicated destination edge */
  179327. LOCAL(void)
  179328. trim_right_edge (j_compress_ptr dstinfo)
  179329. {
  179330. int ci, max_h_samp_factor;
  179331. JDIMENSION MCU_cols;
  179332. /* We have to compute max_h_samp_factor ourselves,
  179333. * because it hasn't been set yet in the destination
  179334. * (and we don't want to use the source's value).
  179335. */
  179336. max_h_samp_factor = 1;
  179337. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179338. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179339. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179340. }
  179341. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179342. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179343. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179344. }
  179345. LOCAL(void)
  179346. trim_bottom_edge (j_compress_ptr dstinfo)
  179347. {
  179348. int ci, max_v_samp_factor;
  179349. JDIMENSION MCU_rows;
  179350. /* We have to compute max_v_samp_factor ourselves,
  179351. * because it hasn't been set yet in the destination
  179352. * (and we don't want to use the source's value).
  179353. */
  179354. max_v_samp_factor = 1;
  179355. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179356. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179357. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179358. }
  179359. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179360. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179361. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179362. }
  179363. /* Adjust output image parameters as needed.
  179364. *
  179365. * This must be called after jpeg_copy_critical_parameters()
  179366. * and before jpeg_write_coefficients().
  179367. *
  179368. * The return value is the set of virtual coefficient arrays to be written
  179369. * (either the ones allocated by jtransform_request_workspace, or the
  179370. * original source data arrays). The caller will need to pass this value
  179371. * to jpeg_write_coefficients().
  179372. */
  179373. GLOBAL(jvirt_barray_ptr *)
  179374. jtransform_adjust_parameters (j_decompress_ptr,
  179375. j_compress_ptr dstinfo,
  179376. jvirt_barray_ptr *src_coef_arrays,
  179377. jpeg_transform_info *info)
  179378. {
  179379. /* If force-to-grayscale is requested, adjust destination parameters */
  179380. if (info->force_grayscale) {
  179381. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179382. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179383. * will get set to 1, which typically won't match the source.
  179384. * In fact we do this even if the source is already grayscale; that
  179385. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179386. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179387. */
  179388. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179389. dstinfo->num_components == 3) ||
  179390. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179391. dstinfo->num_components == 1)) {
  179392. /* We have to preserve the source's quantization table number. */
  179393. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179394. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179395. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179396. } else {
  179397. /* Sorry, can't do it */
  179398. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179399. }
  179400. }
  179401. /* Correct the destination's image dimensions etc if necessary */
  179402. switch (info->transform) {
  179403. case JXFORM_NONE:
  179404. /* Nothing to do */
  179405. break;
  179406. case JXFORM_FLIP_H:
  179407. if (info->trim)
  179408. trim_right_edge(dstinfo);
  179409. break;
  179410. case JXFORM_FLIP_V:
  179411. if (info->trim)
  179412. trim_bottom_edge(dstinfo);
  179413. break;
  179414. case JXFORM_TRANSPOSE:
  179415. transpose_critical_parameters(dstinfo);
  179416. /* transpose does NOT have to trim anything */
  179417. break;
  179418. case JXFORM_TRANSVERSE:
  179419. transpose_critical_parameters(dstinfo);
  179420. if (info->trim) {
  179421. trim_right_edge(dstinfo);
  179422. trim_bottom_edge(dstinfo);
  179423. }
  179424. break;
  179425. case JXFORM_ROT_90:
  179426. transpose_critical_parameters(dstinfo);
  179427. if (info->trim)
  179428. trim_right_edge(dstinfo);
  179429. break;
  179430. case JXFORM_ROT_180:
  179431. if (info->trim) {
  179432. trim_right_edge(dstinfo);
  179433. trim_bottom_edge(dstinfo);
  179434. }
  179435. break;
  179436. case JXFORM_ROT_270:
  179437. transpose_critical_parameters(dstinfo);
  179438. if (info->trim)
  179439. trim_bottom_edge(dstinfo);
  179440. break;
  179441. }
  179442. /* Return the appropriate output data set */
  179443. if (info->workspace_coef_arrays != NULL)
  179444. return info->workspace_coef_arrays;
  179445. return src_coef_arrays;
  179446. }
  179447. /* Execute the actual transformation, if any.
  179448. *
  179449. * This must be called *after* jpeg_write_coefficients, because it depends
  179450. * on jpeg_write_coefficients to have computed subsidiary values such as
  179451. * the per-component width and height fields in the destination object.
  179452. *
  179453. * Note that some transformations will modify the source data arrays!
  179454. */
  179455. GLOBAL(void)
  179456. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179457. j_compress_ptr dstinfo,
  179458. jvirt_barray_ptr *src_coef_arrays,
  179459. jpeg_transform_info *info)
  179460. {
  179461. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179462. switch (info->transform) {
  179463. case JXFORM_NONE:
  179464. break;
  179465. case JXFORM_FLIP_H:
  179466. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179467. break;
  179468. case JXFORM_FLIP_V:
  179469. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179470. break;
  179471. case JXFORM_TRANSPOSE:
  179472. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179473. break;
  179474. case JXFORM_TRANSVERSE:
  179475. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179476. break;
  179477. case JXFORM_ROT_90:
  179478. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179479. break;
  179480. case JXFORM_ROT_180:
  179481. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179482. break;
  179483. case JXFORM_ROT_270:
  179484. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179485. break;
  179486. }
  179487. }
  179488. #endif /* TRANSFORMS_SUPPORTED */
  179489. /* Setup decompression object to save desired markers in memory.
  179490. * This must be called before jpeg_read_header() to have the desired effect.
  179491. */
  179492. GLOBAL(void)
  179493. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179494. {
  179495. #ifdef SAVE_MARKERS_SUPPORTED
  179496. int m;
  179497. /* Save comments except under NONE option */
  179498. if (option != JCOPYOPT_NONE) {
  179499. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179500. }
  179501. /* Save all types of APPn markers iff ALL option */
  179502. if (option == JCOPYOPT_ALL) {
  179503. for (m = 0; m < 16; m++)
  179504. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179505. }
  179506. #endif /* SAVE_MARKERS_SUPPORTED */
  179507. }
  179508. /* Copy markers saved in the given source object to the destination object.
  179509. * This should be called just after jpeg_start_compress() or
  179510. * jpeg_write_coefficients().
  179511. * Note that those routines will have written the SOI, and also the
  179512. * JFIF APP0 or Adobe APP14 markers if selected.
  179513. */
  179514. GLOBAL(void)
  179515. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179516. JCOPY_OPTION)
  179517. {
  179518. jpeg_saved_marker_ptr marker;
  179519. /* In the current implementation, we don't actually need to examine the
  179520. * option flag here; we just copy everything that got saved.
  179521. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179522. * if the encoder library already wrote one.
  179523. */
  179524. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179525. if (dstinfo->write_JFIF_header &&
  179526. marker->marker == JPEG_APP0 &&
  179527. marker->data_length >= 5 &&
  179528. GETJOCTET(marker->data[0]) == 0x4A &&
  179529. GETJOCTET(marker->data[1]) == 0x46 &&
  179530. GETJOCTET(marker->data[2]) == 0x49 &&
  179531. GETJOCTET(marker->data[3]) == 0x46 &&
  179532. GETJOCTET(marker->data[4]) == 0)
  179533. continue; /* reject duplicate JFIF */
  179534. if (dstinfo->write_Adobe_marker &&
  179535. marker->marker == JPEG_APP0+14 &&
  179536. marker->data_length >= 5 &&
  179537. GETJOCTET(marker->data[0]) == 0x41 &&
  179538. GETJOCTET(marker->data[1]) == 0x64 &&
  179539. GETJOCTET(marker->data[2]) == 0x6F &&
  179540. GETJOCTET(marker->data[3]) == 0x62 &&
  179541. GETJOCTET(marker->data[4]) == 0x65)
  179542. continue; /* reject duplicate Adobe */
  179543. #ifdef NEED_FAR_POINTERS
  179544. /* We could use jpeg_write_marker if the data weren't FAR... */
  179545. {
  179546. unsigned int i;
  179547. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179548. for (i = 0; i < marker->data_length; i++)
  179549. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179550. }
  179551. #else
  179552. jpeg_write_marker(dstinfo, marker->marker,
  179553. marker->data, marker->data_length);
  179554. #endif
  179555. }
  179556. }
  179557. /*** End of inlined file: transupp.c ***/
  179558. #else
  179559. #define JPEG_INTERNALS
  179560. #undef FAR
  179561. #include <jpeglib.h>
  179562. #endif
  179563. }
  179564. #undef max
  179565. #undef min
  179566. #if JUCE_MSVC
  179567. #pragma warning (pop)
  179568. #endif
  179569. BEGIN_JUCE_NAMESPACE
  179570. namespace JPEGHelpers
  179571. {
  179572. using namespace jpeglibNamespace;
  179573. #if ! JUCE_MSVC
  179574. using jpeglibNamespace::boolean;
  179575. #endif
  179576. struct JPEGDecodingFailure {};
  179577. void fatalErrorHandler (j_common_ptr)
  179578. {
  179579. throw JPEGDecodingFailure();
  179580. }
  179581. void silentErrorCallback1 (j_common_ptr) {}
  179582. void silentErrorCallback2 (j_common_ptr, int) {}
  179583. void silentErrorCallback3 (j_common_ptr, char*) {}
  179584. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179585. {
  179586. zerostruct (err);
  179587. err.error_exit = fatalErrorHandler;
  179588. err.emit_message = silentErrorCallback2;
  179589. err.output_message = silentErrorCallback1;
  179590. err.format_message = silentErrorCallback3;
  179591. err.reset_error_mgr = silentErrorCallback1;
  179592. }
  179593. void dummyCallback1 (j_decompress_ptr)
  179594. {
  179595. }
  179596. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179597. {
  179598. decompStruct->src->next_input_byte += num;
  179599. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179600. decompStruct->src->bytes_in_buffer -= num;
  179601. }
  179602. boolean jpegFill (j_decompress_ptr)
  179603. {
  179604. return 0;
  179605. }
  179606. const int jpegBufferSize = 512;
  179607. struct JuceJpegDest : public jpeg_destination_mgr
  179608. {
  179609. OutputStream* output;
  179610. char* buffer;
  179611. };
  179612. void jpegWriteInit (j_compress_ptr)
  179613. {
  179614. }
  179615. void jpegWriteTerminate (j_compress_ptr cinfo)
  179616. {
  179617. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179618. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179619. dest->output->write (dest->buffer, (int) numToWrite);
  179620. }
  179621. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179622. {
  179623. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179624. const int numToWrite = jpegBufferSize;
  179625. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179626. dest->free_in_buffer = jpegBufferSize;
  179627. return dest->output->write (dest->buffer, numToWrite);
  179628. }
  179629. }
  179630. JPEGImageFormat::JPEGImageFormat()
  179631. : quality (-1.0f)
  179632. {
  179633. }
  179634. JPEGImageFormat::~JPEGImageFormat() {}
  179635. void JPEGImageFormat::setQuality (const float newQuality)
  179636. {
  179637. quality = newQuality;
  179638. }
  179639. const String JPEGImageFormat::getFormatName()
  179640. {
  179641. return "JPEG";
  179642. }
  179643. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179644. {
  179645. const int bytesNeeded = 10;
  179646. uint8 header [bytesNeeded];
  179647. if (in.read (header, bytesNeeded) == bytesNeeded)
  179648. {
  179649. return header[0] == 0xff
  179650. && header[1] == 0xd8
  179651. && header[2] == 0xff
  179652. && (header[3] == 0xe0 || header[3] == 0xe1);
  179653. }
  179654. return false;
  179655. }
  179656. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179657. const Image juce_loadWithCoreImage (InputStream& input);
  179658. #endif
  179659. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179660. {
  179661. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179662. return juce_loadWithCoreImage (in);
  179663. #else
  179664. using namespace jpeglibNamespace;
  179665. using namespace JPEGHelpers;
  179666. MemoryOutputStream mb;
  179667. mb.writeFromInputStream (in, -1);
  179668. Image image;
  179669. if (mb.getDataSize() > 16)
  179670. {
  179671. struct jpeg_decompress_struct jpegDecompStruct;
  179672. struct jpeg_error_mgr jerr;
  179673. setupSilentErrorHandler (jerr);
  179674. jpegDecompStruct.err = &jerr;
  179675. jpeg_create_decompress (&jpegDecompStruct);
  179676. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179677. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179678. jpegDecompStruct.src->init_source = dummyCallback1;
  179679. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179680. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179681. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179682. jpegDecompStruct.src->term_source = dummyCallback1;
  179683. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179684. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179685. try
  179686. {
  179687. jpeg_read_header (&jpegDecompStruct, TRUE);
  179688. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179689. const int width = jpegDecompStruct.output_width;
  179690. const int height = jpegDecompStruct.output_height;
  179691. jpegDecompStruct.out_color_space = JCS_RGB;
  179692. JSAMPARRAY buffer
  179693. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179694. JPOOL_IMAGE,
  179695. width * 3, 1);
  179696. if (jpeg_start_decompress (&jpegDecompStruct))
  179697. {
  179698. image = Image (Image::RGB, width, height, false);
  179699. image.getProperties()->set ("originalImageHadAlpha", false);
  179700. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179701. const Image::BitmapData destData (image, true);
  179702. for (int y = 0; y < height; ++y)
  179703. {
  179704. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179705. const uint8* src = *buffer;
  179706. uint8* dest = destData.getLinePointer (y);
  179707. if (hasAlphaChan)
  179708. {
  179709. for (int i = width; --i >= 0;)
  179710. {
  179711. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179712. ((PixelARGB*) dest)->premultiply();
  179713. dest += destData.pixelStride;
  179714. src += 3;
  179715. }
  179716. }
  179717. else
  179718. {
  179719. for (int i = width; --i >= 0;)
  179720. {
  179721. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179722. dest += destData.pixelStride;
  179723. src += 3;
  179724. }
  179725. }
  179726. }
  179727. jpeg_finish_decompress (&jpegDecompStruct);
  179728. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179729. }
  179730. jpeg_destroy_decompress (&jpegDecompStruct);
  179731. }
  179732. catch (...)
  179733. {}
  179734. }
  179735. return image;
  179736. #endif
  179737. }
  179738. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179739. {
  179740. using namespace jpeglibNamespace;
  179741. using namespace JPEGHelpers;
  179742. if (image.hasAlphaChannel())
  179743. {
  179744. // this method could fill the background in white and still save the image..
  179745. jassertfalse;
  179746. return true;
  179747. }
  179748. struct jpeg_compress_struct jpegCompStruct;
  179749. struct jpeg_error_mgr jerr;
  179750. setupSilentErrorHandler (jerr);
  179751. jpegCompStruct.err = &jerr;
  179752. jpeg_create_compress (&jpegCompStruct);
  179753. JuceJpegDest dest;
  179754. jpegCompStruct.dest = &dest;
  179755. dest.output = &out;
  179756. HeapBlock <char> tempBuffer (jpegBufferSize);
  179757. dest.buffer = tempBuffer;
  179758. dest.next_output_byte = (JOCTET*) dest.buffer;
  179759. dest.free_in_buffer = jpegBufferSize;
  179760. dest.init_destination = jpegWriteInit;
  179761. dest.empty_output_buffer = jpegWriteFlush;
  179762. dest.term_destination = jpegWriteTerminate;
  179763. jpegCompStruct.image_width = image.getWidth();
  179764. jpegCompStruct.image_height = image.getHeight();
  179765. jpegCompStruct.input_components = 3;
  179766. jpegCompStruct.in_color_space = JCS_RGB;
  179767. jpegCompStruct.write_JFIF_header = 1;
  179768. jpegCompStruct.X_density = 72;
  179769. jpegCompStruct.Y_density = 72;
  179770. jpeg_set_defaults (&jpegCompStruct);
  179771. jpegCompStruct.dct_method = JDCT_FLOAT;
  179772. jpegCompStruct.optimize_coding = 1;
  179773. //jpegCompStruct.smoothing_factor = 10;
  179774. if (quality < 0.0f)
  179775. quality = 0.85f;
  179776. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179777. jpeg_start_compress (&jpegCompStruct, TRUE);
  179778. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179779. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179780. JPOOL_IMAGE, strideBytes, 1);
  179781. const Image::BitmapData srcData (image, false);
  179782. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179783. {
  179784. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179785. uint8* dst = *buffer;
  179786. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179787. {
  179788. *dst++ = ((const PixelRGB*) src)->getRed();
  179789. *dst++ = ((const PixelRGB*) src)->getGreen();
  179790. *dst++ = ((const PixelRGB*) src)->getBlue();
  179791. src += srcData.pixelStride;
  179792. }
  179793. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179794. }
  179795. jpeg_finish_compress (&jpegCompStruct);
  179796. jpeg_destroy_compress (&jpegCompStruct);
  179797. out.flush();
  179798. return true;
  179799. }
  179800. END_JUCE_NAMESPACE
  179801. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179802. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179803. #if JUCE_MSVC
  179804. #pragma warning (push)
  179805. #pragma warning (disable: 4390 4611)
  179806. #ifdef __INTEL_COMPILER
  179807. #pragma warning (disable: 2544 2545)
  179808. #endif
  179809. #endif
  179810. namespace zlibNamespace
  179811. {
  179812. #if JUCE_INCLUDE_ZLIB_CODE
  179813. #undef OS_CODE
  179814. #undef fdopen
  179815. #undef OS_CODE
  179816. #else
  179817. #include <zlib.h>
  179818. #endif
  179819. }
  179820. namespace pnglibNamespace
  179821. {
  179822. using namespace zlibNamespace;
  179823. #if JUCE_INCLUDE_PNGLIB_CODE
  179824. #if _MSC_VER != 1310
  179825. using ::calloc; // (causes conflict in VS.NET 2003)
  179826. using ::malloc;
  179827. using ::free;
  179828. #endif
  179829. using ::abs;
  179830. #define PNG_INTERNAL
  179831. #define NO_DUMMY_DECL
  179832. #define PNG_SETJMP_NOT_SUPPORTED
  179833. /*** Start of inlined file: png.h ***/
  179834. /* png.h - header file for PNG reference library
  179835. *
  179836. * libpng version 1.2.21 - October 4, 2007
  179837. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179838. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179839. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179840. *
  179841. * Authors and maintainers:
  179842. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179843. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179844. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179845. * See also "Contributing Authors", below.
  179846. *
  179847. * Note about libpng version numbers:
  179848. *
  179849. * Due to various miscommunications, unforeseen code incompatibilities
  179850. * and occasional factors outside the authors' control, version numbering
  179851. * on the library has not always been consistent and straightforward.
  179852. * The following table summarizes matters since version 0.89c, which was
  179853. * the first widely used release:
  179854. *
  179855. * source png.h png.h shared-lib
  179856. * version string int version
  179857. * ------- ------ ----- ----------
  179858. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179859. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179860. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179861. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179862. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179863. * 0.97c 0.97 97 2.0.97
  179864. * 0.98 0.98 98 2.0.98
  179865. * 0.99 0.99 98 2.0.99
  179866. * 0.99a-m 0.99 99 2.0.99
  179867. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179868. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179869. * 1.0.1 png.h string is 10001 2.1.0
  179870. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179871. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179872. * 1.0.2a-b 10003 version, except as noted.
  179873. * 1.0.3 10003
  179874. * 1.0.3a-d 10004
  179875. * 1.0.4 10004
  179876. * 1.0.4a-f 10005
  179877. * 1.0.5 (+ 2 patches) 10005
  179878. * 1.0.5a-d 10006
  179879. * 1.0.5e-r 10100 (not source compatible)
  179880. * 1.0.5s-v 10006 (not binary compatible)
  179881. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179882. * 1.0.6d-f 10007 (still binary incompatible)
  179883. * 1.0.6g 10007
  179884. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179885. * 1.0.6i 10007 10.6i
  179886. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179887. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179888. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179889. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179890. * 1.0.7 1 10007 (still compatible)
  179891. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179892. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179893. * 1.0.8 1 10008 2.1.0.8
  179894. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179895. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179896. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179897. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179898. * 1.0.9 1 10009 2.1.0.9
  179899. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179900. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179901. * 1.0.10 1 10010 2.1.0.10
  179902. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179903. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179904. * 1.0.11 1 10011 2.1.0.11
  179905. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179906. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179907. * 1.0.12 2 10012 2.1.0.12
  179908. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179909. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179910. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179911. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179912. * 1.2.0 3 10200 3.1.2.0
  179913. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179914. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179915. * 1.2.1 3 10201 3.1.2.1
  179916. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179917. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179918. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179919. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179920. * 1.0.13 10 10013 10.so.0.1.0.13
  179921. * 1.2.2 12 10202 12.so.0.1.2.2
  179922. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179923. * 1.2.3 12 10203 12.so.0.1.2.3
  179924. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179925. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179926. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179927. * 1.0.14 10 10014 10.so.0.1.0.14
  179928. * 1.2.4 13 10204 12.so.0.1.2.4
  179929. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179930. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179931. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179932. * 1.0.15 10 10015 10.so.0.1.0.15
  179933. * 1.2.5 13 10205 12.so.0.1.2.5
  179934. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179935. * 1.0.16 10 10016 10.so.0.1.0.16
  179936. * 1.2.6 13 10206 12.so.0.1.2.6
  179937. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179938. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179939. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179940. * 1.0.17 10 10017 10.so.0.1.0.17
  179941. * 1.2.7 13 10207 12.so.0.1.2.7
  179942. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179943. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179944. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179945. * 1.0.18 10 10018 10.so.0.1.0.18
  179946. * 1.2.8 13 10208 12.so.0.1.2.8
  179947. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179948. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179949. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179950. * 1.2.9 13 10209 12.so.0.9[.0]
  179951. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179952. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179953. * 1.2.10 13 10210 12.so.0.10[.0]
  179954. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179955. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179956. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179957. * 1.0.19 10 10019 10.so.0.19[.0]
  179958. * 1.2.11 13 10211 12.so.0.11[.0]
  179959. * 1.0.20 10 10020 10.so.0.20[.0]
  179960. * 1.2.12 13 10212 12.so.0.12[.0]
  179961. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179962. * 1.0.21 10 10021 10.so.0.21[.0]
  179963. * 1.2.13 13 10213 12.so.0.13[.0]
  179964. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179965. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179966. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179967. * 1.0.22 10 10022 10.so.0.22[.0]
  179968. * 1.2.14 13 10214 12.so.0.14[.0]
  179969. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179970. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179971. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179972. * 1.0.23 10 10023 10.so.0.23[.0]
  179973. * 1.2.15 13 10215 12.so.0.15[.0]
  179974. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179975. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179976. * 1.0.24 10 10024 10.so.0.24[.0]
  179977. * 1.2.16 13 10216 12.so.0.16[.0]
  179978. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179979. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179980. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179981. * 1.0.25 10 10025 10.so.0.25[.0]
  179982. * 1.2.17 13 10217 12.so.0.17[.0]
  179983. * 1.0.26 10 10026 10.so.0.26[.0]
  179984. * 1.2.18 13 10218 12.so.0.18[.0]
  179985. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179986. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179987. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179988. * 1.0.27 10 10027 10.so.0.27[.0]
  179989. * 1.2.19 13 10219 12.so.0.19[.0]
  179990. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179991. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179992. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179993. * 1.0.28 10 10028 10.so.0.28[.0]
  179994. * 1.2.20 13 10220 12.so.0.20[.0]
  179995. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179996. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179997. * 1.0.29 10 10029 10.so.0.29[.0]
  179998. * 1.2.21 13 10221 12.so.0.21[.0]
  179999. *
  180000. * Henceforth the source version will match the shared-library major
  180001. * and minor numbers; the shared-library major version number will be
  180002. * used for changes in backward compatibility, as it is intended. The
  180003. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180004. * for applications, is an unsigned integer of the form xyyzz corresponding
  180005. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180006. * were given the previous public release number plus a letter, until
  180007. * version 1.0.6j; from then on they were given the upcoming public
  180008. * release number plus "betaNN" or "rcN".
  180009. *
  180010. * Binary incompatibility exists only when applications make direct access
  180011. * to the info_ptr or png_ptr members through png.h, and the compiled
  180012. * application is loaded with a different version of the library.
  180013. *
  180014. * DLLNUM will change each time there are forward or backward changes
  180015. * in binary compatibility (e.g., when a new feature is added).
  180016. *
  180017. * See libpng.txt or libpng.3 for more information. The PNG specification
  180018. * is available as a W3C Recommendation and as an ISO Specification,
  180019. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180020. */
  180021. /*
  180022. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180023. *
  180024. * If you modify libpng you may insert additional notices immediately following
  180025. * this sentence.
  180026. *
  180027. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180028. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180029. * distributed according to the same disclaimer and license as libpng-1.2.5
  180030. * with the following individual added to the list of Contributing Authors:
  180031. *
  180032. * Cosmin Truta
  180033. *
  180034. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180035. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180036. * distributed according to the same disclaimer and license as libpng-1.0.6
  180037. * with the following individuals added to the list of Contributing Authors:
  180038. *
  180039. * Simon-Pierre Cadieux
  180040. * Eric S. Raymond
  180041. * Gilles Vollant
  180042. *
  180043. * and with the following additions to the disclaimer:
  180044. *
  180045. * There is no warranty against interference with your enjoyment of the
  180046. * library or against infringement. There is no warranty that our
  180047. * efforts or the library will fulfill any of your particular purposes
  180048. * or needs. This library is provided with all faults, and the entire
  180049. * risk of satisfactory quality, performance, accuracy, and effort is with
  180050. * the user.
  180051. *
  180052. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180053. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180054. * distributed according to the same disclaimer and license as libpng-0.96,
  180055. * with the following individuals added to the list of Contributing Authors:
  180056. *
  180057. * Tom Lane
  180058. * Glenn Randers-Pehrson
  180059. * Willem van Schaik
  180060. *
  180061. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180062. * Copyright (c) 1996, 1997 Andreas Dilger
  180063. * Distributed according to the same disclaimer and license as libpng-0.88,
  180064. * with the following individuals added to the list of Contributing Authors:
  180065. *
  180066. * John Bowler
  180067. * Kevin Bracey
  180068. * Sam Bushell
  180069. * Magnus Holmgren
  180070. * Greg Roelofs
  180071. * Tom Tanner
  180072. *
  180073. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180074. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180075. *
  180076. * For the purposes of this copyright and license, "Contributing Authors"
  180077. * is defined as the following set of individuals:
  180078. *
  180079. * Andreas Dilger
  180080. * Dave Martindale
  180081. * Guy Eric Schalnat
  180082. * Paul Schmidt
  180083. * Tim Wegner
  180084. *
  180085. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180086. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180087. * including, without limitation, the warranties of merchantability and of
  180088. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180089. * assume no liability for direct, indirect, incidental, special, exemplary,
  180090. * or consequential damages, which may result from the use of the PNG
  180091. * Reference Library, even if advised of the possibility of such damage.
  180092. *
  180093. * Permission is hereby granted to use, copy, modify, and distribute this
  180094. * source code, or portions hereof, for any purpose, without fee, subject
  180095. * to the following restrictions:
  180096. *
  180097. * 1. The origin of this source code must not be misrepresented.
  180098. *
  180099. * 2. Altered versions must be plainly marked as such and
  180100. * must not be misrepresented as being the original source.
  180101. *
  180102. * 3. This Copyright notice may not be removed or altered from
  180103. * any source or altered source distribution.
  180104. *
  180105. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180106. * fee, and encourage the use of this source code as a component to
  180107. * supporting the PNG file format in commercial products. If you use this
  180108. * source code in a product, acknowledgment is not required but would be
  180109. * appreciated.
  180110. */
  180111. /*
  180112. * A "png_get_copyright" function is available, for convenient use in "about"
  180113. * boxes and the like:
  180114. *
  180115. * printf("%s",png_get_copyright(NULL));
  180116. *
  180117. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180118. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180119. */
  180120. /*
  180121. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180122. * certification mark of the Open Source Initiative.
  180123. */
  180124. /*
  180125. * The contributing authors would like to thank all those who helped
  180126. * with testing, bug fixes, and patience. This wouldn't have been
  180127. * possible without all of you.
  180128. *
  180129. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180130. */
  180131. /*
  180132. * Y2K compliance in libpng:
  180133. * =========================
  180134. *
  180135. * October 4, 2007
  180136. *
  180137. * Since the PNG Development group is an ad-hoc body, we can't make
  180138. * an official declaration.
  180139. *
  180140. * This is your unofficial assurance that libpng from version 0.71 and
  180141. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180142. * versions were also Y2K compliant.
  180143. *
  180144. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180145. * that will hold years up to 65535. The other two hold the date in text
  180146. * format, and will hold years up to 9999.
  180147. *
  180148. * The integer is
  180149. * "png_uint_16 year" in png_time_struct.
  180150. *
  180151. * The strings are
  180152. * "png_charp time_buffer" in png_struct and
  180153. * "near_time_buffer", which is a local character string in png.c.
  180154. *
  180155. * There are seven time-related functions:
  180156. * png.c: png_convert_to_rfc_1123() in png.c
  180157. * (formerly png_convert_to_rfc_1152() in error)
  180158. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180159. * png_convert_from_time_t() in pngwrite.c
  180160. * png_get_tIME() in pngget.c
  180161. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180162. * png_set_tIME() in pngset.c
  180163. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180164. *
  180165. * All handle dates properly in a Y2K environment. The
  180166. * png_convert_from_time_t() function calls gmtime() to convert from system
  180167. * clock time, which returns (year - 1900), which we properly convert to
  180168. * the full 4-digit year. There is a possibility that applications using
  180169. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180170. * function, or that they are incorrectly passing only a 2-digit year
  180171. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180172. * but this is not under our control. The libpng documentation has always
  180173. * stated that it works with 4-digit years, and the APIs have been
  180174. * documented as such.
  180175. *
  180176. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180177. * integer to hold the year, and can hold years as large as 65535.
  180178. *
  180179. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180180. * no date-related code.
  180181. *
  180182. * Glenn Randers-Pehrson
  180183. * libpng maintainer
  180184. * PNG Development Group
  180185. */
  180186. #ifndef PNG_H
  180187. #define PNG_H
  180188. /* This is not the place to learn how to use libpng. The file libpng.txt
  180189. * describes how to use libpng, and the file example.c summarizes it
  180190. * with some code on which to build. This file is useful for looking
  180191. * at the actual function definitions and structure components.
  180192. */
  180193. /* Version information for png.h - this should match the version in png.c */
  180194. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180195. #define PNG_HEADER_VERSION_STRING \
  180196. " libpng version 1.2.21 - October 4, 2007\n"
  180197. #define PNG_LIBPNG_VER_SONUM 0
  180198. #define PNG_LIBPNG_VER_DLLNUM 13
  180199. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180200. #define PNG_LIBPNG_VER_MAJOR 1
  180201. #define PNG_LIBPNG_VER_MINOR 2
  180202. #define PNG_LIBPNG_VER_RELEASE 21
  180203. /* This should match the numeric part of the final component of
  180204. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180205. #define PNG_LIBPNG_VER_BUILD 0
  180206. /* Release Status */
  180207. #define PNG_LIBPNG_BUILD_ALPHA 1
  180208. #define PNG_LIBPNG_BUILD_BETA 2
  180209. #define PNG_LIBPNG_BUILD_RC 3
  180210. #define PNG_LIBPNG_BUILD_STABLE 4
  180211. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180212. /* Release-Specific Flags */
  180213. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180214. PNG_LIBPNG_BUILD_STABLE only */
  180215. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180216. PNG_LIBPNG_BUILD_SPECIAL */
  180217. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180218. PNG_LIBPNG_BUILD_PRIVATE */
  180219. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180220. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180221. * We must not include leading zeros.
  180222. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180223. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180224. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180225. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180226. #ifndef PNG_VERSION_INFO_ONLY
  180227. /* include the compression library's header */
  180228. #endif
  180229. /* include all user configurable info, including optional assembler routines */
  180230. /*** Start of inlined file: pngconf.h ***/
  180231. /* pngconf.h - machine configurable file for libpng
  180232. *
  180233. * libpng version 1.2.21 - October 4, 2007
  180234. * For conditions of distribution and use, see copyright notice in png.h
  180235. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180236. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180237. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180238. */
  180239. /* Any machine specific code is near the front of this file, so if you
  180240. * are configuring libpng for a machine, you may want to read the section
  180241. * starting here down to where it starts to typedef png_color, png_text,
  180242. * and png_info.
  180243. */
  180244. #ifndef PNGCONF_H
  180245. #define PNGCONF_H
  180246. #define PNG_1_2_X
  180247. // These are some Juce config settings that should remove any unnecessary code bloat..
  180248. #define PNG_NO_STDIO 1
  180249. #define PNG_DEBUG 0
  180250. #define PNG_NO_WARNINGS 1
  180251. #define PNG_NO_ERROR_TEXT 1
  180252. #define PNG_NO_ERROR_NUMBERS 1
  180253. #define PNG_NO_USER_MEM 1
  180254. #define PNG_NO_READ_iCCP 1
  180255. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180256. #define PNG_NO_READ_USER_CHUNKS 1
  180257. #define PNG_NO_READ_iTXt 1
  180258. #define PNG_NO_READ_sCAL 1
  180259. #define PNG_NO_READ_sPLT 1
  180260. #define png_error(a, b) png_err(a)
  180261. #define png_warning(a, b)
  180262. #define png_chunk_error(a, b) png_err(a)
  180263. #define png_chunk_warning(a, b)
  180264. /*
  180265. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180266. * includes the resource compiler for Windows DLL configurations.
  180267. */
  180268. #ifdef PNG_USER_CONFIG
  180269. # ifndef PNG_USER_PRIVATEBUILD
  180270. # define PNG_USER_PRIVATEBUILD
  180271. # endif
  180272. #include "pngusr.h"
  180273. #endif
  180274. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180275. #ifdef PNG_CONFIGURE_LIBPNG
  180276. #ifdef HAVE_CONFIG_H
  180277. #include "config.h"
  180278. #endif
  180279. #endif
  180280. /*
  180281. * Added at libpng-1.2.8
  180282. *
  180283. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180284. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180285. * the DLL was built>
  180286. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180287. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180288. * distinguish your DLL from those of the official release. These
  180289. * correspond to the trailing letters that come after the version
  180290. * number and must match your private DLL name>
  180291. * e.g. // private DLL "libpng13gx.dll"
  180292. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180293. *
  180294. * The following macros are also at your disposal if you want to complete the
  180295. * DLL VERSIONINFO structure.
  180296. * - PNG_USER_VERSIONINFO_COMMENTS
  180297. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180298. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180299. */
  180300. #ifdef __STDC__
  180301. #ifdef SPECIALBUILD
  180302. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180303. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180304. #endif
  180305. #ifdef PRIVATEBUILD
  180306. # pragma message("PRIVATEBUILD is deprecated.\
  180307. Use PNG_USER_PRIVATEBUILD instead.")
  180308. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180309. #endif
  180310. #endif /* __STDC__ */
  180311. #ifndef PNG_VERSION_INFO_ONLY
  180312. /* End of material added to libpng-1.2.8 */
  180313. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180314. Restored at libpng-1.2.21 */
  180315. # define PNG_WARN_UNINITIALIZED_ROW 1
  180316. /* End of material added at libpng-1.2.19/1.2.21 */
  180317. /* This is the size of the compression buffer, and thus the size of
  180318. * an IDAT chunk. Make this whatever size you feel is best for your
  180319. * machine. One of these will be allocated per png_struct. When this
  180320. * is full, it writes the data to the disk, and does some other
  180321. * calculations. Making this an extremely small size will slow
  180322. * the library down, but you may want to experiment to determine
  180323. * where it becomes significant, if you are concerned with memory
  180324. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180325. * this describes the size of the buffer available to read the data in.
  180326. * Unless this gets smaller than the size of a row (compressed),
  180327. * it should not make much difference how big this is.
  180328. */
  180329. #ifndef PNG_ZBUF_SIZE
  180330. # define PNG_ZBUF_SIZE 8192
  180331. #endif
  180332. /* Enable if you want a write-only libpng */
  180333. #ifndef PNG_NO_READ_SUPPORTED
  180334. # define PNG_READ_SUPPORTED
  180335. #endif
  180336. /* Enable if you want a read-only libpng */
  180337. #ifndef PNG_NO_WRITE_SUPPORTED
  180338. # define PNG_WRITE_SUPPORTED
  180339. #endif
  180340. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180341. support PNGs that are embedded in MNG datastreams */
  180342. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180343. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180344. # define PNG_MNG_FEATURES_SUPPORTED
  180345. # endif
  180346. #endif
  180347. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180348. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180349. # define PNG_FLOATING_POINT_SUPPORTED
  180350. # endif
  180351. #endif
  180352. /* If you are running on a machine where you cannot allocate more
  180353. * than 64K of memory at once, uncomment this. While libpng will not
  180354. * normally need that much memory in a chunk (unless you load up a very
  180355. * large file), zlib needs to know how big of a chunk it can use, and
  180356. * libpng thus makes sure to check any memory allocation to verify it
  180357. * will fit into memory.
  180358. #define PNG_MAX_MALLOC_64K
  180359. */
  180360. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180361. # define PNG_MAX_MALLOC_64K
  180362. #endif
  180363. /* Special munging to support doing things the 'cygwin' way:
  180364. * 'Normal' png-on-win32 defines/defaults:
  180365. * PNG_BUILD_DLL -- building dll
  180366. * PNG_USE_DLL -- building an application, linking to dll
  180367. * (no define) -- building static library, or building an
  180368. * application and linking to the static lib
  180369. * 'Cygwin' defines/defaults:
  180370. * PNG_BUILD_DLL -- (ignored) building the dll
  180371. * (no define) -- (ignored) building an application, linking to the dll
  180372. * PNG_STATIC -- (ignored) building the static lib, or building an
  180373. * application that links to the static lib.
  180374. * ALL_STATIC -- (ignored) building various static libs, or building an
  180375. * application that links to the static libs.
  180376. * Thus,
  180377. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180378. * this bit of #ifdefs will define the 'correct' config variables based on
  180379. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180380. * unnecessary.
  180381. *
  180382. * Also, the precedence order is:
  180383. * ALL_STATIC (since we can't #undef something outside our namespace)
  180384. * PNG_BUILD_DLL
  180385. * PNG_STATIC
  180386. * (nothing) == PNG_USE_DLL
  180387. *
  180388. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180389. * of auto-import in binutils, we no longer need to worry about
  180390. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180391. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180392. * to __declspec() stuff. However, we DO need to worry about
  180393. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180394. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180395. */
  180396. #if defined(__CYGWIN__)
  180397. # if defined(ALL_STATIC)
  180398. # if defined(PNG_BUILD_DLL)
  180399. # undef PNG_BUILD_DLL
  180400. # endif
  180401. # if defined(PNG_USE_DLL)
  180402. # undef PNG_USE_DLL
  180403. # endif
  180404. # if defined(PNG_DLL)
  180405. # undef PNG_DLL
  180406. # endif
  180407. # if !defined(PNG_STATIC)
  180408. # define PNG_STATIC
  180409. # endif
  180410. # else
  180411. # if defined (PNG_BUILD_DLL)
  180412. # if defined(PNG_STATIC)
  180413. # undef PNG_STATIC
  180414. # endif
  180415. # if defined(PNG_USE_DLL)
  180416. # undef PNG_USE_DLL
  180417. # endif
  180418. # if !defined(PNG_DLL)
  180419. # define PNG_DLL
  180420. # endif
  180421. # else
  180422. # if defined(PNG_STATIC)
  180423. # if defined(PNG_USE_DLL)
  180424. # undef PNG_USE_DLL
  180425. # endif
  180426. # if defined(PNG_DLL)
  180427. # undef PNG_DLL
  180428. # endif
  180429. # else
  180430. # if !defined(PNG_USE_DLL)
  180431. # define PNG_USE_DLL
  180432. # endif
  180433. # if !defined(PNG_DLL)
  180434. # define PNG_DLL
  180435. # endif
  180436. # endif
  180437. # endif
  180438. # endif
  180439. #endif
  180440. /* This protects us against compilers that run on a windowing system
  180441. * and thus don't have or would rather us not use the stdio types:
  180442. * stdin, stdout, and stderr. The only one currently used is stderr
  180443. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180444. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180445. * will also prevent these, plus will prevent the entire set of stdio
  180446. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180447. * unless (PNG_DEBUG > 0) has been #defined.
  180448. *
  180449. * #define PNG_NO_CONSOLE_IO
  180450. * #define PNG_NO_STDIO
  180451. */
  180452. #if defined(_WIN32_WCE)
  180453. # include <windows.h>
  180454. /* Console I/O functions are not supported on WindowsCE */
  180455. # define PNG_NO_CONSOLE_IO
  180456. # ifdef PNG_DEBUG
  180457. # undef PNG_DEBUG
  180458. # endif
  180459. #endif
  180460. #ifdef PNG_BUILD_DLL
  180461. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180462. # ifndef PNG_NO_CONSOLE_IO
  180463. # define PNG_NO_CONSOLE_IO
  180464. # endif
  180465. # endif
  180466. #endif
  180467. # ifdef PNG_NO_STDIO
  180468. # ifndef PNG_NO_CONSOLE_IO
  180469. # define PNG_NO_CONSOLE_IO
  180470. # endif
  180471. # ifdef PNG_DEBUG
  180472. # if (PNG_DEBUG > 0)
  180473. # include <stdio.h>
  180474. # endif
  180475. # endif
  180476. # else
  180477. # if !defined(_WIN32_WCE)
  180478. /* "stdio.h" functions are not supported on WindowsCE */
  180479. # include <stdio.h>
  180480. # endif
  180481. # endif
  180482. /* This macro protects us against machines that don't have function
  180483. * prototypes (ie K&R style headers). If your compiler does not handle
  180484. * function prototypes, define this macro and use the included ansi2knr.
  180485. * I've always been able to use _NO_PROTO as the indicator, but you may
  180486. * need to drag the empty declaration out in front of here, or change the
  180487. * ifdef to suit your own needs.
  180488. */
  180489. #ifndef PNGARG
  180490. #ifdef OF /* zlib prototype munger */
  180491. # define PNGARG(arglist) OF(arglist)
  180492. #else
  180493. #ifdef _NO_PROTO
  180494. # define PNGARG(arglist) ()
  180495. # ifndef PNG_TYPECAST_NULL
  180496. # define PNG_TYPECAST_NULL
  180497. # endif
  180498. #else
  180499. # define PNGARG(arglist) arglist
  180500. #endif /* _NO_PROTO */
  180501. #endif /* OF */
  180502. #endif /* PNGARG */
  180503. /* Try to determine if we are compiling on a Mac. Note that testing for
  180504. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180505. * on non-Mac platforms.
  180506. */
  180507. #ifndef MACOS
  180508. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180509. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180510. # define MACOS
  180511. # endif
  180512. #endif
  180513. /* enough people need this for various reasons to include it here */
  180514. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180515. # include <sys/types.h>
  180516. #endif
  180517. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180518. # define PNG_SETJMP_SUPPORTED
  180519. #endif
  180520. #ifdef PNG_SETJMP_SUPPORTED
  180521. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180522. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180523. */
  180524. # ifdef __linux__
  180525. # ifdef _BSD_SOURCE
  180526. # define PNG_SAVE_BSD_SOURCE
  180527. # undef _BSD_SOURCE
  180528. # endif
  180529. # ifdef _SETJMP_H
  180530. /* If you encounter a compiler error here, see the explanation
  180531. * near the end of INSTALL.
  180532. */
  180533. __png.h__ already includes setjmp.h;
  180534. __dont__ include it again.;
  180535. # endif
  180536. # endif /* __linux__ */
  180537. /* include setjmp.h for error handling */
  180538. # include <setjmp.h>
  180539. # ifdef __linux__
  180540. # ifdef PNG_SAVE_BSD_SOURCE
  180541. # define _BSD_SOURCE
  180542. # undef PNG_SAVE_BSD_SOURCE
  180543. # endif
  180544. # endif /* __linux__ */
  180545. #endif /* PNG_SETJMP_SUPPORTED */
  180546. #ifdef BSD
  180547. #if ! JUCE_MAC
  180548. # include <strings.h>
  180549. #endif
  180550. #else
  180551. # include <string.h>
  180552. #endif
  180553. /* Other defines for things like memory and the like can go here. */
  180554. #ifdef PNG_INTERNAL
  180555. #include <stdlib.h>
  180556. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180557. * aren't usually used outside the library (as far as I know), so it is
  180558. * debatable if they should be exported at all. In the future, when it is
  180559. * possible to have run-time registry of chunk-handling functions, some of
  180560. * these will be made available again.
  180561. #define PNG_EXTERN extern
  180562. */
  180563. #define PNG_EXTERN
  180564. /* Other defines specific to compilers can go here. Try to keep
  180565. * them inside an appropriate ifdef/endif pair for portability.
  180566. */
  180567. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180568. # if defined(MACOS)
  180569. /* We need to check that <math.h> hasn't already been included earlier
  180570. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180571. * <fp.h> if possible.
  180572. */
  180573. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180574. # include <fp.h>
  180575. # endif
  180576. # else
  180577. # include <math.h>
  180578. # endif
  180579. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180580. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180581. * MATH=68881
  180582. */
  180583. # include <m68881.h>
  180584. # endif
  180585. #endif
  180586. /* Codewarrior on NT has linking problems without this. */
  180587. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180588. # define PNG_ALWAYS_EXTERN
  180589. #endif
  180590. /* This provides the non-ANSI (far) memory allocation routines. */
  180591. #if defined(__TURBOC__) && defined(__MSDOS__)
  180592. # include <mem.h>
  180593. # include <alloc.h>
  180594. #endif
  180595. /* I have no idea why is this necessary... */
  180596. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180597. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180598. # include <malloc.h>
  180599. #endif
  180600. /* This controls how fine the dithering gets. As this allocates
  180601. * a largish chunk of memory (32K), those who are not as concerned
  180602. * with dithering quality can decrease some or all of these.
  180603. */
  180604. #ifndef PNG_DITHER_RED_BITS
  180605. # define PNG_DITHER_RED_BITS 5
  180606. #endif
  180607. #ifndef PNG_DITHER_GREEN_BITS
  180608. # define PNG_DITHER_GREEN_BITS 5
  180609. #endif
  180610. #ifndef PNG_DITHER_BLUE_BITS
  180611. # define PNG_DITHER_BLUE_BITS 5
  180612. #endif
  180613. /* This controls how fine the gamma correction becomes when you
  180614. * are only interested in 8 bits anyway. Increasing this value
  180615. * results in more memory being used, and more pow() functions
  180616. * being called to fill in the gamma tables. Don't set this value
  180617. * less then 8, and even that may not work (I haven't tested it).
  180618. */
  180619. #ifndef PNG_MAX_GAMMA_8
  180620. # define PNG_MAX_GAMMA_8 11
  180621. #endif
  180622. /* This controls how much a difference in gamma we can tolerate before
  180623. * we actually start doing gamma conversion.
  180624. */
  180625. #ifndef PNG_GAMMA_THRESHOLD
  180626. # define PNG_GAMMA_THRESHOLD 0.05
  180627. #endif
  180628. #endif /* PNG_INTERNAL */
  180629. /* The following uses const char * instead of char * for error
  180630. * and warning message functions, so some compilers won't complain.
  180631. * If you do not want to use const, define PNG_NO_CONST here.
  180632. */
  180633. #ifndef PNG_NO_CONST
  180634. # define PNG_CONST const
  180635. #else
  180636. # define PNG_CONST
  180637. #endif
  180638. /* The following defines give you the ability to remove code from the
  180639. * library that you will not be using. I wish I could figure out how to
  180640. * automate this, but I can't do that without making it seriously hard
  180641. * on the users. So if you are not using an ability, change the #define
  180642. * to and #undef, and that part of the library will not be compiled. If
  180643. * your linker can't find a function, you may want to make sure the
  180644. * ability is defined here. Some of these depend upon some others being
  180645. * defined. I haven't figured out all the interactions here, so you may
  180646. * have to experiment awhile to get everything to compile. If you are
  180647. * creating or using a shared library, you probably shouldn't touch this,
  180648. * as it will affect the size of the structures, and this will cause bad
  180649. * things to happen if the library and/or application ever change.
  180650. */
  180651. /* Any features you will not be using can be undef'ed here */
  180652. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180653. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180654. * on the compile line, then pick and choose which ones to define without
  180655. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180656. * if you only want to have a png-compliant reader/writer but don't need
  180657. * any of the extra transformations. This saves about 80 kbytes in a
  180658. * typical installation of the library. (PNG_NO_* form added in version
  180659. * 1.0.1c, for consistency)
  180660. */
  180661. /* The size of the png_text structure changed in libpng-1.0.6 when
  180662. * iTXt support was added. iTXt support was turned off by default through
  180663. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180664. * instead of calling png_set_text() and letting libpng malloc it. It
  180665. * was turned on by default in libpng-1.3.0.
  180666. */
  180667. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180668. # ifndef PNG_NO_iTXt_SUPPORTED
  180669. # define PNG_NO_iTXt_SUPPORTED
  180670. # endif
  180671. # ifndef PNG_NO_READ_iTXt
  180672. # define PNG_NO_READ_iTXt
  180673. # endif
  180674. # ifndef PNG_NO_WRITE_iTXt
  180675. # define PNG_NO_WRITE_iTXt
  180676. # endif
  180677. #endif
  180678. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180679. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180680. # define PNG_READ_iTXt
  180681. # endif
  180682. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180683. # define PNG_WRITE_iTXt
  180684. # endif
  180685. #endif
  180686. /* The following support, added after version 1.0.0, can be turned off here en
  180687. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180688. * with old applications that require the length of png_struct and png_info
  180689. * to remain unchanged.
  180690. */
  180691. #ifdef PNG_LEGACY_SUPPORTED
  180692. # define PNG_NO_FREE_ME
  180693. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180694. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180695. # define PNG_NO_READ_USER_CHUNKS
  180696. # define PNG_NO_READ_iCCP
  180697. # define PNG_NO_WRITE_iCCP
  180698. # define PNG_NO_READ_iTXt
  180699. # define PNG_NO_WRITE_iTXt
  180700. # define PNG_NO_READ_sCAL
  180701. # define PNG_NO_WRITE_sCAL
  180702. # define PNG_NO_READ_sPLT
  180703. # define PNG_NO_WRITE_sPLT
  180704. # define PNG_NO_INFO_IMAGE
  180705. # define PNG_NO_READ_RGB_TO_GRAY
  180706. # define PNG_NO_READ_USER_TRANSFORM
  180707. # define PNG_NO_WRITE_USER_TRANSFORM
  180708. # define PNG_NO_USER_MEM
  180709. # define PNG_NO_READ_EMPTY_PLTE
  180710. # define PNG_NO_MNG_FEATURES
  180711. # define PNG_NO_FIXED_POINT_SUPPORTED
  180712. #endif
  180713. /* Ignore attempt to turn off both floating and fixed point support */
  180714. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180715. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180716. # define PNG_FIXED_POINT_SUPPORTED
  180717. #endif
  180718. #ifndef PNG_NO_FREE_ME
  180719. # define PNG_FREE_ME_SUPPORTED
  180720. #endif
  180721. #if defined(PNG_READ_SUPPORTED)
  180722. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180723. !defined(PNG_NO_READ_TRANSFORMS)
  180724. # define PNG_READ_TRANSFORMS_SUPPORTED
  180725. #endif
  180726. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180727. # ifndef PNG_NO_READ_EXPAND
  180728. # define PNG_READ_EXPAND_SUPPORTED
  180729. # endif
  180730. # ifndef PNG_NO_READ_SHIFT
  180731. # define PNG_READ_SHIFT_SUPPORTED
  180732. # endif
  180733. # ifndef PNG_NO_READ_PACK
  180734. # define PNG_READ_PACK_SUPPORTED
  180735. # endif
  180736. # ifndef PNG_NO_READ_BGR
  180737. # define PNG_READ_BGR_SUPPORTED
  180738. # endif
  180739. # ifndef PNG_NO_READ_SWAP
  180740. # define PNG_READ_SWAP_SUPPORTED
  180741. # endif
  180742. # ifndef PNG_NO_READ_PACKSWAP
  180743. # define PNG_READ_PACKSWAP_SUPPORTED
  180744. # endif
  180745. # ifndef PNG_NO_READ_INVERT
  180746. # define PNG_READ_INVERT_SUPPORTED
  180747. # endif
  180748. # ifndef PNG_NO_READ_DITHER
  180749. # define PNG_READ_DITHER_SUPPORTED
  180750. # endif
  180751. # ifndef PNG_NO_READ_BACKGROUND
  180752. # define PNG_READ_BACKGROUND_SUPPORTED
  180753. # endif
  180754. # ifndef PNG_NO_READ_16_TO_8
  180755. # define PNG_READ_16_TO_8_SUPPORTED
  180756. # endif
  180757. # ifndef PNG_NO_READ_FILLER
  180758. # define PNG_READ_FILLER_SUPPORTED
  180759. # endif
  180760. # ifndef PNG_NO_READ_GAMMA
  180761. # define PNG_READ_GAMMA_SUPPORTED
  180762. # endif
  180763. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180764. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180765. # endif
  180766. # ifndef PNG_NO_READ_SWAP_ALPHA
  180767. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180768. # endif
  180769. # ifndef PNG_NO_READ_INVERT_ALPHA
  180770. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180771. # endif
  180772. # ifndef PNG_NO_READ_STRIP_ALPHA
  180773. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180774. # endif
  180775. # ifndef PNG_NO_READ_USER_TRANSFORM
  180776. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180777. # endif
  180778. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180779. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180780. # endif
  180781. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180782. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180783. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180784. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180785. #endif /* about interlacing capability! You'll */
  180786. /* still have interlacing unless you change the following line: */
  180787. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180788. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180789. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180790. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180791. # endif
  180792. #endif
  180793. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180794. /* Deprecated, will be removed from version 2.0.0.
  180795. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180796. #ifndef PNG_NO_READ_EMPTY_PLTE
  180797. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180798. #endif
  180799. #endif
  180800. #endif /* PNG_READ_SUPPORTED */
  180801. #if defined(PNG_WRITE_SUPPORTED)
  180802. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180803. !defined(PNG_NO_WRITE_TRANSFORMS)
  180804. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180805. #endif
  180806. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180807. # ifndef PNG_NO_WRITE_SHIFT
  180808. # define PNG_WRITE_SHIFT_SUPPORTED
  180809. # endif
  180810. # ifndef PNG_NO_WRITE_PACK
  180811. # define PNG_WRITE_PACK_SUPPORTED
  180812. # endif
  180813. # ifndef PNG_NO_WRITE_BGR
  180814. # define PNG_WRITE_BGR_SUPPORTED
  180815. # endif
  180816. # ifndef PNG_NO_WRITE_SWAP
  180817. # define PNG_WRITE_SWAP_SUPPORTED
  180818. # endif
  180819. # ifndef PNG_NO_WRITE_PACKSWAP
  180820. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180821. # endif
  180822. # ifndef PNG_NO_WRITE_INVERT
  180823. # define PNG_WRITE_INVERT_SUPPORTED
  180824. # endif
  180825. # ifndef PNG_NO_WRITE_FILLER
  180826. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180827. # endif
  180828. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180829. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180830. # endif
  180831. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180832. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180833. # endif
  180834. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180835. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180836. # endif
  180837. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180838. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180839. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180840. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180841. encoders, but can cause trouble
  180842. if left undefined */
  180843. #endif
  180844. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180845. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180846. defined(PNG_FLOATING_POINT_SUPPORTED)
  180847. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180848. #endif
  180849. #ifndef PNG_NO_WRITE_FLUSH
  180850. # define PNG_WRITE_FLUSH_SUPPORTED
  180851. #endif
  180852. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180853. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180854. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180855. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180856. #endif
  180857. #endif
  180858. #endif /* PNG_WRITE_SUPPORTED */
  180859. #ifndef PNG_1_0_X
  180860. # ifndef PNG_NO_ERROR_NUMBERS
  180861. # define PNG_ERROR_NUMBERS_SUPPORTED
  180862. # endif
  180863. #endif /* PNG_1_0_X */
  180864. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180865. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180866. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180867. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180868. # endif
  180869. #endif
  180870. #ifndef PNG_NO_STDIO
  180871. # define PNG_TIME_RFC1123_SUPPORTED
  180872. #endif
  180873. /* This adds extra functions in pngget.c for accessing data from the
  180874. * info pointer (added in version 0.99)
  180875. * png_get_image_width()
  180876. * png_get_image_height()
  180877. * png_get_bit_depth()
  180878. * png_get_color_type()
  180879. * png_get_compression_type()
  180880. * png_get_filter_type()
  180881. * png_get_interlace_type()
  180882. * png_get_pixel_aspect_ratio()
  180883. * png_get_pixels_per_meter()
  180884. * png_get_x_offset_pixels()
  180885. * png_get_y_offset_pixels()
  180886. * png_get_x_offset_microns()
  180887. * png_get_y_offset_microns()
  180888. */
  180889. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180890. # define PNG_EASY_ACCESS_SUPPORTED
  180891. #endif
  180892. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180893. * and removed from version 1.2.20. The following will be removed
  180894. * from libpng-1.4.0
  180895. */
  180896. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180897. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180898. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180899. # endif
  180900. #endif
  180901. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180902. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180903. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180904. # endif
  180905. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180906. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180907. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180908. # define PNG_NO_MMX_CODE
  180909. # endif
  180910. # endif
  180911. # if defined(__APPLE__)
  180912. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180913. # define PNG_NO_MMX_CODE
  180914. # endif
  180915. # endif
  180916. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180917. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180918. # define PNG_NO_MMX_CODE
  180919. # endif
  180920. # endif
  180921. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180922. # define PNG_MMX_CODE_SUPPORTED
  180923. # endif
  180924. #endif
  180925. /* end of obsolete code to be removed from libpng-1.4.0 */
  180926. #if !defined(PNG_1_0_X)
  180927. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180928. # define PNG_USER_MEM_SUPPORTED
  180929. #endif
  180930. #endif /* PNG_1_0_X */
  180931. /* Added at libpng-1.2.6 */
  180932. #if !defined(PNG_1_0_X)
  180933. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180934. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180935. # define PNG_SET_USER_LIMITS_SUPPORTED
  180936. #endif
  180937. #endif
  180938. #endif /* PNG_1_0_X */
  180939. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180940. * how large, set these limits to 0x7fffffffL
  180941. */
  180942. #ifndef PNG_USER_WIDTH_MAX
  180943. # define PNG_USER_WIDTH_MAX 1000000L
  180944. #endif
  180945. #ifndef PNG_USER_HEIGHT_MAX
  180946. # define PNG_USER_HEIGHT_MAX 1000000L
  180947. #endif
  180948. /* These are currently experimental features, define them if you want */
  180949. /* very little testing */
  180950. /*
  180951. #ifdef PNG_READ_SUPPORTED
  180952. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180953. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180954. # endif
  180955. #endif
  180956. */
  180957. /* This is only for PowerPC big-endian and 680x0 systems */
  180958. /* some testing */
  180959. /*
  180960. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180961. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180962. #endif
  180963. */
  180964. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180965. /*
  180966. #define PNG_NO_POINTER_INDEXING
  180967. */
  180968. /* These functions are turned off by default, as they will be phased out. */
  180969. /*
  180970. #define PNG_USELESS_TESTS_SUPPORTED
  180971. #define PNG_CORRECT_PALETTE_SUPPORTED
  180972. */
  180973. /* Any chunks you are not interested in, you can undef here. The
  180974. * ones that allocate memory may be expecially important (hIST,
  180975. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180976. * a bit smaller.
  180977. */
  180978. #if defined(PNG_READ_SUPPORTED) && \
  180979. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180980. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180981. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180982. #endif
  180983. #if defined(PNG_WRITE_SUPPORTED) && \
  180984. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180985. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180986. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180987. #endif
  180988. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180989. #ifdef PNG_NO_READ_TEXT
  180990. # define PNG_NO_READ_iTXt
  180991. # define PNG_NO_READ_tEXt
  180992. # define PNG_NO_READ_zTXt
  180993. #endif
  180994. #ifndef PNG_NO_READ_bKGD
  180995. # define PNG_READ_bKGD_SUPPORTED
  180996. # define PNG_bKGD_SUPPORTED
  180997. #endif
  180998. #ifndef PNG_NO_READ_cHRM
  180999. # define PNG_READ_cHRM_SUPPORTED
  181000. # define PNG_cHRM_SUPPORTED
  181001. #endif
  181002. #ifndef PNG_NO_READ_gAMA
  181003. # define PNG_READ_gAMA_SUPPORTED
  181004. # define PNG_gAMA_SUPPORTED
  181005. #endif
  181006. #ifndef PNG_NO_READ_hIST
  181007. # define PNG_READ_hIST_SUPPORTED
  181008. # define PNG_hIST_SUPPORTED
  181009. #endif
  181010. #ifndef PNG_NO_READ_iCCP
  181011. # define PNG_READ_iCCP_SUPPORTED
  181012. # define PNG_iCCP_SUPPORTED
  181013. #endif
  181014. #ifndef PNG_NO_READ_iTXt
  181015. # ifndef PNG_READ_iTXt_SUPPORTED
  181016. # define PNG_READ_iTXt_SUPPORTED
  181017. # endif
  181018. # ifndef PNG_iTXt_SUPPORTED
  181019. # define PNG_iTXt_SUPPORTED
  181020. # endif
  181021. #endif
  181022. #ifndef PNG_NO_READ_oFFs
  181023. # define PNG_READ_oFFs_SUPPORTED
  181024. # define PNG_oFFs_SUPPORTED
  181025. #endif
  181026. #ifndef PNG_NO_READ_pCAL
  181027. # define PNG_READ_pCAL_SUPPORTED
  181028. # define PNG_pCAL_SUPPORTED
  181029. #endif
  181030. #ifndef PNG_NO_READ_sCAL
  181031. # define PNG_READ_sCAL_SUPPORTED
  181032. # define PNG_sCAL_SUPPORTED
  181033. #endif
  181034. #ifndef PNG_NO_READ_pHYs
  181035. # define PNG_READ_pHYs_SUPPORTED
  181036. # define PNG_pHYs_SUPPORTED
  181037. #endif
  181038. #ifndef PNG_NO_READ_sBIT
  181039. # define PNG_READ_sBIT_SUPPORTED
  181040. # define PNG_sBIT_SUPPORTED
  181041. #endif
  181042. #ifndef PNG_NO_READ_sPLT
  181043. # define PNG_READ_sPLT_SUPPORTED
  181044. # define PNG_sPLT_SUPPORTED
  181045. #endif
  181046. #ifndef PNG_NO_READ_sRGB
  181047. # define PNG_READ_sRGB_SUPPORTED
  181048. # define PNG_sRGB_SUPPORTED
  181049. #endif
  181050. #ifndef PNG_NO_READ_tEXt
  181051. # define PNG_READ_tEXt_SUPPORTED
  181052. # define PNG_tEXt_SUPPORTED
  181053. #endif
  181054. #ifndef PNG_NO_READ_tIME
  181055. # define PNG_READ_tIME_SUPPORTED
  181056. # define PNG_tIME_SUPPORTED
  181057. #endif
  181058. #ifndef PNG_NO_READ_tRNS
  181059. # define PNG_READ_tRNS_SUPPORTED
  181060. # define PNG_tRNS_SUPPORTED
  181061. #endif
  181062. #ifndef PNG_NO_READ_zTXt
  181063. # define PNG_READ_zTXt_SUPPORTED
  181064. # define PNG_zTXt_SUPPORTED
  181065. #endif
  181066. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181067. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181068. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181069. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181070. # endif
  181071. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181072. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181073. # endif
  181074. #endif
  181075. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181076. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181077. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181078. # define PNG_USER_CHUNKS_SUPPORTED
  181079. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181080. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181081. # endif
  181082. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181083. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181084. # endif
  181085. #endif
  181086. #ifndef PNG_NO_READ_OPT_PLTE
  181087. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181088. #endif /* optional PLTE chunk in RGB and RGBA images */
  181089. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181090. defined(PNG_READ_zTXt_SUPPORTED)
  181091. # define PNG_READ_TEXT_SUPPORTED
  181092. # define PNG_TEXT_SUPPORTED
  181093. #endif
  181094. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181095. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181096. #ifdef PNG_NO_WRITE_TEXT
  181097. # define PNG_NO_WRITE_iTXt
  181098. # define PNG_NO_WRITE_tEXt
  181099. # define PNG_NO_WRITE_zTXt
  181100. #endif
  181101. #ifndef PNG_NO_WRITE_bKGD
  181102. # define PNG_WRITE_bKGD_SUPPORTED
  181103. # ifndef PNG_bKGD_SUPPORTED
  181104. # define PNG_bKGD_SUPPORTED
  181105. # endif
  181106. #endif
  181107. #ifndef PNG_NO_WRITE_cHRM
  181108. # define PNG_WRITE_cHRM_SUPPORTED
  181109. # ifndef PNG_cHRM_SUPPORTED
  181110. # define PNG_cHRM_SUPPORTED
  181111. # endif
  181112. #endif
  181113. #ifndef PNG_NO_WRITE_gAMA
  181114. # define PNG_WRITE_gAMA_SUPPORTED
  181115. # ifndef PNG_gAMA_SUPPORTED
  181116. # define PNG_gAMA_SUPPORTED
  181117. # endif
  181118. #endif
  181119. #ifndef PNG_NO_WRITE_hIST
  181120. # define PNG_WRITE_hIST_SUPPORTED
  181121. # ifndef PNG_hIST_SUPPORTED
  181122. # define PNG_hIST_SUPPORTED
  181123. # endif
  181124. #endif
  181125. #ifndef PNG_NO_WRITE_iCCP
  181126. # define PNG_WRITE_iCCP_SUPPORTED
  181127. # ifndef PNG_iCCP_SUPPORTED
  181128. # define PNG_iCCP_SUPPORTED
  181129. # endif
  181130. #endif
  181131. #ifndef PNG_NO_WRITE_iTXt
  181132. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181133. # define PNG_WRITE_iTXt_SUPPORTED
  181134. # endif
  181135. # ifndef PNG_iTXt_SUPPORTED
  181136. # define PNG_iTXt_SUPPORTED
  181137. # endif
  181138. #endif
  181139. #ifndef PNG_NO_WRITE_oFFs
  181140. # define PNG_WRITE_oFFs_SUPPORTED
  181141. # ifndef PNG_oFFs_SUPPORTED
  181142. # define PNG_oFFs_SUPPORTED
  181143. # endif
  181144. #endif
  181145. #ifndef PNG_NO_WRITE_pCAL
  181146. # define PNG_WRITE_pCAL_SUPPORTED
  181147. # ifndef PNG_pCAL_SUPPORTED
  181148. # define PNG_pCAL_SUPPORTED
  181149. # endif
  181150. #endif
  181151. #ifndef PNG_NO_WRITE_sCAL
  181152. # define PNG_WRITE_sCAL_SUPPORTED
  181153. # ifndef PNG_sCAL_SUPPORTED
  181154. # define PNG_sCAL_SUPPORTED
  181155. # endif
  181156. #endif
  181157. #ifndef PNG_NO_WRITE_pHYs
  181158. # define PNG_WRITE_pHYs_SUPPORTED
  181159. # ifndef PNG_pHYs_SUPPORTED
  181160. # define PNG_pHYs_SUPPORTED
  181161. # endif
  181162. #endif
  181163. #ifndef PNG_NO_WRITE_sBIT
  181164. # define PNG_WRITE_sBIT_SUPPORTED
  181165. # ifndef PNG_sBIT_SUPPORTED
  181166. # define PNG_sBIT_SUPPORTED
  181167. # endif
  181168. #endif
  181169. #ifndef PNG_NO_WRITE_sPLT
  181170. # define PNG_WRITE_sPLT_SUPPORTED
  181171. # ifndef PNG_sPLT_SUPPORTED
  181172. # define PNG_sPLT_SUPPORTED
  181173. # endif
  181174. #endif
  181175. #ifndef PNG_NO_WRITE_sRGB
  181176. # define PNG_WRITE_sRGB_SUPPORTED
  181177. # ifndef PNG_sRGB_SUPPORTED
  181178. # define PNG_sRGB_SUPPORTED
  181179. # endif
  181180. #endif
  181181. #ifndef PNG_NO_WRITE_tEXt
  181182. # define PNG_WRITE_tEXt_SUPPORTED
  181183. # ifndef PNG_tEXt_SUPPORTED
  181184. # define PNG_tEXt_SUPPORTED
  181185. # endif
  181186. #endif
  181187. #ifndef PNG_NO_WRITE_tIME
  181188. # define PNG_WRITE_tIME_SUPPORTED
  181189. # ifndef PNG_tIME_SUPPORTED
  181190. # define PNG_tIME_SUPPORTED
  181191. # endif
  181192. #endif
  181193. #ifndef PNG_NO_WRITE_tRNS
  181194. # define PNG_WRITE_tRNS_SUPPORTED
  181195. # ifndef PNG_tRNS_SUPPORTED
  181196. # define PNG_tRNS_SUPPORTED
  181197. # endif
  181198. #endif
  181199. #ifndef PNG_NO_WRITE_zTXt
  181200. # define PNG_WRITE_zTXt_SUPPORTED
  181201. # ifndef PNG_zTXt_SUPPORTED
  181202. # define PNG_zTXt_SUPPORTED
  181203. # endif
  181204. #endif
  181205. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181206. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181207. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181208. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181209. # endif
  181210. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181211. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181212. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181213. # endif
  181214. # endif
  181215. #endif
  181216. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181217. defined(PNG_WRITE_zTXt_SUPPORTED)
  181218. # define PNG_WRITE_TEXT_SUPPORTED
  181219. # ifndef PNG_TEXT_SUPPORTED
  181220. # define PNG_TEXT_SUPPORTED
  181221. # endif
  181222. #endif
  181223. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181224. /* Turn this off to disable png_read_png() and
  181225. * png_write_png() and leave the row_pointers member
  181226. * out of the info structure.
  181227. */
  181228. #ifndef PNG_NO_INFO_IMAGE
  181229. # define PNG_INFO_IMAGE_SUPPORTED
  181230. #endif
  181231. /* need the time information for reading tIME chunks */
  181232. #if defined(PNG_tIME_SUPPORTED)
  181233. # if !defined(_WIN32_WCE)
  181234. /* "time.h" functions are not supported on WindowsCE */
  181235. # include <time.h>
  181236. # endif
  181237. #endif
  181238. /* Some typedefs to get us started. These should be safe on most of the
  181239. * common platforms. The typedefs should be at least as large as the
  181240. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181241. * don't have to be exactly that size. Some compilers dislike passing
  181242. * unsigned shorts as function parameters, so you may be better off using
  181243. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181244. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181245. */
  181246. typedef unsigned long png_uint_32;
  181247. typedef long png_int_32;
  181248. typedef unsigned short png_uint_16;
  181249. typedef short png_int_16;
  181250. typedef unsigned char png_byte;
  181251. /* This is usually size_t. It is typedef'ed just in case you need it to
  181252. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181253. #ifdef PNG_SIZE_T
  181254. typedef PNG_SIZE_T png_size_t;
  181255. # define png_sizeof(x) png_convert_size(sizeof (x))
  181256. #else
  181257. typedef size_t png_size_t;
  181258. # define png_sizeof(x) sizeof (x)
  181259. #endif
  181260. /* The following is needed for medium model support. It cannot be in the
  181261. * PNG_INTERNAL section. Needs modification for other compilers besides
  181262. * MSC. Model independent support declares all arrays and pointers to be
  181263. * large using the far keyword. The zlib version used must also support
  181264. * model independent data. As of version zlib 1.0.4, the necessary changes
  181265. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181266. * changes that are needed. (Tim Wegner)
  181267. */
  181268. /* Separate compiler dependencies (problem here is that zlib.h always
  181269. defines FAR. (SJT) */
  181270. #ifdef __BORLANDC__
  181271. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181272. # define LDATA 1
  181273. # else
  181274. # define LDATA 0
  181275. # endif
  181276. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181277. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181278. # define PNG_MAX_MALLOC_64K
  181279. # if (LDATA != 1)
  181280. # ifndef FAR
  181281. # define FAR __far
  181282. # endif
  181283. # define USE_FAR_KEYWORD
  181284. # endif /* LDATA != 1 */
  181285. /* Possibly useful for moving data out of default segment.
  181286. * Uncomment it if you want. Could also define FARDATA as
  181287. * const if your compiler supports it. (SJT)
  181288. # define FARDATA FAR
  181289. */
  181290. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181291. #endif /* __BORLANDC__ */
  181292. /* Suggest testing for specific compiler first before testing for
  181293. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181294. * making reliance oncertain keywords suspect. (SJT)
  181295. */
  181296. /* MSC Medium model */
  181297. #if defined(FAR)
  181298. # if defined(M_I86MM)
  181299. # define USE_FAR_KEYWORD
  181300. # define FARDATA FAR
  181301. # include <dos.h>
  181302. # endif
  181303. #endif
  181304. /* SJT: default case */
  181305. #ifndef FAR
  181306. # define FAR
  181307. #endif
  181308. /* At this point FAR is always defined */
  181309. #ifndef FARDATA
  181310. # define FARDATA
  181311. #endif
  181312. /* Typedef for floating-point numbers that are converted
  181313. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181314. typedef png_int_32 png_fixed_point;
  181315. /* Add typedefs for pointers */
  181316. typedef void FAR * png_voidp;
  181317. typedef png_byte FAR * png_bytep;
  181318. typedef png_uint_32 FAR * png_uint_32p;
  181319. typedef png_int_32 FAR * png_int_32p;
  181320. typedef png_uint_16 FAR * png_uint_16p;
  181321. typedef png_int_16 FAR * png_int_16p;
  181322. typedef PNG_CONST char FAR * png_const_charp;
  181323. typedef char FAR * png_charp;
  181324. typedef png_fixed_point FAR * png_fixed_point_p;
  181325. #ifndef PNG_NO_STDIO
  181326. #if defined(_WIN32_WCE)
  181327. typedef HANDLE png_FILE_p;
  181328. #else
  181329. typedef FILE * png_FILE_p;
  181330. #endif
  181331. #endif
  181332. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181333. typedef double FAR * png_doublep;
  181334. #endif
  181335. /* Pointers to pointers; i.e. arrays */
  181336. typedef png_byte FAR * FAR * png_bytepp;
  181337. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181338. typedef png_int_32 FAR * FAR * png_int_32pp;
  181339. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181340. typedef png_int_16 FAR * FAR * png_int_16pp;
  181341. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181342. typedef char FAR * FAR * png_charpp;
  181343. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181344. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181345. typedef double FAR * FAR * png_doublepp;
  181346. #endif
  181347. /* Pointers to pointers to pointers; i.e., pointer to array */
  181348. typedef char FAR * FAR * FAR * png_charppp;
  181349. #if 0
  181350. /* SPC - Is this stuff deprecated? */
  181351. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181352. /* libpng typedefs for types in zlib. If zlib changes
  181353. * or another compression library is used, then change these.
  181354. * Eliminates need to change all the source files.
  181355. */
  181356. typedef charf * png_zcharp;
  181357. typedef charf * FAR * png_zcharpp;
  181358. typedef z_stream FAR * png_zstreamp;
  181359. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181360. /*
  181361. * Define PNG_BUILD_DLL if the module being built is a Windows
  181362. * LIBPNG DLL.
  181363. *
  181364. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181365. * It is equivalent to Microsoft predefined macro _DLL that is
  181366. * automatically defined when you compile using the share
  181367. * version of the CRT (C Run-Time library)
  181368. *
  181369. * The cygwin mods make this behavior a little different:
  181370. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181371. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181372. * -or- if you are building an application that you want to link to the
  181373. * static library.
  181374. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181375. * the other flags is defined.
  181376. */
  181377. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181378. # define PNG_DLL
  181379. #endif
  181380. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181381. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181382. * command-line override
  181383. */
  181384. #if defined(__CYGWIN__)
  181385. # if !defined(PNG_STATIC)
  181386. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181387. # undef PNG_USE_GLOBAL_ARRAYS
  181388. # endif
  181389. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181390. # define PNG_USE_LOCAL_ARRAYS
  181391. # endif
  181392. # else
  181393. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181394. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181395. # undef PNG_USE_GLOBAL_ARRAYS
  181396. # endif
  181397. # endif
  181398. # endif
  181399. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181400. # define PNG_USE_LOCAL_ARRAYS
  181401. # endif
  181402. #endif
  181403. /* Do not use global arrays (helps with building DLL's)
  181404. * They are no longer used in libpng itself, since version 1.0.5c,
  181405. * but might be required for some pre-1.0.5c applications.
  181406. */
  181407. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181408. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181409. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181410. # define PNG_USE_LOCAL_ARRAYS
  181411. # else
  181412. # define PNG_USE_GLOBAL_ARRAYS
  181413. # endif
  181414. #endif
  181415. #if defined(__CYGWIN__)
  181416. # undef PNGAPI
  181417. # define PNGAPI __cdecl
  181418. # undef PNG_IMPEXP
  181419. # define PNG_IMPEXP
  181420. #endif
  181421. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181422. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181423. * Don't ignore those warnings; you must also reset the default calling
  181424. * convention in your compiler to match your PNGAPI, and you must build
  181425. * zlib and your applications the same way you build libpng.
  181426. */
  181427. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181428. # ifndef PNG_NO_MODULEDEF
  181429. # define PNG_NO_MODULEDEF
  181430. # endif
  181431. #endif
  181432. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181433. # define PNG_IMPEXP
  181434. #endif
  181435. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181436. (( defined(_Windows) || defined(_WINDOWS) || \
  181437. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181438. # ifndef PNGAPI
  181439. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181440. # define PNGAPI __cdecl
  181441. # else
  181442. # define PNGAPI _cdecl
  181443. # endif
  181444. # endif
  181445. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181446. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181447. # define PNG_IMPEXP
  181448. # endif
  181449. # if !defined(PNG_IMPEXP)
  181450. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181451. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181452. /* Borland/Microsoft */
  181453. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181454. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181455. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181456. # else
  181457. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181458. # if defined(PNG_BUILD_DLL)
  181459. # define PNG_IMPEXP __export
  181460. # else
  181461. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181462. VC++ */
  181463. # endif /* Exists in Borland C++ for
  181464. C++ classes (== huge) */
  181465. # endif
  181466. # endif
  181467. # if !defined(PNG_IMPEXP)
  181468. # if defined(PNG_BUILD_DLL)
  181469. # define PNG_IMPEXP __declspec(dllexport)
  181470. # else
  181471. # define PNG_IMPEXP __declspec(dllimport)
  181472. # endif
  181473. # endif
  181474. # endif /* PNG_IMPEXP */
  181475. #else /* !(DLL || non-cygwin WINDOWS) */
  181476. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181477. # ifndef PNGAPI
  181478. # define PNGAPI _System
  181479. # endif
  181480. # else
  181481. # if 0 /* ... other platforms, with other meanings */
  181482. # endif
  181483. # endif
  181484. #endif
  181485. #ifndef PNGAPI
  181486. # define PNGAPI
  181487. #endif
  181488. #ifndef PNG_IMPEXP
  181489. # define PNG_IMPEXP
  181490. #endif
  181491. #ifdef PNG_BUILDSYMS
  181492. # ifndef PNG_EXPORT
  181493. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181494. # endif
  181495. # ifdef PNG_USE_GLOBAL_ARRAYS
  181496. # ifndef PNG_EXPORT_VAR
  181497. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181498. # endif
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_EXPORT
  181502. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181503. #endif
  181504. #ifdef PNG_USE_GLOBAL_ARRAYS
  181505. # ifndef PNG_EXPORT_VAR
  181506. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181507. # endif
  181508. #endif
  181509. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181510. * functions that are passed far data must be model independent.
  181511. */
  181512. #ifndef PNG_ABORT
  181513. # define PNG_ABORT() abort()
  181514. #endif
  181515. #ifdef PNG_SETJMP_SUPPORTED
  181516. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181517. #else
  181518. # define png_jmpbuf(png_ptr) \
  181519. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181520. #endif
  181521. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181522. /* use this to make far-to-near assignments */
  181523. # define CHECK 1
  181524. # define NOCHECK 0
  181525. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181526. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181527. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181528. # define png_strcpy _fstrcpy
  181529. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181530. # define png_strlen _fstrlen
  181531. # define png_memcmp _fmemcmp /* SJT: added */
  181532. # define png_memcpy _fmemcpy
  181533. # define png_memset _fmemset
  181534. #else /* use the usual functions */
  181535. # define CVT_PTR(ptr) (ptr)
  181536. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181537. # ifndef PNG_NO_SNPRINTF
  181538. # ifdef _MSC_VER
  181539. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181540. # define png_snprintf2 _snprintf
  181541. # define png_snprintf6 _snprintf
  181542. # else
  181543. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181544. # define png_snprintf2 snprintf
  181545. # define png_snprintf6 snprintf
  181546. # endif
  181547. # else
  181548. /* You don't have or don't want to use snprintf(). Caution: Using
  181549. * sprintf instead of snprintf exposes your application to accidental
  181550. * or malevolent buffer overflows. If you don't have snprintf()
  181551. * as a general rule you should provide one (you can get one from
  181552. * Portable OpenSSH). */
  181553. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181554. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181555. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181556. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181557. # endif
  181558. # define png_strcpy strcpy
  181559. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181560. # define png_strlen strlen
  181561. # define png_memcmp memcmp /* SJT: added */
  181562. # define png_memcpy memcpy
  181563. # define png_memset memset
  181564. #endif
  181565. /* End of memory model independent support */
  181566. /* Just a little check that someone hasn't tried to define something
  181567. * contradictory.
  181568. */
  181569. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181570. # undef PNG_ZBUF_SIZE
  181571. # define PNG_ZBUF_SIZE 65536L
  181572. #endif
  181573. /* Added at libpng-1.2.8 */
  181574. #endif /* PNG_VERSION_INFO_ONLY */
  181575. #endif /* PNGCONF_H */
  181576. /*** End of inlined file: pngconf.h ***/
  181577. #ifdef _MSC_VER
  181578. #pragma warning (disable: 4996 4100)
  181579. #endif
  181580. /*
  181581. * Added at libpng-1.2.8 */
  181582. /* Ref MSDN: Private as priority over Special
  181583. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181584. * procedures. If this value is given, the StringFileInfo block must
  181585. * contain a PrivateBuild string.
  181586. *
  181587. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181588. * standard release procedures but is a variation of the standard
  181589. * file of the same version number. If this value is given, the
  181590. * StringFileInfo block must contain a SpecialBuild string.
  181591. */
  181592. #if defined(PNG_USER_PRIVATEBUILD)
  181593. # define PNG_LIBPNG_BUILD_TYPE \
  181594. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181595. #else
  181596. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181597. # define PNG_LIBPNG_BUILD_TYPE \
  181598. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181599. # else
  181600. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181601. # endif
  181602. #endif
  181603. #ifndef PNG_VERSION_INFO_ONLY
  181604. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181605. #ifdef __cplusplus
  181606. //extern "C" {
  181607. #endif /* __cplusplus */
  181608. /* This file is arranged in several sections. The first section contains
  181609. * structure and type definitions. The second section contains the external
  181610. * library functions, while the third has the internal library functions,
  181611. * which applications aren't expected to use directly.
  181612. */
  181613. #ifndef PNG_NO_TYPECAST_NULL
  181614. #define int_p_NULL (int *)NULL
  181615. #define png_bytep_NULL (png_bytep)NULL
  181616. #define png_bytepp_NULL (png_bytepp)NULL
  181617. #define png_doublep_NULL (png_doublep)NULL
  181618. #define png_error_ptr_NULL (png_error_ptr)NULL
  181619. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181620. #define png_free_ptr_NULL (png_free_ptr)NULL
  181621. #define png_infopp_NULL (png_infopp)NULL
  181622. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181623. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181624. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181625. #define png_structp_NULL (png_structp)NULL
  181626. #define png_uint_16p_NULL (png_uint_16p)NULL
  181627. #define png_voidp_NULL (png_voidp)NULL
  181628. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181629. #else
  181630. #define int_p_NULL NULL
  181631. #define png_bytep_NULL NULL
  181632. #define png_bytepp_NULL NULL
  181633. #define png_doublep_NULL NULL
  181634. #define png_error_ptr_NULL NULL
  181635. #define png_flush_ptr_NULL NULL
  181636. #define png_free_ptr_NULL NULL
  181637. #define png_infopp_NULL NULL
  181638. #define png_malloc_ptr_NULL NULL
  181639. #define png_read_status_ptr_NULL NULL
  181640. #define png_rw_ptr_NULL NULL
  181641. #define png_structp_NULL NULL
  181642. #define png_uint_16p_NULL NULL
  181643. #define png_voidp_NULL NULL
  181644. #define png_write_status_ptr_NULL NULL
  181645. #endif
  181646. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181647. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181648. /* Version information for C files, stored in png.c. This had better match
  181649. * the version above.
  181650. */
  181651. #ifdef PNG_USE_GLOBAL_ARRAYS
  181652. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181653. /* need room for 99.99.99beta99z */
  181654. #else
  181655. #define png_libpng_ver png_get_header_ver(NULL)
  181656. #endif
  181657. #ifdef PNG_USE_GLOBAL_ARRAYS
  181658. /* This was removed in version 1.0.5c */
  181659. /* Structures to facilitate easy interlacing. See png.c for more details */
  181660. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181661. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181662. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181663. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181664. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181665. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181666. /* This isn't currently used. If you need it, see png.c for more details.
  181667. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181668. */
  181669. #endif
  181670. #endif /* PNG_NO_EXTERN */
  181671. /* Three color definitions. The order of the red, green, and blue, (and the
  181672. * exact size) is not important, although the size of the fields need to
  181673. * be png_byte or png_uint_16 (as defined below).
  181674. */
  181675. typedef struct png_color_struct
  181676. {
  181677. png_byte red;
  181678. png_byte green;
  181679. png_byte blue;
  181680. } png_color;
  181681. typedef png_color FAR * png_colorp;
  181682. typedef png_color FAR * FAR * png_colorpp;
  181683. typedef struct png_color_16_struct
  181684. {
  181685. png_byte index; /* used for palette files */
  181686. png_uint_16 red; /* for use in red green blue files */
  181687. png_uint_16 green;
  181688. png_uint_16 blue;
  181689. png_uint_16 gray; /* for use in grayscale files */
  181690. } png_color_16;
  181691. typedef png_color_16 FAR * png_color_16p;
  181692. typedef png_color_16 FAR * FAR * png_color_16pp;
  181693. typedef struct png_color_8_struct
  181694. {
  181695. png_byte red; /* for use in red green blue files */
  181696. png_byte green;
  181697. png_byte blue;
  181698. png_byte gray; /* for use in grayscale files */
  181699. png_byte alpha; /* for alpha channel files */
  181700. } png_color_8;
  181701. typedef png_color_8 FAR * png_color_8p;
  181702. typedef png_color_8 FAR * FAR * png_color_8pp;
  181703. /*
  181704. * The following two structures are used for the in-core representation
  181705. * of sPLT chunks.
  181706. */
  181707. typedef struct png_sPLT_entry_struct
  181708. {
  181709. png_uint_16 red;
  181710. png_uint_16 green;
  181711. png_uint_16 blue;
  181712. png_uint_16 alpha;
  181713. png_uint_16 frequency;
  181714. } png_sPLT_entry;
  181715. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181716. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181717. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181718. * occupy the LSB of their respective members, and the MSB of each member
  181719. * is zero-filled. The frequency member always occupies the full 16 bits.
  181720. */
  181721. typedef struct png_sPLT_struct
  181722. {
  181723. png_charp name; /* palette name */
  181724. png_byte depth; /* depth of palette samples */
  181725. png_sPLT_entryp entries; /* palette entries */
  181726. png_int_32 nentries; /* number of palette entries */
  181727. } png_sPLT_t;
  181728. typedef png_sPLT_t FAR * png_sPLT_tp;
  181729. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181730. #ifdef PNG_TEXT_SUPPORTED
  181731. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181732. * and whether that contents is compressed or not. The "key" field
  181733. * points to a regular zero-terminated C string. The "text", "lang", and
  181734. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181735. * However, the * structure returned by png_get_text() will always contain
  181736. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181737. * so they can be safely used in printf() and other string-handling functions.
  181738. */
  181739. typedef struct png_text_struct
  181740. {
  181741. int compression; /* compression value:
  181742. -1: tEXt, none
  181743. 0: zTXt, deflate
  181744. 1: iTXt, none
  181745. 2: iTXt, deflate */
  181746. png_charp key; /* keyword, 1-79 character description of "text" */
  181747. png_charp text; /* comment, may be an empty string (ie "")
  181748. or a NULL pointer */
  181749. png_size_t text_length; /* length of the text string */
  181750. #ifdef PNG_iTXt_SUPPORTED
  181751. png_size_t itxt_length; /* length of the itxt string */
  181752. png_charp lang; /* language code, 0-79 characters
  181753. or a NULL pointer */
  181754. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181755. chars or a NULL pointer */
  181756. #endif
  181757. } png_text;
  181758. typedef png_text FAR * png_textp;
  181759. typedef png_text FAR * FAR * png_textpp;
  181760. #endif
  181761. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181762. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181763. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181764. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181765. #define PNG_TEXT_COMPRESSION_NONE -1
  181766. #define PNG_TEXT_COMPRESSION_zTXt 0
  181767. #define PNG_ITXT_COMPRESSION_NONE 1
  181768. #define PNG_ITXT_COMPRESSION_zTXt 2
  181769. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181770. /* png_time is a way to hold the time in an machine independent way.
  181771. * Two conversions are provided, both from time_t and struct tm. There
  181772. * is no portable way to convert to either of these structures, as far
  181773. * as I know. If you know of a portable way, send it to me. As a side
  181774. * note - PNG has always been Year 2000 compliant!
  181775. */
  181776. typedef struct png_time_struct
  181777. {
  181778. png_uint_16 year; /* full year, as in, 1995 */
  181779. png_byte month; /* month of year, 1 - 12 */
  181780. png_byte day; /* day of month, 1 - 31 */
  181781. png_byte hour; /* hour of day, 0 - 23 */
  181782. png_byte minute; /* minute of hour, 0 - 59 */
  181783. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181784. } png_time;
  181785. typedef png_time FAR * png_timep;
  181786. typedef png_time FAR * FAR * png_timepp;
  181787. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181788. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181789. * no specific support. The idea is that we can use this to queue
  181790. * up private chunks for output even though the library doesn't actually
  181791. * know about their semantics.
  181792. */
  181793. typedef struct png_unknown_chunk_t
  181794. {
  181795. png_byte name[5];
  181796. png_byte *data;
  181797. png_size_t size;
  181798. /* libpng-using applications should NOT directly modify this byte. */
  181799. png_byte location; /* mode of operation at read time */
  181800. }
  181801. png_unknown_chunk;
  181802. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181803. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181804. #endif
  181805. /* png_info is a structure that holds the information in a PNG file so
  181806. * that the application can find out the characteristics of the image.
  181807. * If you are reading the file, this structure will tell you what is
  181808. * in the PNG file. If you are writing the file, fill in the information
  181809. * you want to put into the PNG file, then call png_write_info().
  181810. * The names chosen should be very close to the PNG specification, so
  181811. * consult that document for information about the meaning of each field.
  181812. *
  181813. * With libpng < 0.95, it was only possible to directly set and read the
  181814. * the values in the png_info_struct, which meant that the contents and
  181815. * order of the values had to remain fixed. With libpng 0.95 and later,
  181816. * however, there are now functions that abstract the contents of
  181817. * png_info_struct from the application, so this makes it easier to use
  181818. * libpng with dynamic libraries, and even makes it possible to use
  181819. * libraries that don't have all of the libpng ancillary chunk-handing
  181820. * functionality.
  181821. *
  181822. * In any case, the order of the parameters in png_info_struct should NOT
  181823. * be changed for as long as possible to keep compatibility with applications
  181824. * that use the old direct-access method with png_info_struct.
  181825. *
  181826. * The following members may have allocated storage attached that should be
  181827. * cleaned up before the structure is discarded: palette, trans, text,
  181828. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181829. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181830. * are automatically freed when the info structure is deallocated, if they were
  181831. * allocated internally by libpng. This behavior can be changed by means
  181832. * of the png_data_freer() function.
  181833. *
  181834. * More allocation details: all the chunk-reading functions that
  181835. * change these members go through the corresponding png_set_*
  181836. * functions. A function to clear these members is available: see
  181837. * png_free_data(). The png_set_* functions do not depend on being
  181838. * able to point info structure members to any of the storage they are
  181839. * passed (they make their own copies), EXCEPT that the png_set_text
  181840. * functions use the same storage passed to them in the text_ptr or
  181841. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181842. * functions do not make their own copies.
  181843. */
  181844. typedef struct png_info_struct
  181845. {
  181846. /* the following are necessary for every PNG file */
  181847. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181848. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181849. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181850. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181851. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181852. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181853. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181854. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181855. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181856. /* The following three should have been named *_method not *_type */
  181857. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181858. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181859. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181860. /* The following is informational only on read, and not used on writes. */
  181861. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181862. png_byte pixel_depth; /* number of bits per pixel */
  181863. png_byte spare_byte; /* to align the data, and for future use */
  181864. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181865. /* The rest of the data is optional. If you are reading, check the
  181866. * valid field to see if the information in these are valid. If you
  181867. * are writing, set the valid field to those chunks you want written,
  181868. * and initialize the appropriate fields below.
  181869. */
  181870. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181871. /* The gAMA chunk describes the gamma characteristics of the system
  181872. * on which the image was created, normally in the range [1.0, 2.5].
  181873. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181874. */
  181875. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181876. #endif
  181877. #if defined(PNG_sRGB_SUPPORTED)
  181878. /* GR-P, 0.96a */
  181879. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181880. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181881. #endif
  181882. #if defined(PNG_TEXT_SUPPORTED)
  181883. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181884. * uncompressed, compressed, and optionally compressed forms, respectively.
  181885. * The data in "text" is an array of pointers to uncompressed,
  181886. * null-terminated C strings. Each chunk has a keyword that describes the
  181887. * textual data contained in that chunk. Keywords are not required to be
  181888. * unique, and the text string may be empty. Any number of text chunks may
  181889. * be in an image.
  181890. */
  181891. int num_text; /* number of comments read/to write */
  181892. int max_text; /* current size of text array */
  181893. png_textp text; /* array of comments read/to write */
  181894. #endif /* PNG_TEXT_SUPPORTED */
  181895. #if defined(PNG_tIME_SUPPORTED)
  181896. /* The tIME chunk holds the last time the displayed image data was
  181897. * modified. See the png_time struct for the contents of this struct.
  181898. */
  181899. png_time mod_time;
  181900. #endif
  181901. #if defined(PNG_sBIT_SUPPORTED)
  181902. /* The sBIT chunk specifies the number of significant high-order bits
  181903. * in the pixel data. Values are in the range [1, bit_depth], and are
  181904. * only specified for the channels in the pixel data. The contents of
  181905. * the low-order bits is not specified. Data is valid if
  181906. * (valid & PNG_INFO_sBIT) is non-zero.
  181907. */
  181908. png_color_8 sig_bit; /* significant bits in color channels */
  181909. #endif
  181910. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181911. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181912. /* The tRNS chunk supplies transparency data for paletted images and
  181913. * other image types that don't need a full alpha channel. There are
  181914. * "num_trans" transparency values for a paletted image, stored in the
  181915. * same order as the palette colors, starting from index 0. Values
  181916. * for the data are in the range [0, 255], ranging from fully transparent
  181917. * to fully opaque, respectively. For non-paletted images, there is a
  181918. * single color specified that should be treated as fully transparent.
  181919. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181920. */
  181921. png_bytep trans; /* transparent values for paletted image */
  181922. png_color_16 trans_values; /* transparent color for non-palette image */
  181923. #endif
  181924. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181925. /* The bKGD chunk gives the suggested image background color if the
  181926. * display program does not have its own background color and the image
  181927. * is needs to composited onto a background before display. The colors
  181928. * in "background" are normally in the same color space/depth as the
  181929. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181930. */
  181931. png_color_16 background;
  181932. #endif
  181933. #if defined(PNG_oFFs_SUPPORTED)
  181934. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181935. * and downwards from the top-left corner of the display, page, or other
  181936. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181937. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181938. */
  181939. png_int_32 x_offset; /* x offset on page */
  181940. png_int_32 y_offset; /* y offset on page */
  181941. png_byte offset_unit_type; /* offset units type */
  181942. #endif
  181943. #if defined(PNG_pHYs_SUPPORTED)
  181944. /* The pHYs chunk gives the physical pixel density of the image for
  181945. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181946. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181947. */
  181948. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181949. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181950. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181951. #endif
  181952. #if defined(PNG_hIST_SUPPORTED)
  181953. /* The hIST chunk contains the relative frequency or importance of the
  181954. * various palette entries, so that a viewer can intelligently select a
  181955. * reduced-color palette, if required. Data is an array of "num_palette"
  181956. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181957. * is non-zero.
  181958. */
  181959. png_uint_16p hist;
  181960. #endif
  181961. #ifdef PNG_cHRM_SUPPORTED
  181962. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181963. * on which the PNG was created. This data allows the viewer to do gamut
  181964. * mapping of the input image to ensure that the viewer sees the same
  181965. * colors in the image as the creator. Values are in the range
  181966. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181967. */
  181968. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181969. float x_white;
  181970. float y_white;
  181971. float x_red;
  181972. float y_red;
  181973. float x_green;
  181974. float y_green;
  181975. float x_blue;
  181976. float y_blue;
  181977. #endif
  181978. #endif
  181979. #if defined(PNG_pCAL_SUPPORTED)
  181980. /* The pCAL chunk describes a transformation between the stored pixel
  181981. * values and original physical data values used to create the image.
  181982. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181983. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181984. * (possibly non-linear) transformation function given by "pcal_type"
  181985. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181986. * defines below, and the PNG-Group's PNG extensions document for a
  181987. * complete description of the transformations and how they should be
  181988. * implemented, and for a description of the ASCII parameter strings.
  181989. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181990. */
  181991. png_charp pcal_purpose; /* pCAL chunk description string */
  181992. png_int_32 pcal_X0; /* minimum value */
  181993. png_int_32 pcal_X1; /* maximum value */
  181994. png_charp pcal_units; /* Latin-1 string giving physical units */
  181995. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181996. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181997. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181998. #endif
  181999. /* New members added in libpng-1.0.6 */
  182000. #ifdef PNG_FREE_ME_SUPPORTED
  182001. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182002. #endif
  182003. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182004. /* storage for unknown chunks that the library doesn't recognize. */
  182005. png_unknown_chunkp unknown_chunks;
  182006. png_size_t unknown_chunks_num;
  182007. #endif
  182008. #if defined(PNG_iCCP_SUPPORTED)
  182009. /* iCCP chunk data. */
  182010. png_charp iccp_name; /* profile name */
  182011. png_charp iccp_profile; /* International Color Consortium profile data */
  182012. /* Note to maintainer: should be png_bytep */
  182013. png_uint_32 iccp_proflen; /* ICC profile data length */
  182014. png_byte iccp_compression; /* Always zero */
  182015. #endif
  182016. #if defined(PNG_sPLT_SUPPORTED)
  182017. /* data on sPLT chunks (there may be more than one). */
  182018. png_sPLT_tp splt_palettes;
  182019. png_uint_32 splt_palettes_num;
  182020. #endif
  182021. #if defined(PNG_sCAL_SUPPORTED)
  182022. /* The sCAL chunk describes the actual physical dimensions of the
  182023. * subject matter of the graphic. The chunk contains a unit specification
  182024. * a byte value, and two ASCII strings representing floating-point
  182025. * values. The values are width and height corresponsing to one pixel
  182026. * in the image. This external representation is converted to double
  182027. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182028. */
  182029. png_byte scal_unit; /* unit of physical scale */
  182030. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182031. double scal_pixel_width; /* width of one pixel */
  182032. double scal_pixel_height; /* height of one pixel */
  182033. #endif
  182034. #ifdef PNG_FIXED_POINT_SUPPORTED
  182035. png_charp scal_s_width; /* string containing height */
  182036. png_charp scal_s_height; /* string containing width */
  182037. #endif
  182038. #endif
  182039. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182040. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182041. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182042. png_bytepp row_pointers; /* the image bits */
  182043. #endif
  182044. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182045. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182046. #endif
  182047. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182048. png_fixed_point int_x_white;
  182049. png_fixed_point int_y_white;
  182050. png_fixed_point int_x_red;
  182051. png_fixed_point int_y_red;
  182052. png_fixed_point int_x_green;
  182053. png_fixed_point int_y_green;
  182054. png_fixed_point int_x_blue;
  182055. png_fixed_point int_y_blue;
  182056. #endif
  182057. } png_info;
  182058. typedef png_info FAR * png_infop;
  182059. typedef png_info FAR * FAR * png_infopp;
  182060. /* Maximum positive integer used in PNG is (2^31)-1 */
  182061. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182062. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182063. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182064. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182065. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182066. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182067. #endif
  182068. /* These describe the color_type field in png_info. */
  182069. /* color type masks */
  182070. #define PNG_COLOR_MASK_PALETTE 1
  182071. #define PNG_COLOR_MASK_COLOR 2
  182072. #define PNG_COLOR_MASK_ALPHA 4
  182073. /* color types. Note that not all combinations are legal */
  182074. #define PNG_COLOR_TYPE_GRAY 0
  182075. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182076. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182077. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182078. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182079. /* aliases */
  182080. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182081. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182082. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182083. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182084. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182085. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182086. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182087. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182088. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182089. /* These are for the interlacing type. These values should NOT be changed. */
  182090. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182091. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182092. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182093. /* These are for the oFFs chunk. These values should NOT be changed. */
  182094. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182095. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182096. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182097. /* These are for the pCAL chunk. These values should NOT be changed. */
  182098. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182099. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182100. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182101. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182102. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182103. /* These are for the sCAL chunk. These values should NOT be changed. */
  182104. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182105. #define PNG_SCALE_METER 1 /* meters per pixel */
  182106. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182107. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182108. /* These are for the pHYs chunk. These values should NOT be changed. */
  182109. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182110. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182111. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182112. /* These are for the sRGB chunk. These values should NOT be changed. */
  182113. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182114. #define PNG_sRGB_INTENT_RELATIVE 1
  182115. #define PNG_sRGB_INTENT_SATURATION 2
  182116. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182117. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182118. /* This is for text chunks */
  182119. #define PNG_KEYWORD_MAX_LENGTH 79
  182120. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182121. #define PNG_MAX_PALETTE_LENGTH 256
  182122. /* These determine if an ancillary chunk's data has been successfully read
  182123. * from the PNG header, or if the application has filled in the corresponding
  182124. * data in the info_struct to be written into the output file. The values
  182125. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182126. */
  182127. #define PNG_INFO_gAMA 0x0001
  182128. #define PNG_INFO_sBIT 0x0002
  182129. #define PNG_INFO_cHRM 0x0004
  182130. #define PNG_INFO_PLTE 0x0008
  182131. #define PNG_INFO_tRNS 0x0010
  182132. #define PNG_INFO_bKGD 0x0020
  182133. #define PNG_INFO_hIST 0x0040
  182134. #define PNG_INFO_pHYs 0x0080
  182135. #define PNG_INFO_oFFs 0x0100
  182136. #define PNG_INFO_tIME 0x0200
  182137. #define PNG_INFO_pCAL 0x0400
  182138. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182139. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182140. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182141. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182142. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182143. /* This is used for the transformation routines, as some of them
  182144. * change these values for the row. It also should enable using
  182145. * the routines for other purposes.
  182146. */
  182147. typedef struct png_row_info_struct
  182148. {
  182149. png_uint_32 width; /* width of row */
  182150. png_uint_32 rowbytes; /* number of bytes in row */
  182151. png_byte color_type; /* color type of row */
  182152. png_byte bit_depth; /* bit depth of row */
  182153. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182154. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182155. } png_row_info;
  182156. typedef png_row_info FAR * png_row_infop;
  182157. typedef png_row_info FAR * FAR * png_row_infopp;
  182158. /* These are the function types for the I/O functions and for the functions
  182159. * that allow the user to override the default I/O functions with his or her
  182160. * own. The png_error_ptr type should match that of user-supplied warning
  182161. * and error functions, while the png_rw_ptr type should match that of the
  182162. * user read/write data functions.
  182163. */
  182164. typedef struct png_struct_def png_struct;
  182165. typedef png_struct FAR * png_structp;
  182166. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182167. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182168. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182169. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182170. int));
  182171. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182172. int));
  182173. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182174. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182175. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182176. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182177. png_uint_32, int));
  182178. #endif
  182179. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182180. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182181. defined(PNG_LEGACY_SUPPORTED)
  182182. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182183. png_row_infop, png_bytep));
  182184. #endif
  182185. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182186. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182187. #endif
  182188. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182189. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182190. #endif
  182191. /* Transform masks for the high-level interface */
  182192. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182193. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182194. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182195. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182196. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182197. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182198. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182199. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182200. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182201. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182202. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182203. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182204. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182205. /* Flags for MNG supported features */
  182206. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182207. #define PNG_FLAG_MNG_FILTER_64 0x04
  182208. #define PNG_ALL_MNG_FEATURES 0x05
  182209. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182210. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182211. /* The structure that holds the information to read and write PNG files.
  182212. * The only people who need to care about what is inside of this are the
  182213. * people who will be modifying the library for their own special needs.
  182214. * It should NOT be accessed directly by an application, except to store
  182215. * the jmp_buf.
  182216. */
  182217. struct png_struct_def
  182218. {
  182219. #ifdef PNG_SETJMP_SUPPORTED
  182220. jmp_buf jmpbuf; /* used in png_error */
  182221. #endif
  182222. png_error_ptr error_fn; /* function for printing errors and aborting */
  182223. png_error_ptr warning_fn; /* function for printing warnings */
  182224. png_voidp error_ptr; /* user supplied struct for error functions */
  182225. png_rw_ptr write_data_fn; /* function for writing output data */
  182226. png_rw_ptr read_data_fn; /* function for reading input data */
  182227. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182228. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182229. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182230. #endif
  182231. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182232. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182233. #endif
  182234. /* These were added in libpng-1.0.2 */
  182235. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182236. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182237. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182238. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182239. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182240. png_byte user_transform_channels; /* channels in user transformed pixels */
  182241. #endif
  182242. #endif
  182243. png_uint_32 mode; /* tells us where we are in the PNG file */
  182244. png_uint_32 flags; /* flags indicating various things to libpng */
  182245. png_uint_32 transformations; /* which transformations to perform */
  182246. z_stream zstream; /* pointer to decompression structure (below) */
  182247. png_bytep zbuf; /* buffer for zlib */
  182248. png_size_t zbuf_size; /* size of zbuf */
  182249. int zlib_level; /* holds zlib compression level */
  182250. int zlib_method; /* holds zlib compression method */
  182251. int zlib_window_bits; /* holds zlib compression window bits */
  182252. int zlib_mem_level; /* holds zlib compression memory level */
  182253. int zlib_strategy; /* holds zlib compression strategy */
  182254. png_uint_32 width; /* width of image in pixels */
  182255. png_uint_32 height; /* height of image in pixels */
  182256. png_uint_32 num_rows; /* number of rows in current pass */
  182257. png_uint_32 usr_width; /* width of row at start of write */
  182258. png_uint_32 rowbytes; /* size of row in bytes */
  182259. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182260. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182261. png_uint_32 row_number; /* current row in interlace pass */
  182262. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182263. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182264. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182265. png_bytep up_row; /* buffer to save "up" row when filtering */
  182266. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182267. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182268. png_row_info row_info; /* used for transformation routines */
  182269. png_uint_32 idat_size; /* current IDAT size for read */
  182270. png_uint_32 crc; /* current chunk CRC value */
  182271. png_colorp palette; /* palette from the input file */
  182272. png_uint_16 num_palette; /* number of color entries in palette */
  182273. png_uint_16 num_trans; /* number of transparency values */
  182274. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182275. png_byte compression; /* file compression type (always 0) */
  182276. png_byte filter; /* file filter type (always 0) */
  182277. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182278. png_byte pass; /* current interlace pass (0 - 6) */
  182279. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182280. png_byte color_type; /* color type of file */
  182281. png_byte bit_depth; /* bit depth of file */
  182282. png_byte usr_bit_depth; /* bit depth of users row */
  182283. png_byte pixel_depth; /* number of bits per pixel */
  182284. png_byte channels; /* number of channels in file */
  182285. png_byte usr_channels; /* channels at start of write */
  182286. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182287. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182288. #ifdef PNG_LEGACY_SUPPORTED
  182289. png_byte filler; /* filler byte for pixel expansion */
  182290. #else
  182291. png_uint_16 filler; /* filler bytes for pixel expansion */
  182292. #endif
  182293. #endif
  182294. #if defined(PNG_bKGD_SUPPORTED)
  182295. png_byte background_gamma_type;
  182296. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182297. float background_gamma;
  182298. # endif
  182299. png_color_16 background; /* background color in screen gamma space */
  182300. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182301. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182302. #endif
  182303. #endif /* PNG_bKGD_SUPPORTED */
  182304. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182305. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182306. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182307. png_uint_32 flush_rows; /* number of rows written since last flush */
  182308. #endif
  182309. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182310. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182311. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182312. float gamma; /* file gamma value */
  182313. float screen_gamma; /* screen gamma value (display_exponent) */
  182314. #endif
  182315. #endif
  182316. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182317. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182318. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182319. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182320. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182321. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182322. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182323. #endif
  182324. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182325. png_color_8 sig_bit; /* significant bits in each available channel */
  182326. #endif
  182327. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182328. png_color_8 shift; /* shift for significant bit tranformation */
  182329. #endif
  182330. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182331. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182332. png_bytep trans; /* transparency values for paletted files */
  182333. png_color_16 trans_values; /* transparency values for non-paletted files */
  182334. #endif
  182335. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182336. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182337. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182338. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182339. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182340. png_progressive_end_ptr end_fn; /* called after image is complete */
  182341. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182342. png_bytep save_buffer; /* buffer for previously read data */
  182343. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182344. png_bytep current_buffer; /* buffer for recently used data */
  182345. png_uint_32 push_length; /* size of current input chunk */
  182346. png_uint_32 skip_length; /* bytes to skip in input data */
  182347. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182348. png_size_t save_buffer_max; /* total size of save_buffer */
  182349. png_size_t buffer_size; /* total amount of available input data */
  182350. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182351. int process_mode; /* what push library is currently doing */
  182352. int cur_palette; /* current push library palette index */
  182353. # if defined(PNG_TEXT_SUPPORTED)
  182354. png_size_t current_text_size; /* current size of text input data */
  182355. png_size_t current_text_left; /* how much text left to read in input */
  182356. png_charp current_text; /* current text chunk buffer */
  182357. png_charp current_text_ptr; /* current location in current_text */
  182358. # endif /* PNG_TEXT_SUPPORTED */
  182359. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182360. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182361. /* for the Borland special 64K segment handler */
  182362. png_bytepp offset_table_ptr;
  182363. png_bytep offset_table;
  182364. png_uint_16 offset_table_number;
  182365. png_uint_16 offset_table_count;
  182366. png_uint_16 offset_table_count_free;
  182367. #endif
  182368. #if defined(PNG_READ_DITHER_SUPPORTED)
  182369. png_bytep palette_lookup; /* lookup table for dithering */
  182370. png_bytep dither_index; /* index translation for palette files */
  182371. #endif
  182372. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182373. png_uint_16p hist; /* histogram */
  182374. #endif
  182375. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182376. png_byte heuristic_method; /* heuristic for row filter selection */
  182377. png_byte num_prev_filters; /* number of weights for previous rows */
  182378. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182379. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182380. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182381. png_uint_16p filter_costs; /* relative filter calculation cost */
  182382. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182383. #endif
  182384. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182385. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182386. #endif
  182387. /* New members added in libpng-1.0.6 */
  182388. #ifdef PNG_FREE_ME_SUPPORTED
  182389. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182390. #endif
  182391. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182392. png_voidp user_chunk_ptr;
  182393. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182394. #endif
  182395. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182396. int num_chunk_list;
  182397. png_bytep chunk_list;
  182398. #endif
  182399. /* New members added in libpng-1.0.3 */
  182400. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182401. png_byte rgb_to_gray_status;
  182402. /* These were changed from png_byte in libpng-1.0.6 */
  182403. png_uint_16 rgb_to_gray_red_coeff;
  182404. png_uint_16 rgb_to_gray_green_coeff;
  182405. png_uint_16 rgb_to_gray_blue_coeff;
  182406. #endif
  182407. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182408. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182409. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182410. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182411. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182412. #ifdef PNG_1_0_X
  182413. png_byte mng_features_permitted;
  182414. #else
  182415. png_uint_32 mng_features_permitted;
  182416. #endif /* PNG_1_0_X */
  182417. #endif
  182418. /* New member added in libpng-1.0.7 */
  182419. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182420. png_fixed_point int_gamma;
  182421. #endif
  182422. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182423. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182424. png_byte filter_type;
  182425. #endif
  182426. #if defined(PNG_1_0_X)
  182427. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182428. png_uint_32 row_buf_size;
  182429. #endif
  182430. /* New members added in libpng-1.2.0 */
  182431. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182432. # if !defined(PNG_1_0_X)
  182433. # if defined(PNG_MMX_CODE_SUPPORTED)
  182434. png_byte mmx_bitdepth_threshold;
  182435. png_uint_32 mmx_rowbytes_threshold;
  182436. # endif
  182437. png_uint_32 asm_flags;
  182438. # endif
  182439. #endif
  182440. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182441. #ifdef PNG_USER_MEM_SUPPORTED
  182442. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182443. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182444. png_free_ptr free_fn; /* function for freeing memory */
  182445. #endif
  182446. /* New member added in libpng-1.0.13 and 1.2.0 */
  182447. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182448. #if defined(PNG_READ_DITHER_SUPPORTED)
  182449. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182450. png_bytep dither_sort; /* working sort array */
  182451. png_bytep index_to_palette; /* where the original index currently is */
  182452. /* in the palette */
  182453. png_bytep palette_to_index; /* which original index points to this */
  182454. /* palette color */
  182455. #endif
  182456. /* New members added in libpng-1.0.16 and 1.2.6 */
  182457. png_byte compression_type;
  182458. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182459. png_uint_32 user_width_max;
  182460. png_uint_32 user_height_max;
  182461. #endif
  182462. /* New member added in libpng-1.0.25 and 1.2.17 */
  182463. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182464. /* storage for unknown chunk that the library doesn't recognize. */
  182465. png_unknown_chunk unknown_chunk;
  182466. #endif
  182467. };
  182468. /* This triggers a compiler error in png.c, if png.c and png.h
  182469. * do not agree upon the version number.
  182470. */
  182471. typedef png_structp version_1_2_21;
  182472. typedef png_struct FAR * FAR * png_structpp;
  182473. /* Here are the function definitions most commonly used. This is not
  182474. * the place to find out how to use libpng. See libpng.txt for the
  182475. * full explanation, see example.c for the summary. This just provides
  182476. * a simple one line description of the use of each function.
  182477. */
  182478. /* Returns the version number of the library */
  182479. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182480. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182481. * Handling more than 8 bytes from the beginning of the file is an error.
  182482. */
  182483. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182484. int num_bytes));
  182485. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182486. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182487. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182488. * start > 7 will always fail (ie return non-zero).
  182489. */
  182490. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182491. png_size_t num_to_check));
  182492. /* Simple signature checking function. This is the same as calling
  182493. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182494. */
  182495. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182496. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182497. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182498. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182499. png_error_ptr error_fn, png_error_ptr warn_fn));
  182500. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182501. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182502. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182503. png_error_ptr error_fn, png_error_ptr warn_fn));
  182504. #ifdef PNG_WRITE_SUPPORTED
  182505. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182506. PNGARG((png_structp png_ptr));
  182507. #endif
  182508. #ifdef PNG_WRITE_SUPPORTED
  182509. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182510. PNGARG((png_structp png_ptr, png_uint_32 size));
  182511. #endif
  182512. /* Reset the compression stream */
  182513. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182514. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182515. #ifdef PNG_USER_MEM_SUPPORTED
  182516. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182517. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182518. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182519. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182520. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182521. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182522. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182523. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182524. #endif
  182525. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182526. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182527. png_bytep chunk_name, png_bytep data, png_size_t length));
  182528. /* Write the start of a PNG chunk - length and chunk name. */
  182529. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182530. png_bytep chunk_name, png_uint_32 length));
  182531. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182532. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182533. png_bytep data, png_size_t length));
  182534. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182535. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182536. /* Allocate and initialize the info structure */
  182537. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182538. PNGARG((png_structp png_ptr));
  182539. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182540. /* Initialize the info structure (old interface - DEPRECATED) */
  182541. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182542. #undef png_info_init
  182543. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182544. png_sizeof(png_info));
  182545. #endif
  182546. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182547. png_size_t png_info_struct_size));
  182548. /* Writes all the PNG information before the image. */
  182549. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182550. png_infop info_ptr));
  182551. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182552. png_infop info_ptr));
  182553. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182554. /* read the information before the actual image data. */
  182555. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182556. png_infop info_ptr));
  182557. #endif
  182558. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182559. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182560. PNGARG((png_structp png_ptr, png_timep ptime));
  182561. #endif
  182562. #if !defined(_WIN32_WCE)
  182563. /* "time.h" functions are not supported on WindowsCE */
  182564. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182565. /* convert from a struct tm to png_time */
  182566. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182567. struct tm FAR * ttime));
  182568. /* convert from time_t to png_time. Uses gmtime() */
  182569. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182570. time_t ttime));
  182571. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182572. #endif /* _WIN32_WCE */
  182573. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182574. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182575. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182576. #if !defined(PNG_1_0_X)
  182577. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182578. png_ptr));
  182579. #endif
  182580. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182581. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182582. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182583. /* Deprecated */
  182584. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182585. #endif
  182586. #endif
  182587. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182588. /* Use blue, green, red order for pixels. */
  182589. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182590. #endif
  182591. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182592. /* Expand the grayscale to 24-bit RGB if necessary. */
  182593. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182594. #endif
  182595. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182596. /* Reduce RGB to grayscale. */
  182597. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182598. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182599. int error_action, double red, double green ));
  182600. #endif
  182601. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182602. int error_action, png_fixed_point red, png_fixed_point green ));
  182603. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182604. png_ptr));
  182605. #endif
  182606. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182607. png_colorp palette));
  182608. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182609. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182610. #endif
  182611. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182612. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182613. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182614. #endif
  182615. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182616. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182617. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182618. #endif
  182619. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182620. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182621. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182622. png_uint_32 filler, int flags));
  182623. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182624. #define PNG_FILLER_BEFORE 0
  182625. #define PNG_FILLER_AFTER 1
  182626. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182627. #if !defined(PNG_1_0_X)
  182628. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182629. png_uint_32 filler, int flags));
  182630. #endif
  182631. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182632. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182633. /* Swap bytes in 16-bit depth files. */
  182634. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182635. #endif
  182636. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182637. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182638. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182639. #endif
  182640. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182641. /* Swap packing order of pixels in bytes. */
  182642. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182643. #endif
  182644. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182645. /* Converts files to legal bit depths. */
  182646. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182647. png_color_8p true_bits));
  182648. #endif
  182649. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182650. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182651. /* Have the code handle the interlacing. Returns the number of passes. */
  182652. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182653. #endif
  182654. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182655. /* Invert monochrome files */
  182656. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182657. #endif
  182658. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182659. /* Handle alpha and tRNS by replacing with a background color. */
  182660. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182661. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182662. png_color_16p background_color, int background_gamma_code,
  182663. int need_expand, double background_gamma));
  182664. #endif
  182665. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182666. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182667. #define PNG_BACKGROUND_GAMMA_FILE 2
  182668. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182669. #endif
  182670. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182671. /* strip the second byte of information from a 16-bit depth file. */
  182672. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182673. #endif
  182674. #if defined(PNG_READ_DITHER_SUPPORTED)
  182675. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182676. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182677. png_colorp palette, int num_palette, int maximum_colors,
  182678. png_uint_16p histogram, int full_dither));
  182679. #endif
  182680. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182681. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182683. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182684. double screen_gamma, double default_file_gamma));
  182685. #endif
  182686. #endif
  182687. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182688. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182689. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182690. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182691. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182692. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182693. int empty_plte_permitted));
  182694. #endif
  182695. #endif
  182696. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182697. /* Set how many lines between output flushes - 0 for no flushing */
  182698. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182699. /* Flush the current PNG output buffer */
  182700. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182701. #endif
  182702. /* optional update palette with requested transformations */
  182703. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182704. /* optional call to update the users info structure */
  182705. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182706. png_infop info_ptr));
  182707. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182708. /* read one or more rows of image data. */
  182709. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182710. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182711. #endif
  182712. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182713. /* read a row of data. */
  182714. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182715. png_bytep row,
  182716. png_bytep display_row));
  182717. #endif
  182718. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182719. /* read the whole image into memory at once. */
  182720. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182721. png_bytepp image));
  182722. #endif
  182723. /* write a row of image data */
  182724. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182725. png_bytep row));
  182726. /* write a few rows of image data */
  182727. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182728. png_bytepp row, png_uint_32 num_rows));
  182729. /* write the image data */
  182730. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182731. png_bytepp image));
  182732. /* writes the end of the PNG file. */
  182733. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182734. png_infop info_ptr));
  182735. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182736. /* read the end of the PNG file. */
  182737. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182738. png_infop info_ptr));
  182739. #endif
  182740. /* free any memory associated with the png_info_struct */
  182741. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182742. png_infopp info_ptr_ptr));
  182743. /* free any memory associated with the png_struct and the png_info_structs */
  182744. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182745. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182746. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182747. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182748. png_infop end_info_ptr));
  182749. /* free any memory associated with the png_struct and the png_info_structs */
  182750. extern PNG_EXPORT(void,png_destroy_write_struct)
  182751. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182752. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182753. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182754. /* set the libpng method of handling chunk CRC errors */
  182755. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182756. int crit_action, int ancil_action));
  182757. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182758. * ancillary and critical chunks, and whether to use the data contained
  182759. * therein. Note that it is impossible to "discard" data in a critical
  182760. * chunk. For versions prior to 0.90, the action was always error/quit,
  182761. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182762. * chunks is warn/discard. These values should NOT be changed.
  182763. *
  182764. * value action:critical action:ancillary
  182765. */
  182766. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182767. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182768. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182769. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182770. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182771. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182772. /* These functions give the user control over the scan-line filtering in
  182773. * libpng and the compression methods used by zlib. These functions are
  182774. * mainly useful for testing, as the defaults should work with most users.
  182775. * Those users who are tight on memory or want faster performance at the
  182776. * expense of compression can modify them. See the compression library
  182777. * header file (zlib.h) for an explination of the compression functions.
  182778. */
  182779. /* set the filtering method(s) used by libpng. Currently, the only valid
  182780. * value for "method" is 0.
  182781. */
  182782. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182783. int filters));
  182784. /* Flags for png_set_filter() to say which filters to use. The flags
  182785. * are chosen so that they don't conflict with real filter types
  182786. * below, in case they are supplied instead of the #defined constants.
  182787. * These values should NOT be changed.
  182788. */
  182789. #define PNG_NO_FILTERS 0x00
  182790. #define PNG_FILTER_NONE 0x08
  182791. #define PNG_FILTER_SUB 0x10
  182792. #define PNG_FILTER_UP 0x20
  182793. #define PNG_FILTER_AVG 0x40
  182794. #define PNG_FILTER_PAETH 0x80
  182795. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182796. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182797. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182798. * These defines should NOT be changed.
  182799. */
  182800. #define PNG_FILTER_VALUE_NONE 0
  182801. #define PNG_FILTER_VALUE_SUB 1
  182802. #define PNG_FILTER_VALUE_UP 2
  182803. #define PNG_FILTER_VALUE_AVG 3
  182804. #define PNG_FILTER_VALUE_PAETH 4
  182805. #define PNG_FILTER_VALUE_LAST 5
  182806. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182807. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182808. * defines, either the default (minimum-sum-of-absolute-differences), or
  182809. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182810. *
  182811. * Weights are factors >= 1.0, indicating how important it is to keep the
  182812. * filter type consistent between rows. Larger numbers mean the current
  182813. * filter is that many times as likely to be the same as the "num_weights"
  182814. * previous filters. This is cumulative for each previous row with a weight.
  182815. * There needs to be "num_weights" values in "filter_weights", or it can be
  182816. * NULL if the weights aren't being specified. Weights have no influence on
  182817. * the selection of the first row filter. Well chosen weights can (in theory)
  182818. * improve the compression for a given image.
  182819. *
  182820. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182821. * filter type. Higher costs indicate more decoding expense, and are
  182822. * therefore less likely to be selected over a filter with lower computational
  182823. * costs. There needs to be a value in "filter_costs" for each valid filter
  182824. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182825. * setting the costs. Costs try to improve the speed of decompression without
  182826. * unduly increasing the compressed image size.
  182827. *
  182828. * A negative weight or cost indicates the default value is to be used, and
  182829. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182830. * The default values for both weights and costs are currently 1.0, but may
  182831. * change if good general weighting/cost heuristics can be found. If both
  182832. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182833. * to the UNWEIGHTED method, but with added encoding time/computation.
  182834. */
  182835. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182836. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182837. int heuristic_method, int num_weights, png_doublep filter_weights,
  182838. png_doublep filter_costs));
  182839. #endif
  182840. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182841. /* Heuristic used for row filter selection. These defines should NOT be
  182842. * changed.
  182843. */
  182844. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182845. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182846. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182847. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182848. /* Set the library compression level. Currently, valid values range from
  182849. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182850. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182851. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182852. * for PNG images, and do considerably fewer caclulations. In the future,
  182853. * these values may not correspond directly to the zlib compression levels.
  182854. */
  182855. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182856. int level));
  182857. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182858. PNGARG((png_structp png_ptr, int mem_level));
  182859. extern PNG_EXPORT(void,png_set_compression_strategy)
  182860. PNGARG((png_structp png_ptr, int strategy));
  182861. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182862. PNGARG((png_structp png_ptr, int window_bits));
  182863. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182864. int method));
  182865. /* These next functions are called for input/output, memory, and error
  182866. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182867. * and call standard C I/O routines such as fread(), fwrite(), and
  182868. * fprintf(). These functions can be made to use other I/O routines
  182869. * at run time for those applications that need to handle I/O in a
  182870. * different manner by calling png_set_???_fn(). See libpng.txt for
  182871. * more information.
  182872. */
  182873. #if !defined(PNG_NO_STDIO)
  182874. /* Initialize the input/output for the PNG file to the default functions. */
  182875. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182876. #endif
  182877. /* Replace the (error and abort), and warning functions with user
  182878. * supplied functions. If no messages are to be printed you must still
  182879. * write and use replacement functions. The replacement error_fn should
  182880. * still do a longjmp to the last setjmp location if you are using this
  182881. * method of error handling. If error_fn or warning_fn is NULL, the
  182882. * default function will be used.
  182883. */
  182884. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182885. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182886. /* Return the user pointer associated with the error functions */
  182887. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182888. /* Replace the default data output functions with a user supplied one(s).
  182889. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182890. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182891. * output_flush_fn will be ignored (and thus can be NULL).
  182892. */
  182893. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182894. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182895. /* Replace the default data input function with a user supplied one. */
  182896. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182897. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182898. /* Return the user pointer associated with the I/O functions */
  182899. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182900. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182901. png_read_status_ptr read_row_fn));
  182902. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182903. png_write_status_ptr write_row_fn));
  182904. #ifdef PNG_USER_MEM_SUPPORTED
  182905. /* Replace the default memory allocation functions with user supplied one(s). */
  182906. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182907. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182908. /* Return the user pointer associated with the memory functions */
  182909. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182910. #endif
  182911. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182912. defined(PNG_LEGACY_SUPPORTED)
  182913. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182914. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182915. #endif
  182916. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182917. defined(PNG_LEGACY_SUPPORTED)
  182918. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182919. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182920. #endif
  182921. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182922. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182923. defined(PNG_LEGACY_SUPPORTED)
  182924. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182925. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182926. int user_transform_channels));
  182927. /* Return the user pointer associated with the user transform functions */
  182928. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182929. PNGARG((png_structp png_ptr));
  182930. #endif
  182931. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182932. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182933. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182934. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182935. png_ptr));
  182936. #endif
  182937. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182938. /* Sets the function callbacks for the push reader, and a pointer to a
  182939. * user-defined structure available to the callback functions.
  182940. */
  182941. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182942. png_voidp progressive_ptr,
  182943. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182944. png_progressive_end_ptr end_fn));
  182945. /* returns the user pointer associated with the push read functions */
  182946. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182947. PNGARG((png_structp png_ptr));
  182948. /* function to be called when data becomes available */
  182949. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182950. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182951. /* function that combines rows. Not very much different than the
  182952. * png_combine_row() call. Is this even used?????
  182953. */
  182954. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182955. png_bytep old_row, png_bytep new_row));
  182956. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182957. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182958. png_uint_32 size));
  182959. #if defined(PNG_1_0_X)
  182960. # define png_malloc_warn png_malloc
  182961. #else
  182962. /* Added at libpng version 1.2.4 */
  182963. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182964. png_uint_32 size));
  182965. #endif
  182966. /* frees a pointer allocated by png_malloc() */
  182967. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182968. #if defined(PNG_1_0_X)
  182969. /* Function to allocate memory for zlib. */
  182970. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182971. uInt size));
  182972. /* Function to free memory for zlib */
  182973. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182974. #endif
  182975. /* Free data that was allocated internally */
  182976. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182977. png_infop info_ptr, png_uint_32 free_me, int num));
  182978. #ifdef PNG_FREE_ME_SUPPORTED
  182979. /* Reassign responsibility for freeing existing data, whether allocated
  182980. * by libpng or by the application */
  182981. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182982. png_infop info_ptr, int freer, png_uint_32 mask));
  182983. #endif
  182984. /* assignments for png_data_freer */
  182985. #define PNG_DESTROY_WILL_FREE_DATA 1
  182986. #define PNG_SET_WILL_FREE_DATA 1
  182987. #define PNG_USER_WILL_FREE_DATA 2
  182988. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182989. #define PNG_FREE_HIST 0x0008
  182990. #define PNG_FREE_ICCP 0x0010
  182991. #define PNG_FREE_SPLT 0x0020
  182992. #define PNG_FREE_ROWS 0x0040
  182993. #define PNG_FREE_PCAL 0x0080
  182994. #define PNG_FREE_SCAL 0x0100
  182995. #define PNG_FREE_UNKN 0x0200
  182996. #define PNG_FREE_LIST 0x0400
  182997. #define PNG_FREE_PLTE 0x1000
  182998. #define PNG_FREE_TRNS 0x2000
  182999. #define PNG_FREE_TEXT 0x4000
  183000. #define PNG_FREE_ALL 0x7fff
  183001. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183002. #ifdef PNG_USER_MEM_SUPPORTED
  183003. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183004. png_uint_32 size));
  183005. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183006. png_voidp ptr));
  183007. #endif
  183008. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183009. png_voidp s1, png_voidp s2, png_uint_32 size));
  183010. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183011. png_voidp s1, int value, png_uint_32 size));
  183012. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183013. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183014. int check));
  183015. #endif /* USE_FAR_KEYWORD */
  183016. #ifndef PNG_NO_ERROR_TEXT
  183017. /* Fatal error in PNG image of libpng - can't continue */
  183018. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183019. png_const_charp error_message));
  183020. /* The same, but the chunk name is prepended to the error string. */
  183021. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183022. png_const_charp error_message));
  183023. #else
  183024. /* Fatal error in PNG image of libpng - can't continue */
  183025. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183026. #endif
  183027. #ifndef PNG_NO_WARNINGS
  183028. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183029. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183030. png_const_charp warning_message));
  183031. #ifdef PNG_READ_SUPPORTED
  183032. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183033. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183034. png_const_charp warning_message));
  183035. #endif /* PNG_READ_SUPPORTED */
  183036. #endif /* PNG_NO_WARNINGS */
  183037. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183038. * Similarly, the png_get_<chunk> calls are used to read values from the
  183039. * png_info_struct, either storing the parameters in the passed variables, or
  183040. * setting pointers into the png_info_struct where the data is stored. The
  183041. * png_get_<chunk> functions return a non-zero value if the data was available
  183042. * in info_ptr, or return zero and do not change any of the parameters if the
  183043. * data was not available.
  183044. *
  183045. * These functions should be used instead of directly accessing png_info
  183046. * to avoid problems with future changes in the size and internal layout of
  183047. * png_info_struct.
  183048. */
  183049. /* Returns "flag" if chunk data is valid in info_ptr. */
  183050. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183051. png_infop info_ptr, png_uint_32 flag));
  183052. /* Returns number of bytes needed to hold a transformed row. */
  183053. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183054. png_infop info_ptr));
  183055. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183056. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183057. returned from png_read_png(). */
  183058. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183059. png_infop info_ptr));
  183060. /* Set row_pointers, which is an array of pointers to scanlines for use
  183061. by png_write_png(). */
  183062. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183063. png_infop info_ptr, png_bytepp row_pointers));
  183064. #endif
  183065. /* Returns number of color channels in image. */
  183066. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183067. png_infop info_ptr));
  183068. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183069. /* Returns image width in pixels. */
  183070. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183071. png_ptr, png_infop info_ptr));
  183072. /* Returns image height in pixels. */
  183073. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183074. png_ptr, png_infop info_ptr));
  183075. /* Returns image bit_depth. */
  183076. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183077. png_ptr, png_infop info_ptr));
  183078. /* Returns image color_type. */
  183079. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183080. png_ptr, png_infop info_ptr));
  183081. /* Returns image filter_type. */
  183082. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183083. png_ptr, png_infop info_ptr));
  183084. /* Returns image interlace_type. */
  183085. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183086. png_ptr, png_infop info_ptr));
  183087. /* Returns image compression_type. */
  183088. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183089. png_ptr, png_infop info_ptr));
  183090. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183091. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183092. png_ptr, png_infop info_ptr));
  183093. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183094. png_ptr, png_infop info_ptr));
  183095. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183096. png_ptr, png_infop info_ptr));
  183097. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183098. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183099. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183100. png_ptr, png_infop info_ptr));
  183101. #endif
  183102. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183103. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183104. png_ptr, png_infop info_ptr));
  183105. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183106. png_ptr, png_infop info_ptr));
  183107. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183108. png_ptr, png_infop info_ptr));
  183109. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183110. png_ptr, png_infop info_ptr));
  183111. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183112. /* Returns pointer to signature string read from PNG header */
  183113. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183114. png_infop info_ptr));
  183115. #if defined(PNG_bKGD_SUPPORTED)
  183116. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183117. png_infop info_ptr, png_color_16p *background));
  183118. #endif
  183119. #if defined(PNG_bKGD_SUPPORTED)
  183120. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183121. png_infop info_ptr, png_color_16p background));
  183122. #endif
  183123. #if defined(PNG_cHRM_SUPPORTED)
  183124. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183125. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183126. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183127. double *red_y, double *green_x, double *green_y, double *blue_x,
  183128. double *blue_y));
  183129. #endif
  183130. #ifdef PNG_FIXED_POINT_SUPPORTED
  183131. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183132. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183133. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183134. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183135. *int_blue_x, png_fixed_point *int_blue_y));
  183136. #endif
  183137. #endif
  183138. #if defined(PNG_cHRM_SUPPORTED)
  183139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183140. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr, double white_x, double white_y, double red_x,
  183142. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183143. #endif
  183144. #ifdef PNG_FIXED_POINT_SUPPORTED
  183145. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183146. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183147. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183148. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183149. png_fixed_point int_blue_y));
  183150. #endif
  183151. #endif
  183152. #if defined(PNG_gAMA_SUPPORTED)
  183153. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183154. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183155. png_infop info_ptr, double *file_gamma));
  183156. #endif
  183157. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183158. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183159. #endif
  183160. #if defined(PNG_gAMA_SUPPORTED)
  183161. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183162. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183163. png_infop info_ptr, double file_gamma));
  183164. #endif
  183165. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183166. png_infop info_ptr, png_fixed_point int_file_gamma));
  183167. #endif
  183168. #if defined(PNG_hIST_SUPPORTED)
  183169. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183170. png_infop info_ptr, png_uint_16p *hist));
  183171. #endif
  183172. #if defined(PNG_hIST_SUPPORTED)
  183173. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183174. png_infop info_ptr, png_uint_16p hist));
  183175. #endif
  183176. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183177. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183178. int *bit_depth, int *color_type, int *interlace_method,
  183179. int *compression_method, int *filter_method));
  183180. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183181. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183182. int color_type, int interlace_method, int compression_method,
  183183. int filter_method));
  183184. #if defined(PNG_oFFs_SUPPORTED)
  183185. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183186. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183187. int *unit_type));
  183188. #endif
  183189. #if defined(PNG_oFFs_SUPPORTED)
  183190. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183191. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183192. int unit_type));
  183193. #endif
  183194. #if defined(PNG_pCAL_SUPPORTED)
  183195. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183196. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183197. int *type, int *nparams, png_charp *units, png_charpp *params));
  183198. #endif
  183199. #if defined(PNG_pCAL_SUPPORTED)
  183200. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183201. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183202. int type, int nparams, png_charp units, png_charpp params));
  183203. #endif
  183204. #if defined(PNG_pHYs_SUPPORTED)
  183205. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183206. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183207. #endif
  183208. #if defined(PNG_pHYs_SUPPORTED)
  183209. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183210. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183211. #endif
  183212. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183213. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183214. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183215. png_infop info_ptr, png_colorp palette, int num_palette));
  183216. #if defined(PNG_sBIT_SUPPORTED)
  183217. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183218. png_infop info_ptr, png_color_8p *sig_bit));
  183219. #endif
  183220. #if defined(PNG_sBIT_SUPPORTED)
  183221. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183222. png_infop info_ptr, png_color_8p sig_bit));
  183223. #endif
  183224. #if defined(PNG_sRGB_SUPPORTED)
  183225. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183226. png_infop info_ptr, int *intent));
  183227. #endif
  183228. #if defined(PNG_sRGB_SUPPORTED)
  183229. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183230. png_infop info_ptr, int intent));
  183231. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183232. png_infop info_ptr, int intent));
  183233. #endif
  183234. #if defined(PNG_iCCP_SUPPORTED)
  183235. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183236. png_infop info_ptr, png_charpp name, int *compression_type,
  183237. png_charpp profile, png_uint_32 *proflen));
  183238. /* Note to maintainer: profile should be png_bytepp */
  183239. #endif
  183240. #if defined(PNG_iCCP_SUPPORTED)
  183241. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183242. png_infop info_ptr, png_charp name, int compression_type,
  183243. png_charp profile, png_uint_32 proflen));
  183244. /* Note to maintainer: profile should be png_bytep */
  183245. #endif
  183246. #if defined(PNG_sPLT_SUPPORTED)
  183247. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183248. png_infop info_ptr, png_sPLT_tpp entries));
  183249. #endif
  183250. #if defined(PNG_sPLT_SUPPORTED)
  183251. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183252. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183253. #endif
  183254. #if defined(PNG_TEXT_SUPPORTED)
  183255. /* png_get_text also returns the number of text chunks in *num_text */
  183256. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183257. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183258. #endif
  183259. /*
  183260. * Note while png_set_text() will accept a structure whose text,
  183261. * language, and translated keywords are NULL pointers, the structure
  183262. * returned by png_get_text will always contain regular
  183263. * zero-terminated C strings. They might be empty strings but
  183264. * they will never be NULL pointers.
  183265. */
  183266. #if defined(PNG_TEXT_SUPPORTED)
  183267. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183268. png_infop info_ptr, png_textp text_ptr, int num_text));
  183269. #endif
  183270. #if defined(PNG_tIME_SUPPORTED)
  183271. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183272. png_infop info_ptr, png_timep *mod_time));
  183273. #endif
  183274. #if defined(PNG_tIME_SUPPORTED)
  183275. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183276. png_infop info_ptr, png_timep mod_time));
  183277. #endif
  183278. #if defined(PNG_tRNS_SUPPORTED)
  183279. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183280. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183281. png_color_16p *trans_values));
  183282. #endif
  183283. #if defined(PNG_tRNS_SUPPORTED)
  183284. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183285. png_infop info_ptr, png_bytep trans, int num_trans,
  183286. png_color_16p trans_values));
  183287. #endif
  183288. #if defined(PNG_tRNS_SUPPORTED)
  183289. #endif
  183290. #if defined(PNG_sCAL_SUPPORTED)
  183291. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183292. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183293. png_infop info_ptr, int *unit, double *width, double *height));
  183294. #else
  183295. #ifdef PNG_FIXED_POINT_SUPPORTED
  183296. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183297. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183298. #endif
  183299. #endif
  183300. #endif /* PNG_sCAL_SUPPORTED */
  183301. #if defined(PNG_sCAL_SUPPORTED)
  183302. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183303. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183304. png_infop info_ptr, int unit, double width, double height));
  183305. #else
  183306. #ifdef PNG_FIXED_POINT_SUPPORTED
  183307. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183308. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183309. #endif
  183310. #endif
  183311. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183312. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183313. /* provide a list of chunks and how they are to be handled, if the built-in
  183314. handling or default unknown chunk handling is not desired. Any chunks not
  183315. listed will be handled in the default manner. The IHDR and IEND chunks
  183316. must not be listed.
  183317. keep = 0: follow default behaviour
  183318. = 1: do not keep
  183319. = 2: keep only if safe-to-copy
  183320. = 3: keep even if unsafe-to-copy
  183321. */
  183322. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183323. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183324. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183325. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183326. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183327. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183328. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183329. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183330. #endif
  183331. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183332. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183333. chunk_name));
  183334. #endif
  183335. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183336. If you need to turn it off for a chunk that your application has freed,
  183337. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183338. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183339. png_infop info_ptr, int mask));
  183340. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183341. /* The "params" pointer is currently not used and is for future expansion. */
  183342. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183343. png_infop info_ptr,
  183344. int transforms,
  183345. png_voidp params));
  183346. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183347. png_infop info_ptr,
  183348. int transforms,
  183349. png_voidp params));
  183350. #endif
  183351. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183352. * numbers for PNG_DEBUG mean more debugging information. This has
  183353. * only been added since version 0.95 so it is not implemented throughout
  183354. * libpng yet, but more support will be added as needed.
  183355. */
  183356. #ifdef PNG_DEBUG
  183357. #if (PNG_DEBUG > 0)
  183358. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183359. #include <crtdbg.h>
  183360. #if (PNG_DEBUG > 1)
  183361. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183362. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183363. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183364. #endif
  183365. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183366. #ifndef PNG_DEBUG_FILE
  183367. #define PNG_DEBUG_FILE stderr
  183368. #endif /* PNG_DEBUG_FILE */
  183369. #if (PNG_DEBUG > 1)
  183370. #define png_debug(l,m) \
  183371. { \
  183372. int num_tabs=l; \
  183373. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183374. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183375. }
  183376. #define png_debug1(l,m,p1) \
  183377. { \
  183378. int num_tabs=l; \
  183379. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183380. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183381. }
  183382. #define png_debug2(l,m,p1,p2) \
  183383. { \
  183384. int num_tabs=l; \
  183385. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183386. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183387. }
  183388. #endif /* (PNG_DEBUG > 1) */
  183389. #endif /* _MSC_VER */
  183390. #endif /* (PNG_DEBUG > 0) */
  183391. #endif /* PNG_DEBUG */
  183392. #ifndef png_debug
  183393. #define png_debug(l, m)
  183394. #endif
  183395. #ifndef png_debug1
  183396. #define png_debug1(l, m, p1)
  183397. #endif
  183398. #ifndef png_debug2
  183399. #define png_debug2(l, m, p1, p2)
  183400. #endif
  183401. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183402. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183403. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183404. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183405. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183406. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183407. png_ptr, png_uint_32 mng_features_permitted));
  183408. #endif
  183409. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183410. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183411. #define PNG_HANDLE_CHUNK_NEVER 1
  183412. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183413. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183414. /* Added to version 1.2.0 */
  183415. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183416. #if defined(PNG_MMX_CODE_SUPPORTED)
  183417. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183418. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183419. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183420. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183421. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183422. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183423. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183424. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183425. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183426. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183427. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183428. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183429. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183430. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183431. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183432. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183433. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183434. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183435. | PNG_MMX_READ_FLAGS \
  183436. | PNG_MMX_WRITE_FLAGS )
  183437. #define PNG_SELECT_READ 1
  183438. #define PNG_SELECT_WRITE 2
  183439. #endif /* PNG_MMX_CODE_SUPPORTED */
  183440. #if !defined(PNG_1_0_X)
  183441. /* pngget.c */
  183442. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183443. PNGARG((int flag_select, int *compilerID));
  183444. /* pngget.c */
  183445. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183446. PNGARG((int flag_select));
  183447. /* pngget.c */
  183448. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183449. PNGARG((png_structp png_ptr));
  183450. /* pngget.c */
  183451. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183452. PNGARG((png_structp png_ptr));
  183453. /* pngget.c */
  183454. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183455. PNGARG((png_structp png_ptr));
  183456. /* pngset.c */
  183457. extern PNG_EXPORT(void,png_set_asm_flags)
  183458. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183459. /* pngset.c */
  183460. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183461. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183462. png_uint_32 mmx_rowbytes_threshold));
  183463. #endif /* PNG_1_0_X */
  183464. #if !defined(PNG_1_0_X)
  183465. /* png.c, pnggccrd.c, or pngvcrd.c */
  183466. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183467. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183468. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183469. * messages before passing them to the error or warning handler. */
  183470. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183471. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183472. png_ptr, png_uint_32 strip_mode));
  183473. #endif
  183474. #endif /* PNG_1_0_X */
  183475. /* Added at libpng-1.2.6 */
  183476. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183477. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183478. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183479. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183480. png_ptr));
  183481. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183482. png_ptr));
  183483. #endif
  183484. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183485. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183486. /* With these routines we avoid an integer divide, which will be slower on
  183487. * most machines. However, it does take more operations than the corresponding
  183488. * divide method, so it may be slower on a few RISC systems. There are two
  183489. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183490. *
  183491. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183492. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183493. * standard method.
  183494. *
  183495. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183496. */
  183497. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183498. # define png_composite(composite, fg, alpha, bg) \
  183499. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183500. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183501. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183502. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183503. # define png_composite_16(composite, fg, alpha, bg) \
  183504. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183505. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183506. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183507. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183508. #else /* standard method using integer division */
  183509. # define png_composite(composite, fg, alpha, bg) \
  183510. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183511. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183512. (png_uint_16)127) / 255)
  183513. # define png_composite_16(composite, fg, alpha, bg) \
  183514. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183515. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183516. (png_uint_32)32767) / (png_uint_32)65535L)
  183517. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183518. /* Inline macros to do direct reads of bytes from the input buffer. These
  183519. * require that you are using an architecture that uses PNG byte ordering
  183520. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183521. * in big-endian mode and 680x0 are the only ones that will support this.
  183522. * The x86 line of processors definitely do not. The png_get_int_32()
  183523. * routine also assumes we are using two's complement format for negative
  183524. * values, which is almost certainly true.
  183525. */
  183526. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183527. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183528. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183529. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183530. #else
  183531. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183532. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183533. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183534. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183535. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183536. PNGARG((png_structp png_ptr, png_bytep buf));
  183537. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183538. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183539. */
  183540. extern PNG_EXPORT(void,png_save_uint_32)
  183541. PNGARG((png_bytep buf, png_uint_32 i));
  183542. extern PNG_EXPORT(void,png_save_int_32)
  183543. PNGARG((png_bytep buf, png_int_32 i));
  183544. /* Place a 16-bit number into a buffer in PNG byte order.
  183545. * The parameter is declared unsigned int, not png_uint_16,
  183546. * just to avoid potential problems on pre-ANSI C compilers.
  183547. */
  183548. extern PNG_EXPORT(void,png_save_uint_16)
  183549. PNGARG((png_bytep buf, unsigned int i));
  183550. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183551. /* ************************************************************************* */
  183552. /* These next functions are used internally in the code. They generally
  183553. * shouldn't be used unless you are writing code to add or replace some
  183554. * functionality in libpng. More information about most functions can
  183555. * be found in the files where the functions are located.
  183556. */
  183557. /* Various modes of operation, that are visible to applications because
  183558. * they are used for unknown chunk location.
  183559. */
  183560. #define PNG_HAVE_IHDR 0x01
  183561. #define PNG_HAVE_PLTE 0x02
  183562. #define PNG_HAVE_IDAT 0x04
  183563. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183564. #define PNG_HAVE_IEND 0x10
  183565. #if defined(PNG_INTERNAL)
  183566. /* More modes of operation. Note that after an init, mode is set to
  183567. * zero automatically when the structure is created.
  183568. */
  183569. #define PNG_HAVE_gAMA 0x20
  183570. #define PNG_HAVE_cHRM 0x40
  183571. #define PNG_HAVE_sRGB 0x80
  183572. #define PNG_HAVE_CHUNK_HEADER 0x100
  183573. #define PNG_WROTE_tIME 0x200
  183574. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183575. #define PNG_BACKGROUND_IS_GRAY 0x800
  183576. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183577. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183578. /* flags for the transformations the PNG library does on the image data */
  183579. #define PNG_BGR 0x0001
  183580. #define PNG_INTERLACE 0x0002
  183581. #define PNG_PACK 0x0004
  183582. #define PNG_SHIFT 0x0008
  183583. #define PNG_SWAP_BYTES 0x0010
  183584. #define PNG_INVERT_MONO 0x0020
  183585. #define PNG_DITHER 0x0040
  183586. #define PNG_BACKGROUND 0x0080
  183587. #define PNG_BACKGROUND_EXPAND 0x0100
  183588. /* 0x0200 unused */
  183589. #define PNG_16_TO_8 0x0400
  183590. #define PNG_RGBA 0x0800
  183591. #define PNG_EXPAND 0x1000
  183592. #define PNG_GAMMA 0x2000
  183593. #define PNG_GRAY_TO_RGB 0x4000
  183594. #define PNG_FILLER 0x8000L
  183595. #define PNG_PACKSWAP 0x10000L
  183596. #define PNG_SWAP_ALPHA 0x20000L
  183597. #define PNG_STRIP_ALPHA 0x40000L
  183598. #define PNG_INVERT_ALPHA 0x80000L
  183599. #define PNG_USER_TRANSFORM 0x100000L
  183600. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183601. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183602. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183603. /* 0x800000L Unused */
  183604. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183605. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183606. /* 0x4000000L unused */
  183607. /* 0x8000000L unused */
  183608. /* 0x10000000L unused */
  183609. /* 0x20000000L unused */
  183610. /* 0x40000000L unused */
  183611. /* flags for png_create_struct */
  183612. #define PNG_STRUCT_PNG 0x0001
  183613. #define PNG_STRUCT_INFO 0x0002
  183614. /* Scaling factor for filter heuristic weighting calculations */
  183615. #define PNG_WEIGHT_SHIFT 8
  183616. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183617. #define PNG_COST_SHIFT 3
  183618. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183619. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183620. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183621. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183622. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183623. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183624. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183625. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183626. #define PNG_FLAG_ROW_INIT 0x0040
  183627. #define PNG_FLAG_FILLER_AFTER 0x0080
  183628. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183629. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183630. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183631. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183632. #define PNG_FLAG_FREE_PLTE 0x1000
  183633. #define PNG_FLAG_FREE_TRNS 0x2000
  183634. #define PNG_FLAG_FREE_HIST 0x4000
  183635. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183636. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183637. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183638. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183639. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183640. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183641. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183642. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183643. /* 0x800000L unused */
  183644. /* 0x1000000L unused */
  183645. /* 0x2000000L unused */
  183646. /* 0x4000000L unused */
  183647. /* 0x8000000L unused */
  183648. /* 0x10000000L unused */
  183649. /* 0x20000000L unused */
  183650. /* 0x40000000L unused */
  183651. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183652. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183653. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183654. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183655. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183656. PNG_FLAG_CRC_CRITICAL_MASK)
  183657. /* save typing and make code easier to understand */
  183658. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183659. abs((int)((c1).green) - (int)((c2).green)) + \
  183660. abs((int)((c1).blue) - (int)((c2).blue)))
  183661. /* Added to libpng-1.2.6 JB */
  183662. #define PNG_ROWBYTES(pixel_bits, width) \
  183663. ((pixel_bits) >= 8 ? \
  183664. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183665. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183666. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183667. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183668. "ideal" and "delta" should be constants, normally simple
  183669. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183670. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183671. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183672. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183673. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183674. /* place to hold the signature string for a PNG file. */
  183675. #ifdef PNG_USE_GLOBAL_ARRAYS
  183676. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183677. #else
  183678. #endif
  183679. #endif /* PNG_NO_EXTERN */
  183680. /* Constant strings for known chunk types. If you need to add a chunk,
  183681. * define the name here, and add an invocation of the macro in png.c and
  183682. * wherever it's needed.
  183683. */
  183684. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183685. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183686. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183687. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183688. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183689. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183690. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183691. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183692. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183693. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183694. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183695. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183696. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183697. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183698. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183699. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183700. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183701. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183702. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183703. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183704. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183705. #ifdef PNG_USE_GLOBAL_ARRAYS
  183706. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183707. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183708. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183709. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183710. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183711. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183712. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183713. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183714. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183715. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183716. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183717. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183718. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183719. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183720. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183721. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183722. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183723. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183724. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183725. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183726. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183727. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183728. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183729. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183730. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183731. */
  183732. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183733. #undef png_read_init
  183734. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183735. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183736. #endif
  183737. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183738. png_const_charp user_png_ver, png_size_t png_struct_size));
  183739. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183740. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183741. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183742. png_info_size));
  183743. #endif
  183744. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183745. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183746. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183747. */
  183748. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183749. #undef png_write_init
  183750. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183751. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183752. #endif
  183753. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183754. png_const_charp user_png_ver, png_size_t png_struct_size));
  183755. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183756. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183757. png_info_size));
  183758. /* Allocate memory for an internal libpng struct */
  183759. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183760. /* Free memory from internal libpng struct */
  183761. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183762. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183763. malloc_fn, png_voidp mem_ptr));
  183764. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183765. png_free_ptr free_fn, png_voidp mem_ptr));
  183766. /* Free any memory that info_ptr points to and reset struct. */
  183767. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183768. png_infop info_ptr));
  183769. #ifndef PNG_1_0_X
  183770. /* Function to allocate memory for zlib. */
  183771. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183772. /* Function to free memory for zlib */
  183773. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183774. #ifdef PNG_SIZE_T
  183775. /* Function to convert a sizeof an item to png_sizeof item */
  183776. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183777. #endif
  183778. /* Next four functions are used internally as callbacks. PNGAPI is required
  183779. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183780. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183781. png_bytep data, png_size_t length));
  183782. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183783. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183784. png_bytep buffer, png_size_t length));
  183785. #endif
  183786. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183787. png_bytep data, png_size_t length));
  183788. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183789. #if !defined(PNG_NO_STDIO)
  183790. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183791. #endif
  183792. #endif
  183793. #else /* PNG_1_0_X */
  183794. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183795. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183796. png_bytep buffer, png_size_t length));
  183797. #endif
  183798. #endif /* PNG_1_0_X */
  183799. /* Reset the CRC variable */
  183800. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183801. /* Write the "data" buffer to whatever output you are using. */
  183802. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183803. png_size_t length));
  183804. /* Read data from whatever input you are using into the "data" buffer */
  183805. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183806. png_size_t length));
  183807. /* Read bytes into buf, and update png_ptr->crc */
  183808. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183809. png_size_t length));
  183810. /* Decompress data in a chunk that uses compression */
  183811. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183812. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183813. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183814. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183815. png_size_t prefix_length, png_size_t *data_length));
  183816. #endif
  183817. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183818. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183819. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183820. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183821. /* Calculate the CRC over a section of data. Note that we are only
  183822. * passing a maximum of 64K on systems that have this as a memory limit,
  183823. * since this is the maximum buffer size we can specify.
  183824. */
  183825. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183826. png_size_t length));
  183827. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183828. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183829. #endif
  183830. /* simple function to write the signature */
  183831. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183832. /* write various chunks */
  183833. /* Write the IHDR chunk, and update the png_struct with the necessary
  183834. * information.
  183835. */
  183836. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183837. png_uint_32 height,
  183838. int bit_depth, int color_type, int compression_method, int filter_method,
  183839. int interlace_method));
  183840. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183841. png_uint_32 num_pal));
  183842. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183843. png_size_t length));
  183844. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183845. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183846. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183847. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183848. #endif
  183849. #ifdef PNG_FIXED_POINT_SUPPORTED
  183850. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183851. file_gamma));
  183852. #endif
  183853. #endif
  183854. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183855. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183856. int color_type));
  183857. #endif
  183858. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183859. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183860. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183861. double white_x, double white_y,
  183862. double red_x, double red_y, double green_x, double green_y,
  183863. double blue_x, double blue_y));
  183864. #endif
  183865. #ifdef PNG_FIXED_POINT_SUPPORTED
  183866. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183867. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183868. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183869. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183870. png_fixed_point int_blue_y));
  183871. #endif
  183872. #endif
  183873. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183874. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183875. int intent));
  183876. #endif
  183877. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183878. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183879. png_charp name, int compression_type,
  183880. png_charp profile, int proflen));
  183881. /* Note to maintainer: profile should be png_bytep */
  183882. #endif
  183883. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183884. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183885. png_sPLT_tp palette));
  183886. #endif
  183887. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183888. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183889. png_color_16p values, int number, int color_type));
  183890. #endif
  183891. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183892. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183893. png_color_16p values, int color_type));
  183894. #endif
  183895. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183896. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183897. int num_hist));
  183898. #endif
  183899. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183900. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183901. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183902. png_charp key, png_charpp new_key));
  183903. #endif
  183904. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183905. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183906. png_charp text, png_size_t text_len));
  183907. #endif
  183908. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183909. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183910. png_charp text, png_size_t text_len, int compression));
  183911. #endif
  183912. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183913. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183914. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183915. png_charp text));
  183916. #endif
  183917. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183918. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183919. png_infop info_ptr, png_textp text_ptr, int num_text));
  183920. #endif
  183921. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183922. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183923. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183924. #endif
  183925. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183926. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183927. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183928. png_charp units, png_charpp params));
  183929. #endif
  183930. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183931. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183932. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183933. int unit_type));
  183934. #endif
  183935. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183936. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183937. png_timep mod_time));
  183938. #endif
  183939. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183940. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183941. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183942. int unit, double width, double height));
  183943. #else
  183944. #ifdef PNG_FIXED_POINT_SUPPORTED
  183945. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183946. int unit, png_charp width, png_charp height));
  183947. #endif
  183948. #endif
  183949. #endif
  183950. /* Called when finished processing a row of data */
  183951. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183952. /* Internal use only. Called before first row of data */
  183953. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183954. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183955. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183956. #endif
  183957. /* combine a row of data, dealing with alpha, etc. if requested */
  183958. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183959. int mask));
  183960. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183961. /* expand an interlaced row */
  183962. /* OLD pre-1.0.9 interface:
  183963. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183964. png_bytep row, int pass, png_uint_32 transformations));
  183965. */
  183966. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183967. #endif
  183968. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183969. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183970. /* grab pixels out of a row for an interlaced pass */
  183971. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183972. png_bytep row, int pass));
  183973. #endif
  183974. /* unfilter a row */
  183975. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183976. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183977. /* Choose the best filter to use and filter the row data */
  183978. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183979. png_row_infop row_info));
  183980. /* Write out the filtered row. */
  183981. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183982. png_bytep filtered_row));
  183983. /* finish a row while reading, dealing with interlacing passes, etc. */
  183984. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183985. /* initialize the row buffers, etc. */
  183986. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183987. /* optional call to update the users info structure */
  183988. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183989. png_infop info_ptr));
  183990. /* these are the functions that do the transformations */
  183991. #if defined(PNG_READ_FILLER_SUPPORTED)
  183992. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183993. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183994. #endif
  183995. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183996. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183997. png_bytep row));
  183998. #endif
  183999. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184000. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184001. png_bytep row));
  184002. #endif
  184003. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184004. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184005. png_bytep row));
  184006. #endif
  184007. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184008. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184009. png_bytep row));
  184010. #endif
  184011. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184012. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184013. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184014. png_bytep row, png_uint_32 flags));
  184015. #endif
  184016. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184017. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184018. #endif
  184019. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184020. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184021. #endif
  184022. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184023. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184024. row_info, png_bytep row));
  184025. #endif
  184026. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184027. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184028. png_bytep row));
  184029. #endif
  184030. #if defined(PNG_READ_PACK_SUPPORTED)
  184031. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184032. #endif
  184033. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184034. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184035. png_color_8p sig_bits));
  184036. #endif
  184037. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184038. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184039. #endif
  184040. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184041. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184042. #endif
  184043. #if defined(PNG_READ_DITHER_SUPPORTED)
  184044. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184045. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184046. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184047. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184048. png_colorp palette, int num_palette));
  184049. # endif
  184050. #endif
  184051. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184052. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184053. #endif
  184054. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184055. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184056. png_bytep row, png_uint_32 bit_depth));
  184057. #endif
  184058. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184059. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184060. png_color_8p bit_depth));
  184061. #endif
  184062. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184063. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184064. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184065. png_color_16p trans_values, png_color_16p background,
  184066. png_color_16p background_1,
  184067. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184068. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184069. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184070. #else
  184071. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184072. png_color_16p trans_values, png_color_16p background));
  184073. #endif
  184074. #endif
  184075. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184076. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184077. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184078. int gamma_shift));
  184079. #endif
  184080. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184081. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184082. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184083. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184084. png_bytep row, png_color_16p trans_value));
  184085. #endif
  184086. /* The following decodes the appropriate chunks, and does error correction,
  184087. * then calls the appropriate callback for the chunk if it is valid.
  184088. */
  184089. /* decode the IHDR chunk */
  184090. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184091. png_uint_32 length));
  184092. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184093. png_uint_32 length));
  184094. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184095. png_uint_32 length));
  184096. #if defined(PNG_READ_bKGD_SUPPORTED)
  184097. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184098. png_uint_32 length));
  184099. #endif
  184100. #if defined(PNG_READ_cHRM_SUPPORTED)
  184101. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184102. png_uint_32 length));
  184103. #endif
  184104. #if defined(PNG_READ_gAMA_SUPPORTED)
  184105. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184106. png_uint_32 length));
  184107. #endif
  184108. #if defined(PNG_READ_hIST_SUPPORTED)
  184109. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184110. png_uint_32 length));
  184111. #endif
  184112. #if defined(PNG_READ_iCCP_SUPPORTED)
  184113. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184114. png_uint_32 length));
  184115. #endif /* PNG_READ_iCCP_SUPPORTED */
  184116. #if defined(PNG_READ_iTXt_SUPPORTED)
  184117. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184118. png_uint_32 length));
  184119. #endif
  184120. #if defined(PNG_READ_oFFs_SUPPORTED)
  184121. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184122. png_uint_32 length));
  184123. #endif
  184124. #if defined(PNG_READ_pCAL_SUPPORTED)
  184125. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184126. png_uint_32 length));
  184127. #endif
  184128. #if defined(PNG_READ_pHYs_SUPPORTED)
  184129. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184130. png_uint_32 length));
  184131. #endif
  184132. #if defined(PNG_READ_sBIT_SUPPORTED)
  184133. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184134. png_uint_32 length));
  184135. #endif
  184136. #if defined(PNG_READ_sCAL_SUPPORTED)
  184137. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184138. png_uint_32 length));
  184139. #endif
  184140. #if defined(PNG_READ_sPLT_SUPPORTED)
  184141. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184142. png_uint_32 length));
  184143. #endif /* PNG_READ_sPLT_SUPPORTED */
  184144. #if defined(PNG_READ_sRGB_SUPPORTED)
  184145. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184146. png_uint_32 length));
  184147. #endif
  184148. #if defined(PNG_READ_tEXt_SUPPORTED)
  184149. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184150. png_uint_32 length));
  184151. #endif
  184152. #if defined(PNG_READ_tIME_SUPPORTED)
  184153. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184154. png_uint_32 length));
  184155. #endif
  184156. #if defined(PNG_READ_tRNS_SUPPORTED)
  184157. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184158. png_uint_32 length));
  184159. #endif
  184160. #if defined(PNG_READ_zTXt_SUPPORTED)
  184161. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184162. png_uint_32 length));
  184163. #endif
  184164. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184165. png_infop info_ptr, png_uint_32 length));
  184166. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184167. png_bytep chunk_name));
  184168. /* handle the transformations for reading and writing */
  184169. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184170. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184171. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184172. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184173. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184174. png_infop info_ptr));
  184175. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184176. png_infop info_ptr));
  184177. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184178. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184179. png_uint_32 length));
  184180. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184181. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184182. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184183. png_bytep buffer, png_size_t buffer_length));
  184184. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184185. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184186. png_bytep buffer, png_size_t buffer_length));
  184187. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184188. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184189. png_infop info_ptr, png_uint_32 length));
  184190. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184191. png_infop info_ptr));
  184192. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184193. png_infop info_ptr));
  184194. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184195. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184196. png_infop info_ptr));
  184197. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184198. png_infop info_ptr));
  184199. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184200. #if defined(PNG_READ_tEXt_SUPPORTED)
  184201. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184202. png_infop info_ptr, png_uint_32 length));
  184203. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184204. png_infop info_ptr));
  184205. #endif
  184206. #if defined(PNG_READ_zTXt_SUPPORTED)
  184207. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184208. png_infop info_ptr, png_uint_32 length));
  184209. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184210. png_infop info_ptr));
  184211. #endif
  184212. #if defined(PNG_READ_iTXt_SUPPORTED)
  184213. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184214. png_infop info_ptr, png_uint_32 length));
  184215. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184216. png_infop info_ptr));
  184217. #endif
  184218. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184219. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184220. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184221. png_bytep row));
  184222. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184223. png_bytep row));
  184224. #endif
  184225. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184226. #if defined(PNG_MMX_CODE_SUPPORTED)
  184227. /* png.c */ /* PRIVATE */
  184228. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184229. #endif
  184230. #endif
  184231. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184232. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184233. png_infop info_ptr));
  184234. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184235. png_infop info_ptr));
  184236. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184237. png_infop info_ptr));
  184238. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184239. png_infop info_ptr));
  184240. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184241. png_infop info_ptr));
  184242. #if defined(PNG_pHYs_SUPPORTED)
  184243. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184244. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184245. #endif /* PNG_pHYs_SUPPORTED */
  184246. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184247. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184248. #endif /* PNG_INTERNAL */
  184249. #ifdef __cplusplus
  184250. //}
  184251. #endif
  184252. #endif /* PNG_VERSION_INFO_ONLY */
  184253. /* do not put anything past this line */
  184254. #endif /* PNG_H */
  184255. /*** End of inlined file: png.h ***/
  184256. #define PNG_NO_EXTERN
  184257. /*** Start of inlined file: png.c ***/
  184258. /* png.c - location for general purpose libpng functions
  184259. *
  184260. * Last changed in libpng 1.2.21 [October 4, 2007]
  184261. * For conditions of distribution and use, see copyright notice in png.h
  184262. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184263. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184264. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184265. */
  184266. #define PNG_INTERNAL
  184267. #define PNG_NO_EXTERN
  184268. /* Generate a compiler error if there is an old png.h in the search path. */
  184269. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184270. /* Version information for C files. This had better match the version
  184271. * string defined in png.h. */
  184272. #ifdef PNG_USE_GLOBAL_ARRAYS
  184273. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184274. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184275. #ifdef PNG_READ_SUPPORTED
  184276. /* png_sig was changed to a function in version 1.0.5c */
  184277. /* Place to hold the signature string for a PNG file. */
  184278. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184279. #endif /* PNG_READ_SUPPORTED */
  184280. /* Invoke global declarations for constant strings for known chunk types */
  184281. PNG_IHDR;
  184282. PNG_IDAT;
  184283. PNG_IEND;
  184284. PNG_PLTE;
  184285. PNG_bKGD;
  184286. PNG_cHRM;
  184287. PNG_gAMA;
  184288. PNG_hIST;
  184289. PNG_iCCP;
  184290. PNG_iTXt;
  184291. PNG_oFFs;
  184292. PNG_pCAL;
  184293. PNG_sCAL;
  184294. PNG_pHYs;
  184295. PNG_sBIT;
  184296. PNG_sPLT;
  184297. PNG_sRGB;
  184298. PNG_tEXt;
  184299. PNG_tIME;
  184300. PNG_tRNS;
  184301. PNG_zTXt;
  184302. #ifdef PNG_READ_SUPPORTED
  184303. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184304. /* start of interlace block */
  184305. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184306. /* offset to next interlace block */
  184307. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184308. /* start of interlace block in the y direction */
  184309. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184310. /* offset to next interlace block in the y direction */
  184311. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184312. /* Height of interlace block. This is not currently used - if you need
  184313. * it, uncomment it here and in png.h
  184314. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184315. */
  184316. /* Mask to determine which pixels are valid in a pass */
  184317. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184318. /* Mask to determine which pixels to overwrite while displaying */
  184319. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184320. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184321. #endif /* PNG_READ_SUPPORTED */
  184322. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184323. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184324. * of the PNG file signature. If the PNG data is embedded into another
  184325. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184326. * or write any of the magic bytes before it starts on the IHDR.
  184327. */
  184328. #ifdef PNG_READ_SUPPORTED
  184329. void PNGAPI
  184330. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184331. {
  184332. if(png_ptr == NULL) return;
  184333. png_debug(1, "in png_set_sig_bytes\n");
  184334. if (num_bytes > 8)
  184335. png_error(png_ptr, "Too many bytes for PNG signature.");
  184336. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184337. }
  184338. /* Checks whether the supplied bytes match the PNG signature. We allow
  184339. * checking less than the full 8-byte signature so that those apps that
  184340. * already read the first few bytes of a file to determine the file type
  184341. * can simply check the remaining bytes for extra assurance. Returns
  184342. * an integer less than, equal to, or greater than zero if sig is found,
  184343. * respectively, to be less than, to match, or be greater than the correct
  184344. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184345. */
  184346. int PNGAPI
  184347. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184348. {
  184349. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184350. if (num_to_check > 8)
  184351. num_to_check = 8;
  184352. else if (num_to_check < 1)
  184353. return (-1);
  184354. if (start > 7)
  184355. return (-1);
  184356. if (start + num_to_check > 8)
  184357. num_to_check = 8 - start;
  184358. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184359. }
  184360. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184361. /* (Obsolete) function to check signature bytes. It does not allow one
  184362. * to check a partial signature. This function might be removed in the
  184363. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184364. */
  184365. int PNGAPI
  184366. png_check_sig(png_bytep sig, int num)
  184367. {
  184368. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184369. }
  184370. #endif
  184371. #endif /* PNG_READ_SUPPORTED */
  184372. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184373. /* Function to allocate memory for zlib and clear it to 0. */
  184374. #ifdef PNG_1_0_X
  184375. voidpf PNGAPI
  184376. #else
  184377. voidpf /* private */
  184378. #endif
  184379. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184380. {
  184381. png_voidp ptr;
  184382. png_structp p=(png_structp)png_ptr;
  184383. png_uint_32 save_flags=p->flags;
  184384. png_uint_32 num_bytes;
  184385. if(png_ptr == NULL) return (NULL);
  184386. if (items > PNG_UINT_32_MAX/size)
  184387. {
  184388. png_warning (p, "Potential overflow in png_zalloc()");
  184389. return (NULL);
  184390. }
  184391. num_bytes = (png_uint_32)items * size;
  184392. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184393. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184394. p->flags=save_flags;
  184395. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184396. if (ptr == NULL)
  184397. return ((voidpf)ptr);
  184398. if (num_bytes > (png_uint_32)0x8000L)
  184399. {
  184400. png_memset(ptr, 0, (png_size_t)0x8000L);
  184401. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184402. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184403. }
  184404. else
  184405. {
  184406. png_memset(ptr, 0, (png_size_t)num_bytes);
  184407. }
  184408. #endif
  184409. return ((voidpf)ptr);
  184410. }
  184411. /* function to free memory for zlib */
  184412. #ifdef PNG_1_0_X
  184413. void PNGAPI
  184414. #else
  184415. void /* private */
  184416. #endif
  184417. png_zfree(voidpf png_ptr, voidpf ptr)
  184418. {
  184419. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184420. }
  184421. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184422. * in case CRC is > 32 bits to leave the top bits 0.
  184423. */
  184424. void /* PRIVATE */
  184425. png_reset_crc(png_structp png_ptr)
  184426. {
  184427. png_ptr->crc = crc32(0, Z_NULL, 0);
  184428. }
  184429. /* Calculate the CRC over a section of data. We can only pass as
  184430. * much data to this routine as the largest single buffer size. We
  184431. * also check that this data will actually be used before going to the
  184432. * trouble of calculating it.
  184433. */
  184434. void /* PRIVATE */
  184435. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184436. {
  184437. int need_crc = 1;
  184438. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184439. {
  184440. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184441. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184442. need_crc = 0;
  184443. }
  184444. else /* critical */
  184445. {
  184446. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184447. need_crc = 0;
  184448. }
  184449. if (need_crc)
  184450. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184451. }
  184452. /* Allocate the memory for an info_struct for the application. We don't
  184453. * really need the png_ptr, but it could potentially be useful in the
  184454. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184455. * and png_info_init() so that applications that want to use a shared
  184456. * libpng don't have to be recompiled if png_info changes size.
  184457. */
  184458. png_infop PNGAPI
  184459. png_create_info_struct(png_structp png_ptr)
  184460. {
  184461. png_infop info_ptr;
  184462. png_debug(1, "in png_create_info_struct\n");
  184463. if(png_ptr == NULL) return (NULL);
  184464. #ifdef PNG_USER_MEM_SUPPORTED
  184465. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184466. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184467. #else
  184468. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184469. #endif
  184470. if (info_ptr != NULL)
  184471. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184472. return (info_ptr);
  184473. }
  184474. /* This function frees the memory associated with a single info struct.
  184475. * Normally, one would use either png_destroy_read_struct() or
  184476. * png_destroy_write_struct() to free an info struct, but this may be
  184477. * useful for some applications.
  184478. */
  184479. void PNGAPI
  184480. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184481. {
  184482. png_infop info_ptr = NULL;
  184483. if(png_ptr == NULL) return;
  184484. png_debug(1, "in png_destroy_info_struct\n");
  184485. if (info_ptr_ptr != NULL)
  184486. info_ptr = *info_ptr_ptr;
  184487. if (info_ptr != NULL)
  184488. {
  184489. png_info_destroy(png_ptr, info_ptr);
  184490. #ifdef PNG_USER_MEM_SUPPORTED
  184491. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184492. png_ptr->mem_ptr);
  184493. #else
  184494. png_destroy_struct((png_voidp)info_ptr);
  184495. #endif
  184496. *info_ptr_ptr = NULL;
  184497. }
  184498. }
  184499. /* Initialize the info structure. This is now an internal function (0.89)
  184500. * and applications using it are urged to use png_create_info_struct()
  184501. * instead.
  184502. */
  184503. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184504. #undef png_info_init
  184505. void PNGAPI
  184506. png_info_init(png_infop info_ptr)
  184507. {
  184508. /* We only come here via pre-1.0.12-compiled applications */
  184509. png_info_init_3(&info_ptr, 0);
  184510. }
  184511. #endif
  184512. void PNGAPI
  184513. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184514. {
  184515. png_infop info_ptr = *ptr_ptr;
  184516. if(info_ptr == NULL) return;
  184517. png_debug(1, "in png_info_init_3\n");
  184518. if(png_sizeof(png_info) > png_info_struct_size)
  184519. {
  184520. png_destroy_struct(info_ptr);
  184521. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184522. *ptr_ptr = info_ptr;
  184523. }
  184524. /* set everything to 0 */
  184525. png_memset(info_ptr, 0, png_sizeof (png_info));
  184526. }
  184527. #ifdef PNG_FREE_ME_SUPPORTED
  184528. void PNGAPI
  184529. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184530. int freer, png_uint_32 mask)
  184531. {
  184532. png_debug(1, "in png_data_freer\n");
  184533. if (png_ptr == NULL || info_ptr == NULL)
  184534. return;
  184535. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184536. info_ptr->free_me |= mask;
  184537. else if(freer == PNG_USER_WILL_FREE_DATA)
  184538. info_ptr->free_me &= ~mask;
  184539. else
  184540. png_warning(png_ptr,
  184541. "Unknown freer parameter in png_data_freer.");
  184542. }
  184543. #endif
  184544. void PNGAPI
  184545. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184546. int num)
  184547. {
  184548. png_debug(1, "in png_free_data\n");
  184549. if (png_ptr == NULL || info_ptr == NULL)
  184550. return;
  184551. #if defined(PNG_TEXT_SUPPORTED)
  184552. /* free text item num or (if num == -1) all text items */
  184553. #ifdef PNG_FREE_ME_SUPPORTED
  184554. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184555. #else
  184556. if (mask & PNG_FREE_TEXT)
  184557. #endif
  184558. {
  184559. if (num != -1)
  184560. {
  184561. if (info_ptr->text && info_ptr->text[num].key)
  184562. {
  184563. png_free(png_ptr, info_ptr->text[num].key);
  184564. info_ptr->text[num].key = NULL;
  184565. }
  184566. }
  184567. else
  184568. {
  184569. int i;
  184570. for (i = 0; i < info_ptr->num_text; i++)
  184571. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184572. png_free(png_ptr, info_ptr->text);
  184573. info_ptr->text = NULL;
  184574. info_ptr->num_text=0;
  184575. }
  184576. }
  184577. #endif
  184578. #if defined(PNG_tRNS_SUPPORTED)
  184579. /* free any tRNS entry */
  184580. #ifdef PNG_FREE_ME_SUPPORTED
  184581. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184582. #else
  184583. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184584. #endif
  184585. {
  184586. png_free(png_ptr, info_ptr->trans);
  184587. info_ptr->valid &= ~PNG_INFO_tRNS;
  184588. #ifndef PNG_FREE_ME_SUPPORTED
  184589. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184590. #endif
  184591. info_ptr->trans = NULL;
  184592. }
  184593. #endif
  184594. #if defined(PNG_sCAL_SUPPORTED)
  184595. /* free any sCAL entry */
  184596. #ifdef PNG_FREE_ME_SUPPORTED
  184597. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184598. #else
  184599. if (mask & PNG_FREE_SCAL)
  184600. #endif
  184601. {
  184602. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184603. png_free(png_ptr, info_ptr->scal_s_width);
  184604. png_free(png_ptr, info_ptr->scal_s_height);
  184605. info_ptr->scal_s_width = NULL;
  184606. info_ptr->scal_s_height = NULL;
  184607. #endif
  184608. info_ptr->valid &= ~PNG_INFO_sCAL;
  184609. }
  184610. #endif
  184611. #if defined(PNG_pCAL_SUPPORTED)
  184612. /* free any pCAL entry */
  184613. #ifdef PNG_FREE_ME_SUPPORTED
  184614. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184615. #else
  184616. if (mask & PNG_FREE_PCAL)
  184617. #endif
  184618. {
  184619. png_free(png_ptr, info_ptr->pcal_purpose);
  184620. png_free(png_ptr, info_ptr->pcal_units);
  184621. info_ptr->pcal_purpose = NULL;
  184622. info_ptr->pcal_units = NULL;
  184623. if (info_ptr->pcal_params != NULL)
  184624. {
  184625. int i;
  184626. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184627. {
  184628. png_free(png_ptr, info_ptr->pcal_params[i]);
  184629. info_ptr->pcal_params[i]=NULL;
  184630. }
  184631. png_free(png_ptr, info_ptr->pcal_params);
  184632. info_ptr->pcal_params = NULL;
  184633. }
  184634. info_ptr->valid &= ~PNG_INFO_pCAL;
  184635. }
  184636. #endif
  184637. #if defined(PNG_iCCP_SUPPORTED)
  184638. /* free any iCCP entry */
  184639. #ifdef PNG_FREE_ME_SUPPORTED
  184640. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184641. #else
  184642. if (mask & PNG_FREE_ICCP)
  184643. #endif
  184644. {
  184645. png_free(png_ptr, info_ptr->iccp_name);
  184646. png_free(png_ptr, info_ptr->iccp_profile);
  184647. info_ptr->iccp_name = NULL;
  184648. info_ptr->iccp_profile = NULL;
  184649. info_ptr->valid &= ~PNG_INFO_iCCP;
  184650. }
  184651. #endif
  184652. #if defined(PNG_sPLT_SUPPORTED)
  184653. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184654. #ifdef PNG_FREE_ME_SUPPORTED
  184655. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184656. #else
  184657. if (mask & PNG_FREE_SPLT)
  184658. #endif
  184659. {
  184660. if (num != -1)
  184661. {
  184662. if(info_ptr->splt_palettes)
  184663. {
  184664. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184665. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184666. info_ptr->splt_palettes[num].name = NULL;
  184667. info_ptr->splt_palettes[num].entries = NULL;
  184668. }
  184669. }
  184670. else
  184671. {
  184672. if(info_ptr->splt_palettes_num)
  184673. {
  184674. int i;
  184675. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184676. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184677. png_free(png_ptr, info_ptr->splt_palettes);
  184678. info_ptr->splt_palettes = NULL;
  184679. info_ptr->splt_palettes_num = 0;
  184680. }
  184681. info_ptr->valid &= ~PNG_INFO_sPLT;
  184682. }
  184683. }
  184684. #endif
  184685. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184686. if(png_ptr->unknown_chunk.data)
  184687. {
  184688. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184689. png_ptr->unknown_chunk.data = NULL;
  184690. }
  184691. #ifdef PNG_FREE_ME_SUPPORTED
  184692. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184693. #else
  184694. if (mask & PNG_FREE_UNKN)
  184695. #endif
  184696. {
  184697. if (num != -1)
  184698. {
  184699. if(info_ptr->unknown_chunks)
  184700. {
  184701. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184702. info_ptr->unknown_chunks[num].data = NULL;
  184703. }
  184704. }
  184705. else
  184706. {
  184707. int i;
  184708. if(info_ptr->unknown_chunks_num)
  184709. {
  184710. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184711. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184712. png_free(png_ptr, info_ptr->unknown_chunks);
  184713. info_ptr->unknown_chunks = NULL;
  184714. info_ptr->unknown_chunks_num = 0;
  184715. }
  184716. }
  184717. }
  184718. #endif
  184719. #if defined(PNG_hIST_SUPPORTED)
  184720. /* free any hIST entry */
  184721. #ifdef PNG_FREE_ME_SUPPORTED
  184722. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184723. #else
  184724. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184725. #endif
  184726. {
  184727. png_free(png_ptr, info_ptr->hist);
  184728. info_ptr->hist = NULL;
  184729. info_ptr->valid &= ~PNG_INFO_hIST;
  184730. #ifndef PNG_FREE_ME_SUPPORTED
  184731. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184732. #endif
  184733. }
  184734. #endif
  184735. /* free any PLTE entry that was internally allocated */
  184736. #ifdef PNG_FREE_ME_SUPPORTED
  184737. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184738. #else
  184739. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184740. #endif
  184741. {
  184742. png_zfree(png_ptr, info_ptr->palette);
  184743. info_ptr->palette = NULL;
  184744. info_ptr->valid &= ~PNG_INFO_PLTE;
  184745. #ifndef PNG_FREE_ME_SUPPORTED
  184746. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184747. #endif
  184748. info_ptr->num_palette = 0;
  184749. }
  184750. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184751. /* free any image bits attached to the info structure */
  184752. #ifdef PNG_FREE_ME_SUPPORTED
  184753. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184754. #else
  184755. if (mask & PNG_FREE_ROWS)
  184756. #endif
  184757. {
  184758. if(info_ptr->row_pointers)
  184759. {
  184760. int row;
  184761. for (row = 0; row < (int)info_ptr->height; row++)
  184762. {
  184763. png_free(png_ptr, info_ptr->row_pointers[row]);
  184764. info_ptr->row_pointers[row]=NULL;
  184765. }
  184766. png_free(png_ptr, info_ptr->row_pointers);
  184767. info_ptr->row_pointers=NULL;
  184768. }
  184769. info_ptr->valid &= ~PNG_INFO_IDAT;
  184770. }
  184771. #endif
  184772. #ifdef PNG_FREE_ME_SUPPORTED
  184773. if(num == -1)
  184774. info_ptr->free_me &= ~mask;
  184775. else
  184776. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184777. #endif
  184778. }
  184779. /* This is an internal routine to free any memory that the info struct is
  184780. * pointing to before re-using it or freeing the struct itself. Recall
  184781. * that png_free() checks for NULL pointers for us.
  184782. */
  184783. void /* PRIVATE */
  184784. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184785. {
  184786. png_debug(1, "in png_info_destroy\n");
  184787. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184788. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184789. if (png_ptr->num_chunk_list)
  184790. {
  184791. png_free(png_ptr, png_ptr->chunk_list);
  184792. png_ptr->chunk_list=NULL;
  184793. png_ptr->num_chunk_list=0;
  184794. }
  184795. #endif
  184796. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184797. }
  184798. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184799. /* This function returns a pointer to the io_ptr associated with the user
  184800. * functions. The application should free any memory associated with this
  184801. * pointer before png_write_destroy() or png_read_destroy() are called.
  184802. */
  184803. png_voidp PNGAPI
  184804. png_get_io_ptr(png_structp png_ptr)
  184805. {
  184806. if(png_ptr == NULL) return (NULL);
  184807. return (png_ptr->io_ptr);
  184808. }
  184809. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184810. #if !defined(PNG_NO_STDIO)
  184811. /* Initialize the default input/output functions for the PNG file. If you
  184812. * use your own read or write routines, you can call either png_set_read_fn()
  184813. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184814. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184815. * necessarily available.
  184816. */
  184817. void PNGAPI
  184818. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184819. {
  184820. png_debug(1, "in png_init_io\n");
  184821. if(png_ptr == NULL) return;
  184822. png_ptr->io_ptr = (png_voidp)fp;
  184823. }
  184824. #endif
  184825. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184826. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184827. * a "Creation Time" or other text-based time string.
  184828. */
  184829. png_charp PNGAPI
  184830. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184831. {
  184832. static PNG_CONST char short_months[12][4] =
  184833. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184834. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184835. if(png_ptr == NULL) return (NULL);
  184836. if (png_ptr->time_buffer == NULL)
  184837. {
  184838. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184839. png_sizeof(char)));
  184840. }
  184841. #if defined(_WIN32_WCE)
  184842. {
  184843. wchar_t time_buf[29];
  184844. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184845. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184846. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184847. ptime->second % 61);
  184848. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184849. NULL, NULL);
  184850. }
  184851. #else
  184852. #ifdef USE_FAR_KEYWORD
  184853. {
  184854. char near_time_buf[29];
  184855. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184856. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184857. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184858. ptime->second % 61);
  184859. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184860. 29*png_sizeof(char));
  184861. }
  184862. #else
  184863. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184864. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184865. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184866. ptime->second % 61);
  184867. #endif
  184868. #endif /* _WIN32_WCE */
  184869. return ((png_charp)png_ptr->time_buffer);
  184870. }
  184871. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184872. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184873. png_charp PNGAPI
  184874. png_get_copyright(png_structp png_ptr)
  184875. {
  184876. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184877. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184878. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184879. Copyright (c) 1996-1997 Andreas Dilger\n\
  184880. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184881. }
  184882. /* The following return the library version as a short string in the
  184883. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184884. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184885. * is defined in png.h.
  184886. * Note: now there is no difference between png_get_libpng_ver() and
  184887. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184888. * it is guaranteed that png.c uses the correct version of png.h.
  184889. */
  184890. png_charp PNGAPI
  184891. png_get_libpng_ver(png_structp png_ptr)
  184892. {
  184893. /* Version of *.c files used when building libpng */
  184894. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184895. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184896. }
  184897. png_charp PNGAPI
  184898. png_get_header_ver(png_structp png_ptr)
  184899. {
  184900. /* Version of *.h files used when building libpng */
  184901. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184902. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184903. }
  184904. png_charp PNGAPI
  184905. png_get_header_version(png_structp png_ptr)
  184906. {
  184907. /* Returns longer string containing both version and date */
  184908. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184909. return ((png_charp) PNG_HEADER_VERSION_STRING
  184910. #ifndef PNG_READ_SUPPORTED
  184911. " (NO READ SUPPORT)"
  184912. #endif
  184913. "\n");
  184914. }
  184915. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184916. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184917. int PNGAPI
  184918. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184919. {
  184920. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184921. int i;
  184922. png_bytep p;
  184923. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184924. return 0;
  184925. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184926. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184927. if (!png_memcmp(chunk_name, p, 4))
  184928. return ((int)*(p+4));
  184929. return 0;
  184930. }
  184931. #endif
  184932. /* This function, added to libpng-1.0.6g, is untested. */
  184933. int PNGAPI
  184934. png_reset_zstream(png_structp png_ptr)
  184935. {
  184936. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184937. return (inflateReset(&png_ptr->zstream));
  184938. }
  184939. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184940. /* This function was added to libpng-1.0.7 */
  184941. png_uint_32 PNGAPI
  184942. png_access_version_number(void)
  184943. {
  184944. /* Version of *.c files used when building libpng */
  184945. return((png_uint_32) PNG_LIBPNG_VER);
  184946. }
  184947. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184948. #if !defined(PNG_1_0_X)
  184949. /* this function was added to libpng 1.2.0 */
  184950. int PNGAPI
  184951. png_mmx_support(void)
  184952. {
  184953. /* obsolete, to be removed from libpng-1.4.0 */
  184954. return -1;
  184955. }
  184956. #endif /* PNG_1_0_X */
  184957. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184958. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184959. #ifdef PNG_SIZE_T
  184960. /* Added at libpng version 1.2.6 */
  184961. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184962. png_size_t PNGAPI
  184963. png_convert_size(size_t size)
  184964. {
  184965. if (size > (png_size_t)-1)
  184966. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184967. return ((png_size_t)size);
  184968. }
  184969. #endif /* PNG_SIZE_T */
  184970. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184971. /*** End of inlined file: png.c ***/
  184972. /*** Start of inlined file: pngerror.c ***/
  184973. /* pngerror.c - stub functions for i/o and memory allocation
  184974. *
  184975. * Last changed in libpng 1.2.20 October 4, 2007
  184976. * For conditions of distribution and use, see copyright notice in png.h
  184977. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184978. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184979. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184980. *
  184981. * This file provides a location for all error handling. Users who
  184982. * need special error handling are expected to write replacement functions
  184983. * and use png_set_error_fn() to use those functions. See the instructions
  184984. * at each function.
  184985. */
  184986. #define PNG_INTERNAL
  184987. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184988. static void /* PRIVATE */
  184989. png_default_error PNGARG((png_structp png_ptr,
  184990. png_const_charp error_message));
  184991. #ifndef PNG_NO_WARNINGS
  184992. static void /* PRIVATE */
  184993. png_default_warning PNGARG((png_structp png_ptr,
  184994. png_const_charp warning_message));
  184995. #endif /* PNG_NO_WARNINGS */
  184996. /* This function is called whenever there is a fatal error. This function
  184997. * should not be changed. If there is a need to handle errors differently,
  184998. * you should supply a replacement error function and use png_set_error_fn()
  184999. * to replace the error function at run-time.
  185000. */
  185001. #ifndef PNG_NO_ERROR_TEXT
  185002. void PNGAPI
  185003. png_error(png_structp png_ptr, png_const_charp error_message)
  185004. {
  185005. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185006. char msg[16];
  185007. if (png_ptr != NULL)
  185008. {
  185009. if (png_ptr->flags&
  185010. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185011. {
  185012. if (*error_message == '#')
  185013. {
  185014. int offset;
  185015. for (offset=1; offset<15; offset++)
  185016. if (*(error_message+offset) == ' ')
  185017. break;
  185018. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185019. {
  185020. int i;
  185021. for (i=0; i<offset-1; i++)
  185022. msg[i]=error_message[i+1];
  185023. msg[i]='\0';
  185024. error_message=msg;
  185025. }
  185026. else
  185027. error_message+=offset;
  185028. }
  185029. else
  185030. {
  185031. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185032. {
  185033. msg[0]='0';
  185034. msg[1]='\0';
  185035. error_message=msg;
  185036. }
  185037. }
  185038. }
  185039. }
  185040. #endif
  185041. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185042. (*(png_ptr->error_fn))(png_ptr, error_message);
  185043. /* If the custom handler doesn't exist, or if it returns,
  185044. use the default handler, which will not return. */
  185045. png_default_error(png_ptr, error_message);
  185046. }
  185047. #else
  185048. void PNGAPI
  185049. png_err(png_structp png_ptr)
  185050. {
  185051. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185052. (*(png_ptr->error_fn))(png_ptr, '\0');
  185053. /* If the custom handler doesn't exist, or if it returns,
  185054. use the default handler, which will not return. */
  185055. png_default_error(png_ptr, '\0');
  185056. }
  185057. #endif /* PNG_NO_ERROR_TEXT */
  185058. #ifndef PNG_NO_WARNINGS
  185059. /* This function is called whenever there is a non-fatal error. This function
  185060. * should not be changed. If there is a need to handle warnings differently,
  185061. * you should supply a replacement warning function and use
  185062. * png_set_error_fn() to replace the warning function at run-time.
  185063. */
  185064. void PNGAPI
  185065. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185066. {
  185067. int offset = 0;
  185068. if (png_ptr != NULL)
  185069. {
  185070. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185071. if (png_ptr->flags&
  185072. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185073. #endif
  185074. {
  185075. if (*warning_message == '#')
  185076. {
  185077. for (offset=1; offset<15; offset++)
  185078. if (*(warning_message+offset) == ' ')
  185079. break;
  185080. }
  185081. }
  185082. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185083. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185084. }
  185085. else
  185086. png_default_warning(png_ptr, warning_message+offset);
  185087. }
  185088. #endif /* PNG_NO_WARNINGS */
  185089. /* These utilities are used internally to build an error message that relates
  185090. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185091. * this is used to prefix the message. The message is limited in length
  185092. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185093. * if the character is invalid.
  185094. */
  185095. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185096. /*static PNG_CONST char png_digit[16] = {
  185097. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185098. 'A', 'B', 'C', 'D', 'E', 'F'
  185099. };*/
  185100. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185101. static void /* PRIVATE */
  185102. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185103. error_message)
  185104. {
  185105. int iout = 0, iin = 0;
  185106. while (iin < 4)
  185107. {
  185108. int c = png_ptr->chunk_name[iin++];
  185109. if (isnonalpha(c))
  185110. {
  185111. buffer[iout++] = '[';
  185112. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185113. buffer[iout++] = png_digit[c & 0x0f];
  185114. buffer[iout++] = ']';
  185115. }
  185116. else
  185117. {
  185118. buffer[iout++] = (png_byte)c;
  185119. }
  185120. }
  185121. if (error_message == NULL)
  185122. buffer[iout] = 0;
  185123. else
  185124. {
  185125. buffer[iout++] = ':';
  185126. buffer[iout++] = ' ';
  185127. png_strncpy(buffer+iout, error_message, 63);
  185128. buffer[iout+63] = 0;
  185129. }
  185130. }
  185131. #ifdef PNG_READ_SUPPORTED
  185132. void PNGAPI
  185133. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185134. {
  185135. char msg[18+64];
  185136. if (png_ptr == NULL)
  185137. png_error(png_ptr, error_message);
  185138. else
  185139. {
  185140. png_format_buffer(png_ptr, msg, error_message);
  185141. png_error(png_ptr, msg);
  185142. }
  185143. }
  185144. #endif /* PNG_READ_SUPPORTED */
  185145. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185146. #ifndef PNG_NO_WARNINGS
  185147. void PNGAPI
  185148. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185149. {
  185150. char msg[18+64];
  185151. if (png_ptr == NULL)
  185152. png_warning(png_ptr, warning_message);
  185153. else
  185154. {
  185155. png_format_buffer(png_ptr, msg, warning_message);
  185156. png_warning(png_ptr, msg);
  185157. }
  185158. }
  185159. #endif /* PNG_NO_WARNINGS */
  185160. /* This is the default error handling function. Note that replacements for
  185161. * this function MUST NOT RETURN, or the program will likely crash. This
  185162. * function is used by default, or if the program supplies NULL for the
  185163. * error function pointer in png_set_error_fn().
  185164. */
  185165. static void /* PRIVATE */
  185166. png_default_error(png_structp, png_const_charp error_message)
  185167. {
  185168. #ifndef PNG_NO_CONSOLE_IO
  185169. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185170. if (*error_message == '#')
  185171. {
  185172. int offset;
  185173. char error_number[16];
  185174. for (offset=0; offset<15; offset++)
  185175. {
  185176. error_number[offset] = *(error_message+offset+1);
  185177. if (*(error_message+offset) == ' ')
  185178. break;
  185179. }
  185180. if((offset > 1) && (offset < 15))
  185181. {
  185182. error_number[offset-1]='\0';
  185183. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185184. error_message+offset);
  185185. }
  185186. else
  185187. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185188. }
  185189. else
  185190. #endif
  185191. fprintf(stderr, "libpng error: %s\n", error_message);
  185192. #endif
  185193. #ifdef PNG_SETJMP_SUPPORTED
  185194. if (png_ptr)
  185195. {
  185196. # ifdef USE_FAR_KEYWORD
  185197. {
  185198. jmp_buf jmpbuf;
  185199. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185200. longjmp(jmpbuf, 1);
  185201. }
  185202. # else
  185203. longjmp(png_ptr->jmpbuf, 1);
  185204. # endif
  185205. }
  185206. #else
  185207. PNG_ABORT();
  185208. #endif
  185209. #ifdef PNG_NO_CONSOLE_IO
  185210. error_message = error_message; /* make compiler happy */
  185211. #endif
  185212. }
  185213. #ifndef PNG_NO_WARNINGS
  185214. /* This function is called when there is a warning, but the library thinks
  185215. * it can continue anyway. Replacement functions don't have to do anything
  185216. * here if you don't want them to. In the default configuration, png_ptr is
  185217. * not used, but it is passed in case it may be useful.
  185218. */
  185219. static void /* PRIVATE */
  185220. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185221. {
  185222. #ifndef PNG_NO_CONSOLE_IO
  185223. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185224. if (*warning_message == '#')
  185225. {
  185226. int offset;
  185227. char warning_number[16];
  185228. for (offset=0; offset<15; offset++)
  185229. {
  185230. warning_number[offset]=*(warning_message+offset+1);
  185231. if (*(warning_message+offset) == ' ')
  185232. break;
  185233. }
  185234. if((offset > 1) && (offset < 15))
  185235. {
  185236. warning_number[offset-1]='\0';
  185237. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185238. warning_message+offset);
  185239. }
  185240. else
  185241. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185242. }
  185243. else
  185244. # endif
  185245. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185246. #else
  185247. warning_message = warning_message; /* make compiler happy */
  185248. #endif
  185249. png_ptr = png_ptr; /* make compiler happy */
  185250. }
  185251. #endif /* PNG_NO_WARNINGS */
  185252. /* This function is called when the application wants to use another method
  185253. * of handling errors and warnings. Note that the error function MUST NOT
  185254. * return to the calling routine or serious problems will occur. The return
  185255. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185256. */
  185257. void PNGAPI
  185258. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185259. png_error_ptr error_fn, png_error_ptr warning_fn)
  185260. {
  185261. if (png_ptr == NULL)
  185262. return;
  185263. png_ptr->error_ptr = error_ptr;
  185264. png_ptr->error_fn = error_fn;
  185265. png_ptr->warning_fn = warning_fn;
  185266. }
  185267. /* This function returns a pointer to the error_ptr associated with the user
  185268. * functions. The application should free any memory associated with this
  185269. * pointer before png_write_destroy and png_read_destroy are called.
  185270. */
  185271. png_voidp PNGAPI
  185272. png_get_error_ptr(png_structp png_ptr)
  185273. {
  185274. if (png_ptr == NULL)
  185275. return NULL;
  185276. return ((png_voidp)png_ptr->error_ptr);
  185277. }
  185278. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185279. void PNGAPI
  185280. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185281. {
  185282. if(png_ptr != NULL)
  185283. {
  185284. png_ptr->flags &=
  185285. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185286. }
  185287. }
  185288. #endif
  185289. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185290. /*** End of inlined file: pngerror.c ***/
  185291. /*** Start of inlined file: pngget.c ***/
  185292. /* pngget.c - retrieval of values from info struct
  185293. *
  185294. * Last changed in libpng 1.2.15 January 5, 2007
  185295. * For conditions of distribution and use, see copyright notice in png.h
  185296. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185297. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185298. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185299. */
  185300. #define PNG_INTERNAL
  185301. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185302. png_uint_32 PNGAPI
  185303. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185304. {
  185305. if (png_ptr != NULL && info_ptr != NULL)
  185306. return(info_ptr->valid & flag);
  185307. else
  185308. return(0);
  185309. }
  185310. png_uint_32 PNGAPI
  185311. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185312. {
  185313. if (png_ptr != NULL && info_ptr != NULL)
  185314. return(info_ptr->rowbytes);
  185315. else
  185316. return(0);
  185317. }
  185318. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185319. png_bytepp PNGAPI
  185320. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185321. {
  185322. if (png_ptr != NULL && info_ptr != NULL)
  185323. return(info_ptr->row_pointers);
  185324. else
  185325. return(0);
  185326. }
  185327. #endif
  185328. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185329. /* easy access to info, added in libpng-0.99 */
  185330. png_uint_32 PNGAPI
  185331. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185332. {
  185333. if (png_ptr != NULL && info_ptr != NULL)
  185334. {
  185335. return info_ptr->width;
  185336. }
  185337. return (0);
  185338. }
  185339. png_uint_32 PNGAPI
  185340. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185341. {
  185342. if (png_ptr != NULL && info_ptr != NULL)
  185343. {
  185344. return info_ptr->height;
  185345. }
  185346. return (0);
  185347. }
  185348. png_byte PNGAPI
  185349. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185350. {
  185351. if (png_ptr != NULL && info_ptr != NULL)
  185352. {
  185353. return info_ptr->bit_depth;
  185354. }
  185355. return (0);
  185356. }
  185357. png_byte PNGAPI
  185358. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185359. {
  185360. if (png_ptr != NULL && info_ptr != NULL)
  185361. {
  185362. return info_ptr->color_type;
  185363. }
  185364. return (0);
  185365. }
  185366. png_byte PNGAPI
  185367. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185368. {
  185369. if (png_ptr != NULL && info_ptr != NULL)
  185370. {
  185371. return info_ptr->filter_type;
  185372. }
  185373. return (0);
  185374. }
  185375. png_byte PNGAPI
  185376. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185377. {
  185378. if (png_ptr != NULL && info_ptr != NULL)
  185379. {
  185380. return info_ptr->interlace_type;
  185381. }
  185382. return (0);
  185383. }
  185384. png_byte PNGAPI
  185385. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185386. {
  185387. if (png_ptr != NULL && info_ptr != NULL)
  185388. {
  185389. return info_ptr->compression_type;
  185390. }
  185391. return (0);
  185392. }
  185393. png_uint_32 PNGAPI
  185394. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185395. {
  185396. if (png_ptr != NULL && info_ptr != NULL)
  185397. #if defined(PNG_pHYs_SUPPORTED)
  185398. if (info_ptr->valid & PNG_INFO_pHYs)
  185399. {
  185400. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185401. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185402. return (0);
  185403. else return (info_ptr->x_pixels_per_unit);
  185404. }
  185405. #else
  185406. return (0);
  185407. #endif
  185408. return (0);
  185409. }
  185410. png_uint_32 PNGAPI
  185411. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185412. {
  185413. if (png_ptr != NULL && info_ptr != NULL)
  185414. #if defined(PNG_pHYs_SUPPORTED)
  185415. if (info_ptr->valid & PNG_INFO_pHYs)
  185416. {
  185417. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185418. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185419. return (0);
  185420. else return (info_ptr->y_pixels_per_unit);
  185421. }
  185422. #else
  185423. return (0);
  185424. #endif
  185425. return (0);
  185426. }
  185427. png_uint_32 PNGAPI
  185428. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185429. {
  185430. if (png_ptr != NULL && info_ptr != NULL)
  185431. #if defined(PNG_pHYs_SUPPORTED)
  185432. if (info_ptr->valid & PNG_INFO_pHYs)
  185433. {
  185434. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185435. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185436. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185437. return (0);
  185438. else return (info_ptr->x_pixels_per_unit);
  185439. }
  185440. #else
  185441. return (0);
  185442. #endif
  185443. return (0);
  185444. }
  185445. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185446. float PNGAPI
  185447. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185448. {
  185449. if (png_ptr != NULL && info_ptr != NULL)
  185450. #if defined(PNG_pHYs_SUPPORTED)
  185451. if (info_ptr->valid & PNG_INFO_pHYs)
  185452. {
  185453. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185454. if (info_ptr->x_pixels_per_unit == 0)
  185455. return ((float)0.0);
  185456. else
  185457. return ((float)((float)info_ptr->y_pixels_per_unit
  185458. /(float)info_ptr->x_pixels_per_unit));
  185459. }
  185460. #else
  185461. return (0.0);
  185462. #endif
  185463. return ((float)0.0);
  185464. }
  185465. #endif
  185466. png_int_32 PNGAPI
  185467. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185468. {
  185469. if (png_ptr != NULL && info_ptr != NULL)
  185470. #if defined(PNG_oFFs_SUPPORTED)
  185471. if (info_ptr->valid & PNG_INFO_oFFs)
  185472. {
  185473. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185474. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185475. return (0);
  185476. else return (info_ptr->x_offset);
  185477. }
  185478. #else
  185479. return (0);
  185480. #endif
  185481. return (0);
  185482. }
  185483. png_int_32 PNGAPI
  185484. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185485. {
  185486. if (png_ptr != NULL && info_ptr != NULL)
  185487. #if defined(PNG_oFFs_SUPPORTED)
  185488. if (info_ptr->valid & PNG_INFO_oFFs)
  185489. {
  185490. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185491. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185492. return (0);
  185493. else return (info_ptr->y_offset);
  185494. }
  185495. #else
  185496. return (0);
  185497. #endif
  185498. return (0);
  185499. }
  185500. png_int_32 PNGAPI
  185501. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185502. {
  185503. if (png_ptr != NULL && info_ptr != NULL)
  185504. #if defined(PNG_oFFs_SUPPORTED)
  185505. if (info_ptr->valid & PNG_INFO_oFFs)
  185506. {
  185507. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185508. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185509. return (0);
  185510. else return (info_ptr->x_offset);
  185511. }
  185512. #else
  185513. return (0);
  185514. #endif
  185515. return (0);
  185516. }
  185517. png_int_32 PNGAPI
  185518. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185519. {
  185520. if (png_ptr != NULL && info_ptr != NULL)
  185521. #if defined(PNG_oFFs_SUPPORTED)
  185522. if (info_ptr->valid & PNG_INFO_oFFs)
  185523. {
  185524. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185525. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185526. return (0);
  185527. else return (info_ptr->y_offset);
  185528. }
  185529. #else
  185530. return (0);
  185531. #endif
  185532. return (0);
  185533. }
  185534. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185535. png_uint_32 PNGAPI
  185536. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185537. {
  185538. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185539. *.0254 +.5));
  185540. }
  185541. png_uint_32 PNGAPI
  185542. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185543. {
  185544. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185545. *.0254 +.5));
  185546. }
  185547. png_uint_32 PNGAPI
  185548. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185549. {
  185550. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185551. *.0254 +.5));
  185552. }
  185553. float PNGAPI
  185554. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185555. {
  185556. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185557. *.00003937);
  185558. }
  185559. float PNGAPI
  185560. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185561. {
  185562. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185563. *.00003937);
  185564. }
  185565. #if defined(PNG_pHYs_SUPPORTED)
  185566. png_uint_32 PNGAPI
  185567. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185568. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185569. {
  185570. png_uint_32 retval = 0;
  185571. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185572. {
  185573. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185574. if (res_x != NULL)
  185575. {
  185576. *res_x = info_ptr->x_pixels_per_unit;
  185577. retval |= PNG_INFO_pHYs;
  185578. }
  185579. if (res_y != NULL)
  185580. {
  185581. *res_y = info_ptr->y_pixels_per_unit;
  185582. retval |= PNG_INFO_pHYs;
  185583. }
  185584. if (unit_type != NULL)
  185585. {
  185586. *unit_type = (int)info_ptr->phys_unit_type;
  185587. retval |= PNG_INFO_pHYs;
  185588. if(*unit_type == 1)
  185589. {
  185590. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185591. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185592. }
  185593. }
  185594. }
  185595. return (retval);
  185596. }
  185597. #endif /* PNG_pHYs_SUPPORTED */
  185598. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185599. /* png_get_channels really belongs in here, too, but it's been around longer */
  185600. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185601. png_byte PNGAPI
  185602. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185603. {
  185604. if (png_ptr != NULL && info_ptr != NULL)
  185605. return(info_ptr->channels);
  185606. else
  185607. return (0);
  185608. }
  185609. png_bytep PNGAPI
  185610. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185611. {
  185612. if (png_ptr != NULL && info_ptr != NULL)
  185613. return(info_ptr->signature);
  185614. else
  185615. return (NULL);
  185616. }
  185617. #if defined(PNG_bKGD_SUPPORTED)
  185618. png_uint_32 PNGAPI
  185619. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185620. png_color_16p *background)
  185621. {
  185622. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185623. && background != NULL)
  185624. {
  185625. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185626. *background = &(info_ptr->background);
  185627. return (PNG_INFO_bKGD);
  185628. }
  185629. return (0);
  185630. }
  185631. #endif
  185632. #if defined(PNG_cHRM_SUPPORTED)
  185633. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185634. png_uint_32 PNGAPI
  185635. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185636. double *white_x, double *white_y, double *red_x, double *red_y,
  185637. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185638. {
  185639. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185640. {
  185641. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185642. if (white_x != NULL)
  185643. *white_x = (double)info_ptr->x_white;
  185644. if (white_y != NULL)
  185645. *white_y = (double)info_ptr->y_white;
  185646. if (red_x != NULL)
  185647. *red_x = (double)info_ptr->x_red;
  185648. if (red_y != NULL)
  185649. *red_y = (double)info_ptr->y_red;
  185650. if (green_x != NULL)
  185651. *green_x = (double)info_ptr->x_green;
  185652. if (green_y != NULL)
  185653. *green_y = (double)info_ptr->y_green;
  185654. if (blue_x != NULL)
  185655. *blue_x = (double)info_ptr->x_blue;
  185656. if (blue_y != NULL)
  185657. *blue_y = (double)info_ptr->y_blue;
  185658. return (PNG_INFO_cHRM);
  185659. }
  185660. return (0);
  185661. }
  185662. #endif
  185663. #ifdef PNG_FIXED_POINT_SUPPORTED
  185664. png_uint_32 PNGAPI
  185665. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185666. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185667. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185668. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185669. {
  185670. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185671. {
  185672. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185673. if (white_x != NULL)
  185674. *white_x = info_ptr->int_x_white;
  185675. if (white_y != NULL)
  185676. *white_y = info_ptr->int_y_white;
  185677. if (red_x != NULL)
  185678. *red_x = info_ptr->int_x_red;
  185679. if (red_y != NULL)
  185680. *red_y = info_ptr->int_y_red;
  185681. if (green_x != NULL)
  185682. *green_x = info_ptr->int_x_green;
  185683. if (green_y != NULL)
  185684. *green_y = info_ptr->int_y_green;
  185685. if (blue_x != NULL)
  185686. *blue_x = info_ptr->int_x_blue;
  185687. if (blue_y != NULL)
  185688. *blue_y = info_ptr->int_y_blue;
  185689. return (PNG_INFO_cHRM);
  185690. }
  185691. return (0);
  185692. }
  185693. #endif
  185694. #endif
  185695. #if defined(PNG_gAMA_SUPPORTED)
  185696. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185697. png_uint_32 PNGAPI
  185698. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185699. {
  185700. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185701. && file_gamma != NULL)
  185702. {
  185703. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185704. *file_gamma = (double)info_ptr->gamma;
  185705. return (PNG_INFO_gAMA);
  185706. }
  185707. return (0);
  185708. }
  185709. #endif
  185710. #ifdef PNG_FIXED_POINT_SUPPORTED
  185711. png_uint_32 PNGAPI
  185712. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185713. png_fixed_point *int_file_gamma)
  185714. {
  185715. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185716. && int_file_gamma != NULL)
  185717. {
  185718. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185719. *int_file_gamma = info_ptr->int_gamma;
  185720. return (PNG_INFO_gAMA);
  185721. }
  185722. return (0);
  185723. }
  185724. #endif
  185725. #endif
  185726. #if defined(PNG_sRGB_SUPPORTED)
  185727. png_uint_32 PNGAPI
  185728. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185729. {
  185730. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185731. && file_srgb_intent != NULL)
  185732. {
  185733. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185734. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185735. return (PNG_INFO_sRGB);
  185736. }
  185737. return (0);
  185738. }
  185739. #endif
  185740. #if defined(PNG_iCCP_SUPPORTED)
  185741. png_uint_32 PNGAPI
  185742. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185743. png_charpp name, int *compression_type,
  185744. png_charpp profile, png_uint_32 *proflen)
  185745. {
  185746. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185747. && name != NULL && profile != NULL && proflen != NULL)
  185748. {
  185749. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185750. *name = info_ptr->iccp_name;
  185751. *profile = info_ptr->iccp_profile;
  185752. /* compression_type is a dummy so the API won't have to change
  185753. if we introduce multiple compression types later. */
  185754. *proflen = (int)info_ptr->iccp_proflen;
  185755. *compression_type = (int)info_ptr->iccp_compression;
  185756. return (PNG_INFO_iCCP);
  185757. }
  185758. return (0);
  185759. }
  185760. #endif
  185761. #if defined(PNG_sPLT_SUPPORTED)
  185762. png_uint_32 PNGAPI
  185763. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185764. png_sPLT_tpp spalettes)
  185765. {
  185766. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185767. {
  185768. *spalettes = info_ptr->splt_palettes;
  185769. return ((png_uint_32)info_ptr->splt_palettes_num);
  185770. }
  185771. return (0);
  185772. }
  185773. #endif
  185774. #if defined(PNG_hIST_SUPPORTED)
  185775. png_uint_32 PNGAPI
  185776. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185777. {
  185778. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185779. && hist != NULL)
  185780. {
  185781. png_debug1(1, "in %s retrieval function\n", "hIST");
  185782. *hist = info_ptr->hist;
  185783. return (PNG_INFO_hIST);
  185784. }
  185785. return (0);
  185786. }
  185787. #endif
  185788. png_uint_32 PNGAPI
  185789. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185790. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185791. int *color_type, int *interlace_type, int *compression_type,
  185792. int *filter_type)
  185793. {
  185794. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185795. bit_depth != NULL && color_type != NULL)
  185796. {
  185797. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185798. *width = info_ptr->width;
  185799. *height = info_ptr->height;
  185800. *bit_depth = info_ptr->bit_depth;
  185801. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185802. png_error(png_ptr, "Invalid bit depth");
  185803. *color_type = info_ptr->color_type;
  185804. if (info_ptr->color_type > 6)
  185805. png_error(png_ptr, "Invalid color type");
  185806. if (compression_type != NULL)
  185807. *compression_type = info_ptr->compression_type;
  185808. if (filter_type != NULL)
  185809. *filter_type = info_ptr->filter_type;
  185810. if (interlace_type != NULL)
  185811. *interlace_type = info_ptr->interlace_type;
  185812. /* check for potential overflow of rowbytes */
  185813. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185814. png_error(png_ptr, "Invalid image width");
  185815. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185816. png_error(png_ptr, "Invalid image height");
  185817. if (info_ptr->width > (PNG_UINT_32_MAX
  185818. >> 3) /* 8-byte RGBA pixels */
  185819. - 64 /* bigrowbuf hack */
  185820. - 1 /* filter byte */
  185821. - 7*8 /* rounding of width to multiple of 8 pixels */
  185822. - 8) /* extra max_pixel_depth pad */
  185823. {
  185824. png_warning(png_ptr,
  185825. "Width too large for libpng to process image data.");
  185826. }
  185827. return (1);
  185828. }
  185829. return (0);
  185830. }
  185831. #if defined(PNG_oFFs_SUPPORTED)
  185832. png_uint_32 PNGAPI
  185833. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185834. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185835. {
  185836. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185837. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185838. {
  185839. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185840. *offset_x = info_ptr->x_offset;
  185841. *offset_y = info_ptr->y_offset;
  185842. *unit_type = (int)info_ptr->offset_unit_type;
  185843. return (PNG_INFO_oFFs);
  185844. }
  185845. return (0);
  185846. }
  185847. #endif
  185848. #if defined(PNG_pCAL_SUPPORTED)
  185849. png_uint_32 PNGAPI
  185850. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185851. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185852. png_charp *units, png_charpp *params)
  185853. {
  185854. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185855. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185856. nparams != NULL && units != NULL && params != NULL)
  185857. {
  185858. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185859. *purpose = info_ptr->pcal_purpose;
  185860. *X0 = info_ptr->pcal_X0;
  185861. *X1 = info_ptr->pcal_X1;
  185862. *type = (int)info_ptr->pcal_type;
  185863. *nparams = (int)info_ptr->pcal_nparams;
  185864. *units = info_ptr->pcal_units;
  185865. *params = info_ptr->pcal_params;
  185866. return (PNG_INFO_pCAL);
  185867. }
  185868. return (0);
  185869. }
  185870. #endif
  185871. #if defined(PNG_sCAL_SUPPORTED)
  185872. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185873. png_uint_32 PNGAPI
  185874. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185875. int *unit, double *width, double *height)
  185876. {
  185877. if (png_ptr != NULL && info_ptr != NULL &&
  185878. (info_ptr->valid & PNG_INFO_sCAL))
  185879. {
  185880. *unit = info_ptr->scal_unit;
  185881. *width = info_ptr->scal_pixel_width;
  185882. *height = info_ptr->scal_pixel_height;
  185883. return (PNG_INFO_sCAL);
  185884. }
  185885. return(0);
  185886. }
  185887. #else
  185888. #ifdef PNG_FIXED_POINT_SUPPORTED
  185889. png_uint_32 PNGAPI
  185890. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185891. int *unit, png_charpp width, png_charpp height)
  185892. {
  185893. if (png_ptr != NULL && info_ptr != NULL &&
  185894. (info_ptr->valid & PNG_INFO_sCAL))
  185895. {
  185896. *unit = info_ptr->scal_unit;
  185897. *width = info_ptr->scal_s_width;
  185898. *height = info_ptr->scal_s_height;
  185899. return (PNG_INFO_sCAL);
  185900. }
  185901. return(0);
  185902. }
  185903. #endif
  185904. #endif
  185905. #endif
  185906. #if defined(PNG_pHYs_SUPPORTED)
  185907. png_uint_32 PNGAPI
  185908. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185909. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185910. {
  185911. png_uint_32 retval = 0;
  185912. if (png_ptr != NULL && info_ptr != NULL &&
  185913. (info_ptr->valid & PNG_INFO_pHYs))
  185914. {
  185915. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185916. if (res_x != NULL)
  185917. {
  185918. *res_x = info_ptr->x_pixels_per_unit;
  185919. retval |= PNG_INFO_pHYs;
  185920. }
  185921. if (res_y != NULL)
  185922. {
  185923. *res_y = info_ptr->y_pixels_per_unit;
  185924. retval |= PNG_INFO_pHYs;
  185925. }
  185926. if (unit_type != NULL)
  185927. {
  185928. *unit_type = (int)info_ptr->phys_unit_type;
  185929. retval |= PNG_INFO_pHYs;
  185930. }
  185931. }
  185932. return (retval);
  185933. }
  185934. #endif
  185935. png_uint_32 PNGAPI
  185936. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185937. int *num_palette)
  185938. {
  185939. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185940. && palette != NULL)
  185941. {
  185942. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185943. *palette = info_ptr->palette;
  185944. *num_palette = info_ptr->num_palette;
  185945. png_debug1(3, "num_palette = %d\n", *num_palette);
  185946. return (PNG_INFO_PLTE);
  185947. }
  185948. return (0);
  185949. }
  185950. #if defined(PNG_sBIT_SUPPORTED)
  185951. png_uint_32 PNGAPI
  185952. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185953. {
  185954. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185955. && sig_bit != NULL)
  185956. {
  185957. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185958. *sig_bit = &(info_ptr->sig_bit);
  185959. return (PNG_INFO_sBIT);
  185960. }
  185961. return (0);
  185962. }
  185963. #endif
  185964. #if defined(PNG_TEXT_SUPPORTED)
  185965. png_uint_32 PNGAPI
  185966. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185967. int *num_text)
  185968. {
  185969. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185970. {
  185971. png_debug1(1, "in %s retrieval function\n",
  185972. (png_ptr->chunk_name[0] == '\0' ? "text"
  185973. : (png_const_charp)png_ptr->chunk_name));
  185974. if (text_ptr != NULL)
  185975. *text_ptr = info_ptr->text;
  185976. if (num_text != NULL)
  185977. *num_text = info_ptr->num_text;
  185978. return ((png_uint_32)info_ptr->num_text);
  185979. }
  185980. if (num_text != NULL)
  185981. *num_text = 0;
  185982. return(0);
  185983. }
  185984. #endif
  185985. #if defined(PNG_tIME_SUPPORTED)
  185986. png_uint_32 PNGAPI
  185987. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185988. {
  185989. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185990. && mod_time != NULL)
  185991. {
  185992. png_debug1(1, "in %s retrieval function\n", "tIME");
  185993. *mod_time = &(info_ptr->mod_time);
  185994. return (PNG_INFO_tIME);
  185995. }
  185996. return (0);
  185997. }
  185998. #endif
  185999. #if defined(PNG_tRNS_SUPPORTED)
  186000. png_uint_32 PNGAPI
  186001. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186002. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186003. {
  186004. png_uint_32 retval = 0;
  186005. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186006. {
  186007. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186008. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186009. {
  186010. if (trans != NULL)
  186011. {
  186012. *trans = info_ptr->trans;
  186013. retval |= PNG_INFO_tRNS;
  186014. }
  186015. if (trans_values != NULL)
  186016. *trans_values = &(info_ptr->trans_values);
  186017. }
  186018. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186019. {
  186020. if (trans_values != NULL)
  186021. {
  186022. *trans_values = &(info_ptr->trans_values);
  186023. retval |= PNG_INFO_tRNS;
  186024. }
  186025. if(trans != NULL)
  186026. *trans = NULL;
  186027. }
  186028. if(num_trans != NULL)
  186029. {
  186030. *num_trans = info_ptr->num_trans;
  186031. retval |= PNG_INFO_tRNS;
  186032. }
  186033. }
  186034. return (retval);
  186035. }
  186036. #endif
  186037. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186038. png_uint_32 PNGAPI
  186039. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186040. png_unknown_chunkpp unknowns)
  186041. {
  186042. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186043. {
  186044. *unknowns = info_ptr->unknown_chunks;
  186045. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186046. }
  186047. return (0);
  186048. }
  186049. #endif
  186050. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186051. png_byte PNGAPI
  186052. png_get_rgb_to_gray_status (png_structp png_ptr)
  186053. {
  186054. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186055. }
  186056. #endif
  186057. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186058. png_voidp PNGAPI
  186059. png_get_user_chunk_ptr(png_structp png_ptr)
  186060. {
  186061. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186062. }
  186063. #endif
  186064. #ifdef PNG_WRITE_SUPPORTED
  186065. png_uint_32 PNGAPI
  186066. png_get_compression_buffer_size(png_structp png_ptr)
  186067. {
  186068. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186069. }
  186070. #endif
  186071. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186072. #ifndef PNG_1_0_X
  186073. /* this function was added to libpng 1.2.0 and should exist by default */
  186074. png_uint_32 PNGAPI
  186075. png_get_asm_flags (png_structp png_ptr)
  186076. {
  186077. /* obsolete, to be removed from libpng-1.4.0 */
  186078. return (png_ptr? 0L: 0L);
  186079. }
  186080. /* this function was added to libpng 1.2.0 and should exist by default */
  186081. png_uint_32 PNGAPI
  186082. png_get_asm_flagmask (int flag_select)
  186083. {
  186084. /* obsolete, to be removed from libpng-1.4.0 */
  186085. flag_select=flag_select;
  186086. return 0L;
  186087. }
  186088. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186089. /* this function was added to libpng 1.2.0 */
  186090. png_uint_32 PNGAPI
  186091. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186092. {
  186093. /* obsolete, to be removed from libpng-1.4.0 */
  186094. flag_select=flag_select;
  186095. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186096. return 0L;
  186097. }
  186098. /* this function was added to libpng 1.2.0 */
  186099. png_byte PNGAPI
  186100. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186101. {
  186102. /* obsolete, to be removed from libpng-1.4.0 */
  186103. return (png_ptr? 0: 0);
  186104. }
  186105. /* this function was added to libpng 1.2.0 */
  186106. png_uint_32 PNGAPI
  186107. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186108. {
  186109. /* obsolete, to be removed from libpng-1.4.0 */
  186110. return (png_ptr? 0L: 0L);
  186111. }
  186112. #endif /* ?PNG_1_0_X */
  186113. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186114. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186115. /* these functions were added to libpng 1.2.6 */
  186116. png_uint_32 PNGAPI
  186117. png_get_user_width_max (png_structp png_ptr)
  186118. {
  186119. return (png_ptr? png_ptr->user_width_max : 0);
  186120. }
  186121. png_uint_32 PNGAPI
  186122. png_get_user_height_max (png_structp png_ptr)
  186123. {
  186124. return (png_ptr? png_ptr->user_height_max : 0);
  186125. }
  186126. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186127. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186128. /*** End of inlined file: pngget.c ***/
  186129. /*** Start of inlined file: pngmem.c ***/
  186130. /* pngmem.c - stub functions for memory allocation
  186131. *
  186132. * Last changed in libpng 1.2.13 November 13, 2006
  186133. * For conditions of distribution and use, see copyright notice in png.h
  186134. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186135. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186136. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186137. *
  186138. * This file provides a location for all memory allocation. Users who
  186139. * need special memory handling are expected to supply replacement
  186140. * functions for png_malloc() and png_free(), and to use
  186141. * png_create_read_struct_2() and png_create_write_struct_2() to
  186142. * identify the replacement functions.
  186143. */
  186144. #define PNG_INTERNAL
  186145. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186146. /* Borland DOS special memory handler */
  186147. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186148. /* if you change this, be sure to change the one in png.h also */
  186149. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186150. by a single call to calloc() if this is thought to improve performance. */
  186151. png_voidp /* PRIVATE */
  186152. png_create_struct(int type)
  186153. {
  186154. #ifdef PNG_USER_MEM_SUPPORTED
  186155. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186156. }
  186157. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186158. png_voidp /* PRIVATE */
  186159. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186160. {
  186161. #endif /* PNG_USER_MEM_SUPPORTED */
  186162. png_size_t size;
  186163. png_voidp struct_ptr;
  186164. if (type == PNG_STRUCT_INFO)
  186165. size = png_sizeof(png_info);
  186166. else if (type == PNG_STRUCT_PNG)
  186167. size = png_sizeof(png_struct);
  186168. else
  186169. return (png_get_copyright(NULL));
  186170. #ifdef PNG_USER_MEM_SUPPORTED
  186171. if(malloc_fn != NULL)
  186172. {
  186173. png_struct dummy_struct;
  186174. png_structp png_ptr = &dummy_struct;
  186175. png_ptr->mem_ptr=mem_ptr;
  186176. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186177. }
  186178. else
  186179. #endif /* PNG_USER_MEM_SUPPORTED */
  186180. struct_ptr = (png_voidp)farmalloc(size);
  186181. if (struct_ptr != NULL)
  186182. png_memset(struct_ptr, 0, size);
  186183. return (struct_ptr);
  186184. }
  186185. /* Free memory allocated by a png_create_struct() call */
  186186. void /* PRIVATE */
  186187. png_destroy_struct(png_voidp struct_ptr)
  186188. {
  186189. #ifdef PNG_USER_MEM_SUPPORTED
  186190. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186191. }
  186192. /* Free memory allocated by a png_create_struct() call */
  186193. void /* PRIVATE */
  186194. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186195. png_voidp mem_ptr)
  186196. {
  186197. #endif
  186198. if (struct_ptr != NULL)
  186199. {
  186200. #ifdef PNG_USER_MEM_SUPPORTED
  186201. if(free_fn != NULL)
  186202. {
  186203. png_struct dummy_struct;
  186204. png_structp png_ptr = &dummy_struct;
  186205. png_ptr->mem_ptr=mem_ptr;
  186206. (*(free_fn))(png_ptr, struct_ptr);
  186207. return;
  186208. }
  186209. #endif /* PNG_USER_MEM_SUPPORTED */
  186210. farfree (struct_ptr);
  186211. }
  186212. }
  186213. /* Allocate memory. For reasonable files, size should never exceed
  186214. * 64K. However, zlib may allocate more then 64K if you don't tell
  186215. * it not to. See zconf.h and png.h for more information. zlib does
  186216. * need to allocate exactly 64K, so whatever you call here must
  186217. * have the ability to do that.
  186218. *
  186219. * Borland seems to have a problem in DOS mode for exactly 64K.
  186220. * It gives you a segment with an offset of 8 (perhaps to store its
  186221. * memory stuff). zlib doesn't like this at all, so we have to
  186222. * detect and deal with it. This code should not be needed in
  186223. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186224. * been updated by Alexander Lehmann for version 0.89 to waste less
  186225. * memory.
  186226. *
  186227. * Note that we can't use png_size_t for the "size" declaration,
  186228. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186229. * result, we would be truncating potentially larger memory requests
  186230. * (which should cause a fatal error) and introducing major problems.
  186231. */
  186232. png_voidp PNGAPI
  186233. png_malloc(png_structp png_ptr, png_uint_32 size)
  186234. {
  186235. png_voidp ret;
  186236. if (png_ptr == NULL || size == 0)
  186237. return (NULL);
  186238. #ifdef PNG_USER_MEM_SUPPORTED
  186239. if(png_ptr->malloc_fn != NULL)
  186240. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186241. else
  186242. ret = (png_malloc_default(png_ptr, size));
  186243. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186244. png_error(png_ptr, "Out of memory!");
  186245. return (ret);
  186246. }
  186247. png_voidp PNGAPI
  186248. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186249. {
  186250. png_voidp ret;
  186251. #endif /* PNG_USER_MEM_SUPPORTED */
  186252. if (png_ptr == NULL || size == 0)
  186253. return (NULL);
  186254. #ifdef PNG_MAX_MALLOC_64K
  186255. if (size > (png_uint_32)65536L)
  186256. {
  186257. png_warning(png_ptr, "Cannot Allocate > 64K");
  186258. ret = NULL;
  186259. }
  186260. else
  186261. #endif
  186262. if (size != (size_t)size)
  186263. ret = NULL;
  186264. else if (size == (png_uint_32)65536L)
  186265. {
  186266. if (png_ptr->offset_table == NULL)
  186267. {
  186268. /* try to see if we need to do any of this fancy stuff */
  186269. ret = farmalloc(size);
  186270. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186271. {
  186272. int num_blocks;
  186273. png_uint_32 total_size;
  186274. png_bytep table;
  186275. int i;
  186276. png_byte huge * hptr;
  186277. if (ret != NULL)
  186278. {
  186279. farfree(ret);
  186280. ret = NULL;
  186281. }
  186282. if(png_ptr->zlib_window_bits > 14)
  186283. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186284. else
  186285. num_blocks = 1;
  186286. if (png_ptr->zlib_mem_level >= 7)
  186287. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186288. else
  186289. num_blocks++;
  186290. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186291. table = farmalloc(total_size);
  186292. if (table == NULL)
  186293. {
  186294. #ifndef PNG_USER_MEM_SUPPORTED
  186295. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186296. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186297. else
  186298. png_warning(png_ptr, "Out Of Memory.");
  186299. #endif
  186300. return (NULL);
  186301. }
  186302. if ((png_size_t)table & 0xfff0)
  186303. {
  186304. #ifndef PNG_USER_MEM_SUPPORTED
  186305. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186306. png_error(png_ptr,
  186307. "Farmalloc didn't return normalized pointer");
  186308. else
  186309. png_warning(png_ptr,
  186310. "Farmalloc didn't return normalized pointer");
  186311. #endif
  186312. return (NULL);
  186313. }
  186314. png_ptr->offset_table = table;
  186315. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186316. png_sizeof (png_bytep));
  186317. if (png_ptr->offset_table_ptr == NULL)
  186318. {
  186319. #ifndef PNG_USER_MEM_SUPPORTED
  186320. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186321. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186322. else
  186323. png_warning(png_ptr, "Out Of memory.");
  186324. #endif
  186325. return (NULL);
  186326. }
  186327. hptr = (png_byte huge *)table;
  186328. if ((png_size_t)hptr & 0xf)
  186329. {
  186330. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186331. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186332. }
  186333. for (i = 0; i < num_blocks; i++)
  186334. {
  186335. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186336. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186337. }
  186338. png_ptr->offset_table_number = num_blocks;
  186339. png_ptr->offset_table_count = 0;
  186340. png_ptr->offset_table_count_free = 0;
  186341. }
  186342. }
  186343. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186344. {
  186345. #ifndef PNG_USER_MEM_SUPPORTED
  186346. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186347. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186348. else
  186349. png_warning(png_ptr, "Out of Memory.");
  186350. #endif
  186351. return (NULL);
  186352. }
  186353. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186354. }
  186355. else
  186356. ret = farmalloc(size);
  186357. #ifndef PNG_USER_MEM_SUPPORTED
  186358. if (ret == NULL)
  186359. {
  186360. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186361. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186362. else
  186363. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186364. }
  186365. #endif
  186366. return (ret);
  186367. }
  186368. /* free a pointer allocated by png_malloc(). In the default
  186369. configuration, png_ptr is not used, but is passed in case it
  186370. is needed. If ptr is NULL, return without taking any action. */
  186371. void PNGAPI
  186372. png_free(png_structp png_ptr, png_voidp ptr)
  186373. {
  186374. if (png_ptr == NULL || ptr == NULL)
  186375. return;
  186376. #ifdef PNG_USER_MEM_SUPPORTED
  186377. if (png_ptr->free_fn != NULL)
  186378. {
  186379. (*(png_ptr->free_fn))(png_ptr, ptr);
  186380. return;
  186381. }
  186382. else png_free_default(png_ptr, ptr);
  186383. }
  186384. void PNGAPI
  186385. png_free_default(png_structp png_ptr, png_voidp ptr)
  186386. {
  186387. #endif /* PNG_USER_MEM_SUPPORTED */
  186388. if(png_ptr == NULL) return;
  186389. if (png_ptr->offset_table != NULL)
  186390. {
  186391. int i;
  186392. for (i = 0; i < png_ptr->offset_table_count; i++)
  186393. {
  186394. if (ptr == png_ptr->offset_table_ptr[i])
  186395. {
  186396. ptr = NULL;
  186397. png_ptr->offset_table_count_free++;
  186398. break;
  186399. }
  186400. }
  186401. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186402. {
  186403. farfree(png_ptr->offset_table);
  186404. farfree(png_ptr->offset_table_ptr);
  186405. png_ptr->offset_table = NULL;
  186406. png_ptr->offset_table_ptr = NULL;
  186407. }
  186408. }
  186409. if (ptr != NULL)
  186410. {
  186411. farfree(ptr);
  186412. }
  186413. }
  186414. #else /* Not the Borland DOS special memory handler */
  186415. /* Allocate memory for a png_struct or a png_info. The malloc and
  186416. memset can be replaced by a single call to calloc() if this is thought
  186417. to improve performance noticably. */
  186418. png_voidp /* PRIVATE */
  186419. png_create_struct(int type)
  186420. {
  186421. #ifdef PNG_USER_MEM_SUPPORTED
  186422. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186423. }
  186424. /* Allocate memory for a png_struct or a png_info. The malloc and
  186425. memset can be replaced by a single call to calloc() if this is thought
  186426. to improve performance noticably. */
  186427. png_voidp /* PRIVATE */
  186428. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186429. {
  186430. #endif /* PNG_USER_MEM_SUPPORTED */
  186431. png_size_t size;
  186432. png_voidp struct_ptr;
  186433. if (type == PNG_STRUCT_INFO)
  186434. size = png_sizeof(png_info);
  186435. else if (type == PNG_STRUCT_PNG)
  186436. size = png_sizeof(png_struct);
  186437. else
  186438. return (NULL);
  186439. #ifdef PNG_USER_MEM_SUPPORTED
  186440. if(malloc_fn != NULL)
  186441. {
  186442. png_struct dummy_struct;
  186443. png_structp png_ptr = &dummy_struct;
  186444. png_ptr->mem_ptr=mem_ptr;
  186445. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186446. if (struct_ptr != NULL)
  186447. png_memset(struct_ptr, 0, size);
  186448. return (struct_ptr);
  186449. }
  186450. #endif /* PNG_USER_MEM_SUPPORTED */
  186451. #if defined(__TURBOC__) && !defined(__FLAT__)
  186452. struct_ptr = (png_voidp)farmalloc(size);
  186453. #else
  186454. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186455. struct_ptr = (png_voidp)halloc(size,1);
  186456. # else
  186457. struct_ptr = (png_voidp)malloc(size);
  186458. # endif
  186459. #endif
  186460. if (struct_ptr != NULL)
  186461. png_memset(struct_ptr, 0, size);
  186462. return (struct_ptr);
  186463. }
  186464. /* Free memory allocated by a png_create_struct() call */
  186465. void /* PRIVATE */
  186466. png_destroy_struct(png_voidp struct_ptr)
  186467. {
  186468. #ifdef PNG_USER_MEM_SUPPORTED
  186469. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186470. }
  186471. /* Free memory allocated by a png_create_struct() call */
  186472. void /* PRIVATE */
  186473. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186474. png_voidp mem_ptr)
  186475. {
  186476. #endif /* PNG_USER_MEM_SUPPORTED */
  186477. if (struct_ptr != NULL)
  186478. {
  186479. #ifdef PNG_USER_MEM_SUPPORTED
  186480. if(free_fn != NULL)
  186481. {
  186482. png_struct dummy_struct;
  186483. png_structp png_ptr = &dummy_struct;
  186484. png_ptr->mem_ptr=mem_ptr;
  186485. (*(free_fn))(png_ptr, struct_ptr);
  186486. return;
  186487. }
  186488. #endif /* PNG_USER_MEM_SUPPORTED */
  186489. #if defined(__TURBOC__) && !defined(__FLAT__)
  186490. farfree(struct_ptr);
  186491. #else
  186492. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186493. hfree(struct_ptr);
  186494. # else
  186495. free(struct_ptr);
  186496. # endif
  186497. #endif
  186498. }
  186499. }
  186500. /* Allocate memory. For reasonable files, size should never exceed
  186501. 64K. However, zlib may allocate more then 64K if you don't tell
  186502. it not to. See zconf.h and png.h for more information. zlib does
  186503. need to allocate exactly 64K, so whatever you call here must
  186504. have the ability to do that. */
  186505. png_voidp PNGAPI
  186506. png_malloc(png_structp png_ptr, png_uint_32 size)
  186507. {
  186508. png_voidp ret;
  186509. #ifdef PNG_USER_MEM_SUPPORTED
  186510. if (png_ptr == NULL || size == 0)
  186511. return (NULL);
  186512. if(png_ptr->malloc_fn != NULL)
  186513. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186514. else
  186515. ret = (png_malloc_default(png_ptr, size));
  186516. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186517. png_error(png_ptr, "Out of Memory!");
  186518. return (ret);
  186519. }
  186520. png_voidp PNGAPI
  186521. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186522. {
  186523. png_voidp ret;
  186524. #endif /* PNG_USER_MEM_SUPPORTED */
  186525. if (png_ptr == NULL || size == 0)
  186526. return (NULL);
  186527. #ifdef PNG_MAX_MALLOC_64K
  186528. if (size > (png_uint_32)65536L)
  186529. {
  186530. #ifndef PNG_USER_MEM_SUPPORTED
  186531. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186532. png_error(png_ptr, "Cannot Allocate > 64K");
  186533. else
  186534. #endif
  186535. return NULL;
  186536. }
  186537. #endif
  186538. /* Check for overflow */
  186539. #if defined(__TURBOC__) && !defined(__FLAT__)
  186540. if (size != (unsigned long)size)
  186541. ret = NULL;
  186542. else
  186543. ret = farmalloc(size);
  186544. #else
  186545. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186546. if (size != (unsigned long)size)
  186547. ret = NULL;
  186548. else
  186549. ret = halloc(size, 1);
  186550. # else
  186551. if (size != (size_t)size)
  186552. ret = NULL;
  186553. else
  186554. ret = malloc((size_t)size);
  186555. # endif
  186556. #endif
  186557. #ifndef PNG_USER_MEM_SUPPORTED
  186558. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186559. png_error(png_ptr, "Out of Memory");
  186560. #endif
  186561. return (ret);
  186562. }
  186563. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186564. without taking any action. */
  186565. void PNGAPI
  186566. png_free(png_structp png_ptr, png_voidp ptr)
  186567. {
  186568. if (png_ptr == NULL || ptr == NULL)
  186569. return;
  186570. #ifdef PNG_USER_MEM_SUPPORTED
  186571. if (png_ptr->free_fn != NULL)
  186572. {
  186573. (*(png_ptr->free_fn))(png_ptr, ptr);
  186574. return;
  186575. }
  186576. else png_free_default(png_ptr, ptr);
  186577. }
  186578. void PNGAPI
  186579. png_free_default(png_structp png_ptr, png_voidp ptr)
  186580. {
  186581. if (png_ptr == NULL || ptr == NULL)
  186582. return;
  186583. #endif /* PNG_USER_MEM_SUPPORTED */
  186584. #if defined(__TURBOC__) && !defined(__FLAT__)
  186585. farfree(ptr);
  186586. #else
  186587. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186588. hfree(ptr);
  186589. # else
  186590. free(ptr);
  186591. # endif
  186592. #endif
  186593. }
  186594. #endif /* Not Borland DOS special memory handler */
  186595. #if defined(PNG_1_0_X)
  186596. # define png_malloc_warn png_malloc
  186597. #else
  186598. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186599. * function will set up png_malloc() to issue a png_warning and return NULL
  186600. * instead of issuing a png_error, if it fails to allocate the requested
  186601. * memory.
  186602. */
  186603. png_voidp PNGAPI
  186604. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186605. {
  186606. png_voidp ptr;
  186607. png_uint_32 save_flags;
  186608. if(png_ptr == NULL) return (NULL);
  186609. save_flags=png_ptr->flags;
  186610. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186611. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186612. png_ptr->flags=save_flags;
  186613. return(ptr);
  186614. }
  186615. #endif
  186616. png_voidp PNGAPI
  186617. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186618. png_uint_32 length)
  186619. {
  186620. png_size_t size;
  186621. size = (png_size_t)length;
  186622. if ((png_uint_32)size != length)
  186623. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186624. return(png_memcpy (s1, s2, size));
  186625. }
  186626. png_voidp PNGAPI
  186627. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186628. png_uint_32 length)
  186629. {
  186630. png_size_t size;
  186631. size = (png_size_t)length;
  186632. if ((png_uint_32)size != length)
  186633. png_error(png_ptr,"Overflow in png_memset_check.");
  186634. return (png_memset (s1, value, size));
  186635. }
  186636. #ifdef PNG_USER_MEM_SUPPORTED
  186637. /* This function is called when the application wants to use another method
  186638. * of allocating and freeing memory.
  186639. */
  186640. void PNGAPI
  186641. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186642. malloc_fn, png_free_ptr free_fn)
  186643. {
  186644. if(png_ptr != NULL) {
  186645. png_ptr->mem_ptr = mem_ptr;
  186646. png_ptr->malloc_fn = malloc_fn;
  186647. png_ptr->free_fn = free_fn;
  186648. }
  186649. }
  186650. /* This function returns a pointer to the mem_ptr associated with the user
  186651. * functions. The application should free any memory associated with this
  186652. * pointer before png_write_destroy and png_read_destroy are called.
  186653. */
  186654. png_voidp PNGAPI
  186655. png_get_mem_ptr(png_structp png_ptr)
  186656. {
  186657. if(png_ptr == NULL) return (NULL);
  186658. return ((png_voidp)png_ptr->mem_ptr);
  186659. }
  186660. #endif /* PNG_USER_MEM_SUPPORTED */
  186661. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186662. /*** End of inlined file: pngmem.c ***/
  186663. /*** Start of inlined file: pngread.c ***/
  186664. /* pngread.c - read a PNG file
  186665. *
  186666. * Last changed in libpng 1.2.20 September 7, 2007
  186667. * For conditions of distribution and use, see copyright notice in png.h
  186668. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186669. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186670. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186671. *
  186672. * This file contains routines that an application calls directly to
  186673. * read a PNG file or stream.
  186674. */
  186675. #define PNG_INTERNAL
  186676. #if defined(PNG_READ_SUPPORTED)
  186677. /* Create a PNG structure for reading, and allocate any memory needed. */
  186678. png_structp PNGAPI
  186679. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186680. png_error_ptr error_fn, png_error_ptr warn_fn)
  186681. {
  186682. #ifdef PNG_USER_MEM_SUPPORTED
  186683. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186684. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186685. }
  186686. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186687. png_structp PNGAPI
  186688. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186689. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186690. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186691. {
  186692. #endif /* PNG_USER_MEM_SUPPORTED */
  186693. png_structp png_ptr;
  186694. #ifdef PNG_SETJMP_SUPPORTED
  186695. #ifdef USE_FAR_KEYWORD
  186696. jmp_buf jmpbuf;
  186697. #endif
  186698. #endif
  186699. int i;
  186700. png_debug(1, "in png_create_read_struct\n");
  186701. #ifdef PNG_USER_MEM_SUPPORTED
  186702. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186703. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186704. #else
  186705. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186706. #endif
  186707. if (png_ptr == NULL)
  186708. return (NULL);
  186709. /* added at libpng-1.2.6 */
  186710. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186711. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186712. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186713. #endif
  186714. #ifdef PNG_SETJMP_SUPPORTED
  186715. #ifdef USE_FAR_KEYWORD
  186716. if (setjmp(jmpbuf))
  186717. #else
  186718. if (setjmp(png_ptr->jmpbuf))
  186719. #endif
  186720. {
  186721. png_free(png_ptr, png_ptr->zbuf);
  186722. png_ptr->zbuf=NULL;
  186723. #ifdef PNG_USER_MEM_SUPPORTED
  186724. png_destroy_struct_2((png_voidp)png_ptr,
  186725. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186726. #else
  186727. png_destroy_struct((png_voidp)png_ptr);
  186728. #endif
  186729. return (NULL);
  186730. }
  186731. #ifdef USE_FAR_KEYWORD
  186732. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186733. #endif
  186734. #endif
  186735. #ifdef PNG_USER_MEM_SUPPORTED
  186736. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186737. #endif
  186738. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186739. i=0;
  186740. do
  186741. {
  186742. if(user_png_ver[i] != png_libpng_ver[i])
  186743. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186744. } while (png_libpng_ver[i++]);
  186745. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186746. {
  186747. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186748. * we must recompile any applications that use any older library version.
  186749. * For versions after libpng 1.0, we will be compatible, so we need
  186750. * only check the first digit.
  186751. */
  186752. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186753. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186754. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186755. {
  186756. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186757. char msg[80];
  186758. if (user_png_ver)
  186759. {
  186760. png_snprintf(msg, 80,
  186761. "Application was compiled with png.h from libpng-%.20s",
  186762. user_png_ver);
  186763. png_warning(png_ptr, msg);
  186764. }
  186765. png_snprintf(msg, 80,
  186766. "Application is running with png.c from libpng-%.20s",
  186767. png_libpng_ver);
  186768. png_warning(png_ptr, msg);
  186769. #endif
  186770. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186771. png_ptr->flags=0;
  186772. #endif
  186773. png_error(png_ptr,
  186774. "Incompatible libpng version in application and library");
  186775. }
  186776. }
  186777. /* initialize zbuf - compression buffer */
  186778. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186779. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186780. (png_uint_32)png_ptr->zbuf_size);
  186781. png_ptr->zstream.zalloc = png_zalloc;
  186782. png_ptr->zstream.zfree = png_zfree;
  186783. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186784. switch (inflateInit(&png_ptr->zstream))
  186785. {
  186786. case Z_OK: /* Do nothing */ break;
  186787. case Z_MEM_ERROR:
  186788. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186789. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186790. default: png_error(png_ptr, "Unknown zlib error");
  186791. }
  186792. png_ptr->zstream.next_out = png_ptr->zbuf;
  186793. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186794. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186795. #ifdef PNG_SETJMP_SUPPORTED
  186796. /* Applications that neglect to set up their own setjmp() and then encounter
  186797. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186798. abort instead of returning. */
  186799. #ifdef USE_FAR_KEYWORD
  186800. if (setjmp(jmpbuf))
  186801. PNG_ABORT();
  186802. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186803. #else
  186804. if (setjmp(png_ptr->jmpbuf))
  186805. PNG_ABORT();
  186806. #endif
  186807. #endif
  186808. return (png_ptr);
  186809. }
  186810. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186811. /* Initialize PNG structure for reading, and allocate any memory needed.
  186812. This interface is deprecated in favour of the png_create_read_struct(),
  186813. and it will disappear as of libpng-1.3.0. */
  186814. #undef png_read_init
  186815. void PNGAPI
  186816. png_read_init(png_structp png_ptr)
  186817. {
  186818. /* We only come here via pre-1.0.7-compiled applications */
  186819. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186820. }
  186821. void PNGAPI
  186822. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186823. png_size_t png_struct_size, png_size_t png_info_size)
  186824. {
  186825. /* We only come here via pre-1.0.12-compiled applications */
  186826. if(png_ptr == NULL) return;
  186827. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186828. if(png_sizeof(png_struct) > png_struct_size ||
  186829. png_sizeof(png_info) > png_info_size)
  186830. {
  186831. char msg[80];
  186832. png_ptr->warning_fn=NULL;
  186833. if (user_png_ver)
  186834. {
  186835. png_snprintf(msg, 80,
  186836. "Application was compiled with png.h from libpng-%.20s",
  186837. user_png_ver);
  186838. png_warning(png_ptr, msg);
  186839. }
  186840. png_snprintf(msg, 80,
  186841. "Application is running with png.c from libpng-%.20s",
  186842. png_libpng_ver);
  186843. png_warning(png_ptr, msg);
  186844. }
  186845. #endif
  186846. if(png_sizeof(png_struct) > png_struct_size)
  186847. {
  186848. png_ptr->error_fn=NULL;
  186849. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186850. png_ptr->flags=0;
  186851. #endif
  186852. png_error(png_ptr,
  186853. "The png struct allocated by the application for reading is too small.");
  186854. }
  186855. if(png_sizeof(png_info) > png_info_size)
  186856. {
  186857. png_ptr->error_fn=NULL;
  186858. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186859. png_ptr->flags=0;
  186860. #endif
  186861. png_error(png_ptr,
  186862. "The info struct allocated by application for reading is too small.");
  186863. }
  186864. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186865. }
  186866. #endif /* PNG_1_0_X || PNG_1_2_X */
  186867. void PNGAPI
  186868. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186869. png_size_t png_struct_size)
  186870. {
  186871. #ifdef PNG_SETJMP_SUPPORTED
  186872. jmp_buf tmp_jmp; /* to save current jump buffer */
  186873. #endif
  186874. int i=0;
  186875. png_structp png_ptr=*ptr_ptr;
  186876. if(png_ptr == NULL) return;
  186877. do
  186878. {
  186879. if(user_png_ver[i] != png_libpng_ver[i])
  186880. {
  186881. #ifdef PNG_LEGACY_SUPPORTED
  186882. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186883. #else
  186884. png_ptr->warning_fn=NULL;
  186885. png_warning(png_ptr,
  186886. "Application uses deprecated png_read_init() and should be recompiled.");
  186887. break;
  186888. #endif
  186889. }
  186890. } while (png_libpng_ver[i++]);
  186891. png_debug(1, "in png_read_init_3\n");
  186892. #ifdef PNG_SETJMP_SUPPORTED
  186893. /* save jump buffer and error functions */
  186894. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186895. #endif
  186896. if(png_sizeof(png_struct) > png_struct_size)
  186897. {
  186898. png_destroy_struct(png_ptr);
  186899. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186900. png_ptr = *ptr_ptr;
  186901. }
  186902. /* reset all variables to 0 */
  186903. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186904. #ifdef PNG_SETJMP_SUPPORTED
  186905. /* restore jump buffer */
  186906. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186907. #endif
  186908. /* added at libpng-1.2.6 */
  186909. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186910. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186911. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186912. #endif
  186913. /* initialize zbuf - compression buffer */
  186914. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186915. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186916. (png_uint_32)png_ptr->zbuf_size);
  186917. png_ptr->zstream.zalloc = png_zalloc;
  186918. png_ptr->zstream.zfree = png_zfree;
  186919. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186920. switch (inflateInit(&png_ptr->zstream))
  186921. {
  186922. case Z_OK: /* Do nothing */ break;
  186923. case Z_MEM_ERROR:
  186924. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186925. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186926. default: png_error(png_ptr, "Unknown zlib error");
  186927. }
  186928. png_ptr->zstream.next_out = png_ptr->zbuf;
  186929. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186930. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186931. }
  186932. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186933. /* Read the information before the actual image data. This has been
  186934. * changed in v0.90 to allow reading a file that already has the magic
  186935. * bytes read from the stream. You can tell libpng how many bytes have
  186936. * been read from the beginning of the stream (up to the maximum of 8)
  186937. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186938. * here. The application can then have access to the signature bytes we
  186939. * read if it is determined that this isn't a valid PNG file.
  186940. */
  186941. void PNGAPI
  186942. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186943. {
  186944. if(png_ptr == NULL) return;
  186945. png_debug(1, "in png_read_info\n");
  186946. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186947. if (png_ptr->sig_bytes < 8)
  186948. {
  186949. png_size_t num_checked = png_ptr->sig_bytes,
  186950. num_to_check = 8 - num_checked;
  186951. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186952. png_ptr->sig_bytes = 8;
  186953. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186954. {
  186955. if (num_checked < 4 &&
  186956. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186957. png_error(png_ptr, "Not a PNG file");
  186958. else
  186959. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186960. }
  186961. if (num_checked < 3)
  186962. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186963. }
  186964. for(;;)
  186965. {
  186966. #ifdef PNG_USE_LOCAL_ARRAYS
  186967. PNG_CONST PNG_IHDR;
  186968. PNG_CONST PNG_IDAT;
  186969. PNG_CONST PNG_IEND;
  186970. PNG_CONST PNG_PLTE;
  186971. #if defined(PNG_READ_bKGD_SUPPORTED)
  186972. PNG_CONST PNG_bKGD;
  186973. #endif
  186974. #if defined(PNG_READ_cHRM_SUPPORTED)
  186975. PNG_CONST PNG_cHRM;
  186976. #endif
  186977. #if defined(PNG_READ_gAMA_SUPPORTED)
  186978. PNG_CONST PNG_gAMA;
  186979. #endif
  186980. #if defined(PNG_READ_hIST_SUPPORTED)
  186981. PNG_CONST PNG_hIST;
  186982. #endif
  186983. #if defined(PNG_READ_iCCP_SUPPORTED)
  186984. PNG_CONST PNG_iCCP;
  186985. #endif
  186986. #if defined(PNG_READ_iTXt_SUPPORTED)
  186987. PNG_CONST PNG_iTXt;
  186988. #endif
  186989. #if defined(PNG_READ_oFFs_SUPPORTED)
  186990. PNG_CONST PNG_oFFs;
  186991. #endif
  186992. #if defined(PNG_READ_pCAL_SUPPORTED)
  186993. PNG_CONST PNG_pCAL;
  186994. #endif
  186995. #if defined(PNG_READ_pHYs_SUPPORTED)
  186996. PNG_CONST PNG_pHYs;
  186997. #endif
  186998. #if defined(PNG_READ_sBIT_SUPPORTED)
  186999. PNG_CONST PNG_sBIT;
  187000. #endif
  187001. #if defined(PNG_READ_sCAL_SUPPORTED)
  187002. PNG_CONST PNG_sCAL;
  187003. #endif
  187004. #if defined(PNG_READ_sPLT_SUPPORTED)
  187005. PNG_CONST PNG_sPLT;
  187006. #endif
  187007. #if defined(PNG_READ_sRGB_SUPPORTED)
  187008. PNG_CONST PNG_sRGB;
  187009. #endif
  187010. #if defined(PNG_READ_tEXt_SUPPORTED)
  187011. PNG_CONST PNG_tEXt;
  187012. #endif
  187013. #if defined(PNG_READ_tIME_SUPPORTED)
  187014. PNG_CONST PNG_tIME;
  187015. #endif
  187016. #if defined(PNG_READ_tRNS_SUPPORTED)
  187017. PNG_CONST PNG_tRNS;
  187018. #endif
  187019. #if defined(PNG_READ_zTXt_SUPPORTED)
  187020. PNG_CONST PNG_zTXt;
  187021. #endif
  187022. #endif /* PNG_USE_LOCAL_ARRAYS */
  187023. png_byte chunk_length[4];
  187024. png_uint_32 length;
  187025. png_read_data(png_ptr, chunk_length, 4);
  187026. length = png_get_uint_31(png_ptr,chunk_length);
  187027. png_reset_crc(png_ptr);
  187028. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187029. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187030. length);
  187031. /* This should be a binary subdivision search or a hash for
  187032. * matching the chunk name rather than a linear search.
  187033. */
  187034. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187035. if(png_ptr->mode & PNG_AFTER_IDAT)
  187036. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187037. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187038. png_handle_IHDR(png_ptr, info_ptr, length);
  187039. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187040. png_handle_IEND(png_ptr, info_ptr, length);
  187041. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187042. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187043. {
  187044. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187045. png_ptr->mode |= PNG_HAVE_IDAT;
  187046. png_handle_unknown(png_ptr, info_ptr, length);
  187047. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187048. png_ptr->mode |= PNG_HAVE_PLTE;
  187049. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187050. {
  187051. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187052. png_error(png_ptr, "Missing IHDR before IDAT");
  187053. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187054. !(png_ptr->mode & PNG_HAVE_PLTE))
  187055. png_error(png_ptr, "Missing PLTE before IDAT");
  187056. break;
  187057. }
  187058. }
  187059. #endif
  187060. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187061. png_handle_PLTE(png_ptr, info_ptr, length);
  187062. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187063. {
  187064. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187065. png_error(png_ptr, "Missing IHDR before IDAT");
  187066. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187067. !(png_ptr->mode & PNG_HAVE_PLTE))
  187068. png_error(png_ptr, "Missing PLTE before IDAT");
  187069. png_ptr->idat_size = length;
  187070. png_ptr->mode |= PNG_HAVE_IDAT;
  187071. break;
  187072. }
  187073. #if defined(PNG_READ_bKGD_SUPPORTED)
  187074. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187075. png_handle_bKGD(png_ptr, info_ptr, length);
  187076. #endif
  187077. #if defined(PNG_READ_cHRM_SUPPORTED)
  187078. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187079. png_handle_cHRM(png_ptr, info_ptr, length);
  187080. #endif
  187081. #if defined(PNG_READ_gAMA_SUPPORTED)
  187082. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187083. png_handle_gAMA(png_ptr, info_ptr, length);
  187084. #endif
  187085. #if defined(PNG_READ_hIST_SUPPORTED)
  187086. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187087. png_handle_hIST(png_ptr, info_ptr, length);
  187088. #endif
  187089. #if defined(PNG_READ_oFFs_SUPPORTED)
  187090. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187091. png_handle_oFFs(png_ptr, info_ptr, length);
  187092. #endif
  187093. #if defined(PNG_READ_pCAL_SUPPORTED)
  187094. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187095. png_handle_pCAL(png_ptr, info_ptr, length);
  187096. #endif
  187097. #if defined(PNG_READ_sCAL_SUPPORTED)
  187098. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187099. png_handle_sCAL(png_ptr, info_ptr, length);
  187100. #endif
  187101. #if defined(PNG_READ_pHYs_SUPPORTED)
  187102. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187103. png_handle_pHYs(png_ptr, info_ptr, length);
  187104. #endif
  187105. #if defined(PNG_READ_sBIT_SUPPORTED)
  187106. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187107. png_handle_sBIT(png_ptr, info_ptr, length);
  187108. #endif
  187109. #if defined(PNG_READ_sRGB_SUPPORTED)
  187110. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187111. png_handle_sRGB(png_ptr, info_ptr, length);
  187112. #endif
  187113. #if defined(PNG_READ_iCCP_SUPPORTED)
  187114. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187115. png_handle_iCCP(png_ptr, info_ptr, length);
  187116. #endif
  187117. #if defined(PNG_READ_sPLT_SUPPORTED)
  187118. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187119. png_handle_sPLT(png_ptr, info_ptr, length);
  187120. #endif
  187121. #if defined(PNG_READ_tEXt_SUPPORTED)
  187122. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187123. png_handle_tEXt(png_ptr, info_ptr, length);
  187124. #endif
  187125. #if defined(PNG_READ_tIME_SUPPORTED)
  187126. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187127. png_handle_tIME(png_ptr, info_ptr, length);
  187128. #endif
  187129. #if defined(PNG_READ_tRNS_SUPPORTED)
  187130. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187131. png_handle_tRNS(png_ptr, info_ptr, length);
  187132. #endif
  187133. #if defined(PNG_READ_zTXt_SUPPORTED)
  187134. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187135. png_handle_zTXt(png_ptr, info_ptr, length);
  187136. #endif
  187137. #if defined(PNG_READ_iTXt_SUPPORTED)
  187138. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187139. png_handle_iTXt(png_ptr, info_ptr, length);
  187140. #endif
  187141. else
  187142. png_handle_unknown(png_ptr, info_ptr, length);
  187143. }
  187144. }
  187145. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187146. /* optional call to update the users info_ptr structure */
  187147. void PNGAPI
  187148. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187149. {
  187150. png_debug(1, "in png_read_update_info\n");
  187151. if(png_ptr == NULL) return;
  187152. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187153. png_read_start_row(png_ptr);
  187154. else
  187155. png_warning(png_ptr,
  187156. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187157. png_read_transform_info(png_ptr, info_ptr);
  187158. }
  187159. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187160. /* Initialize palette, background, etc, after transformations
  187161. * are set, but before any reading takes place. This allows
  187162. * the user to obtain a gamma-corrected palette, for example.
  187163. * If the user doesn't call this, we will do it ourselves.
  187164. */
  187165. void PNGAPI
  187166. png_start_read_image(png_structp png_ptr)
  187167. {
  187168. png_debug(1, "in png_start_read_image\n");
  187169. if(png_ptr == NULL) return;
  187170. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187171. png_read_start_row(png_ptr);
  187172. }
  187173. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187174. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187175. void PNGAPI
  187176. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187177. {
  187178. #ifdef PNG_USE_LOCAL_ARRAYS
  187179. PNG_CONST PNG_IDAT;
  187180. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187181. 0xff};
  187182. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187183. #endif
  187184. int ret;
  187185. if(png_ptr == NULL) return;
  187186. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187187. png_ptr->row_number, png_ptr->pass);
  187188. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187189. png_read_start_row(png_ptr);
  187190. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187191. {
  187192. /* check for transforms that have been set but were defined out */
  187193. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187194. if (png_ptr->transformations & PNG_INVERT_MONO)
  187195. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187196. #endif
  187197. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187198. if (png_ptr->transformations & PNG_FILLER)
  187199. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187200. #endif
  187201. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187202. if (png_ptr->transformations & PNG_PACKSWAP)
  187203. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187204. #endif
  187205. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187206. if (png_ptr->transformations & PNG_PACK)
  187207. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187208. #endif
  187209. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187210. if (png_ptr->transformations & PNG_SHIFT)
  187211. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187212. #endif
  187213. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187214. if (png_ptr->transformations & PNG_BGR)
  187215. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187216. #endif
  187217. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187218. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187219. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187220. #endif
  187221. }
  187222. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187223. /* if interlaced and we do not need a new row, combine row and return */
  187224. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187225. {
  187226. switch (png_ptr->pass)
  187227. {
  187228. case 0:
  187229. if (png_ptr->row_number & 0x07)
  187230. {
  187231. if (dsp_row != NULL)
  187232. png_combine_row(png_ptr, dsp_row,
  187233. png_pass_dsp_mask[png_ptr->pass]);
  187234. png_read_finish_row(png_ptr);
  187235. return;
  187236. }
  187237. break;
  187238. case 1:
  187239. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187240. {
  187241. if (dsp_row != NULL)
  187242. png_combine_row(png_ptr, dsp_row,
  187243. png_pass_dsp_mask[png_ptr->pass]);
  187244. png_read_finish_row(png_ptr);
  187245. return;
  187246. }
  187247. break;
  187248. case 2:
  187249. if ((png_ptr->row_number & 0x07) != 4)
  187250. {
  187251. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187252. png_combine_row(png_ptr, dsp_row,
  187253. png_pass_dsp_mask[png_ptr->pass]);
  187254. png_read_finish_row(png_ptr);
  187255. return;
  187256. }
  187257. break;
  187258. case 3:
  187259. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187260. {
  187261. if (dsp_row != NULL)
  187262. png_combine_row(png_ptr, dsp_row,
  187263. png_pass_dsp_mask[png_ptr->pass]);
  187264. png_read_finish_row(png_ptr);
  187265. return;
  187266. }
  187267. break;
  187268. case 4:
  187269. if ((png_ptr->row_number & 3) != 2)
  187270. {
  187271. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187272. png_combine_row(png_ptr, dsp_row,
  187273. png_pass_dsp_mask[png_ptr->pass]);
  187274. png_read_finish_row(png_ptr);
  187275. return;
  187276. }
  187277. break;
  187278. case 5:
  187279. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187280. {
  187281. if (dsp_row != NULL)
  187282. png_combine_row(png_ptr, dsp_row,
  187283. png_pass_dsp_mask[png_ptr->pass]);
  187284. png_read_finish_row(png_ptr);
  187285. return;
  187286. }
  187287. break;
  187288. case 6:
  187289. if (!(png_ptr->row_number & 1))
  187290. {
  187291. png_read_finish_row(png_ptr);
  187292. return;
  187293. }
  187294. break;
  187295. }
  187296. }
  187297. #endif
  187298. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187299. png_error(png_ptr, "Invalid attempt to read row data");
  187300. png_ptr->zstream.next_out = png_ptr->row_buf;
  187301. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187302. do
  187303. {
  187304. if (!(png_ptr->zstream.avail_in))
  187305. {
  187306. while (!png_ptr->idat_size)
  187307. {
  187308. png_byte chunk_length[4];
  187309. png_crc_finish(png_ptr, 0);
  187310. png_read_data(png_ptr, chunk_length, 4);
  187311. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187312. png_reset_crc(png_ptr);
  187313. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187314. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187315. png_error(png_ptr, "Not enough image data");
  187316. }
  187317. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187318. png_ptr->zstream.next_in = png_ptr->zbuf;
  187319. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187320. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187321. png_crc_read(png_ptr, png_ptr->zbuf,
  187322. (png_size_t)png_ptr->zstream.avail_in);
  187323. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187324. }
  187325. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187326. if (ret == Z_STREAM_END)
  187327. {
  187328. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187329. png_ptr->idat_size)
  187330. png_error(png_ptr, "Extra compressed data");
  187331. png_ptr->mode |= PNG_AFTER_IDAT;
  187332. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187333. break;
  187334. }
  187335. if (ret != Z_OK)
  187336. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187337. "Decompression error");
  187338. } while (png_ptr->zstream.avail_out);
  187339. png_ptr->row_info.color_type = png_ptr->color_type;
  187340. png_ptr->row_info.width = png_ptr->iwidth;
  187341. png_ptr->row_info.channels = png_ptr->channels;
  187342. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187343. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187344. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187345. png_ptr->row_info.width);
  187346. if(png_ptr->row_buf[0])
  187347. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187348. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187349. (int)(png_ptr->row_buf[0]));
  187350. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187351. png_ptr->rowbytes + 1);
  187352. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187353. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187354. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187355. {
  187356. /* Intrapixel differencing */
  187357. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187358. }
  187359. #endif
  187360. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187361. png_do_read_transformations(png_ptr);
  187362. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187363. /* blow up interlaced rows to full size */
  187364. if (png_ptr->interlaced &&
  187365. (png_ptr->transformations & PNG_INTERLACE))
  187366. {
  187367. if (png_ptr->pass < 6)
  187368. /* old interface (pre-1.0.9):
  187369. png_do_read_interlace(&(png_ptr->row_info),
  187370. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187371. */
  187372. png_do_read_interlace(png_ptr);
  187373. if (dsp_row != NULL)
  187374. png_combine_row(png_ptr, dsp_row,
  187375. png_pass_dsp_mask[png_ptr->pass]);
  187376. if (row != NULL)
  187377. png_combine_row(png_ptr, row,
  187378. png_pass_mask[png_ptr->pass]);
  187379. }
  187380. else
  187381. #endif
  187382. {
  187383. if (row != NULL)
  187384. png_combine_row(png_ptr, row, 0xff);
  187385. if (dsp_row != NULL)
  187386. png_combine_row(png_ptr, dsp_row, 0xff);
  187387. }
  187388. png_read_finish_row(png_ptr);
  187389. if (png_ptr->read_row_fn != NULL)
  187390. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187391. }
  187392. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187393. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187394. /* Read one or more rows of image data. If the image is interlaced,
  187395. * and png_set_interlace_handling() has been called, the rows need to
  187396. * contain the contents of the rows from the previous pass. If the
  187397. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187398. * called, the rows contents must be initialized to the contents of the
  187399. * screen.
  187400. *
  187401. * "row" holds the actual image, and pixels are placed in it
  187402. * as they arrive. If the image is displayed after each pass, it will
  187403. * appear to "sparkle" in. "display_row" can be used to display a
  187404. * "chunky" progressive image, with finer detail added as it becomes
  187405. * available. If you do not want this "chunky" display, you may pass
  187406. * NULL for display_row. If you do not want the sparkle display, and
  187407. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187408. * If you have called png_handle_alpha(), and the image has either an
  187409. * alpha channel or a transparency chunk, you must provide a buffer for
  187410. * rows. In this case, you do not have to provide a display_row buffer
  187411. * also, but you may. If the image is not interlaced, or if you have
  187412. * not called png_set_interlace_handling(), the display_row buffer will
  187413. * be ignored, so pass NULL to it.
  187414. *
  187415. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187416. */
  187417. void PNGAPI
  187418. png_read_rows(png_structp png_ptr, png_bytepp row,
  187419. png_bytepp display_row, png_uint_32 num_rows)
  187420. {
  187421. png_uint_32 i;
  187422. png_bytepp rp;
  187423. png_bytepp dp;
  187424. png_debug(1, "in png_read_rows\n");
  187425. if(png_ptr == NULL) return;
  187426. rp = row;
  187427. dp = display_row;
  187428. if (rp != NULL && dp != NULL)
  187429. for (i = 0; i < num_rows; i++)
  187430. {
  187431. png_bytep rptr = *rp++;
  187432. png_bytep dptr = *dp++;
  187433. png_read_row(png_ptr, rptr, dptr);
  187434. }
  187435. else if(rp != NULL)
  187436. for (i = 0; i < num_rows; i++)
  187437. {
  187438. png_bytep rptr = *rp;
  187439. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187440. rp++;
  187441. }
  187442. else if(dp != NULL)
  187443. for (i = 0; i < num_rows; i++)
  187444. {
  187445. png_bytep dptr = *dp;
  187446. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187447. dp++;
  187448. }
  187449. }
  187450. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187451. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187452. /* Read the entire image. If the image has an alpha channel or a tRNS
  187453. * chunk, and you have called png_handle_alpha()[*], you will need to
  187454. * initialize the image to the current image that PNG will be overlaying.
  187455. * We set the num_rows again here, in case it was incorrectly set in
  187456. * png_read_start_row() by a call to png_read_update_info() or
  187457. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187458. * prior to either of these functions like it should have been. You can
  187459. * only call this function once. If you desire to have an image for
  187460. * each pass of a interlaced image, use png_read_rows() instead.
  187461. *
  187462. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187463. */
  187464. void PNGAPI
  187465. png_read_image(png_structp png_ptr, png_bytepp image)
  187466. {
  187467. png_uint_32 i,image_height;
  187468. int pass, j;
  187469. png_bytepp rp;
  187470. png_debug(1, "in png_read_image\n");
  187471. if(png_ptr == NULL) return;
  187472. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187473. pass = png_set_interlace_handling(png_ptr);
  187474. #else
  187475. if (png_ptr->interlaced)
  187476. png_error(png_ptr,
  187477. "Cannot read interlaced image -- interlace handler disabled.");
  187478. pass = 1;
  187479. #endif
  187480. image_height=png_ptr->height;
  187481. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187482. for (j = 0; j < pass; j++)
  187483. {
  187484. rp = image;
  187485. for (i = 0; i < image_height; i++)
  187486. {
  187487. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187488. rp++;
  187489. }
  187490. }
  187491. }
  187492. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187493. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187494. /* Read the end of the PNG file. Will not read past the end of the
  187495. * file, will verify the end is accurate, and will read any comments
  187496. * or time information at the end of the file, if info is not NULL.
  187497. */
  187498. void PNGAPI
  187499. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187500. {
  187501. png_byte chunk_length[4];
  187502. png_uint_32 length;
  187503. png_debug(1, "in png_read_end\n");
  187504. if(png_ptr == NULL) return;
  187505. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187506. do
  187507. {
  187508. #ifdef PNG_USE_LOCAL_ARRAYS
  187509. PNG_CONST PNG_IHDR;
  187510. PNG_CONST PNG_IDAT;
  187511. PNG_CONST PNG_IEND;
  187512. PNG_CONST PNG_PLTE;
  187513. #if defined(PNG_READ_bKGD_SUPPORTED)
  187514. PNG_CONST PNG_bKGD;
  187515. #endif
  187516. #if defined(PNG_READ_cHRM_SUPPORTED)
  187517. PNG_CONST PNG_cHRM;
  187518. #endif
  187519. #if defined(PNG_READ_gAMA_SUPPORTED)
  187520. PNG_CONST PNG_gAMA;
  187521. #endif
  187522. #if defined(PNG_READ_hIST_SUPPORTED)
  187523. PNG_CONST PNG_hIST;
  187524. #endif
  187525. #if defined(PNG_READ_iCCP_SUPPORTED)
  187526. PNG_CONST PNG_iCCP;
  187527. #endif
  187528. #if defined(PNG_READ_iTXt_SUPPORTED)
  187529. PNG_CONST PNG_iTXt;
  187530. #endif
  187531. #if defined(PNG_READ_oFFs_SUPPORTED)
  187532. PNG_CONST PNG_oFFs;
  187533. #endif
  187534. #if defined(PNG_READ_pCAL_SUPPORTED)
  187535. PNG_CONST PNG_pCAL;
  187536. #endif
  187537. #if defined(PNG_READ_pHYs_SUPPORTED)
  187538. PNG_CONST PNG_pHYs;
  187539. #endif
  187540. #if defined(PNG_READ_sBIT_SUPPORTED)
  187541. PNG_CONST PNG_sBIT;
  187542. #endif
  187543. #if defined(PNG_READ_sCAL_SUPPORTED)
  187544. PNG_CONST PNG_sCAL;
  187545. #endif
  187546. #if defined(PNG_READ_sPLT_SUPPORTED)
  187547. PNG_CONST PNG_sPLT;
  187548. #endif
  187549. #if defined(PNG_READ_sRGB_SUPPORTED)
  187550. PNG_CONST PNG_sRGB;
  187551. #endif
  187552. #if defined(PNG_READ_tEXt_SUPPORTED)
  187553. PNG_CONST PNG_tEXt;
  187554. #endif
  187555. #if defined(PNG_READ_tIME_SUPPORTED)
  187556. PNG_CONST PNG_tIME;
  187557. #endif
  187558. #if defined(PNG_READ_tRNS_SUPPORTED)
  187559. PNG_CONST PNG_tRNS;
  187560. #endif
  187561. #if defined(PNG_READ_zTXt_SUPPORTED)
  187562. PNG_CONST PNG_zTXt;
  187563. #endif
  187564. #endif /* PNG_USE_LOCAL_ARRAYS */
  187565. png_read_data(png_ptr, chunk_length, 4);
  187566. length = png_get_uint_31(png_ptr,chunk_length);
  187567. png_reset_crc(png_ptr);
  187568. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187569. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187570. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187571. png_handle_IHDR(png_ptr, info_ptr, length);
  187572. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187573. png_handle_IEND(png_ptr, info_ptr, length);
  187574. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187575. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187576. {
  187577. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187578. {
  187579. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187580. png_error(png_ptr, "Too many IDAT's found");
  187581. }
  187582. png_handle_unknown(png_ptr, info_ptr, length);
  187583. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187584. png_ptr->mode |= PNG_HAVE_PLTE;
  187585. }
  187586. #endif
  187587. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187588. {
  187589. /* Zero length IDATs are legal after the last IDAT has been
  187590. * read, but not after other chunks have been read.
  187591. */
  187592. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187593. png_error(png_ptr, "Too many IDAT's found");
  187594. png_crc_finish(png_ptr, length);
  187595. }
  187596. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187597. png_handle_PLTE(png_ptr, info_ptr, length);
  187598. #if defined(PNG_READ_bKGD_SUPPORTED)
  187599. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187600. png_handle_bKGD(png_ptr, info_ptr, length);
  187601. #endif
  187602. #if defined(PNG_READ_cHRM_SUPPORTED)
  187603. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187604. png_handle_cHRM(png_ptr, info_ptr, length);
  187605. #endif
  187606. #if defined(PNG_READ_gAMA_SUPPORTED)
  187607. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187608. png_handle_gAMA(png_ptr, info_ptr, length);
  187609. #endif
  187610. #if defined(PNG_READ_hIST_SUPPORTED)
  187611. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187612. png_handle_hIST(png_ptr, info_ptr, length);
  187613. #endif
  187614. #if defined(PNG_READ_oFFs_SUPPORTED)
  187615. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187616. png_handle_oFFs(png_ptr, info_ptr, length);
  187617. #endif
  187618. #if defined(PNG_READ_pCAL_SUPPORTED)
  187619. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187620. png_handle_pCAL(png_ptr, info_ptr, length);
  187621. #endif
  187622. #if defined(PNG_READ_sCAL_SUPPORTED)
  187623. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187624. png_handle_sCAL(png_ptr, info_ptr, length);
  187625. #endif
  187626. #if defined(PNG_READ_pHYs_SUPPORTED)
  187627. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187628. png_handle_pHYs(png_ptr, info_ptr, length);
  187629. #endif
  187630. #if defined(PNG_READ_sBIT_SUPPORTED)
  187631. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187632. png_handle_sBIT(png_ptr, info_ptr, length);
  187633. #endif
  187634. #if defined(PNG_READ_sRGB_SUPPORTED)
  187635. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187636. png_handle_sRGB(png_ptr, info_ptr, length);
  187637. #endif
  187638. #if defined(PNG_READ_iCCP_SUPPORTED)
  187639. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187640. png_handle_iCCP(png_ptr, info_ptr, length);
  187641. #endif
  187642. #if defined(PNG_READ_sPLT_SUPPORTED)
  187643. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187644. png_handle_sPLT(png_ptr, info_ptr, length);
  187645. #endif
  187646. #if defined(PNG_READ_tEXt_SUPPORTED)
  187647. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187648. png_handle_tEXt(png_ptr, info_ptr, length);
  187649. #endif
  187650. #if defined(PNG_READ_tIME_SUPPORTED)
  187651. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187652. png_handle_tIME(png_ptr, info_ptr, length);
  187653. #endif
  187654. #if defined(PNG_READ_tRNS_SUPPORTED)
  187655. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187656. png_handle_tRNS(png_ptr, info_ptr, length);
  187657. #endif
  187658. #if defined(PNG_READ_zTXt_SUPPORTED)
  187659. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187660. png_handle_zTXt(png_ptr, info_ptr, length);
  187661. #endif
  187662. #if defined(PNG_READ_iTXt_SUPPORTED)
  187663. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187664. png_handle_iTXt(png_ptr, info_ptr, length);
  187665. #endif
  187666. else
  187667. png_handle_unknown(png_ptr, info_ptr, length);
  187668. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187669. }
  187670. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187671. /* free all memory used by the read */
  187672. void PNGAPI
  187673. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187674. png_infopp end_info_ptr_ptr)
  187675. {
  187676. png_structp png_ptr = NULL;
  187677. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187678. #ifdef PNG_USER_MEM_SUPPORTED
  187679. png_free_ptr free_fn;
  187680. png_voidp mem_ptr;
  187681. #endif
  187682. png_debug(1, "in png_destroy_read_struct\n");
  187683. if (png_ptr_ptr != NULL)
  187684. png_ptr = *png_ptr_ptr;
  187685. if (info_ptr_ptr != NULL)
  187686. info_ptr = *info_ptr_ptr;
  187687. if (end_info_ptr_ptr != NULL)
  187688. end_info_ptr = *end_info_ptr_ptr;
  187689. #ifdef PNG_USER_MEM_SUPPORTED
  187690. free_fn = png_ptr->free_fn;
  187691. mem_ptr = png_ptr->mem_ptr;
  187692. #endif
  187693. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187694. if (info_ptr != NULL)
  187695. {
  187696. #if defined(PNG_TEXT_SUPPORTED)
  187697. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187698. #endif
  187699. #ifdef PNG_USER_MEM_SUPPORTED
  187700. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187701. (png_voidp)mem_ptr);
  187702. #else
  187703. png_destroy_struct((png_voidp)info_ptr);
  187704. #endif
  187705. *info_ptr_ptr = NULL;
  187706. }
  187707. if (end_info_ptr != NULL)
  187708. {
  187709. #if defined(PNG_READ_TEXT_SUPPORTED)
  187710. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187711. #endif
  187712. #ifdef PNG_USER_MEM_SUPPORTED
  187713. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187714. (png_voidp)mem_ptr);
  187715. #else
  187716. png_destroy_struct((png_voidp)end_info_ptr);
  187717. #endif
  187718. *end_info_ptr_ptr = NULL;
  187719. }
  187720. if (png_ptr != NULL)
  187721. {
  187722. #ifdef PNG_USER_MEM_SUPPORTED
  187723. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187724. (png_voidp)mem_ptr);
  187725. #else
  187726. png_destroy_struct((png_voidp)png_ptr);
  187727. #endif
  187728. *png_ptr_ptr = NULL;
  187729. }
  187730. }
  187731. /* free all memory used by the read (old method) */
  187732. void /* PRIVATE */
  187733. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187734. {
  187735. #ifdef PNG_SETJMP_SUPPORTED
  187736. jmp_buf tmp_jmp;
  187737. #endif
  187738. png_error_ptr error_fn;
  187739. png_error_ptr warning_fn;
  187740. png_voidp error_ptr;
  187741. #ifdef PNG_USER_MEM_SUPPORTED
  187742. png_free_ptr free_fn;
  187743. #endif
  187744. png_debug(1, "in png_read_destroy\n");
  187745. if (info_ptr != NULL)
  187746. png_info_destroy(png_ptr, info_ptr);
  187747. if (end_info_ptr != NULL)
  187748. png_info_destroy(png_ptr, end_info_ptr);
  187749. png_free(png_ptr, png_ptr->zbuf);
  187750. png_free(png_ptr, png_ptr->big_row_buf);
  187751. png_free(png_ptr, png_ptr->prev_row);
  187752. #if defined(PNG_READ_DITHER_SUPPORTED)
  187753. png_free(png_ptr, png_ptr->palette_lookup);
  187754. png_free(png_ptr, png_ptr->dither_index);
  187755. #endif
  187756. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187757. png_free(png_ptr, png_ptr->gamma_table);
  187758. #endif
  187759. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187760. png_free(png_ptr, png_ptr->gamma_from_1);
  187761. png_free(png_ptr, png_ptr->gamma_to_1);
  187762. #endif
  187763. #ifdef PNG_FREE_ME_SUPPORTED
  187764. if (png_ptr->free_me & PNG_FREE_PLTE)
  187765. png_zfree(png_ptr, png_ptr->palette);
  187766. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187767. #else
  187768. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187769. png_zfree(png_ptr, png_ptr->palette);
  187770. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187771. #endif
  187772. #if defined(PNG_tRNS_SUPPORTED) || \
  187773. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187774. #ifdef PNG_FREE_ME_SUPPORTED
  187775. if (png_ptr->free_me & PNG_FREE_TRNS)
  187776. png_free(png_ptr, png_ptr->trans);
  187777. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187778. #else
  187779. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187780. png_free(png_ptr, png_ptr->trans);
  187781. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187782. #endif
  187783. #endif
  187784. #if defined(PNG_READ_hIST_SUPPORTED)
  187785. #ifdef PNG_FREE_ME_SUPPORTED
  187786. if (png_ptr->free_me & PNG_FREE_HIST)
  187787. png_free(png_ptr, png_ptr->hist);
  187788. png_ptr->free_me &= ~PNG_FREE_HIST;
  187789. #else
  187790. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187791. png_free(png_ptr, png_ptr->hist);
  187792. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187793. #endif
  187794. #endif
  187795. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187796. if (png_ptr->gamma_16_table != NULL)
  187797. {
  187798. int i;
  187799. int istop = (1 << (8 - png_ptr->gamma_shift));
  187800. for (i = 0; i < istop; i++)
  187801. {
  187802. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187803. }
  187804. png_free(png_ptr, png_ptr->gamma_16_table);
  187805. }
  187806. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187807. if (png_ptr->gamma_16_from_1 != NULL)
  187808. {
  187809. int i;
  187810. int istop = (1 << (8 - png_ptr->gamma_shift));
  187811. for (i = 0; i < istop; i++)
  187812. {
  187813. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187814. }
  187815. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187816. }
  187817. if (png_ptr->gamma_16_to_1 != NULL)
  187818. {
  187819. int i;
  187820. int istop = (1 << (8 - png_ptr->gamma_shift));
  187821. for (i = 0; i < istop; i++)
  187822. {
  187823. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187824. }
  187825. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187826. }
  187827. #endif
  187828. #endif
  187829. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187830. png_free(png_ptr, png_ptr->time_buffer);
  187831. #endif
  187832. inflateEnd(&png_ptr->zstream);
  187833. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187834. png_free(png_ptr, png_ptr->save_buffer);
  187835. #endif
  187836. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187837. #ifdef PNG_TEXT_SUPPORTED
  187838. png_free(png_ptr, png_ptr->current_text);
  187839. #endif /* PNG_TEXT_SUPPORTED */
  187840. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187841. /* Save the important info out of the png_struct, in case it is
  187842. * being used again.
  187843. */
  187844. #ifdef PNG_SETJMP_SUPPORTED
  187845. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187846. #endif
  187847. error_fn = png_ptr->error_fn;
  187848. warning_fn = png_ptr->warning_fn;
  187849. error_ptr = png_ptr->error_ptr;
  187850. #ifdef PNG_USER_MEM_SUPPORTED
  187851. free_fn = png_ptr->free_fn;
  187852. #endif
  187853. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187854. png_ptr->error_fn = error_fn;
  187855. png_ptr->warning_fn = warning_fn;
  187856. png_ptr->error_ptr = error_ptr;
  187857. #ifdef PNG_USER_MEM_SUPPORTED
  187858. png_ptr->free_fn = free_fn;
  187859. #endif
  187860. #ifdef PNG_SETJMP_SUPPORTED
  187861. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187862. #endif
  187863. }
  187864. void PNGAPI
  187865. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187866. {
  187867. if(png_ptr == NULL) return;
  187868. png_ptr->read_row_fn = read_row_fn;
  187869. }
  187870. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187871. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187872. void PNGAPI
  187873. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187874. int transforms,
  187875. voidp params)
  187876. {
  187877. int row;
  187878. if(png_ptr == NULL) return;
  187879. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187880. /* invert the alpha channel from opacity to transparency
  187881. */
  187882. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187883. png_set_invert_alpha(png_ptr);
  187884. #endif
  187885. /* png_read_info() gives us all of the information from the
  187886. * PNG file before the first IDAT (image data chunk).
  187887. */
  187888. png_read_info(png_ptr, info_ptr);
  187889. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187890. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187891. /* -------------- image transformations start here ------------------- */
  187892. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187893. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187894. */
  187895. if (transforms & PNG_TRANSFORM_STRIP_16)
  187896. png_set_strip_16(png_ptr);
  187897. #endif
  187898. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187899. /* Strip alpha bytes from the input data without combining with
  187900. * the background (not recommended).
  187901. */
  187902. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187903. png_set_strip_alpha(png_ptr);
  187904. #endif
  187905. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187906. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187907. * byte into separate bytes (useful for paletted and grayscale images).
  187908. */
  187909. if (transforms & PNG_TRANSFORM_PACKING)
  187910. png_set_packing(png_ptr);
  187911. #endif
  187912. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187913. /* Change the order of packed pixels to least significant bit first
  187914. * (not useful if you are using png_set_packing).
  187915. */
  187916. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187917. png_set_packswap(png_ptr);
  187918. #endif
  187919. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187920. /* Expand paletted colors into true RGB triplets
  187921. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187922. * Expand paletted or RGB images with transparency to full alpha
  187923. * channels so the data will be available as RGBA quartets.
  187924. */
  187925. if (transforms & PNG_TRANSFORM_EXPAND)
  187926. if ((png_ptr->bit_depth < 8) ||
  187927. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187928. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187929. png_set_expand(png_ptr);
  187930. #endif
  187931. /* We don't handle background color or gamma transformation or dithering.
  187932. */
  187933. #if defined(PNG_READ_INVERT_SUPPORTED)
  187934. /* invert monochrome files to have 0 as white and 1 as black
  187935. */
  187936. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187937. png_set_invert_mono(png_ptr);
  187938. #endif
  187939. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187940. /* If you want to shift the pixel values from the range [0,255] or
  187941. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187942. * colors were originally in:
  187943. */
  187944. if ((transforms & PNG_TRANSFORM_SHIFT)
  187945. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187946. {
  187947. png_color_8p sig_bit;
  187948. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187949. png_set_shift(png_ptr, sig_bit);
  187950. }
  187951. #endif
  187952. #if defined(PNG_READ_BGR_SUPPORTED)
  187953. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187954. */
  187955. if (transforms & PNG_TRANSFORM_BGR)
  187956. png_set_bgr(png_ptr);
  187957. #endif
  187958. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187959. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187960. */
  187961. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187962. png_set_swap_alpha(png_ptr);
  187963. #endif
  187964. #if defined(PNG_READ_SWAP_SUPPORTED)
  187965. /* swap bytes of 16 bit files to least significant byte first
  187966. */
  187967. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187968. png_set_swap(png_ptr);
  187969. #endif
  187970. /* We don't handle adding filler bytes */
  187971. /* Optional call to gamma correct and add the background to the palette
  187972. * and update info structure. REQUIRED if you are expecting libpng to
  187973. * update the palette for you (i.e., you selected such a transform above).
  187974. */
  187975. png_read_update_info(png_ptr, info_ptr);
  187976. /* -------------- image transformations end here ------------------- */
  187977. #ifdef PNG_FREE_ME_SUPPORTED
  187978. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187979. #endif
  187980. if(info_ptr->row_pointers == NULL)
  187981. {
  187982. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187983. info_ptr->height * png_sizeof(png_bytep));
  187984. #ifdef PNG_FREE_ME_SUPPORTED
  187985. info_ptr->free_me |= PNG_FREE_ROWS;
  187986. #endif
  187987. for (row = 0; row < (int)info_ptr->height; row++)
  187988. {
  187989. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187990. png_get_rowbytes(png_ptr, info_ptr));
  187991. }
  187992. }
  187993. png_read_image(png_ptr, info_ptr->row_pointers);
  187994. info_ptr->valid |= PNG_INFO_IDAT;
  187995. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187996. png_read_end(png_ptr, info_ptr);
  187997. transforms = transforms; /* quiet compiler warnings */
  187998. params = params;
  187999. }
  188000. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188001. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188002. #endif /* PNG_READ_SUPPORTED */
  188003. /*** End of inlined file: pngread.c ***/
  188004. /*** Start of inlined file: pngpread.c ***/
  188005. /* pngpread.c - read a png file in push mode
  188006. *
  188007. * Last changed in libpng 1.2.21 October 4, 2007
  188008. * For conditions of distribution and use, see copyright notice in png.h
  188009. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188010. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188011. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188012. */
  188013. #define PNG_INTERNAL
  188014. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188015. /* push model modes */
  188016. #define PNG_READ_SIG_MODE 0
  188017. #define PNG_READ_CHUNK_MODE 1
  188018. #define PNG_READ_IDAT_MODE 2
  188019. #define PNG_SKIP_MODE 3
  188020. #define PNG_READ_tEXt_MODE 4
  188021. #define PNG_READ_zTXt_MODE 5
  188022. #define PNG_READ_DONE_MODE 6
  188023. #define PNG_READ_iTXt_MODE 7
  188024. #define PNG_ERROR_MODE 8
  188025. void PNGAPI
  188026. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188027. png_bytep buffer, png_size_t buffer_size)
  188028. {
  188029. if(png_ptr == NULL) return;
  188030. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188031. while (png_ptr->buffer_size)
  188032. {
  188033. png_process_some_data(png_ptr, info_ptr);
  188034. }
  188035. }
  188036. /* What we do with the incoming data depends on what we were previously
  188037. * doing before we ran out of data...
  188038. */
  188039. void /* PRIVATE */
  188040. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188041. {
  188042. if(png_ptr == NULL) return;
  188043. switch (png_ptr->process_mode)
  188044. {
  188045. case PNG_READ_SIG_MODE:
  188046. {
  188047. png_push_read_sig(png_ptr, info_ptr);
  188048. break;
  188049. }
  188050. case PNG_READ_CHUNK_MODE:
  188051. {
  188052. png_push_read_chunk(png_ptr, info_ptr);
  188053. break;
  188054. }
  188055. case PNG_READ_IDAT_MODE:
  188056. {
  188057. png_push_read_IDAT(png_ptr);
  188058. break;
  188059. }
  188060. #if defined(PNG_READ_tEXt_SUPPORTED)
  188061. case PNG_READ_tEXt_MODE:
  188062. {
  188063. png_push_read_tEXt(png_ptr, info_ptr);
  188064. break;
  188065. }
  188066. #endif
  188067. #if defined(PNG_READ_zTXt_SUPPORTED)
  188068. case PNG_READ_zTXt_MODE:
  188069. {
  188070. png_push_read_zTXt(png_ptr, info_ptr);
  188071. break;
  188072. }
  188073. #endif
  188074. #if defined(PNG_READ_iTXt_SUPPORTED)
  188075. case PNG_READ_iTXt_MODE:
  188076. {
  188077. png_push_read_iTXt(png_ptr, info_ptr);
  188078. break;
  188079. }
  188080. #endif
  188081. case PNG_SKIP_MODE:
  188082. {
  188083. png_push_crc_finish(png_ptr);
  188084. break;
  188085. }
  188086. default:
  188087. {
  188088. png_ptr->buffer_size = 0;
  188089. break;
  188090. }
  188091. }
  188092. }
  188093. /* Read any remaining signature bytes from the stream and compare them with
  188094. * the correct PNG signature. It is possible that this routine is called
  188095. * with bytes already read from the signature, either because they have been
  188096. * checked by the calling application, or because of multiple calls to this
  188097. * routine.
  188098. */
  188099. void /* PRIVATE */
  188100. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188101. {
  188102. png_size_t num_checked = png_ptr->sig_bytes,
  188103. num_to_check = 8 - num_checked;
  188104. if (png_ptr->buffer_size < num_to_check)
  188105. {
  188106. num_to_check = png_ptr->buffer_size;
  188107. }
  188108. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188109. num_to_check);
  188110. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188111. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188112. {
  188113. if (num_checked < 4 &&
  188114. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188115. png_error(png_ptr, "Not a PNG file");
  188116. else
  188117. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188118. }
  188119. else
  188120. {
  188121. if (png_ptr->sig_bytes >= 8)
  188122. {
  188123. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188124. }
  188125. }
  188126. }
  188127. void /* PRIVATE */
  188128. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188129. {
  188130. #ifdef PNG_USE_LOCAL_ARRAYS
  188131. PNG_CONST PNG_IHDR;
  188132. PNG_CONST PNG_IDAT;
  188133. PNG_CONST PNG_IEND;
  188134. PNG_CONST PNG_PLTE;
  188135. #if defined(PNG_READ_bKGD_SUPPORTED)
  188136. PNG_CONST PNG_bKGD;
  188137. #endif
  188138. #if defined(PNG_READ_cHRM_SUPPORTED)
  188139. PNG_CONST PNG_cHRM;
  188140. #endif
  188141. #if defined(PNG_READ_gAMA_SUPPORTED)
  188142. PNG_CONST PNG_gAMA;
  188143. #endif
  188144. #if defined(PNG_READ_hIST_SUPPORTED)
  188145. PNG_CONST PNG_hIST;
  188146. #endif
  188147. #if defined(PNG_READ_iCCP_SUPPORTED)
  188148. PNG_CONST PNG_iCCP;
  188149. #endif
  188150. #if defined(PNG_READ_iTXt_SUPPORTED)
  188151. PNG_CONST PNG_iTXt;
  188152. #endif
  188153. #if defined(PNG_READ_oFFs_SUPPORTED)
  188154. PNG_CONST PNG_oFFs;
  188155. #endif
  188156. #if defined(PNG_READ_pCAL_SUPPORTED)
  188157. PNG_CONST PNG_pCAL;
  188158. #endif
  188159. #if defined(PNG_READ_pHYs_SUPPORTED)
  188160. PNG_CONST PNG_pHYs;
  188161. #endif
  188162. #if defined(PNG_READ_sBIT_SUPPORTED)
  188163. PNG_CONST PNG_sBIT;
  188164. #endif
  188165. #if defined(PNG_READ_sCAL_SUPPORTED)
  188166. PNG_CONST PNG_sCAL;
  188167. #endif
  188168. #if defined(PNG_READ_sRGB_SUPPORTED)
  188169. PNG_CONST PNG_sRGB;
  188170. #endif
  188171. #if defined(PNG_READ_sPLT_SUPPORTED)
  188172. PNG_CONST PNG_sPLT;
  188173. #endif
  188174. #if defined(PNG_READ_tEXt_SUPPORTED)
  188175. PNG_CONST PNG_tEXt;
  188176. #endif
  188177. #if defined(PNG_READ_tIME_SUPPORTED)
  188178. PNG_CONST PNG_tIME;
  188179. #endif
  188180. #if defined(PNG_READ_tRNS_SUPPORTED)
  188181. PNG_CONST PNG_tRNS;
  188182. #endif
  188183. #if defined(PNG_READ_zTXt_SUPPORTED)
  188184. PNG_CONST PNG_zTXt;
  188185. #endif
  188186. #endif /* PNG_USE_LOCAL_ARRAYS */
  188187. /* First we make sure we have enough data for the 4 byte chunk name
  188188. * and the 4 byte chunk length before proceeding with decoding the
  188189. * chunk data. To fully decode each of these chunks, we also make
  188190. * sure we have enough data in the buffer for the 4 byte CRC at the
  188191. * end of every chunk (except IDAT, which is handled separately).
  188192. */
  188193. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188194. {
  188195. png_byte chunk_length[4];
  188196. if (png_ptr->buffer_size < 8)
  188197. {
  188198. png_push_save_buffer(png_ptr);
  188199. return;
  188200. }
  188201. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188202. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188203. png_reset_crc(png_ptr);
  188204. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188205. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188206. }
  188207. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188208. if(png_ptr->mode & PNG_AFTER_IDAT)
  188209. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188210. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188211. {
  188212. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188213. {
  188214. png_push_save_buffer(png_ptr);
  188215. return;
  188216. }
  188217. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188218. }
  188219. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188220. {
  188221. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188222. {
  188223. png_push_save_buffer(png_ptr);
  188224. return;
  188225. }
  188226. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188227. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188228. png_push_have_end(png_ptr, info_ptr);
  188229. }
  188230. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188231. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188232. {
  188233. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188234. {
  188235. png_push_save_buffer(png_ptr);
  188236. return;
  188237. }
  188238. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188239. png_ptr->mode |= PNG_HAVE_IDAT;
  188240. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188241. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188242. png_ptr->mode |= PNG_HAVE_PLTE;
  188243. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188244. {
  188245. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188246. png_error(png_ptr, "Missing IHDR before IDAT");
  188247. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188248. !(png_ptr->mode & PNG_HAVE_PLTE))
  188249. png_error(png_ptr, "Missing PLTE before IDAT");
  188250. }
  188251. }
  188252. #endif
  188253. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188254. {
  188255. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188256. {
  188257. png_push_save_buffer(png_ptr);
  188258. return;
  188259. }
  188260. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188261. }
  188262. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188263. {
  188264. /* If we reach an IDAT chunk, this means we have read all of the
  188265. * header chunks, and we can start reading the image (or if this
  188266. * is called after the image has been read - we have an error).
  188267. */
  188268. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188269. png_error(png_ptr, "Missing IHDR before IDAT");
  188270. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188271. !(png_ptr->mode & PNG_HAVE_PLTE))
  188272. png_error(png_ptr, "Missing PLTE before IDAT");
  188273. if (png_ptr->mode & PNG_HAVE_IDAT)
  188274. {
  188275. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188276. if (png_ptr->push_length == 0)
  188277. return;
  188278. if (png_ptr->mode & PNG_AFTER_IDAT)
  188279. png_error(png_ptr, "Too many IDAT's found");
  188280. }
  188281. png_ptr->idat_size = png_ptr->push_length;
  188282. png_ptr->mode |= PNG_HAVE_IDAT;
  188283. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188284. png_push_have_info(png_ptr, info_ptr);
  188285. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188286. png_ptr->zstream.next_out = png_ptr->row_buf;
  188287. return;
  188288. }
  188289. #if defined(PNG_READ_gAMA_SUPPORTED)
  188290. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188291. {
  188292. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188293. {
  188294. png_push_save_buffer(png_ptr);
  188295. return;
  188296. }
  188297. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188298. }
  188299. #endif
  188300. #if defined(PNG_READ_sBIT_SUPPORTED)
  188301. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188302. {
  188303. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188304. {
  188305. png_push_save_buffer(png_ptr);
  188306. return;
  188307. }
  188308. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188309. }
  188310. #endif
  188311. #if defined(PNG_READ_cHRM_SUPPORTED)
  188312. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188313. {
  188314. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188315. {
  188316. png_push_save_buffer(png_ptr);
  188317. return;
  188318. }
  188319. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188320. }
  188321. #endif
  188322. #if defined(PNG_READ_sRGB_SUPPORTED)
  188323. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188324. {
  188325. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188326. {
  188327. png_push_save_buffer(png_ptr);
  188328. return;
  188329. }
  188330. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188331. }
  188332. #endif
  188333. #if defined(PNG_READ_iCCP_SUPPORTED)
  188334. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188335. {
  188336. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188337. {
  188338. png_push_save_buffer(png_ptr);
  188339. return;
  188340. }
  188341. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188342. }
  188343. #endif
  188344. #if defined(PNG_READ_sPLT_SUPPORTED)
  188345. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188346. {
  188347. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188348. {
  188349. png_push_save_buffer(png_ptr);
  188350. return;
  188351. }
  188352. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188353. }
  188354. #endif
  188355. #if defined(PNG_READ_tRNS_SUPPORTED)
  188356. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188357. {
  188358. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188359. {
  188360. png_push_save_buffer(png_ptr);
  188361. return;
  188362. }
  188363. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188364. }
  188365. #endif
  188366. #if defined(PNG_READ_bKGD_SUPPORTED)
  188367. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188368. {
  188369. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188370. {
  188371. png_push_save_buffer(png_ptr);
  188372. return;
  188373. }
  188374. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188375. }
  188376. #endif
  188377. #if defined(PNG_READ_hIST_SUPPORTED)
  188378. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188379. {
  188380. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188381. {
  188382. png_push_save_buffer(png_ptr);
  188383. return;
  188384. }
  188385. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188386. }
  188387. #endif
  188388. #if defined(PNG_READ_pHYs_SUPPORTED)
  188389. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188390. {
  188391. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188392. {
  188393. png_push_save_buffer(png_ptr);
  188394. return;
  188395. }
  188396. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188397. }
  188398. #endif
  188399. #if defined(PNG_READ_oFFs_SUPPORTED)
  188400. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188401. {
  188402. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188403. {
  188404. png_push_save_buffer(png_ptr);
  188405. return;
  188406. }
  188407. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188408. }
  188409. #endif
  188410. #if defined(PNG_READ_pCAL_SUPPORTED)
  188411. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188412. {
  188413. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188414. {
  188415. png_push_save_buffer(png_ptr);
  188416. return;
  188417. }
  188418. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188419. }
  188420. #endif
  188421. #if defined(PNG_READ_sCAL_SUPPORTED)
  188422. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188423. {
  188424. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188425. {
  188426. png_push_save_buffer(png_ptr);
  188427. return;
  188428. }
  188429. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188430. }
  188431. #endif
  188432. #if defined(PNG_READ_tIME_SUPPORTED)
  188433. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188434. {
  188435. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188436. {
  188437. png_push_save_buffer(png_ptr);
  188438. return;
  188439. }
  188440. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188441. }
  188442. #endif
  188443. #if defined(PNG_READ_tEXt_SUPPORTED)
  188444. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188445. {
  188446. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188447. {
  188448. png_push_save_buffer(png_ptr);
  188449. return;
  188450. }
  188451. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188452. }
  188453. #endif
  188454. #if defined(PNG_READ_zTXt_SUPPORTED)
  188455. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188456. {
  188457. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188458. {
  188459. png_push_save_buffer(png_ptr);
  188460. return;
  188461. }
  188462. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188463. }
  188464. #endif
  188465. #if defined(PNG_READ_iTXt_SUPPORTED)
  188466. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188467. {
  188468. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188469. {
  188470. png_push_save_buffer(png_ptr);
  188471. return;
  188472. }
  188473. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188474. }
  188475. #endif
  188476. else
  188477. {
  188478. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188479. {
  188480. png_push_save_buffer(png_ptr);
  188481. return;
  188482. }
  188483. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188484. }
  188485. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188486. }
  188487. void /* PRIVATE */
  188488. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188489. {
  188490. png_ptr->process_mode = PNG_SKIP_MODE;
  188491. png_ptr->skip_length = skip;
  188492. }
  188493. void /* PRIVATE */
  188494. png_push_crc_finish(png_structp png_ptr)
  188495. {
  188496. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188497. {
  188498. png_size_t save_size;
  188499. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188500. save_size = (png_size_t)png_ptr->skip_length;
  188501. else
  188502. save_size = png_ptr->save_buffer_size;
  188503. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188504. png_ptr->skip_length -= save_size;
  188505. png_ptr->buffer_size -= save_size;
  188506. png_ptr->save_buffer_size -= save_size;
  188507. png_ptr->save_buffer_ptr += save_size;
  188508. }
  188509. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188510. {
  188511. png_size_t save_size;
  188512. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188513. save_size = (png_size_t)png_ptr->skip_length;
  188514. else
  188515. save_size = png_ptr->current_buffer_size;
  188516. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188517. png_ptr->skip_length -= save_size;
  188518. png_ptr->buffer_size -= save_size;
  188519. png_ptr->current_buffer_size -= save_size;
  188520. png_ptr->current_buffer_ptr += save_size;
  188521. }
  188522. if (!png_ptr->skip_length)
  188523. {
  188524. if (png_ptr->buffer_size < 4)
  188525. {
  188526. png_push_save_buffer(png_ptr);
  188527. return;
  188528. }
  188529. png_crc_finish(png_ptr, 0);
  188530. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188531. }
  188532. }
  188533. void PNGAPI
  188534. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188535. {
  188536. png_bytep ptr;
  188537. if(png_ptr == NULL) return;
  188538. ptr = buffer;
  188539. if (png_ptr->save_buffer_size)
  188540. {
  188541. png_size_t save_size;
  188542. if (length < png_ptr->save_buffer_size)
  188543. save_size = length;
  188544. else
  188545. save_size = png_ptr->save_buffer_size;
  188546. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188547. length -= save_size;
  188548. ptr += save_size;
  188549. png_ptr->buffer_size -= save_size;
  188550. png_ptr->save_buffer_size -= save_size;
  188551. png_ptr->save_buffer_ptr += save_size;
  188552. }
  188553. if (length && png_ptr->current_buffer_size)
  188554. {
  188555. png_size_t save_size;
  188556. if (length < png_ptr->current_buffer_size)
  188557. save_size = length;
  188558. else
  188559. save_size = png_ptr->current_buffer_size;
  188560. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188561. png_ptr->buffer_size -= save_size;
  188562. png_ptr->current_buffer_size -= save_size;
  188563. png_ptr->current_buffer_ptr += save_size;
  188564. }
  188565. }
  188566. void /* PRIVATE */
  188567. png_push_save_buffer(png_structp png_ptr)
  188568. {
  188569. if (png_ptr->save_buffer_size)
  188570. {
  188571. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188572. {
  188573. png_size_t i,istop;
  188574. png_bytep sp;
  188575. png_bytep dp;
  188576. istop = png_ptr->save_buffer_size;
  188577. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188578. i < istop; i++, sp++, dp++)
  188579. {
  188580. *dp = *sp;
  188581. }
  188582. }
  188583. }
  188584. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188585. png_ptr->save_buffer_max)
  188586. {
  188587. png_size_t new_max;
  188588. png_bytep old_buffer;
  188589. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188590. (png_ptr->current_buffer_size + 256))
  188591. {
  188592. png_error(png_ptr, "Potential overflow of save_buffer");
  188593. }
  188594. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188595. old_buffer = png_ptr->save_buffer;
  188596. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188597. (png_uint_32)new_max);
  188598. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188599. png_free(png_ptr, old_buffer);
  188600. png_ptr->save_buffer_max = new_max;
  188601. }
  188602. if (png_ptr->current_buffer_size)
  188603. {
  188604. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188605. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188606. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188607. png_ptr->current_buffer_size = 0;
  188608. }
  188609. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188610. png_ptr->buffer_size = 0;
  188611. }
  188612. void /* PRIVATE */
  188613. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188614. png_size_t buffer_length)
  188615. {
  188616. png_ptr->current_buffer = buffer;
  188617. png_ptr->current_buffer_size = buffer_length;
  188618. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188619. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188620. }
  188621. void /* PRIVATE */
  188622. png_push_read_IDAT(png_structp png_ptr)
  188623. {
  188624. #ifdef PNG_USE_LOCAL_ARRAYS
  188625. PNG_CONST PNG_IDAT;
  188626. #endif
  188627. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188628. {
  188629. png_byte chunk_length[4];
  188630. if (png_ptr->buffer_size < 8)
  188631. {
  188632. png_push_save_buffer(png_ptr);
  188633. return;
  188634. }
  188635. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188636. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188637. png_reset_crc(png_ptr);
  188638. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188639. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188640. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188641. {
  188642. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188643. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188644. png_error(png_ptr, "Not enough compressed data");
  188645. return;
  188646. }
  188647. png_ptr->idat_size = png_ptr->push_length;
  188648. }
  188649. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188650. {
  188651. png_size_t save_size;
  188652. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188653. {
  188654. save_size = (png_size_t)png_ptr->idat_size;
  188655. /* check for overflow */
  188656. if((png_uint_32)save_size != png_ptr->idat_size)
  188657. png_error(png_ptr, "save_size overflowed in pngpread");
  188658. }
  188659. else
  188660. save_size = png_ptr->save_buffer_size;
  188661. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188662. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188663. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188664. png_ptr->idat_size -= save_size;
  188665. png_ptr->buffer_size -= save_size;
  188666. png_ptr->save_buffer_size -= save_size;
  188667. png_ptr->save_buffer_ptr += save_size;
  188668. }
  188669. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188670. {
  188671. png_size_t save_size;
  188672. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188673. {
  188674. save_size = (png_size_t)png_ptr->idat_size;
  188675. /* check for overflow */
  188676. if((png_uint_32)save_size != png_ptr->idat_size)
  188677. png_error(png_ptr, "save_size overflowed in pngpread");
  188678. }
  188679. else
  188680. save_size = png_ptr->current_buffer_size;
  188681. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188682. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188683. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188684. png_ptr->idat_size -= save_size;
  188685. png_ptr->buffer_size -= save_size;
  188686. png_ptr->current_buffer_size -= save_size;
  188687. png_ptr->current_buffer_ptr += save_size;
  188688. }
  188689. if (!png_ptr->idat_size)
  188690. {
  188691. if (png_ptr->buffer_size < 4)
  188692. {
  188693. png_push_save_buffer(png_ptr);
  188694. return;
  188695. }
  188696. png_crc_finish(png_ptr, 0);
  188697. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188698. png_ptr->mode |= PNG_AFTER_IDAT;
  188699. }
  188700. }
  188701. void /* PRIVATE */
  188702. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188703. png_size_t buffer_length)
  188704. {
  188705. int ret;
  188706. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188707. png_error(png_ptr, "Extra compression data");
  188708. png_ptr->zstream.next_in = buffer;
  188709. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188710. for(;;)
  188711. {
  188712. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188713. if (ret != Z_OK)
  188714. {
  188715. if (ret == Z_STREAM_END)
  188716. {
  188717. if (png_ptr->zstream.avail_in)
  188718. png_error(png_ptr, "Extra compressed data");
  188719. if (!(png_ptr->zstream.avail_out))
  188720. {
  188721. png_push_process_row(png_ptr);
  188722. }
  188723. png_ptr->mode |= PNG_AFTER_IDAT;
  188724. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188725. break;
  188726. }
  188727. else if (ret == Z_BUF_ERROR)
  188728. break;
  188729. else
  188730. png_error(png_ptr, "Decompression Error");
  188731. }
  188732. if (!(png_ptr->zstream.avail_out))
  188733. {
  188734. if ((
  188735. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188736. png_ptr->interlaced && png_ptr->pass > 6) ||
  188737. (!png_ptr->interlaced &&
  188738. #endif
  188739. png_ptr->row_number == png_ptr->num_rows))
  188740. {
  188741. if (png_ptr->zstream.avail_in)
  188742. {
  188743. png_warning(png_ptr, "Too much data in IDAT chunks");
  188744. }
  188745. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188746. break;
  188747. }
  188748. png_push_process_row(png_ptr);
  188749. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188750. png_ptr->zstream.next_out = png_ptr->row_buf;
  188751. }
  188752. else
  188753. break;
  188754. }
  188755. }
  188756. void /* PRIVATE */
  188757. png_push_process_row(png_structp png_ptr)
  188758. {
  188759. png_ptr->row_info.color_type = png_ptr->color_type;
  188760. png_ptr->row_info.width = png_ptr->iwidth;
  188761. png_ptr->row_info.channels = png_ptr->channels;
  188762. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188763. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188764. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188765. png_ptr->row_info.width);
  188766. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188767. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188768. (int)(png_ptr->row_buf[0]));
  188769. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188770. png_ptr->rowbytes + 1);
  188771. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188772. png_do_read_transformations(png_ptr);
  188773. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188774. /* blow up interlaced rows to full size */
  188775. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188776. {
  188777. if (png_ptr->pass < 6)
  188778. /* old interface (pre-1.0.9):
  188779. png_do_read_interlace(&(png_ptr->row_info),
  188780. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188781. */
  188782. png_do_read_interlace(png_ptr);
  188783. switch (png_ptr->pass)
  188784. {
  188785. case 0:
  188786. {
  188787. int i;
  188788. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188789. {
  188790. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188791. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188792. }
  188793. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188794. {
  188795. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188796. {
  188797. png_push_have_row(png_ptr, png_bytep_NULL);
  188798. png_read_push_finish_row(png_ptr);
  188799. }
  188800. }
  188801. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188802. {
  188803. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188804. {
  188805. png_push_have_row(png_ptr, png_bytep_NULL);
  188806. png_read_push_finish_row(png_ptr);
  188807. }
  188808. }
  188809. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188810. {
  188811. png_push_have_row(png_ptr, png_bytep_NULL);
  188812. png_read_push_finish_row(png_ptr);
  188813. }
  188814. break;
  188815. }
  188816. case 1:
  188817. {
  188818. int i;
  188819. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188820. {
  188821. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188822. png_read_push_finish_row(png_ptr);
  188823. }
  188824. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188825. {
  188826. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188827. {
  188828. png_push_have_row(png_ptr, png_bytep_NULL);
  188829. png_read_push_finish_row(png_ptr);
  188830. }
  188831. }
  188832. break;
  188833. }
  188834. case 2:
  188835. {
  188836. int i;
  188837. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188838. {
  188839. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188840. png_read_push_finish_row(png_ptr);
  188841. }
  188842. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188843. {
  188844. png_push_have_row(png_ptr, png_bytep_NULL);
  188845. png_read_push_finish_row(png_ptr);
  188846. }
  188847. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188848. {
  188849. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188850. {
  188851. png_push_have_row(png_ptr, png_bytep_NULL);
  188852. png_read_push_finish_row(png_ptr);
  188853. }
  188854. }
  188855. break;
  188856. }
  188857. case 3:
  188858. {
  188859. int i;
  188860. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188861. {
  188862. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188863. png_read_push_finish_row(png_ptr);
  188864. }
  188865. if (png_ptr->pass == 4) /* skip top two generated rows */
  188866. {
  188867. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188868. {
  188869. png_push_have_row(png_ptr, png_bytep_NULL);
  188870. png_read_push_finish_row(png_ptr);
  188871. }
  188872. }
  188873. break;
  188874. }
  188875. case 4:
  188876. {
  188877. int i;
  188878. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188879. {
  188880. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188881. png_read_push_finish_row(png_ptr);
  188882. }
  188883. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188884. {
  188885. png_push_have_row(png_ptr, png_bytep_NULL);
  188886. png_read_push_finish_row(png_ptr);
  188887. }
  188888. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188889. {
  188890. png_push_have_row(png_ptr, png_bytep_NULL);
  188891. png_read_push_finish_row(png_ptr);
  188892. }
  188893. break;
  188894. }
  188895. case 5:
  188896. {
  188897. int i;
  188898. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188899. {
  188900. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188901. png_read_push_finish_row(png_ptr);
  188902. }
  188903. if (png_ptr->pass == 6) /* skip top generated row */
  188904. {
  188905. png_push_have_row(png_ptr, png_bytep_NULL);
  188906. png_read_push_finish_row(png_ptr);
  188907. }
  188908. break;
  188909. }
  188910. case 6:
  188911. {
  188912. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188913. png_read_push_finish_row(png_ptr);
  188914. if (png_ptr->pass != 6)
  188915. break;
  188916. png_push_have_row(png_ptr, png_bytep_NULL);
  188917. png_read_push_finish_row(png_ptr);
  188918. }
  188919. }
  188920. }
  188921. else
  188922. #endif
  188923. {
  188924. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188925. png_read_push_finish_row(png_ptr);
  188926. }
  188927. }
  188928. void /* PRIVATE */
  188929. png_read_push_finish_row(png_structp png_ptr)
  188930. {
  188931. #ifdef PNG_USE_LOCAL_ARRAYS
  188932. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188933. /* start of interlace block */
  188934. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188935. /* offset to next interlace block */
  188936. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188937. /* start of interlace block in the y direction */
  188938. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188939. /* offset to next interlace block in the y direction */
  188940. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188941. /* Height of interlace block. This is not currently used - if you need
  188942. * it, uncomment it here and in png.h
  188943. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188944. */
  188945. #endif
  188946. png_ptr->row_number++;
  188947. if (png_ptr->row_number < png_ptr->num_rows)
  188948. return;
  188949. if (png_ptr->interlaced)
  188950. {
  188951. png_ptr->row_number = 0;
  188952. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188953. png_ptr->rowbytes + 1);
  188954. do
  188955. {
  188956. png_ptr->pass++;
  188957. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188958. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188959. (png_ptr->pass == 5 && png_ptr->width < 2))
  188960. png_ptr->pass++;
  188961. if (png_ptr->pass > 7)
  188962. png_ptr->pass--;
  188963. if (png_ptr->pass >= 7)
  188964. break;
  188965. png_ptr->iwidth = (png_ptr->width +
  188966. png_pass_inc[png_ptr->pass] - 1 -
  188967. png_pass_start[png_ptr->pass]) /
  188968. png_pass_inc[png_ptr->pass];
  188969. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188970. png_ptr->iwidth) + 1;
  188971. if (png_ptr->transformations & PNG_INTERLACE)
  188972. break;
  188973. png_ptr->num_rows = (png_ptr->height +
  188974. png_pass_yinc[png_ptr->pass] - 1 -
  188975. png_pass_ystart[png_ptr->pass]) /
  188976. png_pass_yinc[png_ptr->pass];
  188977. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188978. }
  188979. }
  188980. #if defined(PNG_READ_tEXt_SUPPORTED)
  188981. void /* PRIVATE */
  188982. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188983. length)
  188984. {
  188985. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188986. {
  188987. png_error(png_ptr, "Out of place tEXt");
  188988. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188989. }
  188990. #ifdef PNG_MAX_MALLOC_64K
  188991. png_ptr->skip_length = 0; /* This may not be necessary */
  188992. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188993. {
  188994. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188995. png_ptr->skip_length = length - (png_uint_32)65535L;
  188996. length = (png_uint_32)65535L;
  188997. }
  188998. #endif
  188999. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189000. (png_uint_32)(length+1));
  189001. png_ptr->current_text[length] = '\0';
  189002. png_ptr->current_text_ptr = png_ptr->current_text;
  189003. png_ptr->current_text_size = (png_size_t)length;
  189004. png_ptr->current_text_left = (png_size_t)length;
  189005. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189006. }
  189007. void /* PRIVATE */
  189008. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189009. {
  189010. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189011. {
  189012. png_size_t text_size;
  189013. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189014. text_size = png_ptr->buffer_size;
  189015. else
  189016. text_size = png_ptr->current_text_left;
  189017. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189018. png_ptr->current_text_left -= text_size;
  189019. png_ptr->current_text_ptr += text_size;
  189020. }
  189021. if (!(png_ptr->current_text_left))
  189022. {
  189023. png_textp text_ptr;
  189024. png_charp text;
  189025. png_charp key;
  189026. int ret;
  189027. if (png_ptr->buffer_size < 4)
  189028. {
  189029. png_push_save_buffer(png_ptr);
  189030. return;
  189031. }
  189032. png_push_crc_finish(png_ptr);
  189033. #if defined(PNG_MAX_MALLOC_64K)
  189034. if (png_ptr->skip_length)
  189035. return;
  189036. #endif
  189037. key = png_ptr->current_text;
  189038. for (text = key; *text; text++)
  189039. /* empty loop */ ;
  189040. if (text < key + png_ptr->current_text_size)
  189041. text++;
  189042. text_ptr = (png_textp)png_malloc(png_ptr,
  189043. (png_uint_32)png_sizeof(png_text));
  189044. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189045. text_ptr->key = key;
  189046. #ifdef PNG_iTXt_SUPPORTED
  189047. text_ptr->lang = NULL;
  189048. text_ptr->lang_key = NULL;
  189049. #endif
  189050. text_ptr->text = text;
  189051. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189052. png_free(png_ptr, key);
  189053. png_free(png_ptr, text_ptr);
  189054. png_ptr->current_text = NULL;
  189055. if (ret)
  189056. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189057. }
  189058. }
  189059. #endif
  189060. #if defined(PNG_READ_zTXt_SUPPORTED)
  189061. void /* PRIVATE */
  189062. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189063. length)
  189064. {
  189065. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189066. {
  189067. png_error(png_ptr, "Out of place zTXt");
  189068. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189069. }
  189070. #ifdef PNG_MAX_MALLOC_64K
  189071. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189072. * to be able to store the uncompressed data. Actually, the threshold
  189073. * is probably around 32K, but it isn't as definite as 64K is.
  189074. */
  189075. if (length > (png_uint_32)65535L)
  189076. {
  189077. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189078. png_push_crc_skip(png_ptr, length);
  189079. return;
  189080. }
  189081. #endif
  189082. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189083. (png_uint_32)(length+1));
  189084. png_ptr->current_text[length] = '\0';
  189085. png_ptr->current_text_ptr = png_ptr->current_text;
  189086. png_ptr->current_text_size = (png_size_t)length;
  189087. png_ptr->current_text_left = (png_size_t)length;
  189088. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189089. }
  189090. void /* PRIVATE */
  189091. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189092. {
  189093. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189094. {
  189095. png_size_t text_size;
  189096. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189097. text_size = png_ptr->buffer_size;
  189098. else
  189099. text_size = png_ptr->current_text_left;
  189100. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189101. png_ptr->current_text_left -= text_size;
  189102. png_ptr->current_text_ptr += text_size;
  189103. }
  189104. if (!(png_ptr->current_text_left))
  189105. {
  189106. png_textp text_ptr;
  189107. png_charp text;
  189108. png_charp key;
  189109. int ret;
  189110. png_size_t text_size, key_size;
  189111. if (png_ptr->buffer_size < 4)
  189112. {
  189113. png_push_save_buffer(png_ptr);
  189114. return;
  189115. }
  189116. png_push_crc_finish(png_ptr);
  189117. key = png_ptr->current_text;
  189118. for (text = key; *text; text++)
  189119. /* empty loop */ ;
  189120. /* zTXt can't have zero text */
  189121. if (text >= key + png_ptr->current_text_size)
  189122. {
  189123. png_ptr->current_text = NULL;
  189124. png_free(png_ptr, key);
  189125. return;
  189126. }
  189127. text++;
  189128. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189129. {
  189130. png_ptr->current_text = NULL;
  189131. png_free(png_ptr, key);
  189132. return;
  189133. }
  189134. text++;
  189135. png_ptr->zstream.next_in = (png_bytep )text;
  189136. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189137. (text - key));
  189138. png_ptr->zstream.next_out = png_ptr->zbuf;
  189139. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189140. key_size = text - key;
  189141. text_size = 0;
  189142. text = NULL;
  189143. ret = Z_STREAM_END;
  189144. while (png_ptr->zstream.avail_in)
  189145. {
  189146. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189147. if (ret != Z_OK && ret != Z_STREAM_END)
  189148. {
  189149. inflateReset(&png_ptr->zstream);
  189150. png_ptr->zstream.avail_in = 0;
  189151. png_ptr->current_text = NULL;
  189152. png_free(png_ptr, key);
  189153. png_free(png_ptr, text);
  189154. return;
  189155. }
  189156. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189157. {
  189158. if (text == NULL)
  189159. {
  189160. text = (png_charp)png_malloc(png_ptr,
  189161. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189162. + key_size + 1));
  189163. png_memcpy(text + key_size, png_ptr->zbuf,
  189164. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189165. png_memcpy(text, key, key_size);
  189166. text_size = key_size + png_ptr->zbuf_size -
  189167. png_ptr->zstream.avail_out;
  189168. *(text + text_size) = '\0';
  189169. }
  189170. else
  189171. {
  189172. png_charp tmp;
  189173. tmp = text;
  189174. text = (png_charp)png_malloc(png_ptr, text_size +
  189175. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189176. + 1));
  189177. png_memcpy(text, tmp, text_size);
  189178. png_free(png_ptr, tmp);
  189179. png_memcpy(text + text_size, png_ptr->zbuf,
  189180. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189181. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189182. *(text + text_size) = '\0';
  189183. }
  189184. if (ret != Z_STREAM_END)
  189185. {
  189186. png_ptr->zstream.next_out = png_ptr->zbuf;
  189187. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189188. }
  189189. }
  189190. else
  189191. {
  189192. break;
  189193. }
  189194. if (ret == Z_STREAM_END)
  189195. break;
  189196. }
  189197. inflateReset(&png_ptr->zstream);
  189198. png_ptr->zstream.avail_in = 0;
  189199. if (ret != Z_STREAM_END)
  189200. {
  189201. png_ptr->current_text = NULL;
  189202. png_free(png_ptr, key);
  189203. png_free(png_ptr, text);
  189204. return;
  189205. }
  189206. png_ptr->current_text = NULL;
  189207. png_free(png_ptr, key);
  189208. key = text;
  189209. text += key_size;
  189210. text_ptr = (png_textp)png_malloc(png_ptr,
  189211. (png_uint_32)png_sizeof(png_text));
  189212. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189213. text_ptr->key = key;
  189214. #ifdef PNG_iTXt_SUPPORTED
  189215. text_ptr->lang = NULL;
  189216. text_ptr->lang_key = NULL;
  189217. #endif
  189218. text_ptr->text = text;
  189219. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189220. png_free(png_ptr, key);
  189221. png_free(png_ptr, text_ptr);
  189222. if (ret)
  189223. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189224. }
  189225. }
  189226. #endif
  189227. #if defined(PNG_READ_iTXt_SUPPORTED)
  189228. void /* PRIVATE */
  189229. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189230. length)
  189231. {
  189232. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189233. {
  189234. png_error(png_ptr, "Out of place iTXt");
  189235. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189236. }
  189237. #ifdef PNG_MAX_MALLOC_64K
  189238. png_ptr->skip_length = 0; /* This may not be necessary */
  189239. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189240. {
  189241. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189242. png_ptr->skip_length = length - (png_uint_32)65535L;
  189243. length = (png_uint_32)65535L;
  189244. }
  189245. #endif
  189246. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189247. (png_uint_32)(length+1));
  189248. png_ptr->current_text[length] = '\0';
  189249. png_ptr->current_text_ptr = png_ptr->current_text;
  189250. png_ptr->current_text_size = (png_size_t)length;
  189251. png_ptr->current_text_left = (png_size_t)length;
  189252. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189253. }
  189254. void /* PRIVATE */
  189255. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189256. {
  189257. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189258. {
  189259. png_size_t text_size;
  189260. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189261. text_size = png_ptr->buffer_size;
  189262. else
  189263. text_size = png_ptr->current_text_left;
  189264. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189265. png_ptr->current_text_left -= text_size;
  189266. png_ptr->current_text_ptr += text_size;
  189267. }
  189268. if (!(png_ptr->current_text_left))
  189269. {
  189270. png_textp text_ptr;
  189271. png_charp key;
  189272. int comp_flag;
  189273. png_charp lang;
  189274. png_charp lang_key;
  189275. png_charp text;
  189276. int ret;
  189277. if (png_ptr->buffer_size < 4)
  189278. {
  189279. png_push_save_buffer(png_ptr);
  189280. return;
  189281. }
  189282. png_push_crc_finish(png_ptr);
  189283. #if defined(PNG_MAX_MALLOC_64K)
  189284. if (png_ptr->skip_length)
  189285. return;
  189286. #endif
  189287. key = png_ptr->current_text;
  189288. for (lang = key; *lang; lang++)
  189289. /* empty loop */ ;
  189290. if (lang < key + png_ptr->current_text_size - 3)
  189291. lang++;
  189292. comp_flag = *lang++;
  189293. lang++; /* skip comp_type, always zero */
  189294. for (lang_key = lang; *lang_key; lang_key++)
  189295. /* empty loop */ ;
  189296. lang_key++; /* skip NUL separator */
  189297. text=lang_key;
  189298. if (lang_key < key + png_ptr->current_text_size - 1)
  189299. {
  189300. for (; *text; text++)
  189301. /* empty loop */ ;
  189302. }
  189303. if (text < key + png_ptr->current_text_size)
  189304. text++;
  189305. text_ptr = (png_textp)png_malloc(png_ptr,
  189306. (png_uint_32)png_sizeof(png_text));
  189307. text_ptr->compression = comp_flag + 2;
  189308. text_ptr->key = key;
  189309. text_ptr->lang = lang;
  189310. text_ptr->lang_key = lang_key;
  189311. text_ptr->text = text;
  189312. text_ptr->text_length = 0;
  189313. text_ptr->itxt_length = png_strlen(text);
  189314. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189315. png_ptr->current_text = NULL;
  189316. png_free(png_ptr, text_ptr);
  189317. if (ret)
  189318. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189319. }
  189320. }
  189321. #endif
  189322. /* This function is called when we haven't found a handler for this
  189323. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189324. * name or a critical chunk), the chunk is (currently) silently ignored.
  189325. */
  189326. void /* PRIVATE */
  189327. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189328. length)
  189329. {
  189330. png_uint_32 skip=0;
  189331. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189332. if (!(png_ptr->chunk_name[0] & 0x20))
  189333. {
  189334. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189335. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189336. PNG_HANDLE_CHUNK_ALWAYS
  189337. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189338. && png_ptr->read_user_chunk_fn == NULL
  189339. #endif
  189340. )
  189341. #endif
  189342. png_chunk_error(png_ptr, "unknown critical chunk");
  189343. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189344. }
  189345. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189346. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189347. {
  189348. #ifdef PNG_MAX_MALLOC_64K
  189349. if (length > (png_uint_32)65535L)
  189350. {
  189351. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189352. skip = length - (png_uint_32)65535L;
  189353. length = (png_uint_32)65535L;
  189354. }
  189355. #endif
  189356. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189357. (png_charp)png_ptr->chunk_name, 5);
  189358. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189359. png_ptr->unknown_chunk.size = (png_size_t)length;
  189360. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189361. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189362. if(png_ptr->read_user_chunk_fn != NULL)
  189363. {
  189364. /* callback to user unknown chunk handler */
  189365. int ret;
  189366. ret = (*(png_ptr->read_user_chunk_fn))
  189367. (png_ptr, &png_ptr->unknown_chunk);
  189368. if (ret < 0)
  189369. png_chunk_error(png_ptr, "error in user chunk");
  189370. if (ret == 0)
  189371. {
  189372. if (!(png_ptr->chunk_name[0] & 0x20))
  189373. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189374. PNG_HANDLE_CHUNK_ALWAYS)
  189375. png_chunk_error(png_ptr, "unknown critical chunk");
  189376. png_set_unknown_chunks(png_ptr, info_ptr,
  189377. &png_ptr->unknown_chunk, 1);
  189378. }
  189379. }
  189380. #else
  189381. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189382. #endif
  189383. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189384. png_ptr->unknown_chunk.data = NULL;
  189385. }
  189386. else
  189387. #endif
  189388. skip=length;
  189389. png_push_crc_skip(png_ptr, skip);
  189390. }
  189391. void /* PRIVATE */
  189392. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189393. {
  189394. if (png_ptr->info_fn != NULL)
  189395. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189396. }
  189397. void /* PRIVATE */
  189398. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189399. {
  189400. if (png_ptr->end_fn != NULL)
  189401. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189402. }
  189403. void /* PRIVATE */
  189404. png_push_have_row(png_structp png_ptr, png_bytep row)
  189405. {
  189406. if (png_ptr->row_fn != NULL)
  189407. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189408. (int)png_ptr->pass);
  189409. }
  189410. void PNGAPI
  189411. png_progressive_combine_row (png_structp png_ptr,
  189412. png_bytep old_row, png_bytep new_row)
  189413. {
  189414. #ifdef PNG_USE_LOCAL_ARRAYS
  189415. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189416. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189417. #endif
  189418. if(png_ptr == NULL) return;
  189419. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189420. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189421. }
  189422. void PNGAPI
  189423. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189424. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189425. png_progressive_end_ptr end_fn)
  189426. {
  189427. if(png_ptr == NULL) return;
  189428. png_ptr->info_fn = info_fn;
  189429. png_ptr->row_fn = row_fn;
  189430. png_ptr->end_fn = end_fn;
  189431. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189432. }
  189433. png_voidp PNGAPI
  189434. png_get_progressive_ptr(png_structp png_ptr)
  189435. {
  189436. if(png_ptr == NULL) return (NULL);
  189437. return png_ptr->io_ptr;
  189438. }
  189439. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189440. /*** End of inlined file: pngpread.c ***/
  189441. /*** Start of inlined file: pngrio.c ***/
  189442. /* pngrio.c - functions for data input
  189443. *
  189444. * Last changed in libpng 1.2.13 November 13, 2006
  189445. * For conditions of distribution and use, see copyright notice in png.h
  189446. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189447. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189448. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189449. *
  189450. * This file provides a location for all input. Users who need
  189451. * special handling are expected to write a function that has the same
  189452. * arguments as this and performs a similar function, but that possibly
  189453. * has a different input method. Note that you shouldn't change this
  189454. * function, but rather write a replacement function and then make
  189455. * libpng use it at run time with png_set_read_fn(...).
  189456. */
  189457. #define PNG_INTERNAL
  189458. #if defined(PNG_READ_SUPPORTED)
  189459. /* Read the data from whatever input you are using. The default routine
  189460. reads from a file pointer. Note that this routine sometimes gets called
  189461. with very small lengths, so you should implement some kind of simple
  189462. buffering if you are using unbuffered reads. This should never be asked
  189463. to read more then 64K on a 16 bit machine. */
  189464. void /* PRIVATE */
  189465. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189466. {
  189467. png_debug1(4,"reading %d bytes\n", (int)length);
  189468. if (png_ptr->read_data_fn != NULL)
  189469. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189470. else
  189471. png_error(png_ptr, "Call to NULL read function");
  189472. }
  189473. #if !defined(PNG_NO_STDIO)
  189474. /* This is the function that does the actual reading of data. If you are
  189475. not reading from a standard C stream, you should create a replacement
  189476. read_data function and use it at run time with png_set_read_fn(), rather
  189477. than changing the library. */
  189478. #ifndef USE_FAR_KEYWORD
  189479. void PNGAPI
  189480. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189481. {
  189482. png_size_t check;
  189483. if(png_ptr == NULL) return;
  189484. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189485. * instead of an int, which is what fread() actually returns.
  189486. */
  189487. #if defined(_WIN32_WCE)
  189488. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189489. check = 0;
  189490. #else
  189491. check = (png_size_t)fread(data, (png_size_t)1, length,
  189492. (png_FILE_p)png_ptr->io_ptr);
  189493. #endif
  189494. if (check != length)
  189495. png_error(png_ptr, "Read Error");
  189496. }
  189497. #else
  189498. /* this is the model-independent version. Since the standard I/O library
  189499. can't handle far buffers in the medium and small models, we have to copy
  189500. the data.
  189501. */
  189502. #define NEAR_BUF_SIZE 1024
  189503. #define MIN(a,b) (a <= b ? a : b)
  189504. static void PNGAPI
  189505. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189506. {
  189507. int check;
  189508. png_byte *n_data;
  189509. png_FILE_p io_ptr;
  189510. if(png_ptr == NULL) return;
  189511. /* Check if data really is near. If so, use usual code. */
  189512. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189513. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189514. if ((png_bytep)n_data == data)
  189515. {
  189516. #if defined(_WIN32_WCE)
  189517. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189518. check = 0;
  189519. #else
  189520. check = fread(n_data, 1, length, io_ptr);
  189521. #endif
  189522. }
  189523. else
  189524. {
  189525. png_byte buf[NEAR_BUF_SIZE];
  189526. png_size_t read, remaining, err;
  189527. check = 0;
  189528. remaining = length;
  189529. do
  189530. {
  189531. read = MIN(NEAR_BUF_SIZE, remaining);
  189532. #if defined(_WIN32_WCE)
  189533. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189534. err = 0;
  189535. #else
  189536. err = fread(buf, (png_size_t)1, read, io_ptr);
  189537. #endif
  189538. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189539. if(err != read)
  189540. break;
  189541. else
  189542. check += err;
  189543. data += read;
  189544. remaining -= read;
  189545. }
  189546. while (remaining != 0);
  189547. }
  189548. if ((png_uint_32)check != (png_uint_32)length)
  189549. png_error(png_ptr, "read Error");
  189550. }
  189551. #endif
  189552. #endif
  189553. /* This function allows the application to supply a new input function
  189554. for libpng if standard C streams aren't being used.
  189555. This function takes as its arguments:
  189556. png_ptr - pointer to a png input data structure
  189557. io_ptr - pointer to user supplied structure containing info about
  189558. the input functions. May be NULL.
  189559. read_data_fn - pointer to a new input function that takes as its
  189560. arguments a pointer to a png_struct, a pointer to
  189561. a location where input data can be stored, and a 32-bit
  189562. unsigned int that is the number of bytes to be read.
  189563. To exit and output any fatal error messages the new write
  189564. function should call png_error(png_ptr, "Error msg"). */
  189565. void PNGAPI
  189566. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189567. png_rw_ptr read_data_fn)
  189568. {
  189569. if(png_ptr == NULL) return;
  189570. png_ptr->io_ptr = io_ptr;
  189571. #if !defined(PNG_NO_STDIO)
  189572. if (read_data_fn != NULL)
  189573. png_ptr->read_data_fn = read_data_fn;
  189574. else
  189575. png_ptr->read_data_fn = png_default_read_data;
  189576. #else
  189577. png_ptr->read_data_fn = read_data_fn;
  189578. #endif
  189579. /* It is an error to write to a read device */
  189580. if (png_ptr->write_data_fn != NULL)
  189581. {
  189582. png_ptr->write_data_fn = NULL;
  189583. png_warning(png_ptr,
  189584. "It's an error to set both read_data_fn and write_data_fn in the ");
  189585. png_warning(png_ptr,
  189586. "same structure. Resetting write_data_fn to NULL.");
  189587. }
  189588. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189589. png_ptr->output_flush_fn = NULL;
  189590. #endif
  189591. }
  189592. #endif /* PNG_READ_SUPPORTED */
  189593. /*** End of inlined file: pngrio.c ***/
  189594. /*** Start of inlined file: pngrtran.c ***/
  189595. /* pngrtran.c - transforms the data in a row for PNG readers
  189596. *
  189597. * Last changed in libpng 1.2.21 [October 4, 2007]
  189598. * For conditions of distribution and use, see copyright notice in png.h
  189599. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189600. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189601. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189602. *
  189603. * This file contains functions optionally called by an application
  189604. * in order to tell libpng how to handle data when reading a PNG.
  189605. * Transformations that are used in both reading and writing are
  189606. * in pngtrans.c.
  189607. */
  189608. #define PNG_INTERNAL
  189609. #if defined(PNG_READ_SUPPORTED)
  189610. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189611. void PNGAPI
  189612. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189613. {
  189614. png_debug(1, "in png_set_crc_action\n");
  189615. /* Tell libpng how we react to CRC errors in critical chunks */
  189616. if(png_ptr == NULL) return;
  189617. switch (crit_action)
  189618. {
  189619. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189620. break;
  189621. case PNG_CRC_WARN_USE: /* warn/use data */
  189622. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189623. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189624. break;
  189625. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189626. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189627. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189628. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189629. break;
  189630. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189631. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189632. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189633. case PNG_CRC_DEFAULT:
  189634. default:
  189635. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189636. break;
  189637. }
  189638. switch (ancil_action)
  189639. {
  189640. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189641. break;
  189642. case PNG_CRC_WARN_USE: /* warn/use data */
  189643. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189644. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189645. break;
  189646. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189647. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189648. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189649. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189650. break;
  189651. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189652. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189653. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189654. break;
  189655. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189656. case PNG_CRC_DEFAULT:
  189657. default:
  189658. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189659. break;
  189660. }
  189661. }
  189662. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189663. defined(PNG_FLOATING_POINT_SUPPORTED)
  189664. /* handle alpha and tRNS via a background color */
  189665. void PNGAPI
  189666. png_set_background(png_structp png_ptr,
  189667. png_color_16p background_color, int background_gamma_code,
  189668. int need_expand, double background_gamma)
  189669. {
  189670. png_debug(1, "in png_set_background\n");
  189671. if(png_ptr == NULL) return;
  189672. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189673. {
  189674. png_warning(png_ptr, "Application must supply a known background gamma");
  189675. return;
  189676. }
  189677. png_ptr->transformations |= PNG_BACKGROUND;
  189678. png_memcpy(&(png_ptr->background), background_color,
  189679. png_sizeof(png_color_16));
  189680. png_ptr->background_gamma = (float)background_gamma;
  189681. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189682. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189683. }
  189684. #endif
  189685. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189686. /* strip 16 bit depth files to 8 bit depth */
  189687. void PNGAPI
  189688. png_set_strip_16(png_structp png_ptr)
  189689. {
  189690. png_debug(1, "in png_set_strip_16\n");
  189691. if(png_ptr == NULL) return;
  189692. png_ptr->transformations |= PNG_16_TO_8;
  189693. }
  189694. #endif
  189695. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189696. void PNGAPI
  189697. png_set_strip_alpha(png_structp png_ptr)
  189698. {
  189699. png_debug(1, "in png_set_strip_alpha\n");
  189700. if(png_ptr == NULL) return;
  189701. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189702. }
  189703. #endif
  189704. #if defined(PNG_READ_DITHER_SUPPORTED)
  189705. /* Dither file to 8 bit. Supply a palette, the current number
  189706. * of elements in the palette, the maximum number of elements
  189707. * allowed, and a histogram if possible. If the current number
  189708. * of colors is greater then the maximum number, the palette will be
  189709. * modified to fit in the maximum number. "full_dither" indicates
  189710. * whether we need a dithering cube set up for RGB images, or if we
  189711. * simply are reducing the number of colors in a paletted image.
  189712. */
  189713. typedef struct png_dsort_struct
  189714. {
  189715. struct png_dsort_struct FAR * next;
  189716. png_byte left;
  189717. png_byte right;
  189718. } png_dsort;
  189719. typedef png_dsort FAR * png_dsortp;
  189720. typedef png_dsort FAR * FAR * png_dsortpp;
  189721. void PNGAPI
  189722. png_set_dither(png_structp png_ptr, png_colorp palette,
  189723. int num_palette, int maximum_colors, png_uint_16p histogram,
  189724. int full_dither)
  189725. {
  189726. png_debug(1, "in png_set_dither\n");
  189727. if(png_ptr == NULL) return;
  189728. png_ptr->transformations |= PNG_DITHER;
  189729. if (!full_dither)
  189730. {
  189731. int i;
  189732. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189733. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189734. for (i = 0; i < num_palette; i++)
  189735. png_ptr->dither_index[i] = (png_byte)i;
  189736. }
  189737. if (num_palette > maximum_colors)
  189738. {
  189739. if (histogram != NULL)
  189740. {
  189741. /* This is easy enough, just throw out the least used colors.
  189742. Perhaps not the best solution, but good enough. */
  189743. int i;
  189744. /* initialize an array to sort colors */
  189745. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189746. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189747. /* initialize the dither_sort array */
  189748. for (i = 0; i < num_palette; i++)
  189749. png_ptr->dither_sort[i] = (png_byte)i;
  189750. /* Find the least used palette entries by starting a
  189751. bubble sort, and running it until we have sorted
  189752. out enough colors. Note that we don't care about
  189753. sorting all the colors, just finding which are
  189754. least used. */
  189755. for (i = num_palette - 1; i >= maximum_colors; i--)
  189756. {
  189757. int done; /* to stop early if the list is pre-sorted */
  189758. int j;
  189759. done = 1;
  189760. for (j = 0; j < i; j++)
  189761. {
  189762. if (histogram[png_ptr->dither_sort[j]]
  189763. < histogram[png_ptr->dither_sort[j + 1]])
  189764. {
  189765. png_byte t;
  189766. t = png_ptr->dither_sort[j];
  189767. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189768. png_ptr->dither_sort[j + 1] = t;
  189769. done = 0;
  189770. }
  189771. }
  189772. if (done)
  189773. break;
  189774. }
  189775. /* swap the palette around, and set up a table, if necessary */
  189776. if (full_dither)
  189777. {
  189778. int j = num_palette;
  189779. /* put all the useful colors within the max, but don't
  189780. move the others */
  189781. for (i = 0; i < maximum_colors; i++)
  189782. {
  189783. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189784. {
  189785. do
  189786. j--;
  189787. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189788. palette[i] = palette[j];
  189789. }
  189790. }
  189791. }
  189792. else
  189793. {
  189794. int j = num_palette;
  189795. /* move all the used colors inside the max limit, and
  189796. develop a translation table */
  189797. for (i = 0; i < maximum_colors; i++)
  189798. {
  189799. /* only move the colors we need to */
  189800. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189801. {
  189802. png_color tmp_color;
  189803. do
  189804. j--;
  189805. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189806. tmp_color = palette[j];
  189807. palette[j] = palette[i];
  189808. palette[i] = tmp_color;
  189809. /* indicate where the color went */
  189810. png_ptr->dither_index[j] = (png_byte)i;
  189811. png_ptr->dither_index[i] = (png_byte)j;
  189812. }
  189813. }
  189814. /* find closest color for those colors we are not using */
  189815. for (i = 0; i < num_palette; i++)
  189816. {
  189817. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189818. {
  189819. int min_d, k, min_k, d_index;
  189820. /* find the closest color to one we threw out */
  189821. d_index = png_ptr->dither_index[i];
  189822. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189823. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189824. {
  189825. int d;
  189826. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189827. if (d < min_d)
  189828. {
  189829. min_d = d;
  189830. min_k = k;
  189831. }
  189832. }
  189833. /* point to closest color */
  189834. png_ptr->dither_index[i] = (png_byte)min_k;
  189835. }
  189836. }
  189837. }
  189838. png_free(png_ptr, png_ptr->dither_sort);
  189839. png_ptr->dither_sort=NULL;
  189840. }
  189841. else
  189842. {
  189843. /* This is much harder to do simply (and quickly). Perhaps
  189844. we need to go through a median cut routine, but those
  189845. don't always behave themselves with only a few colors
  189846. as input. So we will just find the closest two colors,
  189847. and throw out one of them (chosen somewhat randomly).
  189848. [We don't understand this at all, so if someone wants to
  189849. work on improving it, be our guest - AED, GRP]
  189850. */
  189851. int i;
  189852. int max_d;
  189853. int num_new_palette;
  189854. png_dsortp t;
  189855. png_dsortpp hash;
  189856. t=NULL;
  189857. /* initialize palette index arrays */
  189858. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189859. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189860. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189861. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189862. /* initialize the sort array */
  189863. for (i = 0; i < num_palette; i++)
  189864. {
  189865. png_ptr->index_to_palette[i] = (png_byte)i;
  189866. png_ptr->palette_to_index[i] = (png_byte)i;
  189867. }
  189868. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189869. png_sizeof (png_dsortp)));
  189870. for (i = 0; i < 769; i++)
  189871. hash[i] = NULL;
  189872. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189873. num_new_palette = num_palette;
  189874. /* initial wild guess at how far apart the farthest pixel
  189875. pair we will be eliminating will be. Larger
  189876. numbers mean more areas will be allocated, Smaller
  189877. numbers run the risk of not saving enough data, and
  189878. having to do this all over again.
  189879. I have not done extensive checking on this number.
  189880. */
  189881. max_d = 96;
  189882. while (num_new_palette > maximum_colors)
  189883. {
  189884. for (i = 0; i < num_new_palette - 1; i++)
  189885. {
  189886. int j;
  189887. for (j = i + 1; j < num_new_palette; j++)
  189888. {
  189889. int d;
  189890. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189891. if (d <= max_d)
  189892. {
  189893. t = (png_dsortp)png_malloc_warn(png_ptr,
  189894. (png_uint_32)(png_sizeof(png_dsort)));
  189895. if (t == NULL)
  189896. break;
  189897. t->next = hash[d];
  189898. t->left = (png_byte)i;
  189899. t->right = (png_byte)j;
  189900. hash[d] = t;
  189901. }
  189902. }
  189903. if (t == NULL)
  189904. break;
  189905. }
  189906. if (t != NULL)
  189907. for (i = 0; i <= max_d; i++)
  189908. {
  189909. if (hash[i] != NULL)
  189910. {
  189911. png_dsortp p;
  189912. for (p = hash[i]; p; p = p->next)
  189913. {
  189914. if ((int)png_ptr->index_to_palette[p->left]
  189915. < num_new_palette &&
  189916. (int)png_ptr->index_to_palette[p->right]
  189917. < num_new_palette)
  189918. {
  189919. int j, next_j;
  189920. if (num_new_palette & 0x01)
  189921. {
  189922. j = p->left;
  189923. next_j = p->right;
  189924. }
  189925. else
  189926. {
  189927. j = p->right;
  189928. next_j = p->left;
  189929. }
  189930. num_new_palette--;
  189931. palette[png_ptr->index_to_palette[j]]
  189932. = palette[num_new_palette];
  189933. if (!full_dither)
  189934. {
  189935. int k;
  189936. for (k = 0; k < num_palette; k++)
  189937. {
  189938. if (png_ptr->dither_index[k] ==
  189939. png_ptr->index_to_palette[j])
  189940. png_ptr->dither_index[k] =
  189941. png_ptr->index_to_palette[next_j];
  189942. if ((int)png_ptr->dither_index[k] ==
  189943. num_new_palette)
  189944. png_ptr->dither_index[k] =
  189945. png_ptr->index_to_palette[j];
  189946. }
  189947. }
  189948. png_ptr->index_to_palette[png_ptr->palette_to_index
  189949. [num_new_palette]] = png_ptr->index_to_palette[j];
  189950. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189951. = png_ptr->palette_to_index[num_new_palette];
  189952. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189953. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189954. }
  189955. if (num_new_palette <= maximum_colors)
  189956. break;
  189957. }
  189958. if (num_new_palette <= maximum_colors)
  189959. break;
  189960. }
  189961. }
  189962. for (i = 0; i < 769; i++)
  189963. {
  189964. if (hash[i] != NULL)
  189965. {
  189966. png_dsortp p = hash[i];
  189967. while (p)
  189968. {
  189969. t = p->next;
  189970. png_free(png_ptr, p);
  189971. p = t;
  189972. }
  189973. }
  189974. hash[i] = 0;
  189975. }
  189976. max_d += 96;
  189977. }
  189978. png_free(png_ptr, hash);
  189979. png_free(png_ptr, png_ptr->palette_to_index);
  189980. png_free(png_ptr, png_ptr->index_to_palette);
  189981. png_ptr->palette_to_index=NULL;
  189982. png_ptr->index_to_palette=NULL;
  189983. }
  189984. num_palette = maximum_colors;
  189985. }
  189986. if (png_ptr->palette == NULL)
  189987. {
  189988. png_ptr->palette = palette;
  189989. }
  189990. png_ptr->num_palette = (png_uint_16)num_palette;
  189991. if (full_dither)
  189992. {
  189993. int i;
  189994. png_bytep distance;
  189995. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189996. PNG_DITHER_BLUE_BITS;
  189997. int num_red = (1 << PNG_DITHER_RED_BITS);
  189998. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189999. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190000. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190001. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190002. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190003. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190004. png_sizeof (png_byte));
  190005. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190006. png_sizeof(png_byte)));
  190007. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190008. for (i = 0; i < num_palette; i++)
  190009. {
  190010. int ir, ig, ib;
  190011. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190012. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190013. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190014. for (ir = 0; ir < num_red; ir++)
  190015. {
  190016. /* int dr = abs(ir - r); */
  190017. int dr = ((ir > r) ? ir - r : r - ir);
  190018. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190019. for (ig = 0; ig < num_green; ig++)
  190020. {
  190021. /* int dg = abs(ig - g); */
  190022. int dg = ((ig > g) ? ig - g : g - ig);
  190023. int dt = dr + dg;
  190024. int dm = ((dr > dg) ? dr : dg);
  190025. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190026. for (ib = 0; ib < num_blue; ib++)
  190027. {
  190028. int d_index = index_g | ib;
  190029. /* int db = abs(ib - b); */
  190030. int db = ((ib > b) ? ib - b : b - ib);
  190031. int dmax = ((dm > db) ? dm : db);
  190032. int d = dmax + dt + db;
  190033. if (d < (int)distance[d_index])
  190034. {
  190035. distance[d_index] = (png_byte)d;
  190036. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190037. }
  190038. }
  190039. }
  190040. }
  190041. }
  190042. png_free(png_ptr, distance);
  190043. }
  190044. }
  190045. #endif
  190046. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190047. /* Transform the image from the file_gamma to the screen_gamma. We
  190048. * only do transformations on images where the file_gamma and screen_gamma
  190049. * are not close reciprocals, otherwise it slows things down slightly, and
  190050. * also needlessly introduces small errors.
  190051. *
  190052. * We will turn off gamma transformation later if no semitransparent entries
  190053. * are present in the tRNS array for palette images. We can't do it here
  190054. * because we don't necessarily have the tRNS chunk yet.
  190055. */
  190056. void PNGAPI
  190057. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190058. {
  190059. png_debug(1, "in png_set_gamma\n");
  190060. if(png_ptr == NULL) return;
  190061. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190062. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190063. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190064. png_ptr->transformations |= PNG_GAMMA;
  190065. png_ptr->gamma = (float)file_gamma;
  190066. png_ptr->screen_gamma = (float)scrn_gamma;
  190067. }
  190068. #endif
  190069. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190070. /* Expand paletted images to RGB, expand grayscale images of
  190071. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190072. * to alpha channels.
  190073. */
  190074. void PNGAPI
  190075. png_set_expand(png_structp png_ptr)
  190076. {
  190077. png_debug(1, "in png_set_expand\n");
  190078. if(png_ptr == NULL) return;
  190079. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190080. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190081. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190082. #endif
  190083. }
  190084. /* GRR 19990627: the following three functions currently are identical
  190085. * to png_set_expand(). However, it is entirely reasonable that someone
  190086. * might wish to expand an indexed image to RGB but *not* expand a single,
  190087. * fully transparent palette entry to a full alpha channel--perhaps instead
  190088. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190089. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190090. * IOW, a future version of the library may make the transformations flag
  190091. * a bit more fine-grained, with separate bits for each of these three
  190092. * functions.
  190093. *
  190094. * More to the point, these functions make it obvious what libpng will be
  190095. * doing, whereas "expand" can (and does) mean any number of things.
  190096. *
  190097. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190098. * to expand only the sample depth but not to expand the tRNS to alpha.
  190099. */
  190100. /* Expand paletted images to RGB. */
  190101. void PNGAPI
  190102. png_set_palette_to_rgb(png_structp png_ptr)
  190103. {
  190104. png_debug(1, "in png_set_palette_to_rgb\n");
  190105. if(png_ptr == NULL) return;
  190106. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190107. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190108. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190109. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190110. #endif
  190111. }
  190112. #if !defined(PNG_1_0_X)
  190113. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190114. void PNGAPI
  190115. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190116. {
  190117. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190118. if(png_ptr == NULL) return;
  190119. png_ptr->transformations |= PNG_EXPAND;
  190120. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190121. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190122. #endif
  190123. }
  190124. #endif
  190125. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190126. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190127. /* Deprecated as of libpng-1.2.9 */
  190128. void PNGAPI
  190129. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190130. {
  190131. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190132. if(png_ptr == NULL) return;
  190133. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190134. }
  190135. #endif
  190136. /* Expand tRNS chunks to alpha channels. */
  190137. void PNGAPI
  190138. png_set_tRNS_to_alpha(png_structp png_ptr)
  190139. {
  190140. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190141. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190142. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190143. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190144. #endif
  190145. }
  190146. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190147. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190148. void PNGAPI
  190149. png_set_gray_to_rgb(png_structp png_ptr)
  190150. {
  190151. png_debug(1, "in png_set_gray_to_rgb\n");
  190152. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190153. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190154. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190155. #endif
  190156. }
  190157. #endif
  190158. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190159. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190160. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190161. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190162. */
  190163. void PNGAPI
  190164. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190165. double green)
  190166. {
  190167. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190168. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190169. if(png_ptr == NULL) return;
  190170. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190171. }
  190172. #endif
  190173. void PNGAPI
  190174. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190175. png_fixed_point red, png_fixed_point green)
  190176. {
  190177. png_debug(1, "in png_set_rgb_to_gray\n");
  190178. if(png_ptr == NULL) return;
  190179. switch(error_action)
  190180. {
  190181. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190182. break;
  190183. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190184. break;
  190185. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190186. }
  190187. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190188. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190189. png_ptr->transformations |= PNG_EXPAND;
  190190. #else
  190191. {
  190192. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190193. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190194. }
  190195. #endif
  190196. {
  190197. png_uint_16 red_int, green_int;
  190198. if(red < 0 || green < 0)
  190199. {
  190200. red_int = 6968; /* .212671 * 32768 + .5 */
  190201. green_int = 23434; /* .715160 * 32768 + .5 */
  190202. }
  190203. else if(red + green < 100000L)
  190204. {
  190205. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190206. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190207. }
  190208. else
  190209. {
  190210. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190211. red_int = 6968;
  190212. green_int = 23434;
  190213. }
  190214. png_ptr->rgb_to_gray_red_coeff = red_int;
  190215. png_ptr->rgb_to_gray_green_coeff = green_int;
  190216. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190217. }
  190218. }
  190219. #endif
  190220. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190221. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190222. defined(PNG_LEGACY_SUPPORTED)
  190223. void PNGAPI
  190224. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190225. read_user_transform_fn)
  190226. {
  190227. png_debug(1, "in png_set_read_user_transform_fn\n");
  190228. if(png_ptr == NULL) return;
  190229. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190230. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190231. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190232. #endif
  190233. #ifdef PNG_LEGACY_SUPPORTED
  190234. if(read_user_transform_fn)
  190235. png_warning(png_ptr,
  190236. "This version of libpng does not support user transforms");
  190237. #endif
  190238. }
  190239. #endif
  190240. /* Initialize everything needed for the read. This includes modifying
  190241. * the palette.
  190242. */
  190243. void /* PRIVATE */
  190244. png_init_read_transformations(png_structp png_ptr)
  190245. {
  190246. png_debug(1, "in png_init_read_transformations\n");
  190247. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190248. if(png_ptr != NULL)
  190249. #endif
  190250. {
  190251. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190252. || defined(PNG_READ_GAMMA_SUPPORTED)
  190253. int color_type = png_ptr->color_type;
  190254. #endif
  190255. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190256. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190257. /* Detect gray background and attempt to enable optimization
  190258. * for gray --> RGB case */
  190259. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190260. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190261. * background color might actually be gray yet not be flagged as such.
  190262. * This is not a problem for the current code, which uses
  190263. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190264. * png_do_gray_to_rgb() transformation.
  190265. */
  190266. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190267. !(color_type & PNG_COLOR_MASK_COLOR))
  190268. {
  190269. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190270. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190271. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190272. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190273. png_ptr->background.red == png_ptr->background.green &&
  190274. png_ptr->background.red == png_ptr->background.blue)
  190275. {
  190276. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190277. png_ptr->background.gray = png_ptr->background.red;
  190278. }
  190279. #endif
  190280. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190281. (png_ptr->transformations & PNG_EXPAND))
  190282. {
  190283. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190284. {
  190285. /* expand background and tRNS chunks */
  190286. switch (png_ptr->bit_depth)
  190287. {
  190288. case 1:
  190289. png_ptr->background.gray *= (png_uint_16)0xff;
  190290. png_ptr->background.red = png_ptr->background.green
  190291. = png_ptr->background.blue = png_ptr->background.gray;
  190292. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190293. {
  190294. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190295. png_ptr->trans_values.red = png_ptr->trans_values.green
  190296. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190297. }
  190298. break;
  190299. case 2:
  190300. png_ptr->background.gray *= (png_uint_16)0x55;
  190301. png_ptr->background.red = png_ptr->background.green
  190302. = png_ptr->background.blue = png_ptr->background.gray;
  190303. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190304. {
  190305. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190306. png_ptr->trans_values.red = png_ptr->trans_values.green
  190307. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190308. }
  190309. break;
  190310. case 4:
  190311. png_ptr->background.gray *= (png_uint_16)0x11;
  190312. png_ptr->background.red = png_ptr->background.green
  190313. = png_ptr->background.blue = png_ptr->background.gray;
  190314. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190315. {
  190316. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190317. png_ptr->trans_values.red = png_ptr->trans_values.green
  190318. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190319. }
  190320. break;
  190321. case 8:
  190322. case 16:
  190323. png_ptr->background.red = png_ptr->background.green
  190324. = png_ptr->background.blue = png_ptr->background.gray;
  190325. break;
  190326. }
  190327. }
  190328. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190329. {
  190330. png_ptr->background.red =
  190331. png_ptr->palette[png_ptr->background.index].red;
  190332. png_ptr->background.green =
  190333. png_ptr->palette[png_ptr->background.index].green;
  190334. png_ptr->background.blue =
  190335. png_ptr->palette[png_ptr->background.index].blue;
  190336. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190337. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190338. {
  190339. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190340. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190341. #endif
  190342. {
  190343. /* invert the alpha channel (in tRNS) unless the pixels are
  190344. going to be expanded, in which case leave it for later */
  190345. int i,istop;
  190346. istop=(int)png_ptr->num_trans;
  190347. for (i=0; i<istop; i++)
  190348. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190349. }
  190350. }
  190351. #endif
  190352. }
  190353. }
  190354. #endif
  190355. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190356. png_ptr->background_1 = png_ptr->background;
  190357. #endif
  190358. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190359. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190360. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190361. < PNG_GAMMA_THRESHOLD))
  190362. {
  190363. int i,k;
  190364. k=0;
  190365. for (i=0; i<png_ptr->num_trans; i++)
  190366. {
  190367. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190368. k=1; /* partial transparency is present */
  190369. }
  190370. if (k == 0)
  190371. png_ptr->transformations &= (~PNG_GAMMA);
  190372. }
  190373. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190374. png_ptr->gamma != 0.0)
  190375. {
  190376. png_build_gamma_table(png_ptr);
  190377. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190378. if (png_ptr->transformations & PNG_BACKGROUND)
  190379. {
  190380. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190381. {
  190382. /* could skip if no transparency and
  190383. */
  190384. png_color back, back_1;
  190385. png_colorp palette = png_ptr->palette;
  190386. int num_palette = png_ptr->num_palette;
  190387. int i;
  190388. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190389. {
  190390. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190391. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190392. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190393. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190394. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190395. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190396. }
  190397. else
  190398. {
  190399. double g, gs;
  190400. switch (png_ptr->background_gamma_type)
  190401. {
  190402. case PNG_BACKGROUND_GAMMA_SCREEN:
  190403. g = (png_ptr->screen_gamma);
  190404. gs = 1.0;
  190405. break;
  190406. case PNG_BACKGROUND_GAMMA_FILE:
  190407. g = 1.0 / (png_ptr->gamma);
  190408. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190409. break;
  190410. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190411. g = 1.0 / (png_ptr->background_gamma);
  190412. gs = 1.0 / (png_ptr->background_gamma *
  190413. png_ptr->screen_gamma);
  190414. break;
  190415. default:
  190416. g = 1.0; /* back_1 */
  190417. gs = 1.0; /* back */
  190418. }
  190419. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190420. {
  190421. back.red = (png_byte)png_ptr->background.red;
  190422. back.green = (png_byte)png_ptr->background.green;
  190423. back.blue = (png_byte)png_ptr->background.blue;
  190424. }
  190425. else
  190426. {
  190427. back.red = (png_byte)(pow(
  190428. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190429. back.green = (png_byte)(pow(
  190430. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190431. back.blue = (png_byte)(pow(
  190432. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190433. }
  190434. back_1.red = (png_byte)(pow(
  190435. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190436. back_1.green = (png_byte)(pow(
  190437. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190438. back_1.blue = (png_byte)(pow(
  190439. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190440. }
  190441. for (i = 0; i < num_palette; i++)
  190442. {
  190443. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190444. {
  190445. if (png_ptr->trans[i] == 0)
  190446. {
  190447. palette[i] = back;
  190448. }
  190449. else /* if (png_ptr->trans[i] != 0xff) */
  190450. {
  190451. png_byte v, w;
  190452. v = png_ptr->gamma_to_1[palette[i].red];
  190453. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190454. palette[i].red = png_ptr->gamma_from_1[w];
  190455. v = png_ptr->gamma_to_1[palette[i].green];
  190456. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190457. palette[i].green = png_ptr->gamma_from_1[w];
  190458. v = png_ptr->gamma_to_1[palette[i].blue];
  190459. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190460. palette[i].blue = png_ptr->gamma_from_1[w];
  190461. }
  190462. }
  190463. else
  190464. {
  190465. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190466. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190467. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190468. }
  190469. }
  190470. }
  190471. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190472. else
  190473. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190474. {
  190475. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190476. double g = 1.0;
  190477. double gs = 1.0;
  190478. switch (png_ptr->background_gamma_type)
  190479. {
  190480. case PNG_BACKGROUND_GAMMA_SCREEN:
  190481. g = (png_ptr->screen_gamma);
  190482. gs = 1.0;
  190483. break;
  190484. case PNG_BACKGROUND_GAMMA_FILE:
  190485. g = 1.0 / (png_ptr->gamma);
  190486. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190487. break;
  190488. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190489. g = 1.0 / (png_ptr->background_gamma);
  190490. gs = 1.0 / (png_ptr->background_gamma *
  190491. png_ptr->screen_gamma);
  190492. break;
  190493. }
  190494. png_ptr->background_1.gray = (png_uint_16)(pow(
  190495. (double)png_ptr->background.gray / m, g) * m + .5);
  190496. png_ptr->background.gray = (png_uint_16)(pow(
  190497. (double)png_ptr->background.gray / m, gs) * m + .5);
  190498. if ((png_ptr->background.red != png_ptr->background.green) ||
  190499. (png_ptr->background.red != png_ptr->background.blue) ||
  190500. (png_ptr->background.red != png_ptr->background.gray))
  190501. {
  190502. /* RGB or RGBA with color background */
  190503. png_ptr->background_1.red = (png_uint_16)(pow(
  190504. (double)png_ptr->background.red / m, g) * m + .5);
  190505. png_ptr->background_1.green = (png_uint_16)(pow(
  190506. (double)png_ptr->background.green / m, g) * m + .5);
  190507. png_ptr->background_1.blue = (png_uint_16)(pow(
  190508. (double)png_ptr->background.blue / m, g) * m + .5);
  190509. png_ptr->background.red = (png_uint_16)(pow(
  190510. (double)png_ptr->background.red / m, gs) * m + .5);
  190511. png_ptr->background.green = (png_uint_16)(pow(
  190512. (double)png_ptr->background.green / m, gs) * m + .5);
  190513. png_ptr->background.blue = (png_uint_16)(pow(
  190514. (double)png_ptr->background.blue / m, gs) * m + .5);
  190515. }
  190516. else
  190517. {
  190518. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190519. png_ptr->background_1.red = png_ptr->background_1.green
  190520. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190521. png_ptr->background.red = png_ptr->background.green
  190522. = png_ptr->background.blue = png_ptr->background.gray;
  190523. }
  190524. }
  190525. }
  190526. else
  190527. /* transformation does not include PNG_BACKGROUND */
  190528. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190529. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190530. {
  190531. png_colorp palette = png_ptr->palette;
  190532. int num_palette = png_ptr->num_palette;
  190533. int i;
  190534. for (i = 0; i < num_palette; i++)
  190535. {
  190536. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190537. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190538. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190539. }
  190540. }
  190541. }
  190542. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190543. else
  190544. #endif
  190545. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190546. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190547. /* No GAMMA transformation */
  190548. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190549. (color_type == PNG_COLOR_TYPE_PALETTE))
  190550. {
  190551. int i;
  190552. int istop = (int)png_ptr->num_trans;
  190553. png_color back;
  190554. png_colorp palette = png_ptr->palette;
  190555. back.red = (png_byte)png_ptr->background.red;
  190556. back.green = (png_byte)png_ptr->background.green;
  190557. back.blue = (png_byte)png_ptr->background.blue;
  190558. for (i = 0; i < istop; i++)
  190559. {
  190560. if (png_ptr->trans[i] == 0)
  190561. {
  190562. palette[i] = back;
  190563. }
  190564. else if (png_ptr->trans[i] != 0xff)
  190565. {
  190566. /* The png_composite() macro is defined in png.h */
  190567. png_composite(palette[i].red, palette[i].red,
  190568. png_ptr->trans[i], back.red);
  190569. png_composite(palette[i].green, palette[i].green,
  190570. png_ptr->trans[i], back.green);
  190571. png_composite(palette[i].blue, palette[i].blue,
  190572. png_ptr->trans[i], back.blue);
  190573. }
  190574. }
  190575. }
  190576. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190577. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190578. if ((png_ptr->transformations & PNG_SHIFT) &&
  190579. (color_type == PNG_COLOR_TYPE_PALETTE))
  190580. {
  190581. png_uint_16 i;
  190582. png_uint_16 istop = png_ptr->num_palette;
  190583. int sr = 8 - png_ptr->sig_bit.red;
  190584. int sg = 8 - png_ptr->sig_bit.green;
  190585. int sb = 8 - png_ptr->sig_bit.blue;
  190586. if (sr < 0 || sr > 8)
  190587. sr = 0;
  190588. if (sg < 0 || sg > 8)
  190589. sg = 0;
  190590. if (sb < 0 || sb > 8)
  190591. sb = 0;
  190592. for (i = 0; i < istop; i++)
  190593. {
  190594. png_ptr->palette[i].red >>= sr;
  190595. png_ptr->palette[i].green >>= sg;
  190596. png_ptr->palette[i].blue >>= sb;
  190597. }
  190598. }
  190599. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190600. }
  190601. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190602. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190603. if(png_ptr)
  190604. return;
  190605. #endif
  190606. }
  190607. /* Modify the info structure to reflect the transformations. The
  190608. * info should be updated so a PNG file could be written with it,
  190609. * assuming the transformations result in valid PNG data.
  190610. */
  190611. void /* PRIVATE */
  190612. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190613. {
  190614. png_debug(1, "in png_read_transform_info\n");
  190615. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190616. if (png_ptr->transformations & PNG_EXPAND)
  190617. {
  190618. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190619. {
  190620. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190621. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190622. else
  190623. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190624. info_ptr->bit_depth = 8;
  190625. info_ptr->num_trans = 0;
  190626. }
  190627. else
  190628. {
  190629. if (png_ptr->num_trans)
  190630. {
  190631. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190632. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190633. else
  190634. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190635. }
  190636. if (info_ptr->bit_depth < 8)
  190637. info_ptr->bit_depth = 8;
  190638. info_ptr->num_trans = 0;
  190639. }
  190640. }
  190641. #endif
  190642. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190643. if (png_ptr->transformations & PNG_BACKGROUND)
  190644. {
  190645. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190646. info_ptr->num_trans = 0;
  190647. info_ptr->background = png_ptr->background;
  190648. }
  190649. #endif
  190650. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190651. if (png_ptr->transformations & PNG_GAMMA)
  190652. {
  190653. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190654. info_ptr->gamma = png_ptr->gamma;
  190655. #endif
  190656. #ifdef PNG_FIXED_POINT_SUPPORTED
  190657. info_ptr->int_gamma = png_ptr->int_gamma;
  190658. #endif
  190659. }
  190660. #endif
  190661. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190662. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190663. info_ptr->bit_depth = 8;
  190664. #endif
  190665. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190666. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190667. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190668. #endif
  190669. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190670. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190671. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190672. #endif
  190673. #if defined(PNG_READ_DITHER_SUPPORTED)
  190674. if (png_ptr->transformations & PNG_DITHER)
  190675. {
  190676. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190677. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190678. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190679. {
  190680. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190681. }
  190682. }
  190683. #endif
  190684. #if defined(PNG_READ_PACK_SUPPORTED)
  190685. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190686. info_ptr->bit_depth = 8;
  190687. #endif
  190688. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190689. info_ptr->channels = 1;
  190690. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190691. info_ptr->channels = 3;
  190692. else
  190693. info_ptr->channels = 1;
  190694. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190695. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190696. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190697. #endif
  190698. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190699. info_ptr->channels++;
  190700. #if defined(PNG_READ_FILLER_SUPPORTED)
  190701. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190702. if ((png_ptr->transformations & PNG_FILLER) &&
  190703. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190704. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190705. {
  190706. info_ptr->channels++;
  190707. /* if adding a true alpha channel not just filler */
  190708. #if !defined(PNG_1_0_X)
  190709. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190710. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190711. #endif
  190712. }
  190713. #endif
  190714. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190715. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190716. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190717. {
  190718. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190719. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190720. if(info_ptr->channels < png_ptr->user_transform_channels)
  190721. info_ptr->channels = png_ptr->user_transform_channels;
  190722. }
  190723. #endif
  190724. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190725. info_ptr->bit_depth);
  190726. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190727. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190728. if(png_ptr)
  190729. return;
  190730. #endif
  190731. }
  190732. /* Transform the row. The order of transformations is significant,
  190733. * and is very touchy. If you add a transformation, take care to
  190734. * decide how it fits in with the other transformations here.
  190735. */
  190736. void /* PRIVATE */
  190737. png_do_read_transformations(png_structp png_ptr)
  190738. {
  190739. png_debug(1, "in png_do_read_transformations\n");
  190740. if (png_ptr->row_buf == NULL)
  190741. {
  190742. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190743. char msg[50];
  190744. png_snprintf2(msg, 50,
  190745. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190746. png_ptr->pass);
  190747. png_error(png_ptr, msg);
  190748. #else
  190749. png_error(png_ptr, "NULL row buffer");
  190750. #endif
  190751. }
  190752. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190753. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190754. /* Application has failed to call either png_read_start_image()
  190755. * or png_read_update_info() after setting transforms that expand
  190756. * pixels. This check added to libpng-1.2.19 */
  190757. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190758. png_error(png_ptr, "Uninitialized row");
  190759. #else
  190760. png_warning(png_ptr, "Uninitialized row");
  190761. #endif
  190762. #endif
  190763. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190764. if (png_ptr->transformations & PNG_EXPAND)
  190765. {
  190766. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190767. {
  190768. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190769. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190770. }
  190771. else
  190772. {
  190773. if (png_ptr->num_trans &&
  190774. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190775. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190776. &(png_ptr->trans_values));
  190777. else
  190778. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190779. NULL);
  190780. }
  190781. }
  190782. #endif
  190783. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190784. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190785. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190786. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190787. #endif
  190788. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190789. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190790. {
  190791. int rgb_error =
  190792. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190793. if(rgb_error)
  190794. {
  190795. png_ptr->rgb_to_gray_status=1;
  190796. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190797. PNG_RGB_TO_GRAY_WARN)
  190798. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190799. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190800. PNG_RGB_TO_GRAY_ERR)
  190801. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190802. }
  190803. }
  190804. #endif
  190805. /*
  190806. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190807. In most cases, the "simple transparency" should be done prior to doing
  190808. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190809. pixel is transparent. You would also need to make sure that the
  190810. transparency information is upgraded to RGB.
  190811. To summarize, the current flow is:
  190812. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190813. with background "in place" if transparent,
  190814. convert to RGB if necessary
  190815. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190816. convert to RGB if necessary
  190817. To support RGB backgrounds for gray images we need:
  190818. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190819. 3 or 6 bytes and composite with background
  190820. "in place" if transparent (3x compare/pixel
  190821. compared to doing composite with gray bkgrnd)
  190822. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190823. remove alpha bytes (3x float operations/pixel
  190824. compared with composite on gray background)
  190825. Greg's change will do this. The reason it wasn't done before is for
  190826. performance, as this increases the per-pixel operations. If we would check
  190827. in advance if the background was gray or RGB, and position the gray-to-RGB
  190828. transform appropriately, then it would save a lot of work/time.
  190829. */
  190830. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190831. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190832. * for performance reasons */
  190833. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190834. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190835. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190836. #endif
  190837. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190838. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190839. ((png_ptr->num_trans != 0 ) ||
  190840. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190841. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190842. &(png_ptr->trans_values), &(png_ptr->background)
  190843. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190844. , &(png_ptr->background_1),
  190845. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190846. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190847. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190848. png_ptr->gamma_shift
  190849. #endif
  190850. );
  190851. #endif
  190852. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190853. if ((png_ptr->transformations & PNG_GAMMA) &&
  190854. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190855. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190856. ((png_ptr->num_trans != 0) ||
  190857. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190858. #endif
  190859. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190860. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190861. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190862. png_ptr->gamma_shift);
  190863. #endif
  190864. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190865. if (png_ptr->transformations & PNG_16_TO_8)
  190866. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190867. #endif
  190868. #if defined(PNG_READ_DITHER_SUPPORTED)
  190869. if (png_ptr->transformations & PNG_DITHER)
  190870. {
  190871. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190872. png_ptr->palette_lookup, png_ptr->dither_index);
  190873. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190874. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190875. }
  190876. #endif
  190877. #if defined(PNG_READ_INVERT_SUPPORTED)
  190878. if (png_ptr->transformations & PNG_INVERT_MONO)
  190879. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190880. #endif
  190881. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190882. if (png_ptr->transformations & PNG_SHIFT)
  190883. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190884. &(png_ptr->shift));
  190885. #endif
  190886. #if defined(PNG_READ_PACK_SUPPORTED)
  190887. if (png_ptr->transformations & PNG_PACK)
  190888. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190889. #endif
  190890. #if defined(PNG_READ_BGR_SUPPORTED)
  190891. if (png_ptr->transformations & PNG_BGR)
  190892. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190893. #endif
  190894. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190895. if (png_ptr->transformations & PNG_PACKSWAP)
  190896. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190897. #endif
  190898. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190899. /* if gray -> RGB, do so now only if we did not do so above */
  190900. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190901. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190902. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190903. #endif
  190904. #if defined(PNG_READ_FILLER_SUPPORTED)
  190905. if (png_ptr->transformations & PNG_FILLER)
  190906. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190907. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190908. #endif
  190909. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190910. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190911. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190912. #endif
  190913. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190914. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190915. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190916. #endif
  190917. #if defined(PNG_READ_SWAP_SUPPORTED)
  190918. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190919. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190920. #endif
  190921. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190922. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190923. {
  190924. if(png_ptr->read_user_transform_fn != NULL)
  190925. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190926. (png_ptr, /* png_ptr */
  190927. &(png_ptr->row_info), /* row_info: */
  190928. /* png_uint_32 width; width of row */
  190929. /* png_uint_32 rowbytes; number of bytes in row */
  190930. /* png_byte color_type; color type of pixels */
  190931. /* png_byte bit_depth; bit depth of samples */
  190932. /* png_byte channels; number of channels (1-4) */
  190933. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190934. png_ptr->row_buf + 1); /* start of pixel data for row */
  190935. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190936. if(png_ptr->user_transform_depth)
  190937. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190938. if(png_ptr->user_transform_channels)
  190939. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190940. #endif
  190941. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190942. png_ptr->row_info.channels);
  190943. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190944. png_ptr->row_info.width);
  190945. }
  190946. #endif
  190947. }
  190948. #if defined(PNG_READ_PACK_SUPPORTED)
  190949. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190950. * without changing the actual values. Thus, if you had a row with
  190951. * a bit depth of 1, you would end up with bytes that only contained
  190952. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190953. * png_do_shift() after this.
  190954. */
  190955. void /* PRIVATE */
  190956. png_do_unpack(png_row_infop row_info, png_bytep row)
  190957. {
  190958. png_debug(1, "in png_do_unpack\n");
  190959. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190960. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190961. #else
  190962. if (row_info->bit_depth < 8)
  190963. #endif
  190964. {
  190965. png_uint_32 i;
  190966. png_uint_32 row_width=row_info->width;
  190967. switch (row_info->bit_depth)
  190968. {
  190969. case 1:
  190970. {
  190971. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190972. png_bytep dp = row + (png_size_t)row_width - 1;
  190973. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190974. for (i = 0; i < row_width; i++)
  190975. {
  190976. *dp = (png_byte)((*sp >> shift) & 0x01);
  190977. if (shift == 7)
  190978. {
  190979. shift = 0;
  190980. sp--;
  190981. }
  190982. else
  190983. shift++;
  190984. dp--;
  190985. }
  190986. break;
  190987. }
  190988. case 2:
  190989. {
  190990. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190991. png_bytep dp = row + (png_size_t)row_width - 1;
  190992. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190993. for (i = 0; i < row_width; i++)
  190994. {
  190995. *dp = (png_byte)((*sp >> shift) & 0x03);
  190996. if (shift == 6)
  190997. {
  190998. shift = 0;
  190999. sp--;
  191000. }
  191001. else
  191002. shift += 2;
  191003. dp--;
  191004. }
  191005. break;
  191006. }
  191007. case 4:
  191008. {
  191009. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191010. png_bytep dp = row + (png_size_t)row_width - 1;
  191011. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191012. for (i = 0; i < row_width; i++)
  191013. {
  191014. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191015. if (shift == 4)
  191016. {
  191017. shift = 0;
  191018. sp--;
  191019. }
  191020. else
  191021. shift = 4;
  191022. dp--;
  191023. }
  191024. break;
  191025. }
  191026. }
  191027. row_info->bit_depth = 8;
  191028. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191029. row_info->rowbytes = row_width * row_info->channels;
  191030. }
  191031. }
  191032. #endif
  191033. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191034. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191035. * pixels back to their significant bits values. Thus, if you have
  191036. * a row of bit depth 8, but only 5 are significant, this will shift
  191037. * the values back to 0 through 31.
  191038. */
  191039. void /* PRIVATE */
  191040. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191041. {
  191042. png_debug(1, "in png_do_unshift\n");
  191043. if (
  191044. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191045. row != NULL && row_info != NULL && sig_bits != NULL &&
  191046. #endif
  191047. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191048. {
  191049. int shift[4];
  191050. int channels = 0;
  191051. int c;
  191052. png_uint_16 value = 0;
  191053. png_uint_32 row_width = row_info->width;
  191054. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191055. {
  191056. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191057. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191058. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191059. }
  191060. else
  191061. {
  191062. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191063. }
  191064. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191065. {
  191066. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191067. }
  191068. for (c = 0; c < channels; c++)
  191069. {
  191070. if (shift[c] <= 0)
  191071. shift[c] = 0;
  191072. else
  191073. value = 1;
  191074. }
  191075. if (!value)
  191076. return;
  191077. switch (row_info->bit_depth)
  191078. {
  191079. case 2:
  191080. {
  191081. png_bytep bp;
  191082. png_uint_32 i;
  191083. png_uint_32 istop = row_info->rowbytes;
  191084. for (bp = row, i = 0; i < istop; i++)
  191085. {
  191086. *bp >>= 1;
  191087. *bp++ &= 0x55;
  191088. }
  191089. break;
  191090. }
  191091. case 4:
  191092. {
  191093. png_bytep bp = row;
  191094. png_uint_32 i;
  191095. png_uint_32 istop = row_info->rowbytes;
  191096. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191097. (png_byte)((int)0xf >> shift[0]));
  191098. for (i = 0; i < istop; i++)
  191099. {
  191100. *bp >>= shift[0];
  191101. *bp++ &= mask;
  191102. }
  191103. break;
  191104. }
  191105. case 8:
  191106. {
  191107. png_bytep bp = row;
  191108. png_uint_32 i;
  191109. png_uint_32 istop = row_width * channels;
  191110. for (i = 0; i < istop; i++)
  191111. {
  191112. *bp++ >>= shift[i%channels];
  191113. }
  191114. break;
  191115. }
  191116. case 16:
  191117. {
  191118. png_bytep bp = row;
  191119. png_uint_32 i;
  191120. png_uint_32 istop = channels * row_width;
  191121. for (i = 0; i < istop; i++)
  191122. {
  191123. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191124. value >>= shift[i%channels];
  191125. *bp++ = (png_byte)(value >> 8);
  191126. *bp++ = (png_byte)(value & 0xff);
  191127. }
  191128. break;
  191129. }
  191130. }
  191131. }
  191132. }
  191133. #endif
  191134. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191135. /* chop rows of bit depth 16 down to 8 */
  191136. void /* PRIVATE */
  191137. png_do_chop(png_row_infop row_info, png_bytep row)
  191138. {
  191139. png_debug(1, "in png_do_chop\n");
  191140. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191141. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191142. #else
  191143. if (row_info->bit_depth == 16)
  191144. #endif
  191145. {
  191146. png_bytep sp = row;
  191147. png_bytep dp = row;
  191148. png_uint_32 i;
  191149. png_uint_32 istop = row_info->width * row_info->channels;
  191150. for (i = 0; i<istop; i++, sp += 2, dp++)
  191151. {
  191152. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191153. /* This does a more accurate scaling of the 16-bit color
  191154. * value, rather than a simple low-byte truncation.
  191155. *
  191156. * What the ideal calculation should be:
  191157. * *dp = (((((png_uint_32)(*sp) << 8) |
  191158. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191159. *
  191160. * GRR: no, I think this is what it really should be:
  191161. * *dp = (((((png_uint_32)(*sp) << 8) |
  191162. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191163. *
  191164. * GRR: here's the exact calculation with shifts:
  191165. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191166. * *dp = (temp - (temp >> 8)) >> 8;
  191167. *
  191168. * Approximate calculation with shift/add instead of multiply/divide:
  191169. * *dp = ((((png_uint_32)(*sp) << 8) |
  191170. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191171. *
  191172. * What we actually do to avoid extra shifting and conversion:
  191173. */
  191174. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191175. #else
  191176. /* Simply discard the low order byte */
  191177. *dp = *sp;
  191178. #endif
  191179. }
  191180. row_info->bit_depth = 8;
  191181. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191182. row_info->rowbytes = row_info->width * row_info->channels;
  191183. }
  191184. }
  191185. #endif
  191186. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191187. void /* PRIVATE */
  191188. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191189. {
  191190. png_debug(1, "in png_do_read_swap_alpha\n");
  191191. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191192. if (row != NULL && row_info != NULL)
  191193. #endif
  191194. {
  191195. png_uint_32 row_width = row_info->width;
  191196. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191197. {
  191198. /* This converts from RGBA to ARGB */
  191199. if (row_info->bit_depth == 8)
  191200. {
  191201. png_bytep sp = row + row_info->rowbytes;
  191202. png_bytep dp = sp;
  191203. png_byte save;
  191204. png_uint_32 i;
  191205. for (i = 0; i < row_width; i++)
  191206. {
  191207. save = *(--sp);
  191208. *(--dp) = *(--sp);
  191209. *(--dp) = *(--sp);
  191210. *(--dp) = *(--sp);
  191211. *(--dp) = save;
  191212. }
  191213. }
  191214. /* This converts from RRGGBBAA to AARRGGBB */
  191215. else
  191216. {
  191217. png_bytep sp = row + row_info->rowbytes;
  191218. png_bytep dp = sp;
  191219. png_byte save[2];
  191220. png_uint_32 i;
  191221. for (i = 0; i < row_width; i++)
  191222. {
  191223. save[0] = *(--sp);
  191224. save[1] = *(--sp);
  191225. *(--dp) = *(--sp);
  191226. *(--dp) = *(--sp);
  191227. *(--dp) = *(--sp);
  191228. *(--dp) = *(--sp);
  191229. *(--dp) = *(--sp);
  191230. *(--dp) = *(--sp);
  191231. *(--dp) = save[0];
  191232. *(--dp) = save[1];
  191233. }
  191234. }
  191235. }
  191236. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191237. {
  191238. /* This converts from GA to AG */
  191239. if (row_info->bit_depth == 8)
  191240. {
  191241. png_bytep sp = row + row_info->rowbytes;
  191242. png_bytep dp = sp;
  191243. png_byte save;
  191244. png_uint_32 i;
  191245. for (i = 0; i < row_width; i++)
  191246. {
  191247. save = *(--sp);
  191248. *(--dp) = *(--sp);
  191249. *(--dp) = save;
  191250. }
  191251. }
  191252. /* This converts from GGAA to AAGG */
  191253. else
  191254. {
  191255. png_bytep sp = row + row_info->rowbytes;
  191256. png_bytep dp = sp;
  191257. png_byte save[2];
  191258. png_uint_32 i;
  191259. for (i = 0; i < row_width; i++)
  191260. {
  191261. save[0] = *(--sp);
  191262. save[1] = *(--sp);
  191263. *(--dp) = *(--sp);
  191264. *(--dp) = *(--sp);
  191265. *(--dp) = save[0];
  191266. *(--dp) = save[1];
  191267. }
  191268. }
  191269. }
  191270. }
  191271. }
  191272. #endif
  191273. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191274. void /* PRIVATE */
  191275. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191276. {
  191277. png_debug(1, "in png_do_read_invert_alpha\n");
  191278. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191279. if (row != NULL && row_info != NULL)
  191280. #endif
  191281. {
  191282. png_uint_32 row_width = row_info->width;
  191283. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191284. {
  191285. /* This inverts the alpha channel in RGBA */
  191286. if (row_info->bit_depth == 8)
  191287. {
  191288. png_bytep sp = row + row_info->rowbytes;
  191289. png_bytep dp = sp;
  191290. png_uint_32 i;
  191291. for (i = 0; i < row_width; i++)
  191292. {
  191293. *(--dp) = (png_byte)(255 - *(--sp));
  191294. /* This does nothing:
  191295. *(--dp) = *(--sp);
  191296. *(--dp) = *(--sp);
  191297. *(--dp) = *(--sp);
  191298. We can replace it with:
  191299. */
  191300. sp-=3;
  191301. dp=sp;
  191302. }
  191303. }
  191304. /* This inverts the alpha channel in RRGGBBAA */
  191305. else
  191306. {
  191307. png_bytep sp = row + row_info->rowbytes;
  191308. png_bytep dp = sp;
  191309. png_uint_32 i;
  191310. for (i = 0; i < row_width; i++)
  191311. {
  191312. *(--dp) = (png_byte)(255 - *(--sp));
  191313. *(--dp) = (png_byte)(255 - *(--sp));
  191314. /* This does nothing:
  191315. *(--dp) = *(--sp);
  191316. *(--dp) = *(--sp);
  191317. *(--dp) = *(--sp);
  191318. *(--dp) = *(--sp);
  191319. *(--dp) = *(--sp);
  191320. *(--dp) = *(--sp);
  191321. We can replace it with:
  191322. */
  191323. sp-=6;
  191324. dp=sp;
  191325. }
  191326. }
  191327. }
  191328. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191329. {
  191330. /* This inverts the alpha channel in GA */
  191331. if (row_info->bit_depth == 8)
  191332. {
  191333. png_bytep sp = row + row_info->rowbytes;
  191334. png_bytep dp = sp;
  191335. png_uint_32 i;
  191336. for (i = 0; i < row_width; i++)
  191337. {
  191338. *(--dp) = (png_byte)(255 - *(--sp));
  191339. *(--dp) = *(--sp);
  191340. }
  191341. }
  191342. /* This inverts the alpha channel in GGAA */
  191343. else
  191344. {
  191345. png_bytep sp = row + row_info->rowbytes;
  191346. png_bytep dp = sp;
  191347. png_uint_32 i;
  191348. for (i = 0; i < row_width; i++)
  191349. {
  191350. *(--dp) = (png_byte)(255 - *(--sp));
  191351. *(--dp) = (png_byte)(255 - *(--sp));
  191352. /*
  191353. *(--dp) = *(--sp);
  191354. *(--dp) = *(--sp);
  191355. */
  191356. sp-=2;
  191357. dp=sp;
  191358. }
  191359. }
  191360. }
  191361. }
  191362. }
  191363. #endif
  191364. #if defined(PNG_READ_FILLER_SUPPORTED)
  191365. /* Add filler channel if we have RGB color */
  191366. void /* PRIVATE */
  191367. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191368. png_uint_32 filler, png_uint_32 flags)
  191369. {
  191370. png_uint_32 i;
  191371. png_uint_32 row_width = row_info->width;
  191372. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191373. png_byte lo_filler = (png_byte)(filler & 0xff);
  191374. png_debug(1, "in png_do_read_filler\n");
  191375. if (
  191376. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191377. row != NULL && row_info != NULL &&
  191378. #endif
  191379. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191380. {
  191381. if(row_info->bit_depth == 8)
  191382. {
  191383. /* This changes the data from G to GX */
  191384. if (flags & PNG_FLAG_FILLER_AFTER)
  191385. {
  191386. png_bytep sp = row + (png_size_t)row_width;
  191387. png_bytep dp = sp + (png_size_t)row_width;
  191388. for (i = 1; i < row_width; i++)
  191389. {
  191390. *(--dp) = lo_filler;
  191391. *(--dp) = *(--sp);
  191392. }
  191393. *(--dp) = lo_filler;
  191394. row_info->channels = 2;
  191395. row_info->pixel_depth = 16;
  191396. row_info->rowbytes = row_width * 2;
  191397. }
  191398. /* This changes the data from G to XG */
  191399. else
  191400. {
  191401. png_bytep sp = row + (png_size_t)row_width;
  191402. png_bytep dp = sp + (png_size_t)row_width;
  191403. for (i = 0; i < row_width; i++)
  191404. {
  191405. *(--dp) = *(--sp);
  191406. *(--dp) = lo_filler;
  191407. }
  191408. row_info->channels = 2;
  191409. row_info->pixel_depth = 16;
  191410. row_info->rowbytes = row_width * 2;
  191411. }
  191412. }
  191413. else if(row_info->bit_depth == 16)
  191414. {
  191415. /* This changes the data from GG to GGXX */
  191416. if (flags & PNG_FLAG_FILLER_AFTER)
  191417. {
  191418. png_bytep sp = row + (png_size_t)row_width * 2;
  191419. png_bytep dp = sp + (png_size_t)row_width * 2;
  191420. for (i = 1; i < row_width; i++)
  191421. {
  191422. *(--dp) = hi_filler;
  191423. *(--dp) = lo_filler;
  191424. *(--dp) = *(--sp);
  191425. *(--dp) = *(--sp);
  191426. }
  191427. *(--dp) = hi_filler;
  191428. *(--dp) = lo_filler;
  191429. row_info->channels = 2;
  191430. row_info->pixel_depth = 32;
  191431. row_info->rowbytes = row_width * 4;
  191432. }
  191433. /* This changes the data from GG to XXGG */
  191434. else
  191435. {
  191436. png_bytep sp = row + (png_size_t)row_width * 2;
  191437. png_bytep dp = sp + (png_size_t)row_width * 2;
  191438. for (i = 0; i < row_width; i++)
  191439. {
  191440. *(--dp) = *(--sp);
  191441. *(--dp) = *(--sp);
  191442. *(--dp) = hi_filler;
  191443. *(--dp) = lo_filler;
  191444. }
  191445. row_info->channels = 2;
  191446. row_info->pixel_depth = 32;
  191447. row_info->rowbytes = row_width * 4;
  191448. }
  191449. }
  191450. } /* COLOR_TYPE == GRAY */
  191451. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191452. {
  191453. if(row_info->bit_depth == 8)
  191454. {
  191455. /* This changes the data from RGB to RGBX */
  191456. if (flags & PNG_FLAG_FILLER_AFTER)
  191457. {
  191458. png_bytep sp = row + (png_size_t)row_width * 3;
  191459. png_bytep dp = sp + (png_size_t)row_width;
  191460. for (i = 1; i < row_width; i++)
  191461. {
  191462. *(--dp) = lo_filler;
  191463. *(--dp) = *(--sp);
  191464. *(--dp) = *(--sp);
  191465. *(--dp) = *(--sp);
  191466. }
  191467. *(--dp) = lo_filler;
  191468. row_info->channels = 4;
  191469. row_info->pixel_depth = 32;
  191470. row_info->rowbytes = row_width * 4;
  191471. }
  191472. /* This changes the data from RGB to XRGB */
  191473. else
  191474. {
  191475. png_bytep sp = row + (png_size_t)row_width * 3;
  191476. png_bytep dp = sp + (png_size_t)row_width;
  191477. for (i = 0; i < row_width; i++)
  191478. {
  191479. *(--dp) = *(--sp);
  191480. *(--dp) = *(--sp);
  191481. *(--dp) = *(--sp);
  191482. *(--dp) = lo_filler;
  191483. }
  191484. row_info->channels = 4;
  191485. row_info->pixel_depth = 32;
  191486. row_info->rowbytes = row_width * 4;
  191487. }
  191488. }
  191489. else if(row_info->bit_depth == 16)
  191490. {
  191491. /* This changes the data from RRGGBB to RRGGBBXX */
  191492. if (flags & PNG_FLAG_FILLER_AFTER)
  191493. {
  191494. png_bytep sp = row + (png_size_t)row_width * 6;
  191495. png_bytep dp = sp + (png_size_t)row_width * 2;
  191496. for (i = 1; i < row_width; i++)
  191497. {
  191498. *(--dp) = hi_filler;
  191499. *(--dp) = lo_filler;
  191500. *(--dp) = *(--sp);
  191501. *(--dp) = *(--sp);
  191502. *(--dp) = *(--sp);
  191503. *(--dp) = *(--sp);
  191504. *(--dp) = *(--sp);
  191505. *(--dp) = *(--sp);
  191506. }
  191507. *(--dp) = hi_filler;
  191508. *(--dp) = lo_filler;
  191509. row_info->channels = 4;
  191510. row_info->pixel_depth = 64;
  191511. row_info->rowbytes = row_width * 8;
  191512. }
  191513. /* This changes the data from RRGGBB to XXRRGGBB */
  191514. else
  191515. {
  191516. png_bytep sp = row + (png_size_t)row_width * 6;
  191517. png_bytep dp = sp + (png_size_t)row_width * 2;
  191518. for (i = 0; i < row_width; i++)
  191519. {
  191520. *(--dp) = *(--sp);
  191521. *(--dp) = *(--sp);
  191522. *(--dp) = *(--sp);
  191523. *(--dp) = *(--sp);
  191524. *(--dp) = *(--sp);
  191525. *(--dp) = *(--sp);
  191526. *(--dp) = hi_filler;
  191527. *(--dp) = lo_filler;
  191528. }
  191529. row_info->channels = 4;
  191530. row_info->pixel_depth = 64;
  191531. row_info->rowbytes = row_width * 8;
  191532. }
  191533. }
  191534. } /* COLOR_TYPE == RGB */
  191535. }
  191536. #endif
  191537. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191538. /* expand grayscale files to RGB, with or without alpha */
  191539. void /* PRIVATE */
  191540. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191541. {
  191542. png_uint_32 i;
  191543. png_uint_32 row_width = row_info->width;
  191544. png_debug(1, "in png_do_gray_to_rgb\n");
  191545. if (row_info->bit_depth >= 8 &&
  191546. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191547. row != NULL && row_info != NULL &&
  191548. #endif
  191549. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191550. {
  191551. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191552. {
  191553. if (row_info->bit_depth == 8)
  191554. {
  191555. png_bytep sp = row + (png_size_t)row_width - 1;
  191556. png_bytep dp = sp + (png_size_t)row_width * 2;
  191557. for (i = 0; i < row_width; i++)
  191558. {
  191559. *(dp--) = *sp;
  191560. *(dp--) = *sp;
  191561. *(dp--) = *(sp--);
  191562. }
  191563. }
  191564. else
  191565. {
  191566. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191567. png_bytep dp = sp + (png_size_t)row_width * 4;
  191568. for (i = 0; i < row_width; i++)
  191569. {
  191570. *(dp--) = *sp;
  191571. *(dp--) = *(sp - 1);
  191572. *(dp--) = *sp;
  191573. *(dp--) = *(sp - 1);
  191574. *(dp--) = *(sp--);
  191575. *(dp--) = *(sp--);
  191576. }
  191577. }
  191578. }
  191579. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191580. {
  191581. if (row_info->bit_depth == 8)
  191582. {
  191583. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191584. png_bytep dp = sp + (png_size_t)row_width * 2;
  191585. for (i = 0; i < row_width; i++)
  191586. {
  191587. *(dp--) = *(sp--);
  191588. *(dp--) = *sp;
  191589. *(dp--) = *sp;
  191590. *(dp--) = *(sp--);
  191591. }
  191592. }
  191593. else
  191594. {
  191595. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191596. png_bytep dp = sp + (png_size_t)row_width * 4;
  191597. for (i = 0; i < row_width; i++)
  191598. {
  191599. *(dp--) = *(sp--);
  191600. *(dp--) = *(sp--);
  191601. *(dp--) = *sp;
  191602. *(dp--) = *(sp - 1);
  191603. *(dp--) = *sp;
  191604. *(dp--) = *(sp - 1);
  191605. *(dp--) = *(sp--);
  191606. *(dp--) = *(sp--);
  191607. }
  191608. }
  191609. }
  191610. row_info->channels += (png_byte)2;
  191611. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191612. row_info->pixel_depth = (png_byte)(row_info->channels *
  191613. row_info->bit_depth);
  191614. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191615. }
  191616. }
  191617. #endif
  191618. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191619. /* reduce RGB files to grayscale, with or without alpha
  191620. * using the equation given in Poynton's ColorFAQ at
  191621. * <http://www.inforamp.net/~poynton/>
  191622. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191623. *
  191624. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191625. *
  191626. * We approximate this with
  191627. *
  191628. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191629. *
  191630. * which can be expressed with integers as
  191631. *
  191632. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191633. *
  191634. * The calculation is to be done in a linear colorspace.
  191635. *
  191636. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191637. */
  191638. int /* PRIVATE */
  191639. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191640. {
  191641. png_uint_32 i;
  191642. png_uint_32 row_width = row_info->width;
  191643. int rgb_error = 0;
  191644. png_debug(1, "in png_do_rgb_to_gray\n");
  191645. if (
  191646. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191647. row != NULL && row_info != NULL &&
  191648. #endif
  191649. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191650. {
  191651. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191652. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191653. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191654. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191655. {
  191656. if (row_info->bit_depth == 8)
  191657. {
  191658. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191659. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191660. {
  191661. png_bytep sp = row;
  191662. png_bytep dp = row;
  191663. for (i = 0; i < row_width; i++)
  191664. {
  191665. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191666. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191667. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191668. if(red != green || red != blue)
  191669. {
  191670. rgb_error |= 1;
  191671. *(dp++) = png_ptr->gamma_from_1[
  191672. (rc*red+gc*green+bc*blue)>>15];
  191673. }
  191674. else
  191675. *(dp++) = *(sp-1);
  191676. }
  191677. }
  191678. else
  191679. #endif
  191680. {
  191681. png_bytep sp = row;
  191682. png_bytep dp = row;
  191683. for (i = 0; i < row_width; i++)
  191684. {
  191685. png_byte red = *(sp++);
  191686. png_byte green = *(sp++);
  191687. png_byte blue = *(sp++);
  191688. if(red != green || red != blue)
  191689. {
  191690. rgb_error |= 1;
  191691. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191692. }
  191693. else
  191694. *(dp++) = *(sp-1);
  191695. }
  191696. }
  191697. }
  191698. else /* RGB bit_depth == 16 */
  191699. {
  191700. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191701. if (png_ptr->gamma_16_to_1 != NULL &&
  191702. png_ptr->gamma_16_from_1 != NULL)
  191703. {
  191704. png_bytep sp = row;
  191705. png_bytep dp = row;
  191706. for (i = 0; i < row_width; i++)
  191707. {
  191708. png_uint_16 red, green, blue, w;
  191709. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191710. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191711. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191712. if(red == green && red == blue)
  191713. w = red;
  191714. else
  191715. {
  191716. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191717. png_ptr->gamma_shift][red>>8];
  191718. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191719. png_ptr->gamma_shift][green>>8];
  191720. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191721. png_ptr->gamma_shift][blue>>8];
  191722. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191723. + bc*blue_1)>>15);
  191724. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191725. png_ptr->gamma_shift][gray16 >> 8];
  191726. rgb_error |= 1;
  191727. }
  191728. *(dp++) = (png_byte)((w>>8) & 0xff);
  191729. *(dp++) = (png_byte)(w & 0xff);
  191730. }
  191731. }
  191732. else
  191733. #endif
  191734. {
  191735. png_bytep sp = row;
  191736. png_bytep dp = row;
  191737. for (i = 0; i < row_width; i++)
  191738. {
  191739. png_uint_16 red, green, blue, gray16;
  191740. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191741. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191742. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191743. if(red != green || red != blue)
  191744. rgb_error |= 1;
  191745. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191746. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191747. *(dp++) = (png_byte)(gray16 & 0xff);
  191748. }
  191749. }
  191750. }
  191751. }
  191752. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191753. {
  191754. if (row_info->bit_depth == 8)
  191755. {
  191756. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191757. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191758. {
  191759. png_bytep sp = row;
  191760. png_bytep dp = row;
  191761. for (i = 0; i < row_width; i++)
  191762. {
  191763. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191764. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191765. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191766. if(red != green || red != blue)
  191767. rgb_error |= 1;
  191768. *(dp++) = png_ptr->gamma_from_1
  191769. [(rc*red + gc*green + bc*blue)>>15];
  191770. *(dp++) = *(sp++); /* alpha */
  191771. }
  191772. }
  191773. else
  191774. #endif
  191775. {
  191776. png_bytep sp = row;
  191777. png_bytep dp = row;
  191778. for (i = 0; i < row_width; i++)
  191779. {
  191780. png_byte red = *(sp++);
  191781. png_byte green = *(sp++);
  191782. png_byte blue = *(sp++);
  191783. if(red != green || red != blue)
  191784. rgb_error |= 1;
  191785. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191786. *(dp++) = *(sp++); /* alpha */
  191787. }
  191788. }
  191789. }
  191790. else /* RGBA bit_depth == 16 */
  191791. {
  191792. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191793. if (png_ptr->gamma_16_to_1 != NULL &&
  191794. png_ptr->gamma_16_from_1 != NULL)
  191795. {
  191796. png_bytep sp = row;
  191797. png_bytep dp = row;
  191798. for (i = 0; i < row_width; i++)
  191799. {
  191800. png_uint_16 red, green, blue, w;
  191801. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191802. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191803. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191804. if(red == green && red == blue)
  191805. w = red;
  191806. else
  191807. {
  191808. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191809. png_ptr->gamma_shift][red>>8];
  191810. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191811. png_ptr->gamma_shift][green>>8];
  191812. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191813. png_ptr->gamma_shift][blue>>8];
  191814. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191815. + gc * green_1 + bc * blue_1)>>15);
  191816. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191817. png_ptr->gamma_shift][gray16 >> 8];
  191818. rgb_error |= 1;
  191819. }
  191820. *(dp++) = (png_byte)((w>>8) & 0xff);
  191821. *(dp++) = (png_byte)(w & 0xff);
  191822. *(dp++) = *(sp++); /* alpha */
  191823. *(dp++) = *(sp++);
  191824. }
  191825. }
  191826. else
  191827. #endif
  191828. {
  191829. png_bytep sp = row;
  191830. png_bytep dp = row;
  191831. for (i = 0; i < row_width; i++)
  191832. {
  191833. png_uint_16 red, green, blue, gray16;
  191834. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191835. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191836. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191837. if(red != green || red != blue)
  191838. rgb_error |= 1;
  191839. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191840. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191841. *(dp++) = (png_byte)(gray16 & 0xff);
  191842. *(dp++) = *(sp++); /* alpha */
  191843. *(dp++) = *(sp++);
  191844. }
  191845. }
  191846. }
  191847. }
  191848. row_info->channels -= (png_byte)2;
  191849. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191850. row_info->pixel_depth = (png_byte)(row_info->channels *
  191851. row_info->bit_depth);
  191852. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191853. }
  191854. return rgb_error;
  191855. }
  191856. #endif
  191857. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191858. * large of png_color. This lets grayscale images be treated as
  191859. * paletted. Most useful for gamma correction and simplification
  191860. * of code.
  191861. */
  191862. void PNGAPI
  191863. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191864. {
  191865. int num_palette;
  191866. int color_inc;
  191867. int i;
  191868. int v;
  191869. png_debug(1, "in png_do_build_grayscale_palette\n");
  191870. if (palette == NULL)
  191871. return;
  191872. switch (bit_depth)
  191873. {
  191874. case 1:
  191875. num_palette = 2;
  191876. color_inc = 0xff;
  191877. break;
  191878. case 2:
  191879. num_palette = 4;
  191880. color_inc = 0x55;
  191881. break;
  191882. case 4:
  191883. num_palette = 16;
  191884. color_inc = 0x11;
  191885. break;
  191886. case 8:
  191887. num_palette = 256;
  191888. color_inc = 1;
  191889. break;
  191890. default:
  191891. num_palette = 0;
  191892. color_inc = 0;
  191893. break;
  191894. }
  191895. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191896. {
  191897. palette[i].red = (png_byte)v;
  191898. palette[i].green = (png_byte)v;
  191899. palette[i].blue = (png_byte)v;
  191900. }
  191901. }
  191902. /* This function is currently unused. Do we really need it? */
  191903. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191904. void /* PRIVATE */
  191905. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191906. int num_palette)
  191907. {
  191908. png_debug(1, "in png_correct_palette\n");
  191909. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191910. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191911. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191912. {
  191913. png_color back, back_1;
  191914. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191915. {
  191916. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191917. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191918. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191919. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191920. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191921. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191922. }
  191923. else
  191924. {
  191925. double g;
  191926. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191927. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191928. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191929. {
  191930. back.red = png_ptr->background.red;
  191931. back.green = png_ptr->background.green;
  191932. back.blue = png_ptr->background.blue;
  191933. }
  191934. else
  191935. {
  191936. back.red =
  191937. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191938. 255.0 + 0.5);
  191939. back.green =
  191940. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191941. 255.0 + 0.5);
  191942. back.blue =
  191943. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191944. 255.0 + 0.5);
  191945. }
  191946. g = 1.0 / png_ptr->background_gamma;
  191947. back_1.red =
  191948. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191949. 255.0 + 0.5);
  191950. back_1.green =
  191951. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191952. 255.0 + 0.5);
  191953. back_1.blue =
  191954. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191955. 255.0 + 0.5);
  191956. }
  191957. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191958. {
  191959. png_uint_32 i;
  191960. for (i = 0; i < (png_uint_32)num_palette; i++)
  191961. {
  191962. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191963. {
  191964. palette[i] = back;
  191965. }
  191966. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191967. {
  191968. png_byte v, w;
  191969. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191970. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191971. palette[i].red = png_ptr->gamma_from_1[w];
  191972. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191973. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191974. palette[i].green = png_ptr->gamma_from_1[w];
  191975. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191976. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191977. palette[i].blue = png_ptr->gamma_from_1[w];
  191978. }
  191979. else
  191980. {
  191981. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191982. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191983. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191984. }
  191985. }
  191986. }
  191987. else
  191988. {
  191989. int i;
  191990. for (i = 0; i < num_palette; i++)
  191991. {
  191992. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191993. {
  191994. palette[i] = back;
  191995. }
  191996. else
  191997. {
  191998. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191999. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192000. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192001. }
  192002. }
  192003. }
  192004. }
  192005. else
  192006. #endif
  192007. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192008. if (png_ptr->transformations & PNG_GAMMA)
  192009. {
  192010. int i;
  192011. for (i = 0; i < num_palette; i++)
  192012. {
  192013. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192014. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192015. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192016. }
  192017. }
  192018. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192019. else
  192020. #endif
  192021. #endif
  192022. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192023. if (png_ptr->transformations & PNG_BACKGROUND)
  192024. {
  192025. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192026. {
  192027. png_color back;
  192028. back.red = (png_byte)png_ptr->background.red;
  192029. back.green = (png_byte)png_ptr->background.green;
  192030. back.blue = (png_byte)png_ptr->background.blue;
  192031. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192032. {
  192033. if (png_ptr->trans[i] == 0)
  192034. {
  192035. palette[i].red = back.red;
  192036. palette[i].green = back.green;
  192037. palette[i].blue = back.blue;
  192038. }
  192039. else if (png_ptr->trans[i] != 0xff)
  192040. {
  192041. png_composite(palette[i].red, png_ptr->palette[i].red,
  192042. png_ptr->trans[i], back.red);
  192043. png_composite(palette[i].green, png_ptr->palette[i].green,
  192044. png_ptr->trans[i], back.green);
  192045. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192046. png_ptr->trans[i], back.blue);
  192047. }
  192048. }
  192049. }
  192050. else /* assume grayscale palette (what else could it be?) */
  192051. {
  192052. int i;
  192053. for (i = 0; i < num_palette; i++)
  192054. {
  192055. if (i == (png_byte)png_ptr->trans_values.gray)
  192056. {
  192057. palette[i].red = (png_byte)png_ptr->background.red;
  192058. palette[i].green = (png_byte)png_ptr->background.green;
  192059. palette[i].blue = (png_byte)png_ptr->background.blue;
  192060. }
  192061. }
  192062. }
  192063. }
  192064. #endif
  192065. }
  192066. #endif
  192067. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192068. /* Replace any alpha or transparency with the supplied background color.
  192069. * "background" is already in the screen gamma, while "background_1" is
  192070. * at a gamma of 1.0. Paletted files have already been taken care of.
  192071. */
  192072. void /* PRIVATE */
  192073. png_do_background(png_row_infop row_info, png_bytep row,
  192074. png_color_16p trans_values, png_color_16p background
  192075. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192076. , png_color_16p background_1,
  192077. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192078. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192079. png_uint_16pp gamma_16_to_1, int gamma_shift
  192080. #endif
  192081. )
  192082. {
  192083. png_bytep sp, dp;
  192084. png_uint_32 i;
  192085. png_uint_32 row_width=row_info->width;
  192086. int shift;
  192087. png_debug(1, "in png_do_background\n");
  192088. if (background != NULL &&
  192089. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192090. row != NULL && row_info != NULL &&
  192091. #endif
  192092. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192093. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192094. {
  192095. switch (row_info->color_type)
  192096. {
  192097. case PNG_COLOR_TYPE_GRAY:
  192098. {
  192099. switch (row_info->bit_depth)
  192100. {
  192101. case 1:
  192102. {
  192103. sp = row;
  192104. shift = 7;
  192105. for (i = 0; i < row_width; i++)
  192106. {
  192107. if ((png_uint_16)((*sp >> shift) & 0x01)
  192108. == trans_values->gray)
  192109. {
  192110. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192111. *sp |= (png_byte)(background->gray << shift);
  192112. }
  192113. if (!shift)
  192114. {
  192115. shift = 7;
  192116. sp++;
  192117. }
  192118. else
  192119. shift--;
  192120. }
  192121. break;
  192122. }
  192123. case 2:
  192124. {
  192125. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192126. if (gamma_table != NULL)
  192127. {
  192128. sp = row;
  192129. shift = 6;
  192130. for (i = 0; i < row_width; i++)
  192131. {
  192132. if ((png_uint_16)((*sp >> shift) & 0x03)
  192133. == trans_values->gray)
  192134. {
  192135. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192136. *sp |= (png_byte)(background->gray << shift);
  192137. }
  192138. else
  192139. {
  192140. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192141. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192142. (p << 4) | (p << 6)] >> 6) & 0x03);
  192143. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192144. *sp |= (png_byte)(g << shift);
  192145. }
  192146. if (!shift)
  192147. {
  192148. shift = 6;
  192149. sp++;
  192150. }
  192151. else
  192152. shift -= 2;
  192153. }
  192154. }
  192155. else
  192156. #endif
  192157. {
  192158. sp = row;
  192159. shift = 6;
  192160. for (i = 0; i < row_width; i++)
  192161. {
  192162. if ((png_uint_16)((*sp >> shift) & 0x03)
  192163. == trans_values->gray)
  192164. {
  192165. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192166. *sp |= (png_byte)(background->gray << shift);
  192167. }
  192168. if (!shift)
  192169. {
  192170. shift = 6;
  192171. sp++;
  192172. }
  192173. else
  192174. shift -= 2;
  192175. }
  192176. }
  192177. break;
  192178. }
  192179. case 4:
  192180. {
  192181. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192182. if (gamma_table != NULL)
  192183. {
  192184. sp = row;
  192185. shift = 4;
  192186. for (i = 0; i < row_width; i++)
  192187. {
  192188. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192189. == trans_values->gray)
  192190. {
  192191. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192192. *sp |= (png_byte)(background->gray << shift);
  192193. }
  192194. else
  192195. {
  192196. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192197. png_byte g = (png_byte)((gamma_table[p |
  192198. (p << 4)] >> 4) & 0x0f);
  192199. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192200. *sp |= (png_byte)(g << shift);
  192201. }
  192202. if (!shift)
  192203. {
  192204. shift = 4;
  192205. sp++;
  192206. }
  192207. else
  192208. shift -= 4;
  192209. }
  192210. }
  192211. else
  192212. #endif
  192213. {
  192214. sp = row;
  192215. shift = 4;
  192216. for (i = 0; i < row_width; i++)
  192217. {
  192218. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192219. == trans_values->gray)
  192220. {
  192221. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192222. *sp |= (png_byte)(background->gray << shift);
  192223. }
  192224. if (!shift)
  192225. {
  192226. shift = 4;
  192227. sp++;
  192228. }
  192229. else
  192230. shift -= 4;
  192231. }
  192232. }
  192233. break;
  192234. }
  192235. case 8:
  192236. {
  192237. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192238. if (gamma_table != NULL)
  192239. {
  192240. sp = row;
  192241. for (i = 0; i < row_width; i++, sp++)
  192242. {
  192243. if (*sp == trans_values->gray)
  192244. {
  192245. *sp = (png_byte)background->gray;
  192246. }
  192247. else
  192248. {
  192249. *sp = gamma_table[*sp];
  192250. }
  192251. }
  192252. }
  192253. else
  192254. #endif
  192255. {
  192256. sp = row;
  192257. for (i = 0; i < row_width; i++, sp++)
  192258. {
  192259. if (*sp == trans_values->gray)
  192260. {
  192261. *sp = (png_byte)background->gray;
  192262. }
  192263. }
  192264. }
  192265. break;
  192266. }
  192267. case 16:
  192268. {
  192269. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192270. if (gamma_16 != NULL)
  192271. {
  192272. sp = row;
  192273. for (i = 0; i < row_width; i++, sp += 2)
  192274. {
  192275. png_uint_16 v;
  192276. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192277. if (v == trans_values->gray)
  192278. {
  192279. /* background is already in screen gamma */
  192280. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192281. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192282. }
  192283. else
  192284. {
  192285. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192286. *sp = (png_byte)((v >> 8) & 0xff);
  192287. *(sp + 1) = (png_byte)(v & 0xff);
  192288. }
  192289. }
  192290. }
  192291. else
  192292. #endif
  192293. {
  192294. sp = row;
  192295. for (i = 0; i < row_width; i++, sp += 2)
  192296. {
  192297. png_uint_16 v;
  192298. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192299. if (v == trans_values->gray)
  192300. {
  192301. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192302. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192303. }
  192304. }
  192305. }
  192306. break;
  192307. }
  192308. }
  192309. break;
  192310. }
  192311. case PNG_COLOR_TYPE_RGB:
  192312. {
  192313. if (row_info->bit_depth == 8)
  192314. {
  192315. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192316. if (gamma_table != NULL)
  192317. {
  192318. sp = row;
  192319. for (i = 0; i < row_width; i++, sp += 3)
  192320. {
  192321. if (*sp == trans_values->red &&
  192322. *(sp + 1) == trans_values->green &&
  192323. *(sp + 2) == trans_values->blue)
  192324. {
  192325. *sp = (png_byte)background->red;
  192326. *(sp + 1) = (png_byte)background->green;
  192327. *(sp + 2) = (png_byte)background->blue;
  192328. }
  192329. else
  192330. {
  192331. *sp = gamma_table[*sp];
  192332. *(sp + 1) = gamma_table[*(sp + 1)];
  192333. *(sp + 2) = gamma_table[*(sp + 2)];
  192334. }
  192335. }
  192336. }
  192337. else
  192338. #endif
  192339. {
  192340. sp = row;
  192341. for (i = 0; i < row_width; i++, sp += 3)
  192342. {
  192343. if (*sp == trans_values->red &&
  192344. *(sp + 1) == trans_values->green &&
  192345. *(sp + 2) == trans_values->blue)
  192346. {
  192347. *sp = (png_byte)background->red;
  192348. *(sp + 1) = (png_byte)background->green;
  192349. *(sp + 2) = (png_byte)background->blue;
  192350. }
  192351. }
  192352. }
  192353. }
  192354. else /* if (row_info->bit_depth == 16) */
  192355. {
  192356. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192357. if (gamma_16 != NULL)
  192358. {
  192359. sp = row;
  192360. for (i = 0; i < row_width; i++, sp += 6)
  192361. {
  192362. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192363. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192364. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192365. if (r == trans_values->red && g == trans_values->green &&
  192366. b == trans_values->blue)
  192367. {
  192368. /* background is already in screen gamma */
  192369. *sp = (png_byte)((background->red >> 8) & 0xff);
  192370. *(sp + 1) = (png_byte)(background->red & 0xff);
  192371. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192372. *(sp + 3) = (png_byte)(background->green & 0xff);
  192373. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192374. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192375. }
  192376. else
  192377. {
  192378. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192379. *sp = (png_byte)((v >> 8) & 0xff);
  192380. *(sp + 1) = (png_byte)(v & 0xff);
  192381. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192382. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192383. *(sp + 3) = (png_byte)(v & 0xff);
  192384. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192385. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192386. *(sp + 5) = (png_byte)(v & 0xff);
  192387. }
  192388. }
  192389. }
  192390. else
  192391. #endif
  192392. {
  192393. sp = row;
  192394. for (i = 0; i < row_width; i++, sp += 6)
  192395. {
  192396. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192397. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192398. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192399. if (r == trans_values->red && g == trans_values->green &&
  192400. b == trans_values->blue)
  192401. {
  192402. *sp = (png_byte)((background->red >> 8) & 0xff);
  192403. *(sp + 1) = (png_byte)(background->red & 0xff);
  192404. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192405. *(sp + 3) = (png_byte)(background->green & 0xff);
  192406. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192407. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192408. }
  192409. }
  192410. }
  192411. }
  192412. break;
  192413. }
  192414. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192415. {
  192416. if (row_info->bit_depth == 8)
  192417. {
  192418. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192419. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192420. gamma_table != NULL)
  192421. {
  192422. sp = row;
  192423. dp = row;
  192424. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192425. {
  192426. png_uint_16 a = *(sp + 1);
  192427. if (a == 0xff)
  192428. {
  192429. *dp = gamma_table[*sp];
  192430. }
  192431. else if (a == 0)
  192432. {
  192433. /* background is already in screen gamma */
  192434. *dp = (png_byte)background->gray;
  192435. }
  192436. else
  192437. {
  192438. png_byte v, w;
  192439. v = gamma_to_1[*sp];
  192440. png_composite(w, v, a, background_1->gray);
  192441. *dp = gamma_from_1[w];
  192442. }
  192443. }
  192444. }
  192445. else
  192446. #endif
  192447. {
  192448. sp = row;
  192449. dp = row;
  192450. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192451. {
  192452. png_byte a = *(sp + 1);
  192453. if (a == 0xff)
  192454. {
  192455. *dp = *sp;
  192456. }
  192457. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192458. else if (a == 0)
  192459. {
  192460. *dp = (png_byte)background->gray;
  192461. }
  192462. else
  192463. {
  192464. png_composite(*dp, *sp, a, background_1->gray);
  192465. }
  192466. #else
  192467. *dp = (png_byte)background->gray;
  192468. #endif
  192469. }
  192470. }
  192471. }
  192472. else /* if (png_ptr->bit_depth == 16) */
  192473. {
  192474. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192475. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192476. gamma_16_to_1 != NULL)
  192477. {
  192478. sp = row;
  192479. dp = row;
  192480. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192481. {
  192482. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192483. if (a == (png_uint_16)0xffff)
  192484. {
  192485. png_uint_16 v;
  192486. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192487. *dp = (png_byte)((v >> 8) & 0xff);
  192488. *(dp + 1) = (png_byte)(v & 0xff);
  192489. }
  192490. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192491. else if (a == 0)
  192492. #else
  192493. else
  192494. #endif
  192495. {
  192496. /* background is already in screen gamma */
  192497. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192498. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192499. }
  192500. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192501. else
  192502. {
  192503. png_uint_16 g, v, w;
  192504. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192505. png_composite_16(v, g, a, background_1->gray);
  192506. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192507. *dp = (png_byte)((w >> 8) & 0xff);
  192508. *(dp + 1) = (png_byte)(w & 0xff);
  192509. }
  192510. #endif
  192511. }
  192512. }
  192513. else
  192514. #endif
  192515. {
  192516. sp = row;
  192517. dp = row;
  192518. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192519. {
  192520. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192521. if (a == (png_uint_16)0xffff)
  192522. {
  192523. png_memcpy(dp, sp, 2);
  192524. }
  192525. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192526. else if (a == 0)
  192527. #else
  192528. else
  192529. #endif
  192530. {
  192531. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192532. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192533. }
  192534. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192535. else
  192536. {
  192537. png_uint_16 g, v;
  192538. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192539. png_composite_16(v, g, a, background_1->gray);
  192540. *dp = (png_byte)((v >> 8) & 0xff);
  192541. *(dp + 1) = (png_byte)(v & 0xff);
  192542. }
  192543. #endif
  192544. }
  192545. }
  192546. }
  192547. break;
  192548. }
  192549. case PNG_COLOR_TYPE_RGB_ALPHA:
  192550. {
  192551. if (row_info->bit_depth == 8)
  192552. {
  192553. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192554. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192555. gamma_table != NULL)
  192556. {
  192557. sp = row;
  192558. dp = row;
  192559. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192560. {
  192561. png_byte a = *(sp + 3);
  192562. if (a == 0xff)
  192563. {
  192564. *dp = gamma_table[*sp];
  192565. *(dp + 1) = gamma_table[*(sp + 1)];
  192566. *(dp + 2) = gamma_table[*(sp + 2)];
  192567. }
  192568. else if (a == 0)
  192569. {
  192570. /* background is already in screen gamma */
  192571. *dp = (png_byte)background->red;
  192572. *(dp + 1) = (png_byte)background->green;
  192573. *(dp + 2) = (png_byte)background->blue;
  192574. }
  192575. else
  192576. {
  192577. png_byte v, w;
  192578. v = gamma_to_1[*sp];
  192579. png_composite(w, v, a, background_1->red);
  192580. *dp = gamma_from_1[w];
  192581. v = gamma_to_1[*(sp + 1)];
  192582. png_composite(w, v, a, background_1->green);
  192583. *(dp + 1) = gamma_from_1[w];
  192584. v = gamma_to_1[*(sp + 2)];
  192585. png_composite(w, v, a, background_1->blue);
  192586. *(dp + 2) = gamma_from_1[w];
  192587. }
  192588. }
  192589. }
  192590. else
  192591. #endif
  192592. {
  192593. sp = row;
  192594. dp = row;
  192595. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192596. {
  192597. png_byte a = *(sp + 3);
  192598. if (a == 0xff)
  192599. {
  192600. *dp = *sp;
  192601. *(dp + 1) = *(sp + 1);
  192602. *(dp + 2) = *(sp + 2);
  192603. }
  192604. else if (a == 0)
  192605. {
  192606. *dp = (png_byte)background->red;
  192607. *(dp + 1) = (png_byte)background->green;
  192608. *(dp + 2) = (png_byte)background->blue;
  192609. }
  192610. else
  192611. {
  192612. png_composite(*dp, *sp, a, background->red);
  192613. png_composite(*(dp + 1), *(sp + 1), a,
  192614. background->green);
  192615. png_composite(*(dp + 2), *(sp + 2), a,
  192616. background->blue);
  192617. }
  192618. }
  192619. }
  192620. }
  192621. else /* if (row_info->bit_depth == 16) */
  192622. {
  192623. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192624. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192625. gamma_16_to_1 != NULL)
  192626. {
  192627. sp = row;
  192628. dp = row;
  192629. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192630. {
  192631. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192632. << 8) + (png_uint_16)(*(sp + 7)));
  192633. if (a == (png_uint_16)0xffff)
  192634. {
  192635. png_uint_16 v;
  192636. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192637. *dp = (png_byte)((v >> 8) & 0xff);
  192638. *(dp + 1) = (png_byte)(v & 0xff);
  192639. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192640. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192641. *(dp + 3) = (png_byte)(v & 0xff);
  192642. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192643. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192644. *(dp + 5) = (png_byte)(v & 0xff);
  192645. }
  192646. else if (a == 0)
  192647. {
  192648. /* background is already in screen gamma */
  192649. *dp = (png_byte)((background->red >> 8) & 0xff);
  192650. *(dp + 1) = (png_byte)(background->red & 0xff);
  192651. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192652. *(dp + 3) = (png_byte)(background->green & 0xff);
  192653. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192654. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192655. }
  192656. else
  192657. {
  192658. png_uint_16 v, w, x;
  192659. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192660. png_composite_16(w, v, a, background_1->red);
  192661. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192662. *dp = (png_byte)((x >> 8) & 0xff);
  192663. *(dp + 1) = (png_byte)(x & 0xff);
  192664. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192665. png_composite_16(w, v, a, background_1->green);
  192666. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192667. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192668. *(dp + 3) = (png_byte)(x & 0xff);
  192669. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192670. png_composite_16(w, v, a, background_1->blue);
  192671. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192672. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192673. *(dp + 5) = (png_byte)(x & 0xff);
  192674. }
  192675. }
  192676. }
  192677. else
  192678. #endif
  192679. {
  192680. sp = row;
  192681. dp = row;
  192682. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192683. {
  192684. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192685. << 8) + (png_uint_16)(*(sp + 7)));
  192686. if (a == (png_uint_16)0xffff)
  192687. {
  192688. png_memcpy(dp, sp, 6);
  192689. }
  192690. else if (a == 0)
  192691. {
  192692. *dp = (png_byte)((background->red >> 8) & 0xff);
  192693. *(dp + 1) = (png_byte)(background->red & 0xff);
  192694. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192695. *(dp + 3) = (png_byte)(background->green & 0xff);
  192696. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192697. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192698. }
  192699. else
  192700. {
  192701. png_uint_16 v;
  192702. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192703. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192704. + *(sp + 3));
  192705. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192706. + *(sp + 5));
  192707. png_composite_16(v, r, a, background->red);
  192708. *dp = (png_byte)((v >> 8) & 0xff);
  192709. *(dp + 1) = (png_byte)(v & 0xff);
  192710. png_composite_16(v, g, a, background->green);
  192711. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192712. *(dp + 3) = (png_byte)(v & 0xff);
  192713. png_composite_16(v, b, a, background->blue);
  192714. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192715. *(dp + 5) = (png_byte)(v & 0xff);
  192716. }
  192717. }
  192718. }
  192719. }
  192720. break;
  192721. }
  192722. }
  192723. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192724. {
  192725. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192726. row_info->channels--;
  192727. row_info->pixel_depth = (png_byte)(row_info->channels *
  192728. row_info->bit_depth);
  192729. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192730. }
  192731. }
  192732. }
  192733. #endif
  192734. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192735. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192736. * you do this after you deal with the transparency issue on grayscale
  192737. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192738. * is 16, use gamma_16_table and gamma_shift. Build these with
  192739. * build_gamma_table().
  192740. */
  192741. void /* PRIVATE */
  192742. png_do_gamma(png_row_infop row_info, png_bytep row,
  192743. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192744. int gamma_shift)
  192745. {
  192746. png_bytep sp;
  192747. png_uint_32 i;
  192748. png_uint_32 row_width=row_info->width;
  192749. png_debug(1, "in png_do_gamma\n");
  192750. if (
  192751. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192752. row != NULL && row_info != NULL &&
  192753. #endif
  192754. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192755. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192756. {
  192757. switch (row_info->color_type)
  192758. {
  192759. case PNG_COLOR_TYPE_RGB:
  192760. {
  192761. if (row_info->bit_depth == 8)
  192762. {
  192763. sp = row;
  192764. for (i = 0; i < row_width; i++)
  192765. {
  192766. *sp = gamma_table[*sp];
  192767. sp++;
  192768. *sp = gamma_table[*sp];
  192769. sp++;
  192770. *sp = gamma_table[*sp];
  192771. sp++;
  192772. }
  192773. }
  192774. else /* if (row_info->bit_depth == 16) */
  192775. {
  192776. sp = row;
  192777. for (i = 0; i < row_width; i++)
  192778. {
  192779. png_uint_16 v;
  192780. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192781. *sp = (png_byte)((v >> 8) & 0xff);
  192782. *(sp + 1) = (png_byte)(v & 0xff);
  192783. sp += 2;
  192784. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192785. *sp = (png_byte)((v >> 8) & 0xff);
  192786. *(sp + 1) = (png_byte)(v & 0xff);
  192787. sp += 2;
  192788. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192789. *sp = (png_byte)((v >> 8) & 0xff);
  192790. *(sp + 1) = (png_byte)(v & 0xff);
  192791. sp += 2;
  192792. }
  192793. }
  192794. break;
  192795. }
  192796. case PNG_COLOR_TYPE_RGB_ALPHA:
  192797. {
  192798. if (row_info->bit_depth == 8)
  192799. {
  192800. sp = row;
  192801. for (i = 0; i < row_width; i++)
  192802. {
  192803. *sp = gamma_table[*sp];
  192804. sp++;
  192805. *sp = gamma_table[*sp];
  192806. sp++;
  192807. *sp = gamma_table[*sp];
  192808. sp++;
  192809. sp++;
  192810. }
  192811. }
  192812. else /* if (row_info->bit_depth == 16) */
  192813. {
  192814. sp = row;
  192815. for (i = 0; i < row_width; i++)
  192816. {
  192817. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192818. *sp = (png_byte)((v >> 8) & 0xff);
  192819. *(sp + 1) = (png_byte)(v & 0xff);
  192820. sp += 2;
  192821. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192822. *sp = (png_byte)((v >> 8) & 0xff);
  192823. *(sp + 1) = (png_byte)(v & 0xff);
  192824. sp += 2;
  192825. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192826. *sp = (png_byte)((v >> 8) & 0xff);
  192827. *(sp + 1) = (png_byte)(v & 0xff);
  192828. sp += 4;
  192829. }
  192830. }
  192831. break;
  192832. }
  192833. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192834. {
  192835. if (row_info->bit_depth == 8)
  192836. {
  192837. sp = row;
  192838. for (i = 0; i < row_width; i++)
  192839. {
  192840. *sp = gamma_table[*sp];
  192841. sp += 2;
  192842. }
  192843. }
  192844. else /* if (row_info->bit_depth == 16) */
  192845. {
  192846. sp = row;
  192847. for (i = 0; i < row_width; i++)
  192848. {
  192849. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192850. *sp = (png_byte)((v >> 8) & 0xff);
  192851. *(sp + 1) = (png_byte)(v & 0xff);
  192852. sp += 4;
  192853. }
  192854. }
  192855. break;
  192856. }
  192857. case PNG_COLOR_TYPE_GRAY:
  192858. {
  192859. if (row_info->bit_depth == 2)
  192860. {
  192861. sp = row;
  192862. for (i = 0; i < row_width; i += 4)
  192863. {
  192864. int a = *sp & 0xc0;
  192865. int b = *sp & 0x30;
  192866. int c = *sp & 0x0c;
  192867. int d = *sp & 0x03;
  192868. *sp = (png_byte)(
  192869. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192870. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192871. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192872. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192873. sp++;
  192874. }
  192875. }
  192876. if (row_info->bit_depth == 4)
  192877. {
  192878. sp = row;
  192879. for (i = 0; i < row_width; i += 2)
  192880. {
  192881. int msb = *sp & 0xf0;
  192882. int lsb = *sp & 0x0f;
  192883. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192884. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192885. sp++;
  192886. }
  192887. }
  192888. else if (row_info->bit_depth == 8)
  192889. {
  192890. sp = row;
  192891. for (i = 0; i < row_width; i++)
  192892. {
  192893. *sp = gamma_table[*sp];
  192894. sp++;
  192895. }
  192896. }
  192897. else if (row_info->bit_depth == 16)
  192898. {
  192899. sp = row;
  192900. for (i = 0; i < row_width; i++)
  192901. {
  192902. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192903. *sp = (png_byte)((v >> 8) & 0xff);
  192904. *(sp + 1) = (png_byte)(v & 0xff);
  192905. sp += 2;
  192906. }
  192907. }
  192908. break;
  192909. }
  192910. }
  192911. }
  192912. }
  192913. #endif
  192914. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192915. /* Expands a palette row to an RGB or RGBA row depending
  192916. * upon whether you supply trans and num_trans.
  192917. */
  192918. void /* PRIVATE */
  192919. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192920. png_colorp palette, png_bytep trans, int num_trans)
  192921. {
  192922. int shift, value;
  192923. png_bytep sp, dp;
  192924. png_uint_32 i;
  192925. png_uint_32 row_width=row_info->width;
  192926. png_debug(1, "in png_do_expand_palette\n");
  192927. if (
  192928. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192929. row != NULL && row_info != NULL &&
  192930. #endif
  192931. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192932. {
  192933. if (row_info->bit_depth < 8)
  192934. {
  192935. switch (row_info->bit_depth)
  192936. {
  192937. case 1:
  192938. {
  192939. sp = row + (png_size_t)((row_width - 1) >> 3);
  192940. dp = row + (png_size_t)row_width - 1;
  192941. shift = 7 - (int)((row_width + 7) & 0x07);
  192942. for (i = 0; i < row_width; i++)
  192943. {
  192944. if ((*sp >> shift) & 0x01)
  192945. *dp = 1;
  192946. else
  192947. *dp = 0;
  192948. if (shift == 7)
  192949. {
  192950. shift = 0;
  192951. sp--;
  192952. }
  192953. else
  192954. shift++;
  192955. dp--;
  192956. }
  192957. break;
  192958. }
  192959. case 2:
  192960. {
  192961. sp = row + (png_size_t)((row_width - 1) >> 2);
  192962. dp = row + (png_size_t)row_width - 1;
  192963. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192964. for (i = 0; i < row_width; i++)
  192965. {
  192966. value = (*sp >> shift) & 0x03;
  192967. *dp = (png_byte)value;
  192968. if (shift == 6)
  192969. {
  192970. shift = 0;
  192971. sp--;
  192972. }
  192973. else
  192974. shift += 2;
  192975. dp--;
  192976. }
  192977. break;
  192978. }
  192979. case 4:
  192980. {
  192981. sp = row + (png_size_t)((row_width - 1) >> 1);
  192982. dp = row + (png_size_t)row_width - 1;
  192983. shift = (int)((row_width & 0x01) << 2);
  192984. for (i = 0; i < row_width; i++)
  192985. {
  192986. value = (*sp >> shift) & 0x0f;
  192987. *dp = (png_byte)value;
  192988. if (shift == 4)
  192989. {
  192990. shift = 0;
  192991. sp--;
  192992. }
  192993. else
  192994. shift += 4;
  192995. dp--;
  192996. }
  192997. break;
  192998. }
  192999. }
  193000. row_info->bit_depth = 8;
  193001. row_info->pixel_depth = 8;
  193002. row_info->rowbytes = row_width;
  193003. }
  193004. switch (row_info->bit_depth)
  193005. {
  193006. case 8:
  193007. {
  193008. if (trans != NULL)
  193009. {
  193010. sp = row + (png_size_t)row_width - 1;
  193011. dp = row + (png_size_t)(row_width << 2) - 1;
  193012. for (i = 0; i < row_width; i++)
  193013. {
  193014. if ((int)(*sp) >= num_trans)
  193015. *dp-- = 0xff;
  193016. else
  193017. *dp-- = trans[*sp];
  193018. *dp-- = palette[*sp].blue;
  193019. *dp-- = palette[*sp].green;
  193020. *dp-- = palette[*sp].red;
  193021. sp--;
  193022. }
  193023. row_info->bit_depth = 8;
  193024. row_info->pixel_depth = 32;
  193025. row_info->rowbytes = row_width * 4;
  193026. row_info->color_type = 6;
  193027. row_info->channels = 4;
  193028. }
  193029. else
  193030. {
  193031. sp = row + (png_size_t)row_width - 1;
  193032. dp = row + (png_size_t)(row_width * 3) - 1;
  193033. for (i = 0; i < row_width; i++)
  193034. {
  193035. *dp-- = palette[*sp].blue;
  193036. *dp-- = palette[*sp].green;
  193037. *dp-- = palette[*sp].red;
  193038. sp--;
  193039. }
  193040. row_info->bit_depth = 8;
  193041. row_info->pixel_depth = 24;
  193042. row_info->rowbytes = row_width * 3;
  193043. row_info->color_type = 2;
  193044. row_info->channels = 3;
  193045. }
  193046. break;
  193047. }
  193048. }
  193049. }
  193050. }
  193051. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193052. * expanded transparency value is supplied, an alpha channel is built.
  193053. */
  193054. void /* PRIVATE */
  193055. png_do_expand(png_row_infop row_info, png_bytep row,
  193056. png_color_16p trans_value)
  193057. {
  193058. int shift, value;
  193059. png_bytep sp, dp;
  193060. png_uint_32 i;
  193061. png_uint_32 row_width=row_info->width;
  193062. png_debug(1, "in png_do_expand\n");
  193063. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193064. if (row != NULL && row_info != NULL)
  193065. #endif
  193066. {
  193067. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193068. {
  193069. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193070. if (row_info->bit_depth < 8)
  193071. {
  193072. switch (row_info->bit_depth)
  193073. {
  193074. case 1:
  193075. {
  193076. gray = (png_uint_16)((gray&0x01)*0xff);
  193077. sp = row + (png_size_t)((row_width - 1) >> 3);
  193078. dp = row + (png_size_t)row_width - 1;
  193079. shift = 7 - (int)((row_width + 7) & 0x07);
  193080. for (i = 0; i < row_width; i++)
  193081. {
  193082. if ((*sp >> shift) & 0x01)
  193083. *dp = 0xff;
  193084. else
  193085. *dp = 0;
  193086. if (shift == 7)
  193087. {
  193088. shift = 0;
  193089. sp--;
  193090. }
  193091. else
  193092. shift++;
  193093. dp--;
  193094. }
  193095. break;
  193096. }
  193097. case 2:
  193098. {
  193099. gray = (png_uint_16)((gray&0x03)*0x55);
  193100. sp = row + (png_size_t)((row_width - 1) >> 2);
  193101. dp = row + (png_size_t)row_width - 1;
  193102. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193103. for (i = 0; i < row_width; i++)
  193104. {
  193105. value = (*sp >> shift) & 0x03;
  193106. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193107. (value << 6));
  193108. if (shift == 6)
  193109. {
  193110. shift = 0;
  193111. sp--;
  193112. }
  193113. else
  193114. shift += 2;
  193115. dp--;
  193116. }
  193117. break;
  193118. }
  193119. case 4:
  193120. {
  193121. gray = (png_uint_16)((gray&0x0f)*0x11);
  193122. sp = row + (png_size_t)((row_width - 1) >> 1);
  193123. dp = row + (png_size_t)row_width - 1;
  193124. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193125. for (i = 0; i < row_width; i++)
  193126. {
  193127. value = (*sp >> shift) & 0x0f;
  193128. *dp = (png_byte)(value | (value << 4));
  193129. if (shift == 4)
  193130. {
  193131. shift = 0;
  193132. sp--;
  193133. }
  193134. else
  193135. shift = 4;
  193136. dp--;
  193137. }
  193138. break;
  193139. }
  193140. }
  193141. row_info->bit_depth = 8;
  193142. row_info->pixel_depth = 8;
  193143. row_info->rowbytes = row_width;
  193144. }
  193145. if (trans_value != NULL)
  193146. {
  193147. if (row_info->bit_depth == 8)
  193148. {
  193149. gray = gray & 0xff;
  193150. sp = row + (png_size_t)row_width - 1;
  193151. dp = row + (png_size_t)(row_width << 1) - 1;
  193152. for (i = 0; i < row_width; i++)
  193153. {
  193154. if (*sp == gray)
  193155. *dp-- = 0;
  193156. else
  193157. *dp-- = 0xff;
  193158. *dp-- = *sp--;
  193159. }
  193160. }
  193161. else if (row_info->bit_depth == 16)
  193162. {
  193163. png_byte gray_high = (gray >> 8) & 0xff;
  193164. png_byte gray_low = gray & 0xff;
  193165. sp = row + row_info->rowbytes - 1;
  193166. dp = row + (row_info->rowbytes << 1) - 1;
  193167. for (i = 0; i < row_width; i++)
  193168. {
  193169. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193170. {
  193171. *dp-- = 0;
  193172. *dp-- = 0;
  193173. }
  193174. else
  193175. {
  193176. *dp-- = 0xff;
  193177. *dp-- = 0xff;
  193178. }
  193179. *dp-- = *sp--;
  193180. *dp-- = *sp--;
  193181. }
  193182. }
  193183. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193184. row_info->channels = 2;
  193185. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193186. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193187. row_width);
  193188. }
  193189. }
  193190. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193191. {
  193192. if (row_info->bit_depth == 8)
  193193. {
  193194. png_byte red = trans_value->red & 0xff;
  193195. png_byte green = trans_value->green & 0xff;
  193196. png_byte blue = trans_value->blue & 0xff;
  193197. sp = row + (png_size_t)row_info->rowbytes - 1;
  193198. dp = row + (png_size_t)(row_width << 2) - 1;
  193199. for (i = 0; i < row_width; i++)
  193200. {
  193201. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193202. *dp-- = 0;
  193203. else
  193204. *dp-- = 0xff;
  193205. *dp-- = *sp--;
  193206. *dp-- = *sp--;
  193207. *dp-- = *sp--;
  193208. }
  193209. }
  193210. else if (row_info->bit_depth == 16)
  193211. {
  193212. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193213. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193214. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193215. png_byte red_low = trans_value->red & 0xff;
  193216. png_byte green_low = trans_value->green & 0xff;
  193217. png_byte blue_low = trans_value->blue & 0xff;
  193218. sp = row + row_info->rowbytes - 1;
  193219. dp = row + (png_size_t)(row_width << 3) - 1;
  193220. for (i = 0; i < row_width; i++)
  193221. {
  193222. if (*(sp - 5) == red_high &&
  193223. *(sp - 4) == red_low &&
  193224. *(sp - 3) == green_high &&
  193225. *(sp - 2) == green_low &&
  193226. *(sp - 1) == blue_high &&
  193227. *(sp ) == blue_low)
  193228. {
  193229. *dp-- = 0;
  193230. *dp-- = 0;
  193231. }
  193232. else
  193233. {
  193234. *dp-- = 0xff;
  193235. *dp-- = 0xff;
  193236. }
  193237. *dp-- = *sp--;
  193238. *dp-- = *sp--;
  193239. *dp-- = *sp--;
  193240. *dp-- = *sp--;
  193241. *dp-- = *sp--;
  193242. *dp-- = *sp--;
  193243. }
  193244. }
  193245. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193246. row_info->channels = 4;
  193247. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193248. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193249. }
  193250. }
  193251. }
  193252. #endif
  193253. #if defined(PNG_READ_DITHER_SUPPORTED)
  193254. void /* PRIVATE */
  193255. png_do_dither(png_row_infop row_info, png_bytep row,
  193256. png_bytep palette_lookup, png_bytep dither_lookup)
  193257. {
  193258. png_bytep sp, dp;
  193259. png_uint_32 i;
  193260. png_uint_32 row_width=row_info->width;
  193261. png_debug(1, "in png_do_dither\n");
  193262. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193263. if (row != NULL && row_info != NULL)
  193264. #endif
  193265. {
  193266. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193267. palette_lookup && row_info->bit_depth == 8)
  193268. {
  193269. int r, g, b, p;
  193270. sp = row;
  193271. dp = row;
  193272. for (i = 0; i < row_width; i++)
  193273. {
  193274. r = *sp++;
  193275. g = *sp++;
  193276. b = *sp++;
  193277. /* this looks real messy, but the compiler will reduce
  193278. it down to a reasonable formula. For example, with
  193279. 5 bits per color, we get:
  193280. p = (((r >> 3) & 0x1f) << 10) |
  193281. (((g >> 3) & 0x1f) << 5) |
  193282. ((b >> 3) & 0x1f);
  193283. */
  193284. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193285. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193286. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193287. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193288. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193289. (PNG_DITHER_BLUE_BITS)) |
  193290. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193291. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193292. *dp++ = palette_lookup[p];
  193293. }
  193294. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193295. row_info->channels = 1;
  193296. row_info->pixel_depth = row_info->bit_depth;
  193297. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193298. }
  193299. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193300. palette_lookup != NULL && row_info->bit_depth == 8)
  193301. {
  193302. int r, g, b, p;
  193303. sp = row;
  193304. dp = row;
  193305. for (i = 0; i < row_width; i++)
  193306. {
  193307. r = *sp++;
  193308. g = *sp++;
  193309. b = *sp++;
  193310. sp++;
  193311. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193312. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193313. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193314. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193315. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193316. (PNG_DITHER_BLUE_BITS)) |
  193317. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193318. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193319. *dp++ = palette_lookup[p];
  193320. }
  193321. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193322. row_info->channels = 1;
  193323. row_info->pixel_depth = row_info->bit_depth;
  193324. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193325. }
  193326. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193327. dither_lookup && row_info->bit_depth == 8)
  193328. {
  193329. sp = row;
  193330. for (i = 0; i < row_width; i++, sp++)
  193331. {
  193332. *sp = dither_lookup[*sp];
  193333. }
  193334. }
  193335. }
  193336. }
  193337. #endif
  193338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193339. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193340. static PNG_CONST int png_gamma_shift[] =
  193341. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193342. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193343. * tables, we don't make a full table if we are reducing to 8-bit in
  193344. * the future. Note also how the gamma_16 tables are segmented so that
  193345. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193346. */
  193347. void /* PRIVATE */
  193348. png_build_gamma_table(png_structp png_ptr)
  193349. {
  193350. png_debug(1, "in png_build_gamma_table\n");
  193351. if (png_ptr->bit_depth <= 8)
  193352. {
  193353. int i;
  193354. double g;
  193355. if (png_ptr->screen_gamma > .000001)
  193356. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193357. else
  193358. g = 1.0;
  193359. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193360. (png_uint_32)256);
  193361. for (i = 0; i < 256; i++)
  193362. {
  193363. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193364. g) * 255.0 + .5);
  193365. }
  193366. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193367. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193368. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193369. {
  193370. g = 1.0 / (png_ptr->gamma);
  193371. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193372. (png_uint_32)256);
  193373. for (i = 0; i < 256; i++)
  193374. {
  193375. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193376. g) * 255.0 + .5);
  193377. }
  193378. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193379. (png_uint_32)256);
  193380. if(png_ptr->screen_gamma > 0.000001)
  193381. g = 1.0 / png_ptr->screen_gamma;
  193382. else
  193383. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193384. for (i = 0; i < 256; i++)
  193385. {
  193386. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193387. g) * 255.0 + .5);
  193388. }
  193389. }
  193390. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193391. }
  193392. else
  193393. {
  193394. double g;
  193395. int i, j, shift, num;
  193396. int sig_bit;
  193397. png_uint_32 ig;
  193398. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193399. {
  193400. sig_bit = (int)png_ptr->sig_bit.red;
  193401. if ((int)png_ptr->sig_bit.green > sig_bit)
  193402. sig_bit = png_ptr->sig_bit.green;
  193403. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193404. sig_bit = png_ptr->sig_bit.blue;
  193405. }
  193406. else
  193407. {
  193408. sig_bit = (int)png_ptr->sig_bit.gray;
  193409. }
  193410. if (sig_bit > 0)
  193411. shift = 16 - sig_bit;
  193412. else
  193413. shift = 0;
  193414. if (png_ptr->transformations & PNG_16_TO_8)
  193415. {
  193416. if (shift < (16 - PNG_MAX_GAMMA_8))
  193417. shift = (16 - PNG_MAX_GAMMA_8);
  193418. }
  193419. if (shift > 8)
  193420. shift = 8;
  193421. if (shift < 0)
  193422. shift = 0;
  193423. png_ptr->gamma_shift = (png_byte)shift;
  193424. num = (1 << (8 - shift));
  193425. if (png_ptr->screen_gamma > .000001)
  193426. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193427. else
  193428. g = 1.0;
  193429. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193430. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193431. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193432. {
  193433. double fin, fout;
  193434. png_uint_32 last, max;
  193435. for (i = 0; i < num; i++)
  193436. {
  193437. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193438. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193439. }
  193440. g = 1.0 / g;
  193441. last = 0;
  193442. for (i = 0; i < 256; i++)
  193443. {
  193444. fout = ((double)i + 0.5) / 256.0;
  193445. fin = pow(fout, g);
  193446. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193447. while (last <= max)
  193448. {
  193449. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193450. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193451. (png_uint_16)i | ((png_uint_16)i << 8));
  193452. last++;
  193453. }
  193454. }
  193455. while (last < ((png_uint_32)num << 8))
  193456. {
  193457. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193458. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193459. last++;
  193460. }
  193461. }
  193462. else
  193463. {
  193464. for (i = 0; i < num; i++)
  193465. {
  193466. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193467. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193468. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193469. for (j = 0; j < 256; j++)
  193470. {
  193471. png_ptr->gamma_16_table[i][j] =
  193472. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193473. 65535.0, g) * 65535.0 + .5);
  193474. }
  193475. }
  193476. }
  193477. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193478. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193479. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193480. {
  193481. g = 1.0 / (png_ptr->gamma);
  193482. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193483. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193484. for (i = 0; i < num; i++)
  193485. {
  193486. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193487. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193488. ig = (((png_uint_32)i *
  193489. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193490. for (j = 0; j < 256; j++)
  193491. {
  193492. png_ptr->gamma_16_to_1[i][j] =
  193493. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193494. 65535.0, g) * 65535.0 + .5);
  193495. }
  193496. }
  193497. if(png_ptr->screen_gamma > 0.000001)
  193498. g = 1.0 / png_ptr->screen_gamma;
  193499. else
  193500. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193501. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193502. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193503. for (i = 0; i < num; i++)
  193504. {
  193505. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193506. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193507. ig = (((png_uint_32)i *
  193508. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193509. for (j = 0; j < 256; j++)
  193510. {
  193511. png_ptr->gamma_16_from_1[i][j] =
  193512. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193513. 65535.0, g) * 65535.0 + .5);
  193514. }
  193515. }
  193516. }
  193517. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193518. }
  193519. }
  193520. #endif
  193521. /* To do: install integer version of png_build_gamma_table here */
  193522. #endif
  193523. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193524. /* undoes intrapixel differencing */
  193525. void /* PRIVATE */
  193526. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193527. {
  193528. png_debug(1, "in png_do_read_intrapixel\n");
  193529. if (
  193530. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193531. row != NULL && row_info != NULL &&
  193532. #endif
  193533. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193534. {
  193535. int bytes_per_pixel;
  193536. png_uint_32 row_width = row_info->width;
  193537. if (row_info->bit_depth == 8)
  193538. {
  193539. png_bytep rp;
  193540. png_uint_32 i;
  193541. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193542. bytes_per_pixel = 3;
  193543. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193544. bytes_per_pixel = 4;
  193545. else
  193546. return;
  193547. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193548. {
  193549. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193550. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193551. }
  193552. }
  193553. else if (row_info->bit_depth == 16)
  193554. {
  193555. png_bytep rp;
  193556. png_uint_32 i;
  193557. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193558. bytes_per_pixel = 6;
  193559. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193560. bytes_per_pixel = 8;
  193561. else
  193562. return;
  193563. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193564. {
  193565. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193566. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193567. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193568. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193569. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193570. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193571. *(rp+1) = (png_byte)(red & 0xff);
  193572. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193573. *(rp+5) = (png_byte)(blue & 0xff);
  193574. }
  193575. }
  193576. }
  193577. }
  193578. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193579. #endif /* PNG_READ_SUPPORTED */
  193580. /*** End of inlined file: pngrtran.c ***/
  193581. /*** Start of inlined file: pngrutil.c ***/
  193582. /* pngrutil.c - utilities to read a PNG file
  193583. *
  193584. * Last changed in libpng 1.2.21 [October 4, 2007]
  193585. * For conditions of distribution and use, see copyright notice in png.h
  193586. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193587. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193588. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193589. *
  193590. * This file contains routines that are only called from within
  193591. * libpng itself during the course of reading an image.
  193592. */
  193593. #define PNG_INTERNAL
  193594. #if defined(PNG_READ_SUPPORTED)
  193595. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193596. # define WIN32_WCE_OLD
  193597. #endif
  193598. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193599. # if defined(WIN32_WCE_OLD)
  193600. /* strtod() function is not supported on WindowsCE */
  193601. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193602. {
  193603. double result = 0;
  193604. int len;
  193605. wchar_t *str, *end;
  193606. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193607. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193608. if ( NULL != str )
  193609. {
  193610. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193611. result = wcstod(str, &end);
  193612. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193613. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193614. png_free(png_ptr, str);
  193615. }
  193616. return result;
  193617. }
  193618. # else
  193619. # define png_strtod(p,a,b) strtod(a,b)
  193620. # endif
  193621. #endif
  193622. png_uint_32 PNGAPI
  193623. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193624. {
  193625. png_uint_32 i = png_get_uint_32(buf);
  193626. if (i > PNG_UINT_31_MAX)
  193627. png_error(png_ptr, "PNG unsigned integer out of range.");
  193628. return (i);
  193629. }
  193630. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193631. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193632. png_uint_32 PNGAPI
  193633. png_get_uint_32(png_bytep buf)
  193634. {
  193635. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193636. ((png_uint_32)(*(buf + 1)) << 16) +
  193637. ((png_uint_32)(*(buf + 2)) << 8) +
  193638. (png_uint_32)(*(buf + 3));
  193639. return (i);
  193640. }
  193641. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193642. * data is stored in the PNG file in two's complement format, and it is
  193643. * assumed that the machine format for signed integers is the same. */
  193644. png_int_32 PNGAPI
  193645. png_get_int_32(png_bytep buf)
  193646. {
  193647. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193648. ((png_int_32)(*(buf + 1)) << 16) +
  193649. ((png_int_32)(*(buf + 2)) << 8) +
  193650. (png_int_32)(*(buf + 3));
  193651. return (i);
  193652. }
  193653. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193654. png_uint_16 PNGAPI
  193655. png_get_uint_16(png_bytep buf)
  193656. {
  193657. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193658. (png_uint_16)(*(buf + 1)));
  193659. return (i);
  193660. }
  193661. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193662. /* Read data, and (optionally) run it through the CRC. */
  193663. void /* PRIVATE */
  193664. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193665. {
  193666. if(png_ptr == NULL) return;
  193667. png_read_data(png_ptr, buf, length);
  193668. png_calculate_crc(png_ptr, buf, length);
  193669. }
  193670. /* Optionally skip data and then check the CRC. Depending on whether we
  193671. are reading a ancillary or critical chunk, and how the program has set
  193672. things up, we may calculate the CRC on the data and print a message.
  193673. Returns '1' if there was a CRC error, '0' otherwise. */
  193674. int /* PRIVATE */
  193675. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193676. {
  193677. png_size_t i;
  193678. png_size_t istop = png_ptr->zbuf_size;
  193679. for (i = (png_size_t)skip; i > istop; i -= istop)
  193680. {
  193681. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193682. }
  193683. if (i)
  193684. {
  193685. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193686. }
  193687. if (png_crc_error(png_ptr))
  193688. {
  193689. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193690. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193691. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193692. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193693. {
  193694. png_chunk_warning(png_ptr, "CRC error");
  193695. }
  193696. else
  193697. {
  193698. png_chunk_error(png_ptr, "CRC error");
  193699. }
  193700. return (1);
  193701. }
  193702. return (0);
  193703. }
  193704. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193705. the data it has read thus far. */
  193706. int /* PRIVATE */
  193707. png_crc_error(png_structp png_ptr)
  193708. {
  193709. png_byte crc_bytes[4];
  193710. png_uint_32 crc;
  193711. int need_crc = 1;
  193712. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193713. {
  193714. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193715. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193716. need_crc = 0;
  193717. }
  193718. else /* critical */
  193719. {
  193720. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193721. need_crc = 0;
  193722. }
  193723. png_read_data(png_ptr, crc_bytes, 4);
  193724. if (need_crc)
  193725. {
  193726. crc = png_get_uint_32(crc_bytes);
  193727. return ((int)(crc != png_ptr->crc));
  193728. }
  193729. else
  193730. return (0);
  193731. }
  193732. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193733. defined(PNG_READ_iCCP_SUPPORTED)
  193734. /*
  193735. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193736. * points at an allocated area holding the contents of a chunk with a
  193737. * trailing compressed part. What we get back is an allocated area
  193738. * holding the original prefix part and an uncompressed version of the
  193739. * trailing part (the malloc area passed in is freed).
  193740. */
  193741. png_charp /* PRIVATE */
  193742. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193743. png_charp chunkdata, png_size_t chunklength,
  193744. png_size_t prefix_size, png_size_t *newlength)
  193745. {
  193746. static PNG_CONST char msg[] = "Error decoding compressed text";
  193747. png_charp text;
  193748. png_size_t text_size;
  193749. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193750. {
  193751. int ret = Z_OK;
  193752. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193753. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193754. png_ptr->zstream.next_out = png_ptr->zbuf;
  193755. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193756. text_size = 0;
  193757. text = NULL;
  193758. while (png_ptr->zstream.avail_in)
  193759. {
  193760. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193761. if (ret != Z_OK && ret != Z_STREAM_END)
  193762. {
  193763. if (png_ptr->zstream.msg != NULL)
  193764. png_warning(png_ptr, png_ptr->zstream.msg);
  193765. else
  193766. png_warning(png_ptr, msg);
  193767. inflateReset(&png_ptr->zstream);
  193768. png_ptr->zstream.avail_in = 0;
  193769. if (text == NULL)
  193770. {
  193771. text_size = prefix_size + png_sizeof(msg) + 1;
  193772. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193773. if (text == NULL)
  193774. {
  193775. png_free(png_ptr,chunkdata);
  193776. png_error(png_ptr,"Not enough memory to decompress chunk");
  193777. }
  193778. png_memcpy(text, chunkdata, prefix_size);
  193779. }
  193780. text[text_size - 1] = 0x00;
  193781. /* Copy what we can of the error message into the text chunk */
  193782. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193783. text_size = png_sizeof(msg) > text_size ? text_size :
  193784. png_sizeof(msg);
  193785. png_memcpy(text + prefix_size, msg, text_size + 1);
  193786. break;
  193787. }
  193788. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193789. {
  193790. if (text == NULL)
  193791. {
  193792. text_size = prefix_size +
  193793. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193794. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193795. if (text == NULL)
  193796. {
  193797. png_free(png_ptr,chunkdata);
  193798. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193799. }
  193800. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193801. text_size - prefix_size);
  193802. png_memcpy(text, chunkdata, prefix_size);
  193803. *(text + text_size) = 0x00;
  193804. }
  193805. else
  193806. {
  193807. png_charp tmp;
  193808. tmp = text;
  193809. text = (png_charp)png_malloc_warn(png_ptr,
  193810. (png_uint_32)(text_size +
  193811. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193812. if (text == NULL)
  193813. {
  193814. png_free(png_ptr, tmp);
  193815. png_free(png_ptr, chunkdata);
  193816. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193817. }
  193818. png_memcpy(text, tmp, text_size);
  193819. png_free(png_ptr, tmp);
  193820. png_memcpy(text + text_size, png_ptr->zbuf,
  193821. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193822. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193823. *(text + text_size) = 0x00;
  193824. }
  193825. if (ret == Z_STREAM_END)
  193826. break;
  193827. else
  193828. {
  193829. png_ptr->zstream.next_out = png_ptr->zbuf;
  193830. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193831. }
  193832. }
  193833. }
  193834. if (ret != Z_STREAM_END)
  193835. {
  193836. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193837. char umsg[52];
  193838. if (ret == Z_BUF_ERROR)
  193839. png_snprintf(umsg, 52,
  193840. "Buffer error in compressed datastream in %s chunk",
  193841. png_ptr->chunk_name);
  193842. else if (ret == Z_DATA_ERROR)
  193843. png_snprintf(umsg, 52,
  193844. "Data error in compressed datastream in %s chunk",
  193845. png_ptr->chunk_name);
  193846. else
  193847. png_snprintf(umsg, 52,
  193848. "Incomplete compressed datastream in %s chunk",
  193849. png_ptr->chunk_name);
  193850. png_warning(png_ptr, umsg);
  193851. #else
  193852. png_warning(png_ptr,
  193853. "Incomplete compressed datastream in chunk other than IDAT");
  193854. #endif
  193855. text_size=prefix_size;
  193856. if (text == NULL)
  193857. {
  193858. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193859. if (text == NULL)
  193860. {
  193861. png_free(png_ptr, chunkdata);
  193862. png_error(png_ptr,"Not enough memory for text.");
  193863. }
  193864. png_memcpy(text, chunkdata, prefix_size);
  193865. }
  193866. *(text + text_size) = 0x00;
  193867. }
  193868. inflateReset(&png_ptr->zstream);
  193869. png_ptr->zstream.avail_in = 0;
  193870. png_free(png_ptr, chunkdata);
  193871. chunkdata = text;
  193872. *newlength=text_size;
  193873. }
  193874. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193875. {
  193876. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193877. char umsg[50];
  193878. png_snprintf(umsg, 50,
  193879. "Unknown zTXt compression type %d", comp_type);
  193880. png_warning(png_ptr, umsg);
  193881. #else
  193882. png_warning(png_ptr, "Unknown zTXt compression type");
  193883. #endif
  193884. *(chunkdata + prefix_size) = 0x00;
  193885. *newlength=prefix_size;
  193886. }
  193887. return chunkdata;
  193888. }
  193889. #endif
  193890. /* read and check the IDHR chunk */
  193891. void /* PRIVATE */
  193892. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193893. {
  193894. png_byte buf[13];
  193895. png_uint_32 width, height;
  193896. int bit_depth, color_type, compression_type, filter_type;
  193897. int interlace_type;
  193898. png_debug(1, "in png_handle_IHDR\n");
  193899. if (png_ptr->mode & PNG_HAVE_IHDR)
  193900. png_error(png_ptr, "Out of place IHDR");
  193901. /* check the length */
  193902. if (length != 13)
  193903. png_error(png_ptr, "Invalid IHDR chunk");
  193904. png_ptr->mode |= PNG_HAVE_IHDR;
  193905. png_crc_read(png_ptr, buf, 13);
  193906. png_crc_finish(png_ptr, 0);
  193907. width = png_get_uint_31(png_ptr, buf);
  193908. height = png_get_uint_31(png_ptr, buf + 4);
  193909. bit_depth = buf[8];
  193910. color_type = buf[9];
  193911. compression_type = buf[10];
  193912. filter_type = buf[11];
  193913. interlace_type = buf[12];
  193914. /* set internal variables */
  193915. png_ptr->width = width;
  193916. png_ptr->height = height;
  193917. png_ptr->bit_depth = (png_byte)bit_depth;
  193918. png_ptr->interlaced = (png_byte)interlace_type;
  193919. png_ptr->color_type = (png_byte)color_type;
  193920. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193921. png_ptr->filter_type = (png_byte)filter_type;
  193922. #endif
  193923. png_ptr->compression_type = (png_byte)compression_type;
  193924. /* find number of channels */
  193925. switch (png_ptr->color_type)
  193926. {
  193927. case PNG_COLOR_TYPE_GRAY:
  193928. case PNG_COLOR_TYPE_PALETTE:
  193929. png_ptr->channels = 1;
  193930. break;
  193931. case PNG_COLOR_TYPE_RGB:
  193932. png_ptr->channels = 3;
  193933. break;
  193934. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193935. png_ptr->channels = 2;
  193936. break;
  193937. case PNG_COLOR_TYPE_RGB_ALPHA:
  193938. png_ptr->channels = 4;
  193939. break;
  193940. }
  193941. /* set up other useful info */
  193942. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193943. png_ptr->channels);
  193944. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193945. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193946. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193947. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193948. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193949. color_type, interlace_type, compression_type, filter_type);
  193950. }
  193951. /* read and check the palette */
  193952. void /* PRIVATE */
  193953. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193954. {
  193955. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193956. int num, i;
  193957. #ifndef PNG_NO_POINTER_INDEXING
  193958. png_colorp pal_ptr;
  193959. #endif
  193960. png_debug(1, "in png_handle_PLTE\n");
  193961. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193962. png_error(png_ptr, "Missing IHDR before PLTE");
  193963. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193964. {
  193965. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193966. png_crc_finish(png_ptr, length);
  193967. return;
  193968. }
  193969. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193970. png_error(png_ptr, "Duplicate PLTE chunk");
  193971. png_ptr->mode |= PNG_HAVE_PLTE;
  193972. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193973. {
  193974. png_warning(png_ptr,
  193975. "Ignoring PLTE chunk in grayscale PNG");
  193976. png_crc_finish(png_ptr, length);
  193977. return;
  193978. }
  193979. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193980. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193981. {
  193982. png_crc_finish(png_ptr, length);
  193983. return;
  193984. }
  193985. #endif
  193986. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193987. {
  193988. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193989. {
  193990. png_warning(png_ptr, "Invalid palette chunk");
  193991. png_crc_finish(png_ptr, length);
  193992. return;
  193993. }
  193994. else
  193995. {
  193996. png_error(png_ptr, "Invalid palette chunk");
  193997. }
  193998. }
  193999. num = (int)length / 3;
  194000. #ifndef PNG_NO_POINTER_INDEXING
  194001. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194002. {
  194003. png_byte buf[3];
  194004. png_crc_read(png_ptr, buf, 3);
  194005. pal_ptr->red = buf[0];
  194006. pal_ptr->green = buf[1];
  194007. pal_ptr->blue = buf[2];
  194008. }
  194009. #else
  194010. for (i = 0; i < num; i++)
  194011. {
  194012. png_byte buf[3];
  194013. png_crc_read(png_ptr, buf, 3);
  194014. /* don't depend upon png_color being any order */
  194015. palette[i].red = buf[0];
  194016. palette[i].green = buf[1];
  194017. palette[i].blue = buf[2];
  194018. }
  194019. #endif
  194020. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194021. whatever the normal CRC configuration tells us. However, if we
  194022. have an RGB image, the PLTE can be considered ancillary, so
  194023. we will act as though it is. */
  194024. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194025. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194026. #endif
  194027. {
  194028. png_crc_finish(png_ptr, 0);
  194029. }
  194030. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194031. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194032. {
  194033. /* If we don't want to use the data from an ancillary chunk,
  194034. we have two options: an error abort, or a warning and we
  194035. ignore the data in this chunk (which should be OK, since
  194036. it's considered ancillary for a RGB or RGBA image). */
  194037. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194038. {
  194039. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194040. {
  194041. png_chunk_error(png_ptr, "CRC error");
  194042. }
  194043. else
  194044. {
  194045. png_chunk_warning(png_ptr, "CRC error");
  194046. return;
  194047. }
  194048. }
  194049. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194050. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194051. {
  194052. png_chunk_warning(png_ptr, "CRC error");
  194053. }
  194054. }
  194055. #endif
  194056. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194057. #if defined(PNG_READ_tRNS_SUPPORTED)
  194058. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194059. {
  194060. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194061. {
  194062. if (png_ptr->num_trans > (png_uint_16)num)
  194063. {
  194064. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194065. png_ptr->num_trans = (png_uint_16)num;
  194066. }
  194067. if (info_ptr->num_trans > (png_uint_16)num)
  194068. {
  194069. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194070. info_ptr->num_trans = (png_uint_16)num;
  194071. }
  194072. }
  194073. }
  194074. #endif
  194075. }
  194076. void /* PRIVATE */
  194077. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194078. {
  194079. png_debug(1, "in png_handle_IEND\n");
  194080. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194081. {
  194082. png_error(png_ptr, "No image in file");
  194083. }
  194084. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194085. if (length != 0)
  194086. {
  194087. png_warning(png_ptr, "Incorrect IEND chunk length");
  194088. }
  194089. png_crc_finish(png_ptr, length);
  194090. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194091. }
  194092. #if defined(PNG_READ_gAMA_SUPPORTED)
  194093. void /* PRIVATE */
  194094. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194095. {
  194096. png_fixed_point igamma;
  194097. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194098. float file_gamma;
  194099. #endif
  194100. png_byte buf[4];
  194101. png_debug(1, "in png_handle_gAMA\n");
  194102. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194103. png_error(png_ptr, "Missing IHDR before gAMA");
  194104. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194105. {
  194106. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194107. png_crc_finish(png_ptr, length);
  194108. return;
  194109. }
  194110. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194111. /* Should be an error, but we can cope with it */
  194112. png_warning(png_ptr, "Out of place gAMA chunk");
  194113. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194114. #if defined(PNG_READ_sRGB_SUPPORTED)
  194115. && !(info_ptr->valid & PNG_INFO_sRGB)
  194116. #endif
  194117. )
  194118. {
  194119. png_warning(png_ptr, "Duplicate gAMA chunk");
  194120. png_crc_finish(png_ptr, length);
  194121. return;
  194122. }
  194123. if (length != 4)
  194124. {
  194125. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194126. png_crc_finish(png_ptr, length);
  194127. return;
  194128. }
  194129. png_crc_read(png_ptr, buf, 4);
  194130. if (png_crc_finish(png_ptr, 0))
  194131. return;
  194132. igamma = (png_fixed_point)png_get_uint_32(buf);
  194133. /* check for zero gamma */
  194134. if (igamma == 0)
  194135. {
  194136. png_warning(png_ptr,
  194137. "Ignoring gAMA chunk with gamma=0");
  194138. return;
  194139. }
  194140. #if defined(PNG_READ_sRGB_SUPPORTED)
  194141. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194142. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194143. {
  194144. png_warning(png_ptr,
  194145. "Ignoring incorrect gAMA value when sRGB is also present");
  194146. #ifndef PNG_NO_CONSOLE_IO
  194147. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194148. #endif
  194149. return;
  194150. }
  194151. #endif /* PNG_READ_sRGB_SUPPORTED */
  194152. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194153. file_gamma = (float)igamma / (float)100000.0;
  194154. # ifdef PNG_READ_GAMMA_SUPPORTED
  194155. png_ptr->gamma = file_gamma;
  194156. # endif
  194157. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194158. #endif
  194159. #ifdef PNG_FIXED_POINT_SUPPORTED
  194160. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194161. #endif
  194162. }
  194163. #endif
  194164. #if defined(PNG_READ_sBIT_SUPPORTED)
  194165. void /* PRIVATE */
  194166. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194167. {
  194168. png_size_t truelen;
  194169. png_byte buf[4];
  194170. png_debug(1, "in png_handle_sBIT\n");
  194171. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194172. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194173. png_error(png_ptr, "Missing IHDR before sBIT");
  194174. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194175. {
  194176. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194177. png_crc_finish(png_ptr, length);
  194178. return;
  194179. }
  194180. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194181. {
  194182. /* Should be an error, but we can cope with it */
  194183. png_warning(png_ptr, "Out of place sBIT chunk");
  194184. }
  194185. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194186. {
  194187. png_warning(png_ptr, "Duplicate sBIT chunk");
  194188. png_crc_finish(png_ptr, length);
  194189. return;
  194190. }
  194191. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194192. truelen = 3;
  194193. else
  194194. truelen = (png_size_t)png_ptr->channels;
  194195. if (length != truelen || length > 4)
  194196. {
  194197. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194198. png_crc_finish(png_ptr, length);
  194199. return;
  194200. }
  194201. png_crc_read(png_ptr, buf, truelen);
  194202. if (png_crc_finish(png_ptr, 0))
  194203. return;
  194204. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194205. {
  194206. png_ptr->sig_bit.red = buf[0];
  194207. png_ptr->sig_bit.green = buf[1];
  194208. png_ptr->sig_bit.blue = buf[2];
  194209. png_ptr->sig_bit.alpha = buf[3];
  194210. }
  194211. else
  194212. {
  194213. png_ptr->sig_bit.gray = buf[0];
  194214. png_ptr->sig_bit.red = buf[0];
  194215. png_ptr->sig_bit.green = buf[0];
  194216. png_ptr->sig_bit.blue = buf[0];
  194217. png_ptr->sig_bit.alpha = buf[1];
  194218. }
  194219. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194220. }
  194221. #endif
  194222. #if defined(PNG_READ_cHRM_SUPPORTED)
  194223. void /* PRIVATE */
  194224. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194225. {
  194226. png_byte buf[4];
  194227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194228. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194229. #endif
  194230. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194231. int_y_green, int_x_blue, int_y_blue;
  194232. png_uint_32 uint_x, uint_y;
  194233. png_debug(1, "in png_handle_cHRM\n");
  194234. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194235. png_error(png_ptr, "Missing IHDR before cHRM");
  194236. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194237. {
  194238. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194239. png_crc_finish(png_ptr, length);
  194240. return;
  194241. }
  194242. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194243. /* Should be an error, but we can cope with it */
  194244. png_warning(png_ptr, "Missing PLTE before cHRM");
  194245. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194246. #if defined(PNG_READ_sRGB_SUPPORTED)
  194247. && !(info_ptr->valid & PNG_INFO_sRGB)
  194248. #endif
  194249. )
  194250. {
  194251. png_warning(png_ptr, "Duplicate cHRM chunk");
  194252. png_crc_finish(png_ptr, length);
  194253. return;
  194254. }
  194255. if (length != 32)
  194256. {
  194257. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194258. png_crc_finish(png_ptr, length);
  194259. return;
  194260. }
  194261. png_crc_read(png_ptr, buf, 4);
  194262. uint_x = png_get_uint_32(buf);
  194263. png_crc_read(png_ptr, buf, 4);
  194264. uint_y = png_get_uint_32(buf);
  194265. if (uint_x > 80000L || uint_y > 80000L ||
  194266. uint_x + uint_y > 100000L)
  194267. {
  194268. png_warning(png_ptr, "Invalid cHRM white point");
  194269. png_crc_finish(png_ptr, 24);
  194270. return;
  194271. }
  194272. int_x_white = (png_fixed_point)uint_x;
  194273. int_y_white = (png_fixed_point)uint_y;
  194274. png_crc_read(png_ptr, buf, 4);
  194275. uint_x = png_get_uint_32(buf);
  194276. png_crc_read(png_ptr, buf, 4);
  194277. uint_y = png_get_uint_32(buf);
  194278. if (uint_x + uint_y > 100000L)
  194279. {
  194280. png_warning(png_ptr, "Invalid cHRM red point");
  194281. png_crc_finish(png_ptr, 16);
  194282. return;
  194283. }
  194284. int_x_red = (png_fixed_point)uint_x;
  194285. int_y_red = (png_fixed_point)uint_y;
  194286. png_crc_read(png_ptr, buf, 4);
  194287. uint_x = png_get_uint_32(buf);
  194288. png_crc_read(png_ptr, buf, 4);
  194289. uint_y = png_get_uint_32(buf);
  194290. if (uint_x + uint_y > 100000L)
  194291. {
  194292. png_warning(png_ptr, "Invalid cHRM green point");
  194293. png_crc_finish(png_ptr, 8);
  194294. return;
  194295. }
  194296. int_x_green = (png_fixed_point)uint_x;
  194297. int_y_green = (png_fixed_point)uint_y;
  194298. png_crc_read(png_ptr, buf, 4);
  194299. uint_x = png_get_uint_32(buf);
  194300. png_crc_read(png_ptr, buf, 4);
  194301. uint_y = png_get_uint_32(buf);
  194302. if (uint_x + uint_y > 100000L)
  194303. {
  194304. png_warning(png_ptr, "Invalid cHRM blue point");
  194305. png_crc_finish(png_ptr, 0);
  194306. return;
  194307. }
  194308. int_x_blue = (png_fixed_point)uint_x;
  194309. int_y_blue = (png_fixed_point)uint_y;
  194310. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194311. white_x = (float)int_x_white / (float)100000.0;
  194312. white_y = (float)int_y_white / (float)100000.0;
  194313. red_x = (float)int_x_red / (float)100000.0;
  194314. red_y = (float)int_y_red / (float)100000.0;
  194315. green_x = (float)int_x_green / (float)100000.0;
  194316. green_y = (float)int_y_green / (float)100000.0;
  194317. blue_x = (float)int_x_blue / (float)100000.0;
  194318. blue_y = (float)int_y_blue / (float)100000.0;
  194319. #endif
  194320. #if defined(PNG_READ_sRGB_SUPPORTED)
  194321. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194322. {
  194323. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194324. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194325. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194326. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194327. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194328. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194329. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194330. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194331. {
  194332. png_warning(png_ptr,
  194333. "Ignoring incorrect cHRM value when sRGB is also present");
  194334. #ifndef PNG_NO_CONSOLE_IO
  194335. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194336. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194337. white_x, white_y, red_x, red_y);
  194338. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194339. green_x, green_y, blue_x, blue_y);
  194340. #else
  194341. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194342. int_x_white, int_y_white, int_x_red, int_y_red);
  194343. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194344. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194345. #endif
  194346. #endif /* PNG_NO_CONSOLE_IO */
  194347. }
  194348. png_crc_finish(png_ptr, 0);
  194349. return;
  194350. }
  194351. #endif /* PNG_READ_sRGB_SUPPORTED */
  194352. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194353. png_set_cHRM(png_ptr, info_ptr,
  194354. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194355. #endif
  194356. #ifdef PNG_FIXED_POINT_SUPPORTED
  194357. png_set_cHRM_fixed(png_ptr, info_ptr,
  194358. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194359. int_y_green, int_x_blue, int_y_blue);
  194360. #endif
  194361. if (png_crc_finish(png_ptr, 0))
  194362. return;
  194363. }
  194364. #endif
  194365. #if defined(PNG_READ_sRGB_SUPPORTED)
  194366. void /* PRIVATE */
  194367. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194368. {
  194369. int intent;
  194370. png_byte buf[1];
  194371. png_debug(1, "in png_handle_sRGB\n");
  194372. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194373. png_error(png_ptr, "Missing IHDR before sRGB");
  194374. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194375. {
  194376. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194377. png_crc_finish(png_ptr, length);
  194378. return;
  194379. }
  194380. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194381. /* Should be an error, but we can cope with it */
  194382. png_warning(png_ptr, "Out of place sRGB chunk");
  194383. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194384. {
  194385. png_warning(png_ptr, "Duplicate sRGB chunk");
  194386. png_crc_finish(png_ptr, length);
  194387. return;
  194388. }
  194389. if (length != 1)
  194390. {
  194391. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194392. png_crc_finish(png_ptr, length);
  194393. return;
  194394. }
  194395. png_crc_read(png_ptr, buf, 1);
  194396. if (png_crc_finish(png_ptr, 0))
  194397. return;
  194398. intent = buf[0];
  194399. /* check for bad intent */
  194400. if (intent >= PNG_sRGB_INTENT_LAST)
  194401. {
  194402. png_warning(png_ptr, "Unknown sRGB intent");
  194403. return;
  194404. }
  194405. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194406. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194407. {
  194408. png_fixed_point igamma;
  194409. #ifdef PNG_FIXED_POINT_SUPPORTED
  194410. igamma=info_ptr->int_gamma;
  194411. #else
  194412. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194413. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194414. # endif
  194415. #endif
  194416. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194417. {
  194418. png_warning(png_ptr,
  194419. "Ignoring incorrect gAMA value when sRGB is also present");
  194420. #ifndef PNG_NO_CONSOLE_IO
  194421. # ifdef PNG_FIXED_POINT_SUPPORTED
  194422. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194423. # else
  194424. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194425. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194426. # endif
  194427. # endif
  194428. #endif
  194429. }
  194430. }
  194431. #endif /* PNG_READ_gAMA_SUPPORTED */
  194432. #ifdef PNG_READ_cHRM_SUPPORTED
  194433. #ifdef PNG_FIXED_POINT_SUPPORTED
  194434. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194435. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194436. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194437. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194438. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194439. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194440. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194441. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194442. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194443. {
  194444. png_warning(png_ptr,
  194445. "Ignoring incorrect cHRM value when sRGB is also present");
  194446. }
  194447. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194448. #endif /* PNG_READ_cHRM_SUPPORTED */
  194449. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194450. }
  194451. #endif /* PNG_READ_sRGB_SUPPORTED */
  194452. #if defined(PNG_READ_iCCP_SUPPORTED)
  194453. void /* PRIVATE */
  194454. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194455. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194456. {
  194457. png_charp chunkdata;
  194458. png_byte compression_type;
  194459. png_bytep pC;
  194460. png_charp profile;
  194461. png_uint_32 skip = 0;
  194462. png_uint_32 profile_size, profile_length;
  194463. png_size_t slength, prefix_length, data_length;
  194464. png_debug(1, "in png_handle_iCCP\n");
  194465. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194466. png_error(png_ptr, "Missing IHDR before iCCP");
  194467. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194468. {
  194469. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194470. png_crc_finish(png_ptr, length);
  194471. return;
  194472. }
  194473. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194474. /* Should be an error, but we can cope with it */
  194475. png_warning(png_ptr, "Out of place iCCP chunk");
  194476. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194477. {
  194478. png_warning(png_ptr, "Duplicate iCCP chunk");
  194479. png_crc_finish(png_ptr, length);
  194480. return;
  194481. }
  194482. #ifdef PNG_MAX_MALLOC_64K
  194483. if (length > (png_uint_32)65535L)
  194484. {
  194485. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194486. skip = length - (png_uint_32)65535L;
  194487. length = (png_uint_32)65535L;
  194488. }
  194489. #endif
  194490. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194491. slength = (png_size_t)length;
  194492. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194493. if (png_crc_finish(png_ptr, skip))
  194494. {
  194495. png_free(png_ptr, chunkdata);
  194496. return;
  194497. }
  194498. chunkdata[slength] = 0x00;
  194499. for (profile = chunkdata; *profile; profile++)
  194500. /* empty loop to find end of name */ ;
  194501. ++profile;
  194502. /* there should be at least one zero (the compression type byte)
  194503. following the separator, and we should be on it */
  194504. if ( profile >= chunkdata + slength - 1)
  194505. {
  194506. png_free(png_ptr, chunkdata);
  194507. png_warning(png_ptr, "Malformed iCCP chunk");
  194508. return;
  194509. }
  194510. /* compression_type should always be zero */
  194511. compression_type = *profile++;
  194512. if (compression_type)
  194513. {
  194514. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194515. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194516. wrote nonzero) */
  194517. }
  194518. prefix_length = profile - chunkdata;
  194519. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194520. slength, prefix_length, &data_length);
  194521. profile_length = data_length - prefix_length;
  194522. if ( prefix_length > data_length || profile_length < 4)
  194523. {
  194524. png_free(png_ptr, chunkdata);
  194525. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194526. return;
  194527. }
  194528. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194529. pC = (png_bytep)(chunkdata+prefix_length);
  194530. profile_size = ((*(pC ))<<24) |
  194531. ((*(pC+1))<<16) |
  194532. ((*(pC+2))<< 8) |
  194533. ((*(pC+3)) );
  194534. if(profile_size < profile_length)
  194535. profile_length = profile_size;
  194536. if(profile_size > profile_length)
  194537. {
  194538. png_free(png_ptr, chunkdata);
  194539. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194540. return;
  194541. }
  194542. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194543. chunkdata + prefix_length, profile_length);
  194544. png_free(png_ptr, chunkdata);
  194545. }
  194546. #endif /* PNG_READ_iCCP_SUPPORTED */
  194547. #if defined(PNG_READ_sPLT_SUPPORTED)
  194548. void /* PRIVATE */
  194549. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194550. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194551. {
  194552. png_bytep chunkdata;
  194553. png_bytep entry_start;
  194554. png_sPLT_t new_palette;
  194555. #ifdef PNG_NO_POINTER_INDEXING
  194556. png_sPLT_entryp pp;
  194557. #endif
  194558. int data_length, entry_size, i;
  194559. png_uint_32 skip = 0;
  194560. png_size_t slength;
  194561. png_debug(1, "in png_handle_sPLT\n");
  194562. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194563. png_error(png_ptr, "Missing IHDR before sPLT");
  194564. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194565. {
  194566. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194567. png_crc_finish(png_ptr, length);
  194568. return;
  194569. }
  194570. #ifdef PNG_MAX_MALLOC_64K
  194571. if (length > (png_uint_32)65535L)
  194572. {
  194573. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194574. skip = length - (png_uint_32)65535L;
  194575. length = (png_uint_32)65535L;
  194576. }
  194577. #endif
  194578. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194579. slength = (png_size_t)length;
  194580. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194581. if (png_crc_finish(png_ptr, skip))
  194582. {
  194583. png_free(png_ptr, chunkdata);
  194584. return;
  194585. }
  194586. chunkdata[slength] = 0x00;
  194587. for (entry_start = chunkdata; *entry_start; entry_start++)
  194588. /* empty loop to find end of name */ ;
  194589. ++entry_start;
  194590. /* a sample depth should follow the separator, and we should be on it */
  194591. if (entry_start > chunkdata + slength - 2)
  194592. {
  194593. png_free(png_ptr, chunkdata);
  194594. png_warning(png_ptr, "malformed sPLT chunk");
  194595. return;
  194596. }
  194597. new_palette.depth = *entry_start++;
  194598. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194599. data_length = (slength - (entry_start - chunkdata));
  194600. /* integrity-check the data length */
  194601. if (data_length % entry_size)
  194602. {
  194603. png_free(png_ptr, chunkdata);
  194604. png_warning(png_ptr, "sPLT chunk has bad length");
  194605. return;
  194606. }
  194607. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194608. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194609. png_sizeof(png_sPLT_entry)))
  194610. {
  194611. png_warning(png_ptr, "sPLT chunk too long");
  194612. return;
  194613. }
  194614. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194615. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194616. if (new_palette.entries == NULL)
  194617. {
  194618. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194619. return;
  194620. }
  194621. #ifndef PNG_NO_POINTER_INDEXING
  194622. for (i = 0; i < new_palette.nentries; i++)
  194623. {
  194624. png_sPLT_entryp pp = new_palette.entries + i;
  194625. if (new_palette.depth == 8)
  194626. {
  194627. pp->red = *entry_start++;
  194628. pp->green = *entry_start++;
  194629. pp->blue = *entry_start++;
  194630. pp->alpha = *entry_start++;
  194631. }
  194632. else
  194633. {
  194634. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194635. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194636. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194637. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194638. }
  194639. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194640. }
  194641. #else
  194642. pp = new_palette.entries;
  194643. for (i = 0; i < new_palette.nentries; i++)
  194644. {
  194645. if (new_palette.depth == 8)
  194646. {
  194647. pp[i].red = *entry_start++;
  194648. pp[i].green = *entry_start++;
  194649. pp[i].blue = *entry_start++;
  194650. pp[i].alpha = *entry_start++;
  194651. }
  194652. else
  194653. {
  194654. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194655. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194656. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194657. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194658. }
  194659. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194660. }
  194661. #endif
  194662. /* discard all chunk data except the name and stash that */
  194663. new_palette.name = (png_charp)chunkdata;
  194664. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194665. png_free(png_ptr, chunkdata);
  194666. png_free(png_ptr, new_palette.entries);
  194667. }
  194668. #endif /* PNG_READ_sPLT_SUPPORTED */
  194669. #if defined(PNG_READ_tRNS_SUPPORTED)
  194670. void /* PRIVATE */
  194671. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194672. {
  194673. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194674. int bit_mask;
  194675. png_debug(1, "in png_handle_tRNS\n");
  194676. /* For non-indexed color, mask off any bits in the tRNS value that
  194677. * exceed the bit depth. Some creators were writing extra bits there.
  194678. * This is not needed for indexed color. */
  194679. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194680. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194681. png_error(png_ptr, "Missing IHDR before tRNS");
  194682. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194683. {
  194684. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194685. png_crc_finish(png_ptr, length);
  194686. return;
  194687. }
  194688. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194689. {
  194690. png_warning(png_ptr, "Duplicate tRNS chunk");
  194691. png_crc_finish(png_ptr, length);
  194692. return;
  194693. }
  194694. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194695. {
  194696. png_byte buf[2];
  194697. if (length != 2)
  194698. {
  194699. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194700. png_crc_finish(png_ptr, length);
  194701. return;
  194702. }
  194703. png_crc_read(png_ptr, buf, 2);
  194704. png_ptr->num_trans = 1;
  194705. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194706. }
  194707. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194708. {
  194709. png_byte buf[6];
  194710. if (length != 6)
  194711. {
  194712. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194713. png_crc_finish(png_ptr, length);
  194714. return;
  194715. }
  194716. png_crc_read(png_ptr, buf, (png_size_t)length);
  194717. png_ptr->num_trans = 1;
  194718. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194719. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194720. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194721. }
  194722. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194723. {
  194724. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194725. {
  194726. /* Should be an error, but we can cope with it. */
  194727. png_warning(png_ptr, "Missing PLTE before tRNS");
  194728. }
  194729. if (length > (png_uint_32)png_ptr->num_palette ||
  194730. length > PNG_MAX_PALETTE_LENGTH)
  194731. {
  194732. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194733. png_crc_finish(png_ptr, length);
  194734. return;
  194735. }
  194736. if (length == 0)
  194737. {
  194738. png_warning(png_ptr, "Zero length tRNS chunk");
  194739. png_crc_finish(png_ptr, length);
  194740. return;
  194741. }
  194742. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194743. png_ptr->num_trans = (png_uint_16)length;
  194744. }
  194745. else
  194746. {
  194747. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194748. png_crc_finish(png_ptr, length);
  194749. return;
  194750. }
  194751. if (png_crc_finish(png_ptr, 0))
  194752. {
  194753. png_ptr->num_trans = 0;
  194754. return;
  194755. }
  194756. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194757. &(png_ptr->trans_values));
  194758. }
  194759. #endif
  194760. #if defined(PNG_READ_bKGD_SUPPORTED)
  194761. void /* PRIVATE */
  194762. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194763. {
  194764. png_size_t truelen;
  194765. png_byte buf[6];
  194766. png_debug(1, "in png_handle_bKGD\n");
  194767. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194768. png_error(png_ptr, "Missing IHDR before bKGD");
  194769. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194770. {
  194771. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194772. png_crc_finish(png_ptr, length);
  194773. return;
  194774. }
  194775. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194776. !(png_ptr->mode & PNG_HAVE_PLTE))
  194777. {
  194778. png_warning(png_ptr, "Missing PLTE before bKGD");
  194779. png_crc_finish(png_ptr, length);
  194780. return;
  194781. }
  194782. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194783. {
  194784. png_warning(png_ptr, "Duplicate bKGD chunk");
  194785. png_crc_finish(png_ptr, length);
  194786. return;
  194787. }
  194788. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194789. truelen = 1;
  194790. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194791. truelen = 6;
  194792. else
  194793. truelen = 2;
  194794. if (length != truelen)
  194795. {
  194796. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194797. png_crc_finish(png_ptr, length);
  194798. return;
  194799. }
  194800. png_crc_read(png_ptr, buf, truelen);
  194801. if (png_crc_finish(png_ptr, 0))
  194802. return;
  194803. /* We convert the index value into RGB components so that we can allow
  194804. * arbitrary RGB values for background when we have transparency, and
  194805. * so it is easy to determine the RGB values of the background color
  194806. * from the info_ptr struct. */
  194807. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194808. {
  194809. png_ptr->background.index = buf[0];
  194810. if(info_ptr->num_palette)
  194811. {
  194812. if(buf[0] > info_ptr->num_palette)
  194813. {
  194814. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194815. return;
  194816. }
  194817. png_ptr->background.red =
  194818. (png_uint_16)png_ptr->palette[buf[0]].red;
  194819. png_ptr->background.green =
  194820. (png_uint_16)png_ptr->palette[buf[0]].green;
  194821. png_ptr->background.blue =
  194822. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194823. }
  194824. }
  194825. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194826. {
  194827. png_ptr->background.red =
  194828. png_ptr->background.green =
  194829. png_ptr->background.blue =
  194830. png_ptr->background.gray = png_get_uint_16(buf);
  194831. }
  194832. else
  194833. {
  194834. png_ptr->background.red = png_get_uint_16(buf);
  194835. png_ptr->background.green = png_get_uint_16(buf + 2);
  194836. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194837. }
  194838. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194839. }
  194840. #endif
  194841. #if defined(PNG_READ_hIST_SUPPORTED)
  194842. void /* PRIVATE */
  194843. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194844. {
  194845. unsigned int num, i;
  194846. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194847. png_debug(1, "in png_handle_hIST\n");
  194848. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194849. png_error(png_ptr, "Missing IHDR before hIST");
  194850. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194851. {
  194852. png_warning(png_ptr, "Invalid hIST after IDAT");
  194853. png_crc_finish(png_ptr, length);
  194854. return;
  194855. }
  194856. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194857. {
  194858. png_warning(png_ptr, "Missing PLTE before hIST");
  194859. png_crc_finish(png_ptr, length);
  194860. return;
  194861. }
  194862. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194863. {
  194864. png_warning(png_ptr, "Duplicate hIST chunk");
  194865. png_crc_finish(png_ptr, length);
  194866. return;
  194867. }
  194868. num = length / 2 ;
  194869. if (num != (unsigned int) png_ptr->num_palette || num >
  194870. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194871. {
  194872. png_warning(png_ptr, "Incorrect hIST chunk length");
  194873. png_crc_finish(png_ptr, length);
  194874. return;
  194875. }
  194876. for (i = 0; i < num; i++)
  194877. {
  194878. png_byte buf[2];
  194879. png_crc_read(png_ptr, buf, 2);
  194880. readbuf[i] = png_get_uint_16(buf);
  194881. }
  194882. if (png_crc_finish(png_ptr, 0))
  194883. return;
  194884. png_set_hIST(png_ptr, info_ptr, readbuf);
  194885. }
  194886. #endif
  194887. #if defined(PNG_READ_pHYs_SUPPORTED)
  194888. void /* PRIVATE */
  194889. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194890. {
  194891. png_byte buf[9];
  194892. png_uint_32 res_x, res_y;
  194893. int unit_type;
  194894. png_debug(1, "in png_handle_pHYs\n");
  194895. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194896. png_error(png_ptr, "Missing IHDR before pHYs");
  194897. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194898. {
  194899. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194900. png_crc_finish(png_ptr, length);
  194901. return;
  194902. }
  194903. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194904. {
  194905. png_warning(png_ptr, "Duplicate pHYs chunk");
  194906. png_crc_finish(png_ptr, length);
  194907. return;
  194908. }
  194909. if (length != 9)
  194910. {
  194911. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194912. png_crc_finish(png_ptr, length);
  194913. return;
  194914. }
  194915. png_crc_read(png_ptr, buf, 9);
  194916. if (png_crc_finish(png_ptr, 0))
  194917. return;
  194918. res_x = png_get_uint_32(buf);
  194919. res_y = png_get_uint_32(buf + 4);
  194920. unit_type = buf[8];
  194921. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194922. }
  194923. #endif
  194924. #if defined(PNG_READ_oFFs_SUPPORTED)
  194925. void /* PRIVATE */
  194926. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194927. {
  194928. png_byte buf[9];
  194929. png_int_32 offset_x, offset_y;
  194930. int unit_type;
  194931. png_debug(1, "in png_handle_oFFs\n");
  194932. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194933. png_error(png_ptr, "Missing IHDR before oFFs");
  194934. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194935. {
  194936. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194937. png_crc_finish(png_ptr, length);
  194938. return;
  194939. }
  194940. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194941. {
  194942. png_warning(png_ptr, "Duplicate oFFs chunk");
  194943. png_crc_finish(png_ptr, length);
  194944. return;
  194945. }
  194946. if (length != 9)
  194947. {
  194948. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194949. png_crc_finish(png_ptr, length);
  194950. return;
  194951. }
  194952. png_crc_read(png_ptr, buf, 9);
  194953. if (png_crc_finish(png_ptr, 0))
  194954. return;
  194955. offset_x = png_get_int_32(buf);
  194956. offset_y = png_get_int_32(buf + 4);
  194957. unit_type = buf[8];
  194958. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194959. }
  194960. #endif
  194961. #if defined(PNG_READ_pCAL_SUPPORTED)
  194962. /* read the pCAL chunk (described in the PNG Extensions document) */
  194963. void /* PRIVATE */
  194964. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194965. {
  194966. png_charp purpose;
  194967. png_int_32 X0, X1;
  194968. png_byte type, nparams;
  194969. png_charp buf, units, endptr;
  194970. png_charpp params;
  194971. png_size_t slength;
  194972. int i;
  194973. png_debug(1, "in png_handle_pCAL\n");
  194974. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194975. png_error(png_ptr, "Missing IHDR before pCAL");
  194976. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194977. {
  194978. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194979. png_crc_finish(png_ptr, length);
  194980. return;
  194981. }
  194982. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194983. {
  194984. png_warning(png_ptr, "Duplicate pCAL chunk");
  194985. png_crc_finish(png_ptr, length);
  194986. return;
  194987. }
  194988. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194989. length + 1);
  194990. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194991. if (purpose == NULL)
  194992. {
  194993. png_warning(png_ptr, "No memory for pCAL purpose.");
  194994. return;
  194995. }
  194996. slength = (png_size_t)length;
  194997. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194998. if (png_crc_finish(png_ptr, 0))
  194999. {
  195000. png_free(png_ptr, purpose);
  195001. return;
  195002. }
  195003. purpose[slength] = 0x00; /* null terminate the last string */
  195004. png_debug(3, "Finding end of pCAL purpose string\n");
  195005. for (buf = purpose; *buf; buf++)
  195006. /* empty loop */ ;
  195007. endptr = purpose + slength;
  195008. /* We need to have at least 12 bytes after the purpose string
  195009. in order to get the parameter information. */
  195010. if (endptr <= buf + 12)
  195011. {
  195012. png_warning(png_ptr, "Invalid pCAL data");
  195013. png_free(png_ptr, purpose);
  195014. return;
  195015. }
  195016. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195017. X0 = png_get_int_32((png_bytep)buf+1);
  195018. X1 = png_get_int_32((png_bytep)buf+5);
  195019. type = buf[9];
  195020. nparams = buf[10];
  195021. units = buf + 11;
  195022. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195023. /* Check that we have the right number of parameters for known
  195024. equation types. */
  195025. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195026. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195027. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195028. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195029. {
  195030. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195031. png_free(png_ptr, purpose);
  195032. return;
  195033. }
  195034. else if (type >= PNG_EQUATION_LAST)
  195035. {
  195036. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195037. }
  195038. for (buf = units; *buf; buf++)
  195039. /* Empty loop to move past the units string. */ ;
  195040. png_debug(3, "Allocating pCAL parameters array\n");
  195041. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195042. *png_sizeof(png_charp))) ;
  195043. if (params == NULL)
  195044. {
  195045. png_free(png_ptr, purpose);
  195046. png_warning(png_ptr, "No memory for pCAL params.");
  195047. return;
  195048. }
  195049. /* Get pointers to the start of each parameter string. */
  195050. for (i = 0; i < (int)nparams; i++)
  195051. {
  195052. buf++; /* Skip the null string terminator from previous parameter. */
  195053. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195054. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195055. /* Empty loop to move past each parameter string */ ;
  195056. /* Make sure we haven't run out of data yet */
  195057. if (buf > endptr)
  195058. {
  195059. png_warning(png_ptr, "Invalid pCAL data");
  195060. png_free(png_ptr, purpose);
  195061. png_free(png_ptr, params);
  195062. return;
  195063. }
  195064. }
  195065. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195066. units, params);
  195067. png_free(png_ptr, purpose);
  195068. png_free(png_ptr, params);
  195069. }
  195070. #endif
  195071. #if defined(PNG_READ_sCAL_SUPPORTED)
  195072. /* read the sCAL chunk */
  195073. void /* PRIVATE */
  195074. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195075. {
  195076. png_charp buffer, ep;
  195077. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195078. double width, height;
  195079. png_charp vp;
  195080. #else
  195081. #ifdef PNG_FIXED_POINT_SUPPORTED
  195082. png_charp swidth, sheight;
  195083. #endif
  195084. #endif
  195085. png_size_t slength;
  195086. png_debug(1, "in png_handle_sCAL\n");
  195087. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195088. png_error(png_ptr, "Missing IHDR before sCAL");
  195089. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195090. {
  195091. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195092. png_crc_finish(png_ptr, length);
  195093. return;
  195094. }
  195095. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195096. {
  195097. png_warning(png_ptr, "Duplicate sCAL chunk");
  195098. png_crc_finish(png_ptr, length);
  195099. return;
  195100. }
  195101. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195102. length + 1);
  195103. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195104. if (buffer == NULL)
  195105. {
  195106. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195107. return;
  195108. }
  195109. slength = (png_size_t)length;
  195110. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195111. if (png_crc_finish(png_ptr, 0))
  195112. {
  195113. png_free(png_ptr, buffer);
  195114. return;
  195115. }
  195116. buffer[slength] = 0x00; /* null terminate the last string */
  195117. ep = buffer + 1; /* skip unit byte */
  195118. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195119. width = png_strtod(png_ptr, ep, &vp);
  195120. if (*vp)
  195121. {
  195122. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195123. return;
  195124. }
  195125. #else
  195126. #ifdef PNG_FIXED_POINT_SUPPORTED
  195127. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195128. if (swidth == NULL)
  195129. {
  195130. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195131. return;
  195132. }
  195133. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195134. #endif
  195135. #endif
  195136. for (ep = buffer; *ep; ep++)
  195137. /* empty loop */ ;
  195138. ep++;
  195139. if (buffer + slength < ep)
  195140. {
  195141. png_warning(png_ptr, "Truncated sCAL chunk");
  195142. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195143. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195144. png_free(png_ptr, swidth);
  195145. #endif
  195146. png_free(png_ptr, buffer);
  195147. return;
  195148. }
  195149. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195150. height = png_strtod(png_ptr, ep, &vp);
  195151. if (*vp)
  195152. {
  195153. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195154. return;
  195155. }
  195156. #else
  195157. #ifdef PNG_FIXED_POINT_SUPPORTED
  195158. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195159. if (swidth == NULL)
  195160. {
  195161. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195162. return;
  195163. }
  195164. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195165. #endif
  195166. #endif
  195167. if (buffer + slength < ep
  195168. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195169. || width <= 0. || height <= 0.
  195170. #endif
  195171. )
  195172. {
  195173. png_warning(png_ptr, "Invalid sCAL data");
  195174. png_free(png_ptr, buffer);
  195175. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195176. png_free(png_ptr, swidth);
  195177. png_free(png_ptr, sheight);
  195178. #endif
  195179. return;
  195180. }
  195181. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195182. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195183. #else
  195184. #ifdef PNG_FIXED_POINT_SUPPORTED
  195185. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195186. #endif
  195187. #endif
  195188. png_free(png_ptr, buffer);
  195189. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195190. png_free(png_ptr, swidth);
  195191. png_free(png_ptr, sheight);
  195192. #endif
  195193. }
  195194. #endif
  195195. #if defined(PNG_READ_tIME_SUPPORTED)
  195196. void /* PRIVATE */
  195197. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195198. {
  195199. png_byte buf[7];
  195200. png_time mod_time;
  195201. png_debug(1, "in png_handle_tIME\n");
  195202. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195203. png_error(png_ptr, "Out of place tIME chunk");
  195204. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195205. {
  195206. png_warning(png_ptr, "Duplicate tIME chunk");
  195207. png_crc_finish(png_ptr, length);
  195208. return;
  195209. }
  195210. if (png_ptr->mode & PNG_HAVE_IDAT)
  195211. png_ptr->mode |= PNG_AFTER_IDAT;
  195212. if (length != 7)
  195213. {
  195214. png_warning(png_ptr, "Incorrect tIME chunk length");
  195215. png_crc_finish(png_ptr, length);
  195216. return;
  195217. }
  195218. png_crc_read(png_ptr, buf, 7);
  195219. if (png_crc_finish(png_ptr, 0))
  195220. return;
  195221. mod_time.second = buf[6];
  195222. mod_time.minute = buf[5];
  195223. mod_time.hour = buf[4];
  195224. mod_time.day = buf[3];
  195225. mod_time.month = buf[2];
  195226. mod_time.year = png_get_uint_16(buf);
  195227. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195228. }
  195229. #endif
  195230. #if defined(PNG_READ_tEXt_SUPPORTED)
  195231. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195232. void /* PRIVATE */
  195233. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195234. {
  195235. png_textp text_ptr;
  195236. png_charp key;
  195237. png_charp text;
  195238. png_uint_32 skip = 0;
  195239. png_size_t slength;
  195240. int ret;
  195241. png_debug(1, "in png_handle_tEXt\n");
  195242. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195243. png_error(png_ptr, "Missing IHDR before tEXt");
  195244. if (png_ptr->mode & PNG_HAVE_IDAT)
  195245. png_ptr->mode |= PNG_AFTER_IDAT;
  195246. #ifdef PNG_MAX_MALLOC_64K
  195247. if (length > (png_uint_32)65535L)
  195248. {
  195249. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195250. skip = length - (png_uint_32)65535L;
  195251. length = (png_uint_32)65535L;
  195252. }
  195253. #endif
  195254. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195255. if (key == NULL)
  195256. {
  195257. png_warning(png_ptr, "No memory to process text chunk.");
  195258. return;
  195259. }
  195260. slength = (png_size_t)length;
  195261. png_crc_read(png_ptr, (png_bytep)key, slength);
  195262. if (png_crc_finish(png_ptr, skip))
  195263. {
  195264. png_free(png_ptr, key);
  195265. return;
  195266. }
  195267. key[slength] = 0x00;
  195268. for (text = key; *text; text++)
  195269. /* empty loop to find end of key */ ;
  195270. if (text != key + slength)
  195271. text++;
  195272. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195273. (png_uint_32)png_sizeof(png_text));
  195274. if (text_ptr == NULL)
  195275. {
  195276. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195277. png_free(png_ptr, key);
  195278. return;
  195279. }
  195280. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195281. text_ptr->key = key;
  195282. #ifdef PNG_iTXt_SUPPORTED
  195283. text_ptr->lang = NULL;
  195284. text_ptr->lang_key = NULL;
  195285. text_ptr->itxt_length = 0;
  195286. #endif
  195287. text_ptr->text = text;
  195288. text_ptr->text_length = png_strlen(text);
  195289. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195290. png_free(png_ptr, key);
  195291. png_free(png_ptr, text_ptr);
  195292. if (ret)
  195293. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195294. }
  195295. #endif
  195296. #if defined(PNG_READ_zTXt_SUPPORTED)
  195297. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195298. void /* PRIVATE */
  195299. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195300. {
  195301. png_textp text_ptr;
  195302. png_charp chunkdata;
  195303. png_charp text;
  195304. int comp_type;
  195305. int ret;
  195306. png_size_t slength, prefix_len, data_len;
  195307. png_debug(1, "in png_handle_zTXt\n");
  195308. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195309. png_error(png_ptr, "Missing IHDR before zTXt");
  195310. if (png_ptr->mode & PNG_HAVE_IDAT)
  195311. png_ptr->mode |= PNG_AFTER_IDAT;
  195312. #ifdef PNG_MAX_MALLOC_64K
  195313. /* We will no doubt have problems with chunks even half this size, but
  195314. there is no hard and fast rule to tell us where to stop. */
  195315. if (length > (png_uint_32)65535L)
  195316. {
  195317. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195318. png_crc_finish(png_ptr, length);
  195319. return;
  195320. }
  195321. #endif
  195322. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195323. if (chunkdata == NULL)
  195324. {
  195325. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195326. return;
  195327. }
  195328. slength = (png_size_t)length;
  195329. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195330. if (png_crc_finish(png_ptr, 0))
  195331. {
  195332. png_free(png_ptr, chunkdata);
  195333. return;
  195334. }
  195335. chunkdata[slength] = 0x00;
  195336. for (text = chunkdata; *text; text++)
  195337. /* empty loop */ ;
  195338. /* zTXt must have some text after the chunkdataword */
  195339. if (text >= chunkdata + slength - 2)
  195340. {
  195341. png_warning(png_ptr, "Truncated zTXt chunk");
  195342. png_free(png_ptr, chunkdata);
  195343. return;
  195344. }
  195345. else
  195346. {
  195347. comp_type = *(++text);
  195348. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195349. {
  195350. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195351. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195352. }
  195353. text++; /* skip the compression_method byte */
  195354. }
  195355. prefix_len = text - chunkdata;
  195356. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195357. (png_size_t)length, prefix_len, &data_len);
  195358. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195359. (png_uint_32)png_sizeof(png_text));
  195360. if (text_ptr == NULL)
  195361. {
  195362. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195363. png_free(png_ptr, chunkdata);
  195364. return;
  195365. }
  195366. text_ptr->compression = comp_type;
  195367. text_ptr->key = chunkdata;
  195368. #ifdef PNG_iTXt_SUPPORTED
  195369. text_ptr->lang = NULL;
  195370. text_ptr->lang_key = NULL;
  195371. text_ptr->itxt_length = 0;
  195372. #endif
  195373. text_ptr->text = chunkdata + prefix_len;
  195374. text_ptr->text_length = data_len;
  195375. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195376. png_free(png_ptr, text_ptr);
  195377. png_free(png_ptr, chunkdata);
  195378. if (ret)
  195379. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195380. }
  195381. #endif
  195382. #if defined(PNG_READ_iTXt_SUPPORTED)
  195383. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195384. void /* PRIVATE */
  195385. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195386. {
  195387. png_textp text_ptr;
  195388. png_charp chunkdata;
  195389. png_charp key, lang, text, lang_key;
  195390. int comp_flag;
  195391. int comp_type = 0;
  195392. int ret;
  195393. png_size_t slength, prefix_len, data_len;
  195394. png_debug(1, "in png_handle_iTXt\n");
  195395. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195396. png_error(png_ptr, "Missing IHDR before iTXt");
  195397. if (png_ptr->mode & PNG_HAVE_IDAT)
  195398. png_ptr->mode |= PNG_AFTER_IDAT;
  195399. #ifdef PNG_MAX_MALLOC_64K
  195400. /* We will no doubt have problems with chunks even half this size, but
  195401. there is no hard and fast rule to tell us where to stop. */
  195402. if (length > (png_uint_32)65535L)
  195403. {
  195404. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195405. png_crc_finish(png_ptr, length);
  195406. return;
  195407. }
  195408. #endif
  195409. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195410. if (chunkdata == NULL)
  195411. {
  195412. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195413. return;
  195414. }
  195415. slength = (png_size_t)length;
  195416. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195417. if (png_crc_finish(png_ptr, 0))
  195418. {
  195419. png_free(png_ptr, chunkdata);
  195420. return;
  195421. }
  195422. chunkdata[slength] = 0x00;
  195423. for (lang = chunkdata; *lang; lang++)
  195424. /* empty loop */ ;
  195425. lang++; /* skip NUL separator */
  195426. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195427. translated keyword (possibly empty), and possibly some text after the
  195428. keyword */
  195429. if (lang >= chunkdata + slength - 3)
  195430. {
  195431. png_warning(png_ptr, "Truncated iTXt chunk");
  195432. png_free(png_ptr, chunkdata);
  195433. return;
  195434. }
  195435. else
  195436. {
  195437. comp_flag = *lang++;
  195438. comp_type = *lang++;
  195439. }
  195440. for (lang_key = lang; *lang_key; lang_key++)
  195441. /* empty loop */ ;
  195442. lang_key++; /* skip NUL separator */
  195443. if (lang_key >= chunkdata + slength)
  195444. {
  195445. png_warning(png_ptr, "Truncated iTXt chunk");
  195446. png_free(png_ptr, chunkdata);
  195447. return;
  195448. }
  195449. for (text = lang_key; *text; text++)
  195450. /* empty loop */ ;
  195451. text++; /* skip NUL separator */
  195452. if (text >= chunkdata + slength)
  195453. {
  195454. png_warning(png_ptr, "Malformed iTXt chunk");
  195455. png_free(png_ptr, chunkdata);
  195456. return;
  195457. }
  195458. prefix_len = text - chunkdata;
  195459. key=chunkdata;
  195460. if (comp_flag)
  195461. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195462. (size_t)length, prefix_len, &data_len);
  195463. else
  195464. data_len=png_strlen(chunkdata + prefix_len);
  195465. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195466. (png_uint_32)png_sizeof(png_text));
  195467. if (text_ptr == NULL)
  195468. {
  195469. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195470. png_free(png_ptr, chunkdata);
  195471. return;
  195472. }
  195473. text_ptr->compression = (int)comp_flag + 1;
  195474. text_ptr->lang_key = chunkdata+(lang_key-key);
  195475. text_ptr->lang = chunkdata+(lang-key);
  195476. text_ptr->itxt_length = data_len;
  195477. text_ptr->text_length = 0;
  195478. text_ptr->key = chunkdata;
  195479. text_ptr->text = chunkdata + prefix_len;
  195480. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195481. png_free(png_ptr, text_ptr);
  195482. png_free(png_ptr, chunkdata);
  195483. if (ret)
  195484. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195485. }
  195486. #endif
  195487. /* This function is called when we haven't found a handler for a
  195488. chunk. If there isn't a problem with the chunk itself (ie bad
  195489. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195490. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195491. case it will be saved away to be written out later. */
  195492. void /* PRIVATE */
  195493. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195494. {
  195495. png_uint_32 skip = 0;
  195496. png_debug(1, "in png_handle_unknown\n");
  195497. if (png_ptr->mode & PNG_HAVE_IDAT)
  195498. {
  195499. #ifdef PNG_USE_LOCAL_ARRAYS
  195500. PNG_CONST PNG_IDAT;
  195501. #endif
  195502. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195503. png_ptr->mode |= PNG_AFTER_IDAT;
  195504. }
  195505. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195506. if (!(png_ptr->chunk_name[0] & 0x20))
  195507. {
  195508. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195509. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195510. PNG_HANDLE_CHUNK_ALWAYS
  195511. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195512. && png_ptr->read_user_chunk_fn == NULL
  195513. #endif
  195514. )
  195515. #endif
  195516. png_chunk_error(png_ptr, "unknown critical chunk");
  195517. }
  195518. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195519. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195520. (png_ptr->read_user_chunk_fn != NULL))
  195521. {
  195522. #ifdef PNG_MAX_MALLOC_64K
  195523. if (length > (png_uint_32)65535L)
  195524. {
  195525. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195526. skip = length - (png_uint_32)65535L;
  195527. length = (png_uint_32)65535L;
  195528. }
  195529. #endif
  195530. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195531. (png_charp)png_ptr->chunk_name, 5);
  195532. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195533. png_ptr->unknown_chunk.size = (png_size_t)length;
  195534. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195535. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195536. if(png_ptr->read_user_chunk_fn != NULL)
  195537. {
  195538. /* callback to user unknown chunk handler */
  195539. int ret;
  195540. ret = (*(png_ptr->read_user_chunk_fn))
  195541. (png_ptr, &png_ptr->unknown_chunk);
  195542. if (ret < 0)
  195543. png_chunk_error(png_ptr, "error in user chunk");
  195544. if (ret == 0)
  195545. {
  195546. if (!(png_ptr->chunk_name[0] & 0x20))
  195547. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195548. PNG_HANDLE_CHUNK_ALWAYS)
  195549. png_chunk_error(png_ptr, "unknown critical chunk");
  195550. png_set_unknown_chunks(png_ptr, info_ptr,
  195551. &png_ptr->unknown_chunk, 1);
  195552. }
  195553. }
  195554. #else
  195555. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195556. #endif
  195557. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195558. png_ptr->unknown_chunk.data = NULL;
  195559. }
  195560. else
  195561. #endif
  195562. skip = length;
  195563. png_crc_finish(png_ptr, skip);
  195564. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195565. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195566. #endif
  195567. }
  195568. /* This function is called to verify that a chunk name is valid.
  195569. This function can't have the "critical chunk check" incorporated
  195570. into it, since in the future we will need to be able to call user
  195571. functions to handle unknown critical chunks after we check that
  195572. the chunk name itself is valid. */
  195573. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195574. void /* PRIVATE */
  195575. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195576. {
  195577. png_debug(1, "in png_check_chunk_name\n");
  195578. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195579. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195580. {
  195581. png_chunk_error(png_ptr, "invalid chunk type");
  195582. }
  195583. }
  195584. /* Combines the row recently read in with the existing pixels in the
  195585. row. This routine takes care of alpha and transparency if requested.
  195586. This routine also handles the two methods of progressive display
  195587. of interlaced images, depending on the mask value.
  195588. The mask value describes which pixels are to be combined with
  195589. the row. The pattern always repeats every 8 pixels, so just 8
  195590. bits are needed. A one indicates the pixel is to be combined,
  195591. a zero indicates the pixel is to be skipped. This is in addition
  195592. to any alpha or transparency value associated with the pixel. If
  195593. you want all pixels to be combined, pass 0xff (255) in mask. */
  195594. void /* PRIVATE */
  195595. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195596. {
  195597. png_debug(1,"in png_combine_row\n");
  195598. if (mask == 0xff)
  195599. {
  195600. png_memcpy(row, png_ptr->row_buf + 1,
  195601. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195602. }
  195603. else
  195604. {
  195605. switch (png_ptr->row_info.pixel_depth)
  195606. {
  195607. case 1:
  195608. {
  195609. png_bytep sp = png_ptr->row_buf + 1;
  195610. png_bytep dp = row;
  195611. int s_inc, s_start, s_end;
  195612. int m = 0x80;
  195613. int shift;
  195614. png_uint_32 i;
  195615. png_uint_32 row_width = png_ptr->width;
  195616. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195617. if (png_ptr->transformations & PNG_PACKSWAP)
  195618. {
  195619. s_start = 0;
  195620. s_end = 7;
  195621. s_inc = 1;
  195622. }
  195623. else
  195624. #endif
  195625. {
  195626. s_start = 7;
  195627. s_end = 0;
  195628. s_inc = -1;
  195629. }
  195630. shift = s_start;
  195631. for (i = 0; i < row_width; i++)
  195632. {
  195633. if (m & mask)
  195634. {
  195635. int value;
  195636. value = (*sp >> shift) & 0x01;
  195637. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195638. *dp |= (png_byte)(value << shift);
  195639. }
  195640. if (shift == s_end)
  195641. {
  195642. shift = s_start;
  195643. sp++;
  195644. dp++;
  195645. }
  195646. else
  195647. shift += s_inc;
  195648. if (m == 1)
  195649. m = 0x80;
  195650. else
  195651. m >>= 1;
  195652. }
  195653. break;
  195654. }
  195655. case 2:
  195656. {
  195657. png_bytep sp = png_ptr->row_buf + 1;
  195658. png_bytep dp = row;
  195659. int s_start, s_end, s_inc;
  195660. int m = 0x80;
  195661. int shift;
  195662. png_uint_32 i;
  195663. png_uint_32 row_width = png_ptr->width;
  195664. int value;
  195665. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195666. if (png_ptr->transformations & PNG_PACKSWAP)
  195667. {
  195668. s_start = 0;
  195669. s_end = 6;
  195670. s_inc = 2;
  195671. }
  195672. else
  195673. #endif
  195674. {
  195675. s_start = 6;
  195676. s_end = 0;
  195677. s_inc = -2;
  195678. }
  195679. shift = s_start;
  195680. for (i = 0; i < row_width; i++)
  195681. {
  195682. if (m & mask)
  195683. {
  195684. value = (*sp >> shift) & 0x03;
  195685. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195686. *dp |= (png_byte)(value << shift);
  195687. }
  195688. if (shift == s_end)
  195689. {
  195690. shift = s_start;
  195691. sp++;
  195692. dp++;
  195693. }
  195694. else
  195695. shift += s_inc;
  195696. if (m == 1)
  195697. m = 0x80;
  195698. else
  195699. m >>= 1;
  195700. }
  195701. break;
  195702. }
  195703. case 4:
  195704. {
  195705. png_bytep sp = png_ptr->row_buf + 1;
  195706. png_bytep dp = row;
  195707. int s_start, s_end, s_inc;
  195708. int m = 0x80;
  195709. int shift;
  195710. png_uint_32 i;
  195711. png_uint_32 row_width = png_ptr->width;
  195712. int value;
  195713. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195714. if (png_ptr->transformations & PNG_PACKSWAP)
  195715. {
  195716. s_start = 0;
  195717. s_end = 4;
  195718. s_inc = 4;
  195719. }
  195720. else
  195721. #endif
  195722. {
  195723. s_start = 4;
  195724. s_end = 0;
  195725. s_inc = -4;
  195726. }
  195727. shift = s_start;
  195728. for (i = 0; i < row_width; i++)
  195729. {
  195730. if (m & mask)
  195731. {
  195732. value = (*sp >> shift) & 0xf;
  195733. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195734. *dp |= (png_byte)(value << shift);
  195735. }
  195736. if (shift == s_end)
  195737. {
  195738. shift = s_start;
  195739. sp++;
  195740. dp++;
  195741. }
  195742. else
  195743. shift += s_inc;
  195744. if (m == 1)
  195745. m = 0x80;
  195746. else
  195747. m >>= 1;
  195748. }
  195749. break;
  195750. }
  195751. default:
  195752. {
  195753. png_bytep sp = png_ptr->row_buf + 1;
  195754. png_bytep dp = row;
  195755. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195756. png_uint_32 i;
  195757. png_uint_32 row_width = png_ptr->width;
  195758. png_byte m = 0x80;
  195759. for (i = 0; i < row_width; i++)
  195760. {
  195761. if (m & mask)
  195762. {
  195763. png_memcpy(dp, sp, pixel_bytes);
  195764. }
  195765. sp += pixel_bytes;
  195766. dp += pixel_bytes;
  195767. if (m == 1)
  195768. m = 0x80;
  195769. else
  195770. m >>= 1;
  195771. }
  195772. break;
  195773. }
  195774. }
  195775. }
  195776. }
  195777. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195778. /* OLD pre-1.0.9 interface:
  195779. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195780. png_uint_32 transformations)
  195781. */
  195782. void /* PRIVATE */
  195783. png_do_read_interlace(png_structp png_ptr)
  195784. {
  195785. png_row_infop row_info = &(png_ptr->row_info);
  195786. png_bytep row = png_ptr->row_buf + 1;
  195787. int pass = png_ptr->pass;
  195788. png_uint_32 transformations = png_ptr->transformations;
  195789. #ifdef PNG_USE_LOCAL_ARRAYS
  195790. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195791. /* offset to next interlace block */
  195792. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195793. #endif
  195794. png_debug(1,"in png_do_read_interlace\n");
  195795. if (row != NULL && row_info != NULL)
  195796. {
  195797. png_uint_32 final_width;
  195798. final_width = row_info->width * png_pass_inc[pass];
  195799. switch (row_info->pixel_depth)
  195800. {
  195801. case 1:
  195802. {
  195803. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195804. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195805. int sshift, dshift;
  195806. int s_start, s_end, s_inc;
  195807. int jstop = png_pass_inc[pass];
  195808. png_byte v;
  195809. png_uint_32 i;
  195810. int j;
  195811. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195812. if (transformations & PNG_PACKSWAP)
  195813. {
  195814. sshift = (int)((row_info->width + 7) & 0x07);
  195815. dshift = (int)((final_width + 7) & 0x07);
  195816. s_start = 7;
  195817. s_end = 0;
  195818. s_inc = -1;
  195819. }
  195820. else
  195821. #endif
  195822. {
  195823. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195824. dshift = 7 - (int)((final_width + 7) & 0x07);
  195825. s_start = 0;
  195826. s_end = 7;
  195827. s_inc = 1;
  195828. }
  195829. for (i = 0; i < row_info->width; i++)
  195830. {
  195831. v = (png_byte)((*sp >> sshift) & 0x01);
  195832. for (j = 0; j < jstop; j++)
  195833. {
  195834. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195835. *dp |= (png_byte)(v << dshift);
  195836. if (dshift == s_end)
  195837. {
  195838. dshift = s_start;
  195839. dp--;
  195840. }
  195841. else
  195842. dshift += s_inc;
  195843. }
  195844. if (sshift == s_end)
  195845. {
  195846. sshift = s_start;
  195847. sp--;
  195848. }
  195849. else
  195850. sshift += s_inc;
  195851. }
  195852. break;
  195853. }
  195854. case 2:
  195855. {
  195856. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195857. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195858. int sshift, dshift;
  195859. int s_start, s_end, s_inc;
  195860. int jstop = png_pass_inc[pass];
  195861. png_uint_32 i;
  195862. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195863. if (transformations & PNG_PACKSWAP)
  195864. {
  195865. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195866. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195867. s_start = 6;
  195868. s_end = 0;
  195869. s_inc = -2;
  195870. }
  195871. else
  195872. #endif
  195873. {
  195874. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195875. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195876. s_start = 0;
  195877. s_end = 6;
  195878. s_inc = 2;
  195879. }
  195880. for (i = 0; i < row_info->width; i++)
  195881. {
  195882. png_byte v;
  195883. int j;
  195884. v = (png_byte)((*sp >> sshift) & 0x03);
  195885. for (j = 0; j < jstop; j++)
  195886. {
  195887. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195888. *dp |= (png_byte)(v << dshift);
  195889. if (dshift == s_end)
  195890. {
  195891. dshift = s_start;
  195892. dp--;
  195893. }
  195894. else
  195895. dshift += s_inc;
  195896. }
  195897. if (sshift == s_end)
  195898. {
  195899. sshift = s_start;
  195900. sp--;
  195901. }
  195902. else
  195903. sshift += s_inc;
  195904. }
  195905. break;
  195906. }
  195907. case 4:
  195908. {
  195909. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195910. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195911. int sshift, dshift;
  195912. int s_start, s_end, s_inc;
  195913. png_uint_32 i;
  195914. int jstop = png_pass_inc[pass];
  195915. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195916. if (transformations & PNG_PACKSWAP)
  195917. {
  195918. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195919. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195920. s_start = 4;
  195921. s_end = 0;
  195922. s_inc = -4;
  195923. }
  195924. else
  195925. #endif
  195926. {
  195927. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195928. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195929. s_start = 0;
  195930. s_end = 4;
  195931. s_inc = 4;
  195932. }
  195933. for (i = 0; i < row_info->width; i++)
  195934. {
  195935. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195936. int j;
  195937. for (j = 0; j < jstop; j++)
  195938. {
  195939. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195940. *dp |= (png_byte)(v << dshift);
  195941. if (dshift == s_end)
  195942. {
  195943. dshift = s_start;
  195944. dp--;
  195945. }
  195946. else
  195947. dshift += s_inc;
  195948. }
  195949. if (sshift == s_end)
  195950. {
  195951. sshift = s_start;
  195952. sp--;
  195953. }
  195954. else
  195955. sshift += s_inc;
  195956. }
  195957. break;
  195958. }
  195959. default:
  195960. {
  195961. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195962. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195963. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195964. int jstop = png_pass_inc[pass];
  195965. png_uint_32 i;
  195966. for (i = 0; i < row_info->width; i++)
  195967. {
  195968. png_byte v[8];
  195969. int j;
  195970. png_memcpy(v, sp, pixel_bytes);
  195971. for (j = 0; j < jstop; j++)
  195972. {
  195973. png_memcpy(dp, v, pixel_bytes);
  195974. dp -= pixel_bytes;
  195975. }
  195976. sp -= pixel_bytes;
  195977. }
  195978. break;
  195979. }
  195980. }
  195981. row_info->width = final_width;
  195982. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195983. }
  195984. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195985. transformations = transformations; /* silence compiler warning */
  195986. #endif
  195987. }
  195988. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195989. void /* PRIVATE */
  195990. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195991. png_bytep prev_row, int filter)
  195992. {
  195993. png_debug(1, "in png_read_filter_row\n");
  195994. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195995. switch (filter)
  195996. {
  195997. case PNG_FILTER_VALUE_NONE:
  195998. break;
  195999. case PNG_FILTER_VALUE_SUB:
  196000. {
  196001. png_uint_32 i;
  196002. png_uint_32 istop = row_info->rowbytes;
  196003. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196004. png_bytep rp = row + bpp;
  196005. png_bytep lp = row;
  196006. for (i = bpp; i < istop; i++)
  196007. {
  196008. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196009. rp++;
  196010. }
  196011. break;
  196012. }
  196013. case PNG_FILTER_VALUE_UP:
  196014. {
  196015. png_uint_32 i;
  196016. png_uint_32 istop = row_info->rowbytes;
  196017. png_bytep rp = row;
  196018. png_bytep pp = prev_row;
  196019. for (i = 0; i < istop; i++)
  196020. {
  196021. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196022. rp++;
  196023. }
  196024. break;
  196025. }
  196026. case PNG_FILTER_VALUE_AVG:
  196027. {
  196028. png_uint_32 i;
  196029. png_bytep rp = row;
  196030. png_bytep pp = prev_row;
  196031. png_bytep lp = row;
  196032. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196033. png_uint_32 istop = row_info->rowbytes - bpp;
  196034. for (i = 0; i < bpp; i++)
  196035. {
  196036. *rp = (png_byte)(((int)(*rp) +
  196037. ((int)(*pp++) / 2 )) & 0xff);
  196038. rp++;
  196039. }
  196040. for (i = 0; i < istop; i++)
  196041. {
  196042. *rp = (png_byte)(((int)(*rp) +
  196043. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196044. rp++;
  196045. }
  196046. break;
  196047. }
  196048. case PNG_FILTER_VALUE_PAETH:
  196049. {
  196050. png_uint_32 i;
  196051. png_bytep rp = row;
  196052. png_bytep pp = prev_row;
  196053. png_bytep lp = row;
  196054. png_bytep cp = prev_row;
  196055. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196056. png_uint_32 istop=row_info->rowbytes - bpp;
  196057. for (i = 0; i < bpp; i++)
  196058. {
  196059. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196060. rp++;
  196061. }
  196062. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196063. {
  196064. int a, b, c, pa, pb, pc, p;
  196065. a = *lp++;
  196066. b = *pp++;
  196067. c = *cp++;
  196068. p = b - c;
  196069. pc = a - c;
  196070. #ifdef PNG_USE_ABS
  196071. pa = abs(p);
  196072. pb = abs(pc);
  196073. pc = abs(p + pc);
  196074. #else
  196075. pa = p < 0 ? -p : p;
  196076. pb = pc < 0 ? -pc : pc;
  196077. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196078. #endif
  196079. /*
  196080. if (pa <= pb && pa <= pc)
  196081. p = a;
  196082. else if (pb <= pc)
  196083. p = b;
  196084. else
  196085. p = c;
  196086. */
  196087. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196088. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196089. rp++;
  196090. }
  196091. break;
  196092. }
  196093. default:
  196094. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196095. *row=0;
  196096. break;
  196097. }
  196098. }
  196099. void /* PRIVATE */
  196100. png_read_finish_row(png_structp png_ptr)
  196101. {
  196102. #ifdef PNG_USE_LOCAL_ARRAYS
  196103. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196104. /* start of interlace block */
  196105. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196106. /* offset to next interlace block */
  196107. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196108. /* start of interlace block in the y direction */
  196109. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196110. /* offset to next interlace block in the y direction */
  196111. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196112. #endif
  196113. png_debug(1, "in png_read_finish_row\n");
  196114. png_ptr->row_number++;
  196115. if (png_ptr->row_number < png_ptr->num_rows)
  196116. return;
  196117. if (png_ptr->interlaced)
  196118. {
  196119. png_ptr->row_number = 0;
  196120. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196121. png_ptr->rowbytes + 1);
  196122. do
  196123. {
  196124. png_ptr->pass++;
  196125. if (png_ptr->pass >= 7)
  196126. break;
  196127. png_ptr->iwidth = (png_ptr->width +
  196128. png_pass_inc[png_ptr->pass] - 1 -
  196129. png_pass_start[png_ptr->pass]) /
  196130. png_pass_inc[png_ptr->pass];
  196131. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196132. png_ptr->iwidth) + 1;
  196133. if (!(png_ptr->transformations & PNG_INTERLACE))
  196134. {
  196135. png_ptr->num_rows = (png_ptr->height +
  196136. png_pass_yinc[png_ptr->pass] - 1 -
  196137. png_pass_ystart[png_ptr->pass]) /
  196138. png_pass_yinc[png_ptr->pass];
  196139. if (!(png_ptr->num_rows))
  196140. continue;
  196141. }
  196142. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196143. break;
  196144. } while (png_ptr->iwidth == 0);
  196145. if (png_ptr->pass < 7)
  196146. return;
  196147. }
  196148. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196149. {
  196150. #ifdef PNG_USE_LOCAL_ARRAYS
  196151. PNG_CONST PNG_IDAT;
  196152. #endif
  196153. char extra;
  196154. int ret;
  196155. png_ptr->zstream.next_out = (Bytef *)&extra;
  196156. png_ptr->zstream.avail_out = (uInt)1;
  196157. for(;;)
  196158. {
  196159. if (!(png_ptr->zstream.avail_in))
  196160. {
  196161. while (!png_ptr->idat_size)
  196162. {
  196163. png_byte chunk_length[4];
  196164. png_crc_finish(png_ptr, 0);
  196165. png_read_data(png_ptr, chunk_length, 4);
  196166. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196167. png_reset_crc(png_ptr);
  196168. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196169. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196170. png_error(png_ptr, "Not enough image data");
  196171. }
  196172. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196173. png_ptr->zstream.next_in = png_ptr->zbuf;
  196174. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196175. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196176. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196177. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196178. }
  196179. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196180. if (ret == Z_STREAM_END)
  196181. {
  196182. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196183. png_ptr->idat_size)
  196184. png_warning(png_ptr, "Extra compressed data");
  196185. png_ptr->mode |= PNG_AFTER_IDAT;
  196186. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196187. break;
  196188. }
  196189. if (ret != Z_OK)
  196190. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196191. "Decompression Error");
  196192. if (!(png_ptr->zstream.avail_out))
  196193. {
  196194. png_warning(png_ptr, "Extra compressed data.");
  196195. png_ptr->mode |= PNG_AFTER_IDAT;
  196196. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196197. break;
  196198. }
  196199. }
  196200. png_ptr->zstream.avail_out = 0;
  196201. }
  196202. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196203. png_warning(png_ptr, "Extra compression data");
  196204. inflateReset(&png_ptr->zstream);
  196205. png_ptr->mode |= PNG_AFTER_IDAT;
  196206. }
  196207. void /* PRIVATE */
  196208. png_read_start_row(png_structp png_ptr)
  196209. {
  196210. #ifdef PNG_USE_LOCAL_ARRAYS
  196211. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196212. /* start of interlace block */
  196213. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196214. /* offset to next interlace block */
  196215. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196216. /* start of interlace block in the y direction */
  196217. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196218. /* offset to next interlace block in the y direction */
  196219. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196220. #endif
  196221. int max_pixel_depth;
  196222. png_uint_32 row_bytes;
  196223. png_debug(1, "in png_read_start_row\n");
  196224. png_ptr->zstream.avail_in = 0;
  196225. png_init_read_transformations(png_ptr);
  196226. if (png_ptr->interlaced)
  196227. {
  196228. if (!(png_ptr->transformations & PNG_INTERLACE))
  196229. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196230. png_pass_ystart[0]) / png_pass_yinc[0];
  196231. else
  196232. png_ptr->num_rows = png_ptr->height;
  196233. png_ptr->iwidth = (png_ptr->width +
  196234. png_pass_inc[png_ptr->pass] - 1 -
  196235. png_pass_start[png_ptr->pass]) /
  196236. png_pass_inc[png_ptr->pass];
  196237. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196238. png_ptr->irowbytes = (png_size_t)row_bytes;
  196239. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196240. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196241. }
  196242. else
  196243. {
  196244. png_ptr->num_rows = png_ptr->height;
  196245. png_ptr->iwidth = png_ptr->width;
  196246. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196247. }
  196248. max_pixel_depth = png_ptr->pixel_depth;
  196249. #if defined(PNG_READ_PACK_SUPPORTED)
  196250. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196251. max_pixel_depth = 8;
  196252. #endif
  196253. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196254. if (png_ptr->transformations & PNG_EXPAND)
  196255. {
  196256. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196257. {
  196258. if (png_ptr->num_trans)
  196259. max_pixel_depth = 32;
  196260. else
  196261. max_pixel_depth = 24;
  196262. }
  196263. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196264. {
  196265. if (max_pixel_depth < 8)
  196266. max_pixel_depth = 8;
  196267. if (png_ptr->num_trans)
  196268. max_pixel_depth *= 2;
  196269. }
  196270. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196271. {
  196272. if (png_ptr->num_trans)
  196273. {
  196274. max_pixel_depth *= 4;
  196275. max_pixel_depth /= 3;
  196276. }
  196277. }
  196278. }
  196279. #endif
  196280. #if defined(PNG_READ_FILLER_SUPPORTED)
  196281. if (png_ptr->transformations & (PNG_FILLER))
  196282. {
  196283. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196284. max_pixel_depth = 32;
  196285. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196286. {
  196287. if (max_pixel_depth <= 8)
  196288. max_pixel_depth = 16;
  196289. else
  196290. max_pixel_depth = 32;
  196291. }
  196292. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196293. {
  196294. if (max_pixel_depth <= 32)
  196295. max_pixel_depth = 32;
  196296. else
  196297. max_pixel_depth = 64;
  196298. }
  196299. }
  196300. #endif
  196301. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196302. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196303. {
  196304. if (
  196305. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196306. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196307. #endif
  196308. #if defined(PNG_READ_FILLER_SUPPORTED)
  196309. (png_ptr->transformations & (PNG_FILLER)) ||
  196310. #endif
  196311. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196312. {
  196313. if (max_pixel_depth <= 16)
  196314. max_pixel_depth = 32;
  196315. else
  196316. max_pixel_depth = 64;
  196317. }
  196318. else
  196319. {
  196320. if (max_pixel_depth <= 8)
  196321. {
  196322. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196323. max_pixel_depth = 32;
  196324. else
  196325. max_pixel_depth = 24;
  196326. }
  196327. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196328. max_pixel_depth = 64;
  196329. else
  196330. max_pixel_depth = 48;
  196331. }
  196332. }
  196333. #endif
  196334. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196335. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196336. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196337. {
  196338. int user_pixel_depth=png_ptr->user_transform_depth*
  196339. png_ptr->user_transform_channels;
  196340. if(user_pixel_depth > max_pixel_depth)
  196341. max_pixel_depth=user_pixel_depth;
  196342. }
  196343. #endif
  196344. /* align the width on the next larger 8 pixels. Mainly used
  196345. for interlacing */
  196346. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196347. /* calculate the maximum bytes needed, adding a byte and a pixel
  196348. for safety's sake */
  196349. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196350. 1 + ((max_pixel_depth + 7) >> 3);
  196351. #ifdef PNG_MAX_MALLOC_64K
  196352. if (row_bytes > (png_uint_32)65536L)
  196353. png_error(png_ptr, "This image requires a row greater than 64KB");
  196354. #endif
  196355. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196356. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196357. #ifdef PNG_MAX_MALLOC_64K
  196358. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196359. png_error(png_ptr, "This image requires a row greater than 64KB");
  196360. #endif
  196361. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196362. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196363. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196364. png_ptr->rowbytes + 1));
  196365. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196366. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196367. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196368. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196369. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196370. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196371. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196372. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196373. }
  196374. #endif /* PNG_READ_SUPPORTED */
  196375. /*** End of inlined file: pngrutil.c ***/
  196376. /*** Start of inlined file: pngset.c ***/
  196377. /* pngset.c - storage of image information into info struct
  196378. *
  196379. * Last changed in libpng 1.2.21 [October 4, 2007]
  196380. * For conditions of distribution and use, see copyright notice in png.h
  196381. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196382. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196383. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196384. *
  196385. * The functions here are used during reads to store data from the file
  196386. * into the info struct, and during writes to store application data
  196387. * into the info struct for writing into the file. This abstracts the
  196388. * info struct and allows us to change the structure in the future.
  196389. */
  196390. #define PNG_INTERNAL
  196391. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196392. #if defined(PNG_bKGD_SUPPORTED)
  196393. void PNGAPI
  196394. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196395. {
  196396. png_debug1(1, "in %s storage function\n", "bKGD");
  196397. if (png_ptr == NULL || info_ptr == NULL)
  196398. return;
  196399. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196400. info_ptr->valid |= PNG_INFO_bKGD;
  196401. }
  196402. #endif
  196403. #if defined(PNG_cHRM_SUPPORTED)
  196404. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196405. void PNGAPI
  196406. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196407. double white_x, double white_y, double red_x, double red_y,
  196408. double green_x, double green_y, double blue_x, double blue_y)
  196409. {
  196410. png_debug1(1, "in %s storage function\n", "cHRM");
  196411. if (png_ptr == NULL || info_ptr == NULL)
  196412. return;
  196413. if (white_x < 0.0 || white_y < 0.0 ||
  196414. red_x < 0.0 || red_y < 0.0 ||
  196415. green_x < 0.0 || green_y < 0.0 ||
  196416. blue_x < 0.0 || blue_y < 0.0)
  196417. {
  196418. png_warning(png_ptr,
  196419. "Ignoring attempt to set negative chromaticity value");
  196420. return;
  196421. }
  196422. if (white_x > 21474.83 || white_y > 21474.83 ||
  196423. red_x > 21474.83 || red_y > 21474.83 ||
  196424. green_x > 21474.83 || green_y > 21474.83 ||
  196425. blue_x > 21474.83 || blue_y > 21474.83)
  196426. {
  196427. png_warning(png_ptr,
  196428. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196429. return;
  196430. }
  196431. info_ptr->x_white = (float)white_x;
  196432. info_ptr->y_white = (float)white_y;
  196433. info_ptr->x_red = (float)red_x;
  196434. info_ptr->y_red = (float)red_y;
  196435. info_ptr->x_green = (float)green_x;
  196436. info_ptr->y_green = (float)green_y;
  196437. info_ptr->x_blue = (float)blue_x;
  196438. info_ptr->y_blue = (float)blue_y;
  196439. #ifdef PNG_FIXED_POINT_SUPPORTED
  196440. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196441. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196442. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196443. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196444. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196445. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196446. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196447. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196448. #endif
  196449. info_ptr->valid |= PNG_INFO_cHRM;
  196450. }
  196451. #endif
  196452. #ifdef PNG_FIXED_POINT_SUPPORTED
  196453. void PNGAPI
  196454. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196455. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196456. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196457. png_fixed_point blue_x, png_fixed_point blue_y)
  196458. {
  196459. png_debug1(1, "in %s storage function\n", "cHRM");
  196460. if (png_ptr == NULL || info_ptr == NULL)
  196461. return;
  196462. if (white_x < 0 || white_y < 0 ||
  196463. red_x < 0 || red_y < 0 ||
  196464. green_x < 0 || green_y < 0 ||
  196465. blue_x < 0 || blue_y < 0)
  196466. {
  196467. png_warning(png_ptr,
  196468. "Ignoring attempt to set negative chromaticity value");
  196469. return;
  196470. }
  196471. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196472. if (white_x > (double) PNG_UINT_31_MAX ||
  196473. white_y > (double) PNG_UINT_31_MAX ||
  196474. red_x > (double) PNG_UINT_31_MAX ||
  196475. red_y > (double) PNG_UINT_31_MAX ||
  196476. green_x > (double) PNG_UINT_31_MAX ||
  196477. green_y > (double) PNG_UINT_31_MAX ||
  196478. blue_x > (double) PNG_UINT_31_MAX ||
  196479. blue_y > (double) PNG_UINT_31_MAX)
  196480. #else
  196481. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196482. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196483. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196484. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196485. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196486. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196487. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196488. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196489. #endif
  196490. {
  196491. png_warning(png_ptr,
  196492. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196493. return;
  196494. }
  196495. info_ptr->int_x_white = white_x;
  196496. info_ptr->int_y_white = white_y;
  196497. info_ptr->int_x_red = red_x;
  196498. info_ptr->int_y_red = red_y;
  196499. info_ptr->int_x_green = green_x;
  196500. info_ptr->int_y_green = green_y;
  196501. info_ptr->int_x_blue = blue_x;
  196502. info_ptr->int_y_blue = blue_y;
  196503. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196504. info_ptr->x_white = (float)(white_x/100000.);
  196505. info_ptr->y_white = (float)(white_y/100000.);
  196506. info_ptr->x_red = (float)( red_x/100000.);
  196507. info_ptr->y_red = (float)( red_y/100000.);
  196508. info_ptr->x_green = (float)(green_x/100000.);
  196509. info_ptr->y_green = (float)(green_y/100000.);
  196510. info_ptr->x_blue = (float)( blue_x/100000.);
  196511. info_ptr->y_blue = (float)( blue_y/100000.);
  196512. #endif
  196513. info_ptr->valid |= PNG_INFO_cHRM;
  196514. }
  196515. #endif
  196516. #endif
  196517. #if defined(PNG_gAMA_SUPPORTED)
  196518. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196519. void PNGAPI
  196520. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196521. {
  196522. double gamma;
  196523. png_debug1(1, "in %s storage function\n", "gAMA");
  196524. if (png_ptr == NULL || info_ptr == NULL)
  196525. return;
  196526. /* Check for overflow */
  196527. if (file_gamma > 21474.83)
  196528. {
  196529. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196530. gamma=21474.83;
  196531. }
  196532. else
  196533. gamma=file_gamma;
  196534. info_ptr->gamma = (float)gamma;
  196535. #ifdef PNG_FIXED_POINT_SUPPORTED
  196536. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196537. #endif
  196538. info_ptr->valid |= PNG_INFO_gAMA;
  196539. if(gamma == 0.0)
  196540. png_warning(png_ptr, "Setting gamma=0");
  196541. }
  196542. #endif
  196543. void PNGAPI
  196544. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196545. int_gamma)
  196546. {
  196547. png_fixed_point gamma;
  196548. png_debug1(1, "in %s storage function\n", "gAMA");
  196549. if (png_ptr == NULL || info_ptr == NULL)
  196550. return;
  196551. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196552. {
  196553. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196554. gamma=PNG_UINT_31_MAX;
  196555. }
  196556. else
  196557. {
  196558. if (int_gamma < 0)
  196559. {
  196560. png_warning(png_ptr, "Setting negative gamma to zero");
  196561. gamma=0;
  196562. }
  196563. else
  196564. gamma=int_gamma;
  196565. }
  196566. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196567. info_ptr->gamma = (float)(gamma/100000.);
  196568. #endif
  196569. #ifdef PNG_FIXED_POINT_SUPPORTED
  196570. info_ptr->int_gamma = gamma;
  196571. #endif
  196572. info_ptr->valid |= PNG_INFO_gAMA;
  196573. if(gamma == 0)
  196574. png_warning(png_ptr, "Setting gamma=0");
  196575. }
  196576. #endif
  196577. #if defined(PNG_hIST_SUPPORTED)
  196578. void PNGAPI
  196579. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196580. {
  196581. int i;
  196582. png_debug1(1, "in %s storage function\n", "hIST");
  196583. if (png_ptr == NULL || info_ptr == NULL)
  196584. return;
  196585. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196586. > PNG_MAX_PALETTE_LENGTH)
  196587. {
  196588. png_warning(png_ptr,
  196589. "Invalid palette size, hIST allocation skipped.");
  196590. return;
  196591. }
  196592. #ifdef PNG_FREE_ME_SUPPORTED
  196593. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196594. #endif
  196595. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196596. 1.2.1 */
  196597. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196598. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196599. if (png_ptr->hist == NULL)
  196600. {
  196601. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196602. return;
  196603. }
  196604. for (i = 0; i < info_ptr->num_palette; i++)
  196605. png_ptr->hist[i] = hist[i];
  196606. info_ptr->hist = png_ptr->hist;
  196607. info_ptr->valid |= PNG_INFO_hIST;
  196608. #ifdef PNG_FREE_ME_SUPPORTED
  196609. info_ptr->free_me |= PNG_FREE_HIST;
  196610. #else
  196611. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196612. #endif
  196613. }
  196614. #endif
  196615. void PNGAPI
  196616. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196617. png_uint_32 width, png_uint_32 height, int bit_depth,
  196618. int color_type, int interlace_type, int compression_type,
  196619. int filter_type)
  196620. {
  196621. png_debug1(1, "in %s storage function\n", "IHDR");
  196622. if (png_ptr == NULL || info_ptr == NULL)
  196623. return;
  196624. /* check for width and height valid values */
  196625. if (width == 0 || height == 0)
  196626. png_error(png_ptr, "Image width or height is zero in IHDR");
  196627. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196628. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196629. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196630. #else
  196631. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196632. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196633. #endif
  196634. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196635. png_error(png_ptr, "Invalid image size in IHDR");
  196636. if ( width > (PNG_UINT_32_MAX
  196637. >> 3) /* 8-byte RGBA pixels */
  196638. - 64 /* bigrowbuf hack */
  196639. - 1 /* filter byte */
  196640. - 7*8 /* rounding of width to multiple of 8 pixels */
  196641. - 8) /* extra max_pixel_depth pad */
  196642. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196643. /* check other values */
  196644. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196645. bit_depth != 8 && bit_depth != 16)
  196646. png_error(png_ptr, "Invalid bit depth in IHDR");
  196647. if (color_type < 0 || color_type == 1 ||
  196648. color_type == 5 || color_type > 6)
  196649. png_error(png_ptr, "Invalid color type in IHDR");
  196650. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196651. ((color_type == PNG_COLOR_TYPE_RGB ||
  196652. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196653. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196654. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196655. if (interlace_type >= PNG_INTERLACE_LAST)
  196656. png_error(png_ptr, "Unknown interlace method in IHDR");
  196657. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196658. png_error(png_ptr, "Unknown compression method in IHDR");
  196659. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196660. /* Accept filter_method 64 (intrapixel differencing) only if
  196661. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196662. * 2. Libpng did not read a PNG signature (this filter_method is only
  196663. * used in PNG datastreams that are embedded in MNG datastreams) and
  196664. * 3. The application called png_permit_mng_features with a mask that
  196665. * included PNG_FLAG_MNG_FILTER_64 and
  196666. * 4. The filter_method is 64 and
  196667. * 5. The color_type is RGB or RGBA
  196668. */
  196669. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196670. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196671. if(filter_type != PNG_FILTER_TYPE_BASE)
  196672. {
  196673. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196674. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196675. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196676. (color_type == PNG_COLOR_TYPE_RGB ||
  196677. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196678. png_error(png_ptr, "Unknown filter method in IHDR");
  196679. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196680. png_warning(png_ptr, "Invalid filter method in IHDR");
  196681. }
  196682. #else
  196683. if(filter_type != PNG_FILTER_TYPE_BASE)
  196684. png_error(png_ptr, "Unknown filter method in IHDR");
  196685. #endif
  196686. info_ptr->width = width;
  196687. info_ptr->height = height;
  196688. info_ptr->bit_depth = (png_byte)bit_depth;
  196689. info_ptr->color_type =(png_byte) color_type;
  196690. info_ptr->compression_type = (png_byte)compression_type;
  196691. info_ptr->filter_type = (png_byte)filter_type;
  196692. info_ptr->interlace_type = (png_byte)interlace_type;
  196693. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196694. info_ptr->channels = 1;
  196695. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196696. info_ptr->channels = 3;
  196697. else
  196698. info_ptr->channels = 1;
  196699. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196700. info_ptr->channels++;
  196701. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196702. /* check for potential overflow */
  196703. if (width > (PNG_UINT_32_MAX
  196704. >> 3) /* 8-byte RGBA pixels */
  196705. - 64 /* bigrowbuf hack */
  196706. - 1 /* filter byte */
  196707. - 7*8 /* rounding of width to multiple of 8 pixels */
  196708. - 8) /* extra max_pixel_depth pad */
  196709. info_ptr->rowbytes = (png_size_t)0;
  196710. else
  196711. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196712. }
  196713. #if defined(PNG_oFFs_SUPPORTED)
  196714. void PNGAPI
  196715. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196716. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196717. {
  196718. png_debug1(1, "in %s storage function\n", "oFFs");
  196719. if (png_ptr == NULL || info_ptr == NULL)
  196720. return;
  196721. info_ptr->x_offset = offset_x;
  196722. info_ptr->y_offset = offset_y;
  196723. info_ptr->offset_unit_type = (png_byte)unit_type;
  196724. info_ptr->valid |= PNG_INFO_oFFs;
  196725. }
  196726. #endif
  196727. #if defined(PNG_pCAL_SUPPORTED)
  196728. void PNGAPI
  196729. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196730. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196731. png_charp units, png_charpp params)
  196732. {
  196733. png_uint_32 length;
  196734. int i;
  196735. png_debug1(1, "in %s storage function\n", "pCAL");
  196736. if (png_ptr == NULL || info_ptr == NULL)
  196737. return;
  196738. length = png_strlen(purpose) + 1;
  196739. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196740. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196741. if (info_ptr->pcal_purpose == NULL)
  196742. {
  196743. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196744. return;
  196745. }
  196746. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196747. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196748. info_ptr->pcal_X0 = X0;
  196749. info_ptr->pcal_X1 = X1;
  196750. info_ptr->pcal_type = (png_byte)type;
  196751. info_ptr->pcal_nparams = (png_byte)nparams;
  196752. length = png_strlen(units) + 1;
  196753. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196754. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196755. if (info_ptr->pcal_units == NULL)
  196756. {
  196757. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196758. return;
  196759. }
  196760. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196761. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196762. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196763. if (info_ptr->pcal_params == NULL)
  196764. {
  196765. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196766. return;
  196767. }
  196768. info_ptr->pcal_params[nparams] = NULL;
  196769. for (i = 0; i < nparams; i++)
  196770. {
  196771. length = png_strlen(params[i]) + 1;
  196772. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196773. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196774. if (info_ptr->pcal_params[i] == NULL)
  196775. {
  196776. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196777. return;
  196778. }
  196779. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196780. }
  196781. info_ptr->valid |= PNG_INFO_pCAL;
  196782. #ifdef PNG_FREE_ME_SUPPORTED
  196783. info_ptr->free_me |= PNG_FREE_PCAL;
  196784. #endif
  196785. }
  196786. #endif
  196787. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196788. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196789. void PNGAPI
  196790. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196791. int unit, double width, double height)
  196792. {
  196793. png_debug1(1, "in %s storage function\n", "sCAL");
  196794. if (png_ptr == NULL || info_ptr == NULL)
  196795. return;
  196796. info_ptr->scal_unit = (png_byte)unit;
  196797. info_ptr->scal_pixel_width = width;
  196798. info_ptr->scal_pixel_height = height;
  196799. info_ptr->valid |= PNG_INFO_sCAL;
  196800. }
  196801. #else
  196802. #ifdef PNG_FIXED_POINT_SUPPORTED
  196803. void PNGAPI
  196804. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196805. int unit, png_charp swidth, png_charp sheight)
  196806. {
  196807. png_uint_32 length;
  196808. png_debug1(1, "in %s storage function\n", "sCAL");
  196809. if (png_ptr == NULL || info_ptr == NULL)
  196810. return;
  196811. info_ptr->scal_unit = (png_byte)unit;
  196812. length = png_strlen(swidth) + 1;
  196813. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196814. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196815. if (info_ptr->scal_s_width == NULL)
  196816. {
  196817. png_warning(png_ptr,
  196818. "Memory allocation failed while processing sCAL.");
  196819. }
  196820. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196821. length = png_strlen(sheight) + 1;
  196822. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196823. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196824. if (info_ptr->scal_s_height == NULL)
  196825. {
  196826. png_free (png_ptr, info_ptr->scal_s_width);
  196827. png_warning(png_ptr,
  196828. "Memory allocation failed while processing sCAL.");
  196829. }
  196830. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196831. info_ptr->valid |= PNG_INFO_sCAL;
  196832. #ifdef PNG_FREE_ME_SUPPORTED
  196833. info_ptr->free_me |= PNG_FREE_SCAL;
  196834. #endif
  196835. }
  196836. #endif
  196837. #endif
  196838. #endif
  196839. #if defined(PNG_pHYs_SUPPORTED)
  196840. void PNGAPI
  196841. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196842. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196843. {
  196844. png_debug1(1, "in %s storage function\n", "pHYs");
  196845. if (png_ptr == NULL || info_ptr == NULL)
  196846. return;
  196847. info_ptr->x_pixels_per_unit = res_x;
  196848. info_ptr->y_pixels_per_unit = res_y;
  196849. info_ptr->phys_unit_type = (png_byte)unit_type;
  196850. info_ptr->valid |= PNG_INFO_pHYs;
  196851. }
  196852. #endif
  196853. void PNGAPI
  196854. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196855. png_colorp palette, int num_palette)
  196856. {
  196857. png_debug1(1, "in %s storage function\n", "PLTE");
  196858. if (png_ptr == NULL || info_ptr == NULL)
  196859. return;
  196860. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196861. {
  196862. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196863. png_error(png_ptr, "Invalid palette length");
  196864. else
  196865. {
  196866. png_warning(png_ptr, "Invalid palette length");
  196867. return;
  196868. }
  196869. }
  196870. /*
  196871. * It may not actually be necessary to set png_ptr->palette here;
  196872. * we do it for backward compatibility with the way the png_handle_tRNS
  196873. * function used to do the allocation.
  196874. */
  196875. #ifdef PNG_FREE_ME_SUPPORTED
  196876. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196877. #endif
  196878. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196879. of num_palette entries,
  196880. in case of an invalid PNG file that has too-large sample values. */
  196881. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196882. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196883. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196884. png_sizeof(png_color));
  196885. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196886. info_ptr->palette = png_ptr->palette;
  196887. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196888. #ifdef PNG_FREE_ME_SUPPORTED
  196889. info_ptr->free_me |= PNG_FREE_PLTE;
  196890. #else
  196891. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196892. #endif
  196893. info_ptr->valid |= PNG_INFO_PLTE;
  196894. }
  196895. #if defined(PNG_sBIT_SUPPORTED)
  196896. void PNGAPI
  196897. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196898. png_color_8p sig_bit)
  196899. {
  196900. png_debug1(1, "in %s storage function\n", "sBIT");
  196901. if (png_ptr == NULL || info_ptr == NULL)
  196902. return;
  196903. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196904. info_ptr->valid |= PNG_INFO_sBIT;
  196905. }
  196906. #endif
  196907. #if defined(PNG_sRGB_SUPPORTED)
  196908. void PNGAPI
  196909. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196910. {
  196911. png_debug1(1, "in %s storage function\n", "sRGB");
  196912. if (png_ptr == NULL || info_ptr == NULL)
  196913. return;
  196914. info_ptr->srgb_intent = (png_byte)intent;
  196915. info_ptr->valid |= PNG_INFO_sRGB;
  196916. }
  196917. void PNGAPI
  196918. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196919. int intent)
  196920. {
  196921. #if defined(PNG_gAMA_SUPPORTED)
  196922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196923. float file_gamma;
  196924. #endif
  196925. #ifdef PNG_FIXED_POINT_SUPPORTED
  196926. png_fixed_point int_file_gamma;
  196927. #endif
  196928. #endif
  196929. #if defined(PNG_cHRM_SUPPORTED)
  196930. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196931. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196932. #endif
  196933. #ifdef PNG_FIXED_POINT_SUPPORTED
  196934. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196935. int_green_y, int_blue_x, int_blue_y;
  196936. #endif
  196937. #endif
  196938. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196939. if (png_ptr == NULL || info_ptr == NULL)
  196940. return;
  196941. png_set_sRGB(png_ptr, info_ptr, intent);
  196942. #if defined(PNG_gAMA_SUPPORTED)
  196943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196944. file_gamma = (float).45455;
  196945. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196946. #endif
  196947. #ifdef PNG_FIXED_POINT_SUPPORTED
  196948. int_file_gamma = 45455L;
  196949. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196950. #endif
  196951. #endif
  196952. #if defined(PNG_cHRM_SUPPORTED)
  196953. #ifdef PNG_FIXED_POINT_SUPPORTED
  196954. int_white_x = 31270L;
  196955. int_white_y = 32900L;
  196956. int_red_x = 64000L;
  196957. int_red_y = 33000L;
  196958. int_green_x = 30000L;
  196959. int_green_y = 60000L;
  196960. int_blue_x = 15000L;
  196961. int_blue_y = 6000L;
  196962. png_set_cHRM_fixed(png_ptr, info_ptr,
  196963. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196964. int_blue_x, int_blue_y);
  196965. #endif
  196966. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196967. white_x = (float).3127;
  196968. white_y = (float).3290;
  196969. red_x = (float).64;
  196970. red_y = (float).33;
  196971. green_x = (float).30;
  196972. green_y = (float).60;
  196973. blue_x = (float).15;
  196974. blue_y = (float).06;
  196975. png_set_cHRM(png_ptr, info_ptr,
  196976. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196977. #endif
  196978. #endif
  196979. }
  196980. #endif
  196981. #if defined(PNG_iCCP_SUPPORTED)
  196982. void PNGAPI
  196983. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196984. png_charp name, int compression_type,
  196985. png_charp profile, png_uint_32 proflen)
  196986. {
  196987. png_charp new_iccp_name;
  196988. png_charp new_iccp_profile;
  196989. png_debug1(1, "in %s storage function\n", "iCCP");
  196990. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196991. return;
  196992. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196993. if (new_iccp_name == NULL)
  196994. {
  196995. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196996. return;
  196997. }
  196998. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196999. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197000. if (new_iccp_profile == NULL)
  197001. {
  197002. png_free (png_ptr, new_iccp_name);
  197003. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197004. return;
  197005. }
  197006. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197007. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197008. info_ptr->iccp_proflen = proflen;
  197009. info_ptr->iccp_name = new_iccp_name;
  197010. info_ptr->iccp_profile = new_iccp_profile;
  197011. /* Compression is always zero but is here so the API and info structure
  197012. * does not have to change if we introduce multiple compression types */
  197013. info_ptr->iccp_compression = (png_byte)compression_type;
  197014. #ifdef PNG_FREE_ME_SUPPORTED
  197015. info_ptr->free_me |= PNG_FREE_ICCP;
  197016. #endif
  197017. info_ptr->valid |= PNG_INFO_iCCP;
  197018. }
  197019. #endif
  197020. #if defined(PNG_TEXT_SUPPORTED)
  197021. void PNGAPI
  197022. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197023. int num_text)
  197024. {
  197025. int ret;
  197026. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197027. if (ret)
  197028. png_error(png_ptr, "Insufficient memory to store text");
  197029. }
  197030. int /* PRIVATE */
  197031. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197032. int num_text)
  197033. {
  197034. int i;
  197035. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197036. "text" : (png_const_charp)png_ptr->chunk_name));
  197037. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197038. return(0);
  197039. /* Make sure we have enough space in the "text" array in info_struct
  197040. * to hold all of the incoming text_ptr objects.
  197041. */
  197042. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197043. {
  197044. if (info_ptr->text != NULL)
  197045. {
  197046. png_textp old_text;
  197047. int old_max;
  197048. old_max = info_ptr->max_text;
  197049. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197050. old_text = info_ptr->text;
  197051. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197052. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197053. if (info_ptr->text == NULL)
  197054. {
  197055. png_free(png_ptr, old_text);
  197056. return(1);
  197057. }
  197058. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197059. png_sizeof(png_text)));
  197060. png_free(png_ptr, old_text);
  197061. }
  197062. else
  197063. {
  197064. info_ptr->max_text = num_text + 8;
  197065. info_ptr->num_text = 0;
  197066. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197067. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197068. if (info_ptr->text == NULL)
  197069. return(1);
  197070. #ifdef PNG_FREE_ME_SUPPORTED
  197071. info_ptr->free_me |= PNG_FREE_TEXT;
  197072. #endif
  197073. }
  197074. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197075. info_ptr->max_text);
  197076. }
  197077. for (i = 0; i < num_text; i++)
  197078. {
  197079. png_size_t text_length,key_len;
  197080. png_size_t lang_len,lang_key_len;
  197081. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197082. if (text_ptr[i].key == NULL)
  197083. continue;
  197084. key_len = png_strlen(text_ptr[i].key);
  197085. if(text_ptr[i].compression <= 0)
  197086. {
  197087. lang_len = 0;
  197088. lang_key_len = 0;
  197089. }
  197090. else
  197091. #ifdef PNG_iTXt_SUPPORTED
  197092. {
  197093. /* set iTXt data */
  197094. if (text_ptr[i].lang != NULL)
  197095. lang_len = png_strlen(text_ptr[i].lang);
  197096. else
  197097. lang_len = 0;
  197098. if (text_ptr[i].lang_key != NULL)
  197099. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197100. else
  197101. lang_key_len = 0;
  197102. }
  197103. #else
  197104. {
  197105. png_warning(png_ptr, "iTXt chunk not supported.");
  197106. continue;
  197107. }
  197108. #endif
  197109. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197110. {
  197111. text_length = 0;
  197112. #ifdef PNG_iTXt_SUPPORTED
  197113. if(text_ptr[i].compression > 0)
  197114. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197115. else
  197116. #endif
  197117. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197118. }
  197119. else
  197120. {
  197121. text_length = png_strlen(text_ptr[i].text);
  197122. textp->compression = text_ptr[i].compression;
  197123. }
  197124. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197125. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197126. if (textp->key == NULL)
  197127. return(1);
  197128. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197129. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197130. (int)textp->key);
  197131. png_memcpy(textp->key, text_ptr[i].key,
  197132. (png_size_t)(key_len));
  197133. *(textp->key+key_len) = '\0';
  197134. #ifdef PNG_iTXt_SUPPORTED
  197135. if (text_ptr[i].compression > 0)
  197136. {
  197137. textp->lang=textp->key + key_len + 1;
  197138. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197139. *(textp->lang+lang_len) = '\0';
  197140. textp->lang_key=textp->lang + lang_len + 1;
  197141. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197142. *(textp->lang_key+lang_key_len) = '\0';
  197143. textp->text=textp->lang_key + lang_key_len + 1;
  197144. }
  197145. else
  197146. #endif
  197147. {
  197148. #ifdef PNG_iTXt_SUPPORTED
  197149. textp->lang=NULL;
  197150. textp->lang_key=NULL;
  197151. #endif
  197152. textp->text=textp->key + key_len + 1;
  197153. }
  197154. if(text_length)
  197155. png_memcpy(textp->text, text_ptr[i].text,
  197156. (png_size_t)(text_length));
  197157. *(textp->text+text_length) = '\0';
  197158. #ifdef PNG_iTXt_SUPPORTED
  197159. if(textp->compression > 0)
  197160. {
  197161. textp->text_length = 0;
  197162. textp->itxt_length = text_length;
  197163. }
  197164. else
  197165. #endif
  197166. {
  197167. textp->text_length = text_length;
  197168. #ifdef PNG_iTXt_SUPPORTED
  197169. textp->itxt_length = 0;
  197170. #endif
  197171. }
  197172. info_ptr->num_text++;
  197173. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197174. }
  197175. return(0);
  197176. }
  197177. #endif
  197178. #if defined(PNG_tIME_SUPPORTED)
  197179. void PNGAPI
  197180. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197181. {
  197182. png_debug1(1, "in %s storage function\n", "tIME");
  197183. if (png_ptr == NULL || info_ptr == NULL ||
  197184. (png_ptr->mode & PNG_WROTE_tIME))
  197185. return;
  197186. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197187. info_ptr->valid |= PNG_INFO_tIME;
  197188. }
  197189. #endif
  197190. #if defined(PNG_tRNS_SUPPORTED)
  197191. void PNGAPI
  197192. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197193. png_bytep trans, int num_trans, png_color_16p trans_values)
  197194. {
  197195. png_debug1(1, "in %s storage function\n", "tRNS");
  197196. if (png_ptr == NULL || info_ptr == NULL)
  197197. return;
  197198. if (trans != NULL)
  197199. {
  197200. /*
  197201. * It may not actually be necessary to set png_ptr->trans here;
  197202. * we do it for backward compatibility with the way the png_handle_tRNS
  197203. * function used to do the allocation.
  197204. */
  197205. #ifdef PNG_FREE_ME_SUPPORTED
  197206. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197207. #endif
  197208. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197209. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197210. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197211. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197212. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197213. #ifdef PNG_FREE_ME_SUPPORTED
  197214. info_ptr->free_me |= PNG_FREE_TRNS;
  197215. #else
  197216. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197217. #endif
  197218. }
  197219. if (trans_values != NULL)
  197220. {
  197221. png_memcpy(&(info_ptr->trans_values), trans_values,
  197222. png_sizeof(png_color_16));
  197223. if (num_trans == 0)
  197224. num_trans = 1;
  197225. }
  197226. info_ptr->num_trans = (png_uint_16)num_trans;
  197227. info_ptr->valid |= PNG_INFO_tRNS;
  197228. }
  197229. #endif
  197230. #if defined(PNG_sPLT_SUPPORTED)
  197231. void PNGAPI
  197232. png_set_sPLT(png_structp png_ptr,
  197233. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197234. {
  197235. png_sPLT_tp np;
  197236. int i;
  197237. if (png_ptr == NULL || info_ptr == NULL)
  197238. return;
  197239. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197240. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197241. if (np == NULL)
  197242. {
  197243. png_warning(png_ptr, "No memory for sPLT palettes.");
  197244. return;
  197245. }
  197246. png_memcpy(np, info_ptr->splt_palettes,
  197247. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197248. png_free(png_ptr, info_ptr->splt_palettes);
  197249. info_ptr->splt_palettes=NULL;
  197250. for (i = 0; i < nentries; i++)
  197251. {
  197252. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197253. png_sPLT_tp from = entries + i;
  197254. to->name = (png_charp)png_malloc_warn(png_ptr,
  197255. png_strlen(from->name) + 1);
  197256. if (to->name == NULL)
  197257. {
  197258. png_warning(png_ptr,
  197259. "Out of memory while processing sPLT chunk");
  197260. }
  197261. /* TODO: use png_malloc_warn */
  197262. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197263. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197264. from->nentries * png_sizeof(png_sPLT_entry));
  197265. /* TODO: use png_malloc_warn */
  197266. png_memcpy(to->entries, from->entries,
  197267. from->nentries * png_sizeof(png_sPLT_entry));
  197268. if (to->entries == NULL)
  197269. {
  197270. png_warning(png_ptr,
  197271. "Out of memory while processing sPLT chunk");
  197272. png_free(png_ptr,to->name);
  197273. to->name = NULL;
  197274. }
  197275. to->nentries = from->nentries;
  197276. to->depth = from->depth;
  197277. }
  197278. info_ptr->splt_palettes = np;
  197279. info_ptr->splt_palettes_num += nentries;
  197280. info_ptr->valid |= PNG_INFO_sPLT;
  197281. #ifdef PNG_FREE_ME_SUPPORTED
  197282. info_ptr->free_me |= PNG_FREE_SPLT;
  197283. #endif
  197284. }
  197285. #endif /* PNG_sPLT_SUPPORTED */
  197286. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197287. void PNGAPI
  197288. png_set_unknown_chunks(png_structp png_ptr,
  197289. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197290. {
  197291. png_unknown_chunkp np;
  197292. int i;
  197293. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197294. return;
  197295. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197296. (info_ptr->unknown_chunks_num + num_unknowns) *
  197297. png_sizeof(png_unknown_chunk));
  197298. if (np == NULL)
  197299. {
  197300. png_warning(png_ptr,
  197301. "Out of memory while processing unknown chunk.");
  197302. return;
  197303. }
  197304. png_memcpy(np, info_ptr->unknown_chunks,
  197305. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197306. png_free(png_ptr, info_ptr->unknown_chunks);
  197307. info_ptr->unknown_chunks=NULL;
  197308. for (i = 0; i < num_unknowns; i++)
  197309. {
  197310. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197311. png_unknown_chunkp from = unknowns + i;
  197312. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197313. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197314. if (to->data == NULL)
  197315. {
  197316. png_warning(png_ptr,
  197317. "Out of memory while processing unknown chunk.");
  197318. }
  197319. else
  197320. {
  197321. png_memcpy(to->data, from->data, from->size);
  197322. to->size = from->size;
  197323. /* note our location in the read or write sequence */
  197324. to->location = (png_byte)(png_ptr->mode & 0xff);
  197325. }
  197326. }
  197327. info_ptr->unknown_chunks = np;
  197328. info_ptr->unknown_chunks_num += num_unknowns;
  197329. #ifdef PNG_FREE_ME_SUPPORTED
  197330. info_ptr->free_me |= PNG_FREE_UNKN;
  197331. #endif
  197332. }
  197333. void PNGAPI
  197334. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197335. int chunk, int location)
  197336. {
  197337. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197338. (int)info_ptr->unknown_chunks_num)
  197339. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197340. }
  197341. #endif
  197342. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197343. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197344. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197345. void PNGAPI
  197346. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197347. {
  197348. /* This function is deprecated in favor of png_permit_mng_features()
  197349. and will be removed from libpng-1.3.0 */
  197350. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197351. if (png_ptr == NULL)
  197352. return;
  197353. png_ptr->mng_features_permitted = (png_byte)
  197354. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197355. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197356. }
  197357. #endif
  197358. #endif
  197359. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197360. png_uint_32 PNGAPI
  197361. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197362. {
  197363. png_debug(1, "in png_permit_mng_features\n");
  197364. if (png_ptr == NULL)
  197365. return (png_uint_32)0;
  197366. png_ptr->mng_features_permitted =
  197367. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197368. return (png_uint_32)png_ptr->mng_features_permitted;
  197369. }
  197370. #endif
  197371. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197372. void PNGAPI
  197373. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197374. chunk_list, int num_chunks)
  197375. {
  197376. png_bytep new_list, p;
  197377. int i, old_num_chunks;
  197378. if (png_ptr == NULL)
  197379. return;
  197380. if (num_chunks == 0)
  197381. {
  197382. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197383. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197384. else
  197385. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197386. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197387. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197388. else
  197389. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197390. return;
  197391. }
  197392. if (chunk_list == NULL)
  197393. return;
  197394. old_num_chunks=png_ptr->num_chunk_list;
  197395. new_list=(png_bytep)png_malloc(png_ptr,
  197396. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197397. if(png_ptr->chunk_list != NULL)
  197398. {
  197399. png_memcpy(new_list, png_ptr->chunk_list,
  197400. (png_size_t)(5*old_num_chunks));
  197401. png_free(png_ptr, png_ptr->chunk_list);
  197402. png_ptr->chunk_list=NULL;
  197403. }
  197404. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197405. (png_size_t)(5*num_chunks));
  197406. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197407. *p=(png_byte)keep;
  197408. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197409. png_ptr->chunk_list=new_list;
  197410. #ifdef PNG_FREE_ME_SUPPORTED
  197411. png_ptr->free_me |= PNG_FREE_LIST;
  197412. #endif
  197413. }
  197414. #endif
  197415. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197416. void PNGAPI
  197417. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197418. png_user_chunk_ptr read_user_chunk_fn)
  197419. {
  197420. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197421. if (png_ptr == NULL)
  197422. return;
  197423. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197424. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197425. }
  197426. #endif
  197427. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197428. void PNGAPI
  197429. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197430. {
  197431. png_debug1(1, "in %s storage function\n", "rows");
  197432. if (png_ptr == NULL || info_ptr == NULL)
  197433. return;
  197434. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197435. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197436. info_ptr->row_pointers = row_pointers;
  197437. if(row_pointers)
  197438. info_ptr->valid |= PNG_INFO_IDAT;
  197439. }
  197440. #endif
  197441. #ifdef PNG_WRITE_SUPPORTED
  197442. void PNGAPI
  197443. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197444. {
  197445. if (png_ptr == NULL)
  197446. return;
  197447. if(png_ptr->zbuf)
  197448. png_free(png_ptr, png_ptr->zbuf);
  197449. png_ptr->zbuf_size = (png_size_t)size;
  197450. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197451. png_ptr->zstream.next_out = png_ptr->zbuf;
  197452. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197453. }
  197454. #endif
  197455. void PNGAPI
  197456. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197457. {
  197458. if (png_ptr && info_ptr)
  197459. info_ptr->valid &= ~(mask);
  197460. }
  197461. #ifndef PNG_1_0_X
  197462. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197463. /* function was added to libpng 1.2.0 and should always exist by default */
  197464. void PNGAPI
  197465. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197466. {
  197467. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197468. if (png_ptr != NULL)
  197469. png_ptr->asm_flags = 0;
  197470. }
  197471. /* this function was added to libpng 1.2.0 */
  197472. void PNGAPI
  197473. png_set_mmx_thresholds (png_structp png_ptr,
  197474. png_byte,
  197475. png_uint_32)
  197476. {
  197477. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197478. if (png_ptr == NULL)
  197479. return;
  197480. }
  197481. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197482. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197483. /* this function was added to libpng 1.2.6 */
  197484. void PNGAPI
  197485. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197486. png_uint_32 user_height_max)
  197487. {
  197488. /* Images with dimensions larger than these limits will be
  197489. * rejected by png_set_IHDR(). To accept any PNG datastream
  197490. * regardless of dimensions, set both limits to 0x7ffffffL.
  197491. */
  197492. if(png_ptr == NULL) return;
  197493. png_ptr->user_width_max = user_width_max;
  197494. png_ptr->user_height_max = user_height_max;
  197495. }
  197496. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197497. #endif /* ?PNG_1_0_X */
  197498. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197499. /*** End of inlined file: pngset.c ***/
  197500. /*** Start of inlined file: pngtrans.c ***/
  197501. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197502. *
  197503. * Last changed in libpng 1.2.17 May 15, 2007
  197504. * For conditions of distribution and use, see copyright notice in png.h
  197505. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197506. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197507. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197508. */
  197509. #define PNG_INTERNAL
  197510. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197511. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197512. /* turn on BGR-to-RGB mapping */
  197513. void PNGAPI
  197514. png_set_bgr(png_structp png_ptr)
  197515. {
  197516. png_debug(1, "in png_set_bgr\n");
  197517. if(png_ptr == NULL) return;
  197518. png_ptr->transformations |= PNG_BGR;
  197519. }
  197520. #endif
  197521. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197522. /* turn on 16 bit byte swapping */
  197523. void PNGAPI
  197524. png_set_swap(png_structp png_ptr)
  197525. {
  197526. png_debug(1, "in png_set_swap\n");
  197527. if(png_ptr == NULL) return;
  197528. if (png_ptr->bit_depth == 16)
  197529. png_ptr->transformations |= PNG_SWAP_BYTES;
  197530. }
  197531. #endif
  197532. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197533. /* turn on pixel packing */
  197534. void PNGAPI
  197535. png_set_packing(png_structp png_ptr)
  197536. {
  197537. png_debug(1, "in png_set_packing\n");
  197538. if(png_ptr == NULL) return;
  197539. if (png_ptr->bit_depth < 8)
  197540. {
  197541. png_ptr->transformations |= PNG_PACK;
  197542. png_ptr->usr_bit_depth = 8;
  197543. }
  197544. }
  197545. #endif
  197546. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197547. /* turn on packed pixel swapping */
  197548. void PNGAPI
  197549. png_set_packswap(png_structp png_ptr)
  197550. {
  197551. png_debug(1, "in png_set_packswap\n");
  197552. if(png_ptr == NULL) return;
  197553. if (png_ptr->bit_depth < 8)
  197554. png_ptr->transformations |= PNG_PACKSWAP;
  197555. }
  197556. #endif
  197557. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197558. void PNGAPI
  197559. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197560. {
  197561. png_debug(1, "in png_set_shift\n");
  197562. if(png_ptr == NULL) return;
  197563. png_ptr->transformations |= PNG_SHIFT;
  197564. png_ptr->shift = *true_bits;
  197565. }
  197566. #endif
  197567. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197568. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197569. int PNGAPI
  197570. png_set_interlace_handling(png_structp png_ptr)
  197571. {
  197572. png_debug(1, "in png_set_interlace handling\n");
  197573. if (png_ptr && png_ptr->interlaced)
  197574. {
  197575. png_ptr->transformations |= PNG_INTERLACE;
  197576. return (7);
  197577. }
  197578. return (1);
  197579. }
  197580. #endif
  197581. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197582. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197583. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197584. * for 48-bit input data, as well as to avoid problems with some compilers
  197585. * that don't like bytes as parameters.
  197586. */
  197587. void PNGAPI
  197588. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197589. {
  197590. png_debug(1, "in png_set_filler\n");
  197591. if(png_ptr == NULL) return;
  197592. png_ptr->transformations |= PNG_FILLER;
  197593. png_ptr->filler = (png_byte)filler;
  197594. if (filler_loc == PNG_FILLER_AFTER)
  197595. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197596. else
  197597. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197598. /* This should probably go in the "do_read_filler" routine.
  197599. * I attempted to do that in libpng-1.0.1a but that caused problems
  197600. * so I restored it in libpng-1.0.2a
  197601. */
  197602. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197603. {
  197604. png_ptr->usr_channels = 4;
  197605. }
  197606. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197607. * a less-than-8-bit grayscale to GA? */
  197608. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197609. {
  197610. png_ptr->usr_channels = 2;
  197611. }
  197612. }
  197613. #if !defined(PNG_1_0_X)
  197614. /* Added to libpng-1.2.7 */
  197615. void PNGAPI
  197616. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197617. {
  197618. png_debug(1, "in png_set_add_alpha\n");
  197619. if(png_ptr == NULL) return;
  197620. png_set_filler(png_ptr, filler, filler_loc);
  197621. png_ptr->transformations |= PNG_ADD_ALPHA;
  197622. }
  197623. #endif
  197624. #endif
  197625. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197626. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197627. void PNGAPI
  197628. png_set_swap_alpha(png_structp png_ptr)
  197629. {
  197630. png_debug(1, "in png_set_swap_alpha\n");
  197631. if(png_ptr == NULL) return;
  197632. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197633. }
  197634. #endif
  197635. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197636. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197637. void PNGAPI
  197638. png_set_invert_alpha(png_structp png_ptr)
  197639. {
  197640. png_debug(1, "in png_set_invert_alpha\n");
  197641. if(png_ptr == NULL) return;
  197642. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197643. }
  197644. #endif
  197645. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197646. void PNGAPI
  197647. png_set_invert_mono(png_structp png_ptr)
  197648. {
  197649. png_debug(1, "in png_set_invert_mono\n");
  197650. if(png_ptr == NULL) return;
  197651. png_ptr->transformations |= PNG_INVERT_MONO;
  197652. }
  197653. /* invert monochrome grayscale data */
  197654. void /* PRIVATE */
  197655. png_do_invert(png_row_infop row_info, png_bytep row)
  197656. {
  197657. png_debug(1, "in png_do_invert\n");
  197658. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197659. * if (row_info->bit_depth == 1 &&
  197660. */
  197661. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197662. if (row == NULL || row_info == NULL)
  197663. return;
  197664. #endif
  197665. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197666. {
  197667. png_bytep rp = row;
  197668. png_uint_32 i;
  197669. png_uint_32 istop = row_info->rowbytes;
  197670. for (i = 0; i < istop; i++)
  197671. {
  197672. *rp = (png_byte)(~(*rp));
  197673. rp++;
  197674. }
  197675. }
  197676. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197677. row_info->bit_depth == 8)
  197678. {
  197679. png_bytep rp = row;
  197680. png_uint_32 i;
  197681. png_uint_32 istop = row_info->rowbytes;
  197682. for (i = 0; i < istop; i+=2)
  197683. {
  197684. *rp = (png_byte)(~(*rp));
  197685. rp+=2;
  197686. }
  197687. }
  197688. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197689. row_info->bit_depth == 16)
  197690. {
  197691. png_bytep rp = row;
  197692. png_uint_32 i;
  197693. png_uint_32 istop = row_info->rowbytes;
  197694. for (i = 0; i < istop; i+=4)
  197695. {
  197696. *rp = (png_byte)(~(*rp));
  197697. *(rp+1) = (png_byte)(~(*(rp+1)));
  197698. rp+=4;
  197699. }
  197700. }
  197701. }
  197702. #endif
  197703. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197704. /* swaps byte order on 16 bit depth images */
  197705. void /* PRIVATE */
  197706. png_do_swap(png_row_infop row_info, png_bytep row)
  197707. {
  197708. png_debug(1, "in png_do_swap\n");
  197709. if (
  197710. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197711. row != NULL && row_info != NULL &&
  197712. #endif
  197713. row_info->bit_depth == 16)
  197714. {
  197715. png_bytep rp = row;
  197716. png_uint_32 i;
  197717. png_uint_32 istop= row_info->width * row_info->channels;
  197718. for (i = 0; i < istop; i++, rp += 2)
  197719. {
  197720. png_byte t = *rp;
  197721. *rp = *(rp + 1);
  197722. *(rp + 1) = t;
  197723. }
  197724. }
  197725. }
  197726. #endif
  197727. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197728. static PNG_CONST png_byte onebppswaptable[256] = {
  197729. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197730. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197731. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197732. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197733. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197734. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197735. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197736. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197737. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197738. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197739. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197740. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197741. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197742. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197743. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197744. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197745. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197746. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197747. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197748. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197749. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197750. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197751. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197752. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197753. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197754. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197755. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197756. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197757. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197758. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197759. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197760. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197761. };
  197762. static PNG_CONST png_byte twobppswaptable[256] = {
  197763. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197764. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197765. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197766. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197767. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197768. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197769. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197770. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197771. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197772. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197773. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197774. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197775. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197776. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197777. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197778. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197779. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197780. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197781. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197782. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197783. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197784. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197785. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197786. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197787. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197788. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197789. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197790. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197791. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197792. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197793. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197794. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197795. };
  197796. static PNG_CONST png_byte fourbppswaptable[256] = {
  197797. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197798. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197799. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197800. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197801. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197802. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197803. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197804. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197805. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197806. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197807. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197808. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197809. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197810. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197811. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197812. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197813. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197814. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197815. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197816. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197817. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197818. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197819. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197820. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197821. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197822. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197823. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197824. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197825. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197826. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197827. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197828. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197829. };
  197830. /* swaps pixel packing order within bytes */
  197831. void /* PRIVATE */
  197832. png_do_packswap(png_row_infop row_info, png_bytep row)
  197833. {
  197834. png_debug(1, "in png_do_packswap\n");
  197835. if (
  197836. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197837. row != NULL && row_info != NULL &&
  197838. #endif
  197839. row_info->bit_depth < 8)
  197840. {
  197841. png_bytep rp, end, table;
  197842. end = row + row_info->rowbytes;
  197843. if (row_info->bit_depth == 1)
  197844. table = (png_bytep)onebppswaptable;
  197845. else if (row_info->bit_depth == 2)
  197846. table = (png_bytep)twobppswaptable;
  197847. else if (row_info->bit_depth == 4)
  197848. table = (png_bytep)fourbppswaptable;
  197849. else
  197850. return;
  197851. for (rp = row; rp < end; rp++)
  197852. *rp = table[*rp];
  197853. }
  197854. }
  197855. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197856. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197857. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197858. /* remove filler or alpha byte(s) */
  197859. void /* PRIVATE */
  197860. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197861. {
  197862. png_debug(1, "in png_do_strip_filler\n");
  197863. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197864. if (row != NULL && row_info != NULL)
  197865. #endif
  197866. {
  197867. png_bytep sp=row;
  197868. png_bytep dp=row;
  197869. png_uint_32 row_width=row_info->width;
  197870. png_uint_32 i;
  197871. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197872. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197873. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197874. row_info->channels == 4)
  197875. {
  197876. if (row_info->bit_depth == 8)
  197877. {
  197878. /* This converts from RGBX or RGBA to RGB */
  197879. if (flags & PNG_FLAG_FILLER_AFTER)
  197880. {
  197881. dp+=3; sp+=4;
  197882. for (i = 1; i < row_width; i++)
  197883. {
  197884. *dp++ = *sp++;
  197885. *dp++ = *sp++;
  197886. *dp++ = *sp++;
  197887. sp++;
  197888. }
  197889. }
  197890. /* This converts from XRGB or ARGB to RGB */
  197891. else
  197892. {
  197893. for (i = 0; i < row_width; i++)
  197894. {
  197895. sp++;
  197896. *dp++ = *sp++;
  197897. *dp++ = *sp++;
  197898. *dp++ = *sp++;
  197899. }
  197900. }
  197901. row_info->pixel_depth = 24;
  197902. row_info->rowbytes = row_width * 3;
  197903. }
  197904. else /* if (row_info->bit_depth == 16) */
  197905. {
  197906. if (flags & PNG_FLAG_FILLER_AFTER)
  197907. {
  197908. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197909. sp += 8; dp += 6;
  197910. for (i = 1; i < row_width; i++)
  197911. {
  197912. /* This could be (although png_memcpy is probably slower):
  197913. png_memcpy(dp, sp, 6);
  197914. sp += 8;
  197915. dp += 6;
  197916. */
  197917. *dp++ = *sp++;
  197918. *dp++ = *sp++;
  197919. *dp++ = *sp++;
  197920. *dp++ = *sp++;
  197921. *dp++ = *sp++;
  197922. *dp++ = *sp++;
  197923. sp += 2;
  197924. }
  197925. }
  197926. else
  197927. {
  197928. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197929. for (i = 0; i < row_width; i++)
  197930. {
  197931. /* This could be (although png_memcpy is probably slower):
  197932. png_memcpy(dp, sp, 6);
  197933. sp += 8;
  197934. dp += 6;
  197935. */
  197936. sp+=2;
  197937. *dp++ = *sp++;
  197938. *dp++ = *sp++;
  197939. *dp++ = *sp++;
  197940. *dp++ = *sp++;
  197941. *dp++ = *sp++;
  197942. *dp++ = *sp++;
  197943. }
  197944. }
  197945. row_info->pixel_depth = 48;
  197946. row_info->rowbytes = row_width * 6;
  197947. }
  197948. row_info->channels = 3;
  197949. }
  197950. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197951. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197952. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197953. row_info->channels == 2)
  197954. {
  197955. if (row_info->bit_depth == 8)
  197956. {
  197957. /* This converts from GX or GA to G */
  197958. if (flags & PNG_FLAG_FILLER_AFTER)
  197959. {
  197960. for (i = 0; i < row_width; i++)
  197961. {
  197962. *dp++ = *sp++;
  197963. sp++;
  197964. }
  197965. }
  197966. /* This converts from XG or AG to G */
  197967. else
  197968. {
  197969. for (i = 0; i < row_width; i++)
  197970. {
  197971. sp++;
  197972. *dp++ = *sp++;
  197973. }
  197974. }
  197975. row_info->pixel_depth = 8;
  197976. row_info->rowbytes = row_width;
  197977. }
  197978. else /* if (row_info->bit_depth == 16) */
  197979. {
  197980. if (flags & PNG_FLAG_FILLER_AFTER)
  197981. {
  197982. /* This converts from GGXX or GGAA to GG */
  197983. sp += 4; dp += 2;
  197984. for (i = 1; i < row_width; i++)
  197985. {
  197986. *dp++ = *sp++;
  197987. *dp++ = *sp++;
  197988. sp += 2;
  197989. }
  197990. }
  197991. else
  197992. {
  197993. /* This converts from XXGG or AAGG to GG */
  197994. for (i = 0; i < row_width; i++)
  197995. {
  197996. sp += 2;
  197997. *dp++ = *sp++;
  197998. *dp++ = *sp++;
  197999. }
  198000. }
  198001. row_info->pixel_depth = 16;
  198002. row_info->rowbytes = row_width * 2;
  198003. }
  198004. row_info->channels = 1;
  198005. }
  198006. if (flags & PNG_FLAG_STRIP_ALPHA)
  198007. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198008. }
  198009. }
  198010. #endif
  198011. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198012. /* swaps red and blue bytes within a pixel */
  198013. void /* PRIVATE */
  198014. png_do_bgr(png_row_infop row_info, png_bytep row)
  198015. {
  198016. png_debug(1, "in png_do_bgr\n");
  198017. if (
  198018. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198019. row != NULL && row_info != NULL &&
  198020. #endif
  198021. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198022. {
  198023. png_uint_32 row_width = row_info->width;
  198024. if (row_info->bit_depth == 8)
  198025. {
  198026. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198027. {
  198028. png_bytep rp;
  198029. png_uint_32 i;
  198030. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198031. {
  198032. png_byte save = *rp;
  198033. *rp = *(rp + 2);
  198034. *(rp + 2) = save;
  198035. }
  198036. }
  198037. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198038. {
  198039. png_bytep rp;
  198040. png_uint_32 i;
  198041. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198042. {
  198043. png_byte save = *rp;
  198044. *rp = *(rp + 2);
  198045. *(rp + 2) = save;
  198046. }
  198047. }
  198048. }
  198049. else if (row_info->bit_depth == 16)
  198050. {
  198051. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198052. {
  198053. png_bytep rp;
  198054. png_uint_32 i;
  198055. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198056. {
  198057. png_byte save = *rp;
  198058. *rp = *(rp + 4);
  198059. *(rp + 4) = save;
  198060. save = *(rp + 1);
  198061. *(rp + 1) = *(rp + 5);
  198062. *(rp + 5) = save;
  198063. }
  198064. }
  198065. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198066. {
  198067. png_bytep rp;
  198068. png_uint_32 i;
  198069. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198070. {
  198071. png_byte save = *rp;
  198072. *rp = *(rp + 4);
  198073. *(rp + 4) = save;
  198074. save = *(rp + 1);
  198075. *(rp + 1) = *(rp + 5);
  198076. *(rp + 5) = save;
  198077. }
  198078. }
  198079. }
  198080. }
  198081. }
  198082. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198083. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198084. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198085. defined(PNG_LEGACY_SUPPORTED)
  198086. void PNGAPI
  198087. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198088. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198089. {
  198090. png_debug(1, "in png_set_user_transform_info\n");
  198091. if(png_ptr == NULL) return;
  198092. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198093. png_ptr->user_transform_ptr = user_transform_ptr;
  198094. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198095. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198096. #else
  198097. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198098. png_warning(png_ptr,
  198099. "This version of libpng does not support user transform info");
  198100. #endif
  198101. }
  198102. #endif
  198103. /* This function returns a pointer to the user_transform_ptr associated with
  198104. * the user transform functions. The application should free any memory
  198105. * associated with this pointer before png_write_destroy and png_read_destroy
  198106. * are called.
  198107. */
  198108. png_voidp PNGAPI
  198109. png_get_user_transform_ptr(png_structp png_ptr)
  198110. {
  198111. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198112. if (png_ptr == NULL) return (NULL);
  198113. return ((png_voidp)png_ptr->user_transform_ptr);
  198114. #else
  198115. return (NULL);
  198116. #endif
  198117. }
  198118. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198119. /*** End of inlined file: pngtrans.c ***/
  198120. /*** Start of inlined file: pngwio.c ***/
  198121. /* pngwio.c - functions for data output
  198122. *
  198123. * Last changed in libpng 1.2.13 November 13, 2006
  198124. * For conditions of distribution and use, see copyright notice in png.h
  198125. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198126. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198127. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198128. *
  198129. * This file provides a location for all output. Users who need
  198130. * special handling are expected to write functions that have the same
  198131. * arguments as these and perform similar functions, but that possibly
  198132. * use different output methods. Note that you shouldn't change these
  198133. * functions, but rather write replacement functions and then change
  198134. * them at run time with png_set_write_fn(...).
  198135. */
  198136. #define PNG_INTERNAL
  198137. #ifdef PNG_WRITE_SUPPORTED
  198138. /* Write the data to whatever output you are using. The default routine
  198139. writes to a file pointer. Note that this routine sometimes gets called
  198140. with very small lengths, so you should implement some kind of simple
  198141. buffering if you are using unbuffered writes. This should never be asked
  198142. to write more than 64K on a 16 bit machine. */
  198143. void /* PRIVATE */
  198144. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198145. {
  198146. if (png_ptr->write_data_fn != NULL )
  198147. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198148. else
  198149. png_error(png_ptr, "Call to NULL write function");
  198150. }
  198151. #if !defined(PNG_NO_STDIO)
  198152. /* This is the function that does the actual writing of data. If you are
  198153. not writing to a standard C stream, you should create a replacement
  198154. write_data function and use it at run time with png_set_write_fn(), rather
  198155. than changing the library. */
  198156. #ifndef USE_FAR_KEYWORD
  198157. void PNGAPI
  198158. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198159. {
  198160. png_uint_32 check;
  198161. if(png_ptr == NULL) return;
  198162. #if defined(_WIN32_WCE)
  198163. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198164. check = 0;
  198165. #else
  198166. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198167. #endif
  198168. if (check != length)
  198169. png_error(png_ptr, "Write Error");
  198170. }
  198171. #else
  198172. /* this is the model-independent version. Since the standard I/O library
  198173. can't handle far buffers in the medium and small models, we have to copy
  198174. the data.
  198175. */
  198176. #define NEAR_BUF_SIZE 1024
  198177. #define MIN(a,b) (a <= b ? a : b)
  198178. void PNGAPI
  198179. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198180. {
  198181. png_uint_32 check;
  198182. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198183. png_FILE_p io_ptr;
  198184. if(png_ptr == NULL) return;
  198185. /* Check if data really is near. If so, use usual code. */
  198186. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198187. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198188. if ((png_bytep)near_data == data)
  198189. {
  198190. #if defined(_WIN32_WCE)
  198191. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198192. check = 0;
  198193. #else
  198194. check = fwrite(near_data, 1, length, io_ptr);
  198195. #endif
  198196. }
  198197. else
  198198. {
  198199. png_byte buf[NEAR_BUF_SIZE];
  198200. png_size_t written, remaining, err;
  198201. check = 0;
  198202. remaining = length;
  198203. do
  198204. {
  198205. written = MIN(NEAR_BUF_SIZE, remaining);
  198206. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198207. #if defined(_WIN32_WCE)
  198208. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198209. err = 0;
  198210. #else
  198211. err = fwrite(buf, 1, written, io_ptr);
  198212. #endif
  198213. if (err != written)
  198214. break;
  198215. else
  198216. check += err;
  198217. data += written;
  198218. remaining -= written;
  198219. }
  198220. while (remaining != 0);
  198221. }
  198222. if (check != length)
  198223. png_error(png_ptr, "Write Error");
  198224. }
  198225. #endif
  198226. #endif
  198227. /* This function is called to output any data pending writing (normally
  198228. to disk). After png_flush is called, there should be no data pending
  198229. writing in any buffers. */
  198230. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198231. void /* PRIVATE */
  198232. png_flush(png_structp png_ptr)
  198233. {
  198234. if (png_ptr->output_flush_fn != NULL)
  198235. (*(png_ptr->output_flush_fn))(png_ptr);
  198236. }
  198237. #if !defined(PNG_NO_STDIO)
  198238. void PNGAPI
  198239. png_default_flush(png_structp png_ptr)
  198240. {
  198241. #if !defined(_WIN32_WCE)
  198242. png_FILE_p io_ptr;
  198243. #endif
  198244. if(png_ptr == NULL) return;
  198245. #if !defined(_WIN32_WCE)
  198246. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198247. if (io_ptr != NULL)
  198248. fflush(io_ptr);
  198249. #endif
  198250. }
  198251. #endif
  198252. #endif
  198253. /* This function allows the application to supply new output functions for
  198254. libpng if standard C streams aren't being used.
  198255. This function takes as its arguments:
  198256. png_ptr - pointer to a png output data structure
  198257. io_ptr - pointer to user supplied structure containing info about
  198258. the output functions. May be NULL.
  198259. write_data_fn - pointer to a new output function that takes as its
  198260. arguments a pointer to a png_struct, a pointer to
  198261. data to be written, and a 32-bit unsigned int that is
  198262. the number of bytes to be written. The new write
  198263. function should call png_error(png_ptr, "Error msg")
  198264. to exit and output any fatal error messages.
  198265. flush_data_fn - pointer to a new flush function that takes as its
  198266. arguments a pointer to a png_struct. After a call to
  198267. the flush function, there should be no data in any buffers
  198268. or pending transmission. If the output method doesn't do
  198269. any buffering of ouput, a function prototype must still be
  198270. supplied although it doesn't have to do anything. If
  198271. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198272. time, output_flush_fn will be ignored, although it must be
  198273. supplied for compatibility. */
  198274. void PNGAPI
  198275. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198276. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198277. {
  198278. if(png_ptr == NULL) return;
  198279. png_ptr->io_ptr = io_ptr;
  198280. #if !defined(PNG_NO_STDIO)
  198281. if (write_data_fn != NULL)
  198282. png_ptr->write_data_fn = write_data_fn;
  198283. else
  198284. png_ptr->write_data_fn = png_default_write_data;
  198285. #else
  198286. png_ptr->write_data_fn = write_data_fn;
  198287. #endif
  198288. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198289. #if !defined(PNG_NO_STDIO)
  198290. if (output_flush_fn != NULL)
  198291. png_ptr->output_flush_fn = output_flush_fn;
  198292. else
  198293. png_ptr->output_flush_fn = png_default_flush;
  198294. #else
  198295. png_ptr->output_flush_fn = output_flush_fn;
  198296. #endif
  198297. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198298. /* It is an error to read while writing a png file */
  198299. if (png_ptr->read_data_fn != NULL)
  198300. {
  198301. png_ptr->read_data_fn = NULL;
  198302. png_warning(png_ptr,
  198303. "Attempted to set both read_data_fn and write_data_fn in");
  198304. png_warning(png_ptr,
  198305. "the same structure. Resetting read_data_fn to NULL.");
  198306. }
  198307. }
  198308. #if defined(USE_FAR_KEYWORD)
  198309. #if defined(_MSC_VER)
  198310. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198311. {
  198312. void *near_ptr;
  198313. void FAR *far_ptr;
  198314. FP_OFF(near_ptr) = FP_OFF(ptr);
  198315. far_ptr = (void FAR *)near_ptr;
  198316. if(check != 0)
  198317. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198318. png_error(png_ptr,"segment lost in conversion");
  198319. return(near_ptr);
  198320. }
  198321. # else
  198322. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198323. {
  198324. void *near_ptr;
  198325. void FAR *far_ptr;
  198326. near_ptr = (void FAR *)ptr;
  198327. far_ptr = (void FAR *)near_ptr;
  198328. if(check != 0)
  198329. if(far_ptr != ptr)
  198330. png_error(png_ptr,"segment lost in conversion");
  198331. return(near_ptr);
  198332. }
  198333. # endif
  198334. # endif
  198335. #endif /* PNG_WRITE_SUPPORTED */
  198336. /*** End of inlined file: pngwio.c ***/
  198337. /*** Start of inlined file: pngwrite.c ***/
  198338. /* pngwrite.c - general routines to write a PNG file
  198339. *
  198340. * Last changed in libpng 1.2.15 January 5, 2007
  198341. * For conditions of distribution and use, see copyright notice in png.h
  198342. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198343. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198344. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198345. */
  198346. /* get internal access to png.h */
  198347. #define PNG_INTERNAL
  198348. #ifdef PNG_WRITE_SUPPORTED
  198349. /* Writes all the PNG information. This is the suggested way to use the
  198350. * library. If you have a new chunk to add, make a function to write it,
  198351. * and put it in the correct location here. If you want the chunk written
  198352. * after the image data, put it in png_write_end(). I strongly encourage
  198353. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198354. * the chunk, as that will keep the code from breaking if you want to just
  198355. * write a plain PNG file. If you have long comments, I suggest writing
  198356. * them in png_write_end(), and compressing them.
  198357. */
  198358. void PNGAPI
  198359. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198360. {
  198361. png_debug(1, "in png_write_info_before_PLTE\n");
  198362. if (png_ptr == NULL || info_ptr == NULL)
  198363. return;
  198364. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198365. {
  198366. png_write_sig(png_ptr); /* write PNG signature */
  198367. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198368. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198369. {
  198370. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198371. png_ptr->mng_features_permitted=0;
  198372. }
  198373. #endif
  198374. /* write IHDR information. */
  198375. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198376. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198377. info_ptr->filter_type,
  198378. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198379. info_ptr->interlace_type);
  198380. #else
  198381. 0);
  198382. #endif
  198383. /* the rest of these check to see if the valid field has the appropriate
  198384. flag set, and if it does, writes the chunk. */
  198385. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198386. if (info_ptr->valid & PNG_INFO_gAMA)
  198387. {
  198388. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198389. png_write_gAMA(png_ptr, info_ptr->gamma);
  198390. #else
  198391. #ifdef PNG_FIXED_POINT_SUPPORTED
  198392. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198393. # endif
  198394. #endif
  198395. }
  198396. #endif
  198397. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198398. if (info_ptr->valid & PNG_INFO_sRGB)
  198399. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198400. #endif
  198401. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198402. if (info_ptr->valid & PNG_INFO_iCCP)
  198403. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198404. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198405. #endif
  198406. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198407. if (info_ptr->valid & PNG_INFO_sBIT)
  198408. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198409. #endif
  198410. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198411. if (info_ptr->valid & PNG_INFO_cHRM)
  198412. {
  198413. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198414. png_write_cHRM(png_ptr,
  198415. info_ptr->x_white, info_ptr->y_white,
  198416. info_ptr->x_red, info_ptr->y_red,
  198417. info_ptr->x_green, info_ptr->y_green,
  198418. info_ptr->x_blue, info_ptr->y_blue);
  198419. #else
  198420. # ifdef PNG_FIXED_POINT_SUPPORTED
  198421. png_write_cHRM_fixed(png_ptr,
  198422. info_ptr->int_x_white, info_ptr->int_y_white,
  198423. info_ptr->int_x_red, info_ptr->int_y_red,
  198424. info_ptr->int_x_green, info_ptr->int_y_green,
  198425. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198426. # endif
  198427. #endif
  198428. }
  198429. #endif
  198430. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198431. if (info_ptr->unknown_chunks_num)
  198432. {
  198433. png_unknown_chunk *up;
  198434. png_debug(5, "writing extra chunks\n");
  198435. for (up = info_ptr->unknown_chunks;
  198436. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198437. up++)
  198438. {
  198439. int keep=png_handle_as_unknown(png_ptr, up->name);
  198440. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198441. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198442. !(up->location & PNG_HAVE_IDAT) &&
  198443. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198444. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198445. {
  198446. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198447. }
  198448. }
  198449. }
  198450. #endif
  198451. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198452. }
  198453. }
  198454. void PNGAPI
  198455. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198456. {
  198457. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198458. int i;
  198459. #endif
  198460. png_debug(1, "in png_write_info\n");
  198461. if (png_ptr == NULL || info_ptr == NULL)
  198462. return;
  198463. png_write_info_before_PLTE(png_ptr, info_ptr);
  198464. if (info_ptr->valid & PNG_INFO_PLTE)
  198465. png_write_PLTE(png_ptr, info_ptr->palette,
  198466. (png_uint_32)info_ptr->num_palette);
  198467. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198468. png_error(png_ptr, "Valid palette required for paletted images");
  198469. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198470. if (info_ptr->valid & PNG_INFO_tRNS)
  198471. {
  198472. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198473. /* invert the alpha channel (in tRNS) */
  198474. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198475. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198476. {
  198477. int j;
  198478. for (j=0; j<(int)info_ptr->num_trans; j++)
  198479. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198480. }
  198481. #endif
  198482. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198483. info_ptr->num_trans, info_ptr->color_type);
  198484. }
  198485. #endif
  198486. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198487. if (info_ptr->valid & PNG_INFO_bKGD)
  198488. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198489. #endif
  198490. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198491. if (info_ptr->valid & PNG_INFO_hIST)
  198492. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198493. #endif
  198494. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198495. if (info_ptr->valid & PNG_INFO_oFFs)
  198496. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198497. info_ptr->offset_unit_type);
  198498. #endif
  198499. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198500. if (info_ptr->valid & PNG_INFO_pCAL)
  198501. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198502. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198503. info_ptr->pcal_units, info_ptr->pcal_params);
  198504. #endif
  198505. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198506. if (info_ptr->valid & PNG_INFO_sCAL)
  198507. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198508. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198509. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198510. #else
  198511. #ifdef PNG_FIXED_POINT_SUPPORTED
  198512. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198513. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198514. #else
  198515. png_warning(png_ptr,
  198516. "png_write_sCAL not supported; sCAL chunk not written.");
  198517. #endif
  198518. #endif
  198519. #endif
  198520. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198521. if (info_ptr->valid & PNG_INFO_pHYs)
  198522. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198523. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198524. #endif
  198525. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198526. if (info_ptr->valid & PNG_INFO_tIME)
  198527. {
  198528. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198529. png_ptr->mode |= PNG_WROTE_tIME;
  198530. }
  198531. #endif
  198532. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198533. if (info_ptr->valid & PNG_INFO_sPLT)
  198534. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198535. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198536. #endif
  198537. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198538. /* Check to see if we need to write text chunks */
  198539. for (i = 0; i < info_ptr->num_text; i++)
  198540. {
  198541. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198542. info_ptr->text[i].compression);
  198543. /* an internationalized chunk? */
  198544. if (info_ptr->text[i].compression > 0)
  198545. {
  198546. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198547. /* write international chunk */
  198548. png_write_iTXt(png_ptr,
  198549. info_ptr->text[i].compression,
  198550. info_ptr->text[i].key,
  198551. info_ptr->text[i].lang,
  198552. info_ptr->text[i].lang_key,
  198553. info_ptr->text[i].text);
  198554. #else
  198555. png_warning(png_ptr, "Unable to write international text");
  198556. #endif
  198557. /* Mark this chunk as written */
  198558. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198559. }
  198560. /* If we want a compressed text chunk */
  198561. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198562. {
  198563. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198564. /* write compressed chunk */
  198565. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198566. info_ptr->text[i].text, 0,
  198567. info_ptr->text[i].compression);
  198568. #else
  198569. png_warning(png_ptr, "Unable to write compressed text");
  198570. #endif
  198571. /* Mark this chunk as written */
  198572. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198573. }
  198574. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198575. {
  198576. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198577. /* write uncompressed chunk */
  198578. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198579. info_ptr->text[i].text,
  198580. 0);
  198581. #else
  198582. png_warning(png_ptr, "Unable to write uncompressed text");
  198583. #endif
  198584. /* Mark this chunk as written */
  198585. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198586. }
  198587. }
  198588. #endif
  198589. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198590. if (info_ptr->unknown_chunks_num)
  198591. {
  198592. png_unknown_chunk *up;
  198593. png_debug(5, "writing extra chunks\n");
  198594. for (up = info_ptr->unknown_chunks;
  198595. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198596. up++)
  198597. {
  198598. int keep=png_handle_as_unknown(png_ptr, up->name);
  198599. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198600. up->location && (up->location & PNG_HAVE_PLTE) &&
  198601. !(up->location & PNG_HAVE_IDAT) &&
  198602. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198603. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198604. {
  198605. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198606. }
  198607. }
  198608. }
  198609. #endif
  198610. }
  198611. /* Writes the end of the PNG file. If you don't want to write comments or
  198612. * time information, you can pass NULL for info. If you already wrote these
  198613. * in png_write_info(), do not write them again here. If you have long
  198614. * comments, I suggest writing them here, and compressing them.
  198615. */
  198616. void PNGAPI
  198617. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198618. {
  198619. png_debug(1, "in png_write_end\n");
  198620. if (png_ptr == NULL)
  198621. return;
  198622. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198623. png_error(png_ptr, "No IDATs written into file");
  198624. /* see if user wants us to write information chunks */
  198625. if (info_ptr != NULL)
  198626. {
  198627. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198628. int i; /* local index variable */
  198629. #endif
  198630. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198631. /* check to see if user has supplied a time chunk */
  198632. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198633. !(png_ptr->mode & PNG_WROTE_tIME))
  198634. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198635. #endif
  198636. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198637. /* loop through comment chunks */
  198638. for (i = 0; i < info_ptr->num_text; i++)
  198639. {
  198640. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198641. info_ptr->text[i].compression);
  198642. /* an internationalized chunk? */
  198643. if (info_ptr->text[i].compression > 0)
  198644. {
  198645. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198646. /* write international chunk */
  198647. png_write_iTXt(png_ptr,
  198648. info_ptr->text[i].compression,
  198649. info_ptr->text[i].key,
  198650. info_ptr->text[i].lang,
  198651. info_ptr->text[i].lang_key,
  198652. info_ptr->text[i].text);
  198653. #else
  198654. png_warning(png_ptr, "Unable to write international text");
  198655. #endif
  198656. /* Mark this chunk as written */
  198657. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198658. }
  198659. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198660. {
  198661. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198662. /* write compressed chunk */
  198663. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198664. info_ptr->text[i].text, 0,
  198665. info_ptr->text[i].compression);
  198666. #else
  198667. png_warning(png_ptr, "Unable to write compressed text");
  198668. #endif
  198669. /* Mark this chunk as written */
  198670. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198671. }
  198672. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198673. {
  198674. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198675. /* write uncompressed chunk */
  198676. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198677. info_ptr->text[i].text, 0);
  198678. #else
  198679. png_warning(png_ptr, "Unable to write uncompressed text");
  198680. #endif
  198681. /* Mark this chunk as written */
  198682. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198683. }
  198684. }
  198685. #endif
  198686. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198687. if (info_ptr->unknown_chunks_num)
  198688. {
  198689. png_unknown_chunk *up;
  198690. png_debug(5, "writing extra chunks\n");
  198691. for (up = info_ptr->unknown_chunks;
  198692. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198693. up++)
  198694. {
  198695. int keep=png_handle_as_unknown(png_ptr, up->name);
  198696. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198697. up->location && (up->location & PNG_AFTER_IDAT) &&
  198698. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198699. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198700. {
  198701. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198702. }
  198703. }
  198704. }
  198705. #endif
  198706. }
  198707. png_ptr->mode |= PNG_AFTER_IDAT;
  198708. /* write end of PNG file */
  198709. png_write_IEND(png_ptr);
  198710. }
  198711. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198712. #if !defined(_WIN32_WCE)
  198713. /* "time.h" functions are not supported on WindowsCE */
  198714. void PNGAPI
  198715. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198716. {
  198717. png_debug(1, "in png_convert_from_struct_tm\n");
  198718. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198719. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198720. ptime->day = (png_byte)ttime->tm_mday;
  198721. ptime->hour = (png_byte)ttime->tm_hour;
  198722. ptime->minute = (png_byte)ttime->tm_min;
  198723. ptime->second = (png_byte)ttime->tm_sec;
  198724. }
  198725. void PNGAPI
  198726. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198727. {
  198728. struct tm *tbuf;
  198729. png_debug(1, "in png_convert_from_time_t\n");
  198730. tbuf = gmtime(&ttime);
  198731. png_convert_from_struct_tm(ptime, tbuf);
  198732. }
  198733. #endif
  198734. #endif
  198735. /* Initialize png_ptr structure, and allocate any memory needed */
  198736. png_structp PNGAPI
  198737. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198738. png_error_ptr error_fn, png_error_ptr warn_fn)
  198739. {
  198740. #ifdef PNG_USER_MEM_SUPPORTED
  198741. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198742. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198743. }
  198744. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198745. png_structp PNGAPI
  198746. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198747. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198748. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198749. {
  198750. #endif /* PNG_USER_MEM_SUPPORTED */
  198751. png_structp png_ptr;
  198752. #ifdef PNG_SETJMP_SUPPORTED
  198753. #ifdef USE_FAR_KEYWORD
  198754. jmp_buf jmpbuf;
  198755. #endif
  198756. #endif
  198757. int i;
  198758. png_debug(1, "in png_create_write_struct\n");
  198759. #ifdef PNG_USER_MEM_SUPPORTED
  198760. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198761. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198762. #else
  198763. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198764. #endif /* PNG_USER_MEM_SUPPORTED */
  198765. if (png_ptr == NULL)
  198766. return (NULL);
  198767. /* added at libpng-1.2.6 */
  198768. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198769. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198770. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198771. #endif
  198772. #ifdef PNG_SETJMP_SUPPORTED
  198773. #ifdef USE_FAR_KEYWORD
  198774. if (setjmp(jmpbuf))
  198775. #else
  198776. if (setjmp(png_ptr->jmpbuf))
  198777. #endif
  198778. {
  198779. png_free(png_ptr, png_ptr->zbuf);
  198780. png_ptr->zbuf=NULL;
  198781. png_destroy_struct(png_ptr);
  198782. return (NULL);
  198783. }
  198784. #ifdef USE_FAR_KEYWORD
  198785. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198786. #endif
  198787. #endif
  198788. #ifdef PNG_USER_MEM_SUPPORTED
  198789. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198790. #endif /* PNG_USER_MEM_SUPPORTED */
  198791. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198792. i=0;
  198793. do
  198794. {
  198795. if(user_png_ver[i] != png_libpng_ver[i])
  198796. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198797. } while (png_libpng_ver[i++]);
  198798. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198799. {
  198800. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198801. * we must recompile any applications that use any older library version.
  198802. * For versions after libpng 1.0, we will be compatible, so we need
  198803. * only check the first digit.
  198804. */
  198805. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198806. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198807. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198808. {
  198809. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198810. char msg[80];
  198811. if (user_png_ver)
  198812. {
  198813. png_snprintf(msg, 80,
  198814. "Application was compiled with png.h from libpng-%.20s",
  198815. user_png_ver);
  198816. png_warning(png_ptr, msg);
  198817. }
  198818. png_snprintf(msg, 80,
  198819. "Application is running with png.c from libpng-%.20s",
  198820. png_libpng_ver);
  198821. png_warning(png_ptr, msg);
  198822. #endif
  198823. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198824. png_ptr->flags=0;
  198825. #endif
  198826. png_error(png_ptr,
  198827. "Incompatible libpng version in application and library");
  198828. }
  198829. }
  198830. /* initialize zbuf - compression buffer */
  198831. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198832. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198833. (png_uint_32)png_ptr->zbuf_size);
  198834. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198835. png_flush_ptr_NULL);
  198836. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198837. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198838. 1, png_doublep_NULL, png_doublep_NULL);
  198839. #endif
  198840. #ifdef PNG_SETJMP_SUPPORTED
  198841. /* Applications that neglect to set up their own setjmp() and then encounter
  198842. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198843. abort instead of returning. */
  198844. #ifdef USE_FAR_KEYWORD
  198845. if (setjmp(jmpbuf))
  198846. PNG_ABORT();
  198847. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198848. #else
  198849. if (setjmp(png_ptr->jmpbuf))
  198850. PNG_ABORT();
  198851. #endif
  198852. #endif
  198853. return (png_ptr);
  198854. }
  198855. /* Initialize png_ptr structure, and allocate any memory needed */
  198856. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198857. /* Deprecated. */
  198858. #undef png_write_init
  198859. void PNGAPI
  198860. png_write_init(png_structp png_ptr)
  198861. {
  198862. /* We only come here via pre-1.0.7-compiled applications */
  198863. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198864. }
  198865. void PNGAPI
  198866. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198867. png_size_t png_struct_size, png_size_t png_info_size)
  198868. {
  198869. /* We only come here via pre-1.0.12-compiled applications */
  198870. if(png_ptr == NULL) return;
  198871. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198872. if(png_sizeof(png_struct) > png_struct_size ||
  198873. png_sizeof(png_info) > png_info_size)
  198874. {
  198875. char msg[80];
  198876. png_ptr->warning_fn=NULL;
  198877. if (user_png_ver)
  198878. {
  198879. png_snprintf(msg, 80,
  198880. "Application was compiled with png.h from libpng-%.20s",
  198881. user_png_ver);
  198882. png_warning(png_ptr, msg);
  198883. }
  198884. png_snprintf(msg, 80,
  198885. "Application is running with png.c from libpng-%.20s",
  198886. png_libpng_ver);
  198887. png_warning(png_ptr, msg);
  198888. }
  198889. #endif
  198890. if(png_sizeof(png_struct) > png_struct_size)
  198891. {
  198892. png_ptr->error_fn=NULL;
  198893. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198894. png_ptr->flags=0;
  198895. #endif
  198896. png_error(png_ptr,
  198897. "The png struct allocated by the application for writing is too small.");
  198898. }
  198899. if(png_sizeof(png_info) > png_info_size)
  198900. {
  198901. png_ptr->error_fn=NULL;
  198902. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198903. png_ptr->flags=0;
  198904. #endif
  198905. png_error(png_ptr,
  198906. "The info struct allocated by the application for writing is too small.");
  198907. }
  198908. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198909. }
  198910. #endif /* PNG_1_0_X || PNG_1_2_X */
  198911. void PNGAPI
  198912. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198913. png_size_t png_struct_size)
  198914. {
  198915. png_structp png_ptr=*ptr_ptr;
  198916. #ifdef PNG_SETJMP_SUPPORTED
  198917. jmp_buf tmp_jmp; /* to save current jump buffer */
  198918. #endif
  198919. int i = 0;
  198920. if (png_ptr == NULL)
  198921. return;
  198922. do
  198923. {
  198924. if (user_png_ver[i] != png_libpng_ver[i])
  198925. {
  198926. #ifdef PNG_LEGACY_SUPPORTED
  198927. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198928. #else
  198929. png_ptr->warning_fn=NULL;
  198930. png_warning(png_ptr,
  198931. "Application uses deprecated png_write_init() and should be recompiled.");
  198932. break;
  198933. #endif
  198934. }
  198935. } while (png_libpng_ver[i++]);
  198936. png_debug(1, "in png_write_init_3\n");
  198937. #ifdef PNG_SETJMP_SUPPORTED
  198938. /* save jump buffer and error functions */
  198939. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198940. #endif
  198941. if (png_sizeof(png_struct) > png_struct_size)
  198942. {
  198943. png_destroy_struct(png_ptr);
  198944. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198945. *ptr_ptr = png_ptr;
  198946. }
  198947. /* reset all variables to 0 */
  198948. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198949. /* added at libpng-1.2.6 */
  198950. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198951. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198952. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198953. #endif
  198954. #ifdef PNG_SETJMP_SUPPORTED
  198955. /* restore jump buffer */
  198956. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198957. #endif
  198958. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198959. png_flush_ptr_NULL);
  198960. /* initialize zbuf - compression buffer */
  198961. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198962. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198963. (png_uint_32)png_ptr->zbuf_size);
  198964. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198965. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198966. 1, png_doublep_NULL, png_doublep_NULL);
  198967. #endif
  198968. }
  198969. /* Write a few rows of image data. If the image is interlaced,
  198970. * either you will have to write the 7 sub images, or, if you
  198971. * have called png_set_interlace_handling(), you will have to
  198972. * "write" the image seven times.
  198973. */
  198974. void PNGAPI
  198975. png_write_rows(png_structp png_ptr, png_bytepp row,
  198976. png_uint_32 num_rows)
  198977. {
  198978. png_uint_32 i; /* row counter */
  198979. png_bytepp rp; /* row pointer */
  198980. png_debug(1, "in png_write_rows\n");
  198981. if (png_ptr == NULL)
  198982. return;
  198983. /* loop through the rows */
  198984. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198985. {
  198986. png_write_row(png_ptr, *rp);
  198987. }
  198988. }
  198989. /* Write the image. You only need to call this function once, even
  198990. * if you are writing an interlaced image.
  198991. */
  198992. void PNGAPI
  198993. png_write_image(png_structp png_ptr, png_bytepp image)
  198994. {
  198995. png_uint_32 i; /* row index */
  198996. int pass, num_pass; /* pass variables */
  198997. png_bytepp rp; /* points to current row */
  198998. if (png_ptr == NULL)
  198999. return;
  199000. png_debug(1, "in png_write_image\n");
  199001. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199002. /* intialize interlace handling. If image is not interlaced,
  199003. this will set pass to 1 */
  199004. num_pass = png_set_interlace_handling(png_ptr);
  199005. #else
  199006. num_pass = 1;
  199007. #endif
  199008. /* loop through passes */
  199009. for (pass = 0; pass < num_pass; pass++)
  199010. {
  199011. /* loop through image */
  199012. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199013. {
  199014. png_write_row(png_ptr, *rp);
  199015. }
  199016. }
  199017. }
  199018. /* called by user to write a row of image data */
  199019. void PNGAPI
  199020. png_write_row(png_structp png_ptr, png_bytep row)
  199021. {
  199022. if (png_ptr == NULL)
  199023. return;
  199024. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199025. png_ptr->row_number, png_ptr->pass);
  199026. /* initialize transformations and other stuff if first time */
  199027. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199028. {
  199029. /* make sure we wrote the header info */
  199030. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199031. png_error(png_ptr,
  199032. "png_write_info was never called before png_write_row.");
  199033. /* check for transforms that have been set but were defined out */
  199034. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199035. if (png_ptr->transformations & PNG_INVERT_MONO)
  199036. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199037. #endif
  199038. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199039. if (png_ptr->transformations & PNG_FILLER)
  199040. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199041. #endif
  199042. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199043. if (png_ptr->transformations & PNG_PACKSWAP)
  199044. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199045. #endif
  199046. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199047. if (png_ptr->transformations & PNG_PACK)
  199048. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199049. #endif
  199050. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199051. if (png_ptr->transformations & PNG_SHIFT)
  199052. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199053. #endif
  199054. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199055. if (png_ptr->transformations & PNG_BGR)
  199056. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199057. #endif
  199058. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199059. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199060. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199061. #endif
  199062. png_write_start_row(png_ptr);
  199063. }
  199064. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199065. /* if interlaced and not interested in row, return */
  199066. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199067. {
  199068. switch (png_ptr->pass)
  199069. {
  199070. case 0:
  199071. if (png_ptr->row_number & 0x07)
  199072. {
  199073. png_write_finish_row(png_ptr);
  199074. return;
  199075. }
  199076. break;
  199077. case 1:
  199078. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199079. {
  199080. png_write_finish_row(png_ptr);
  199081. return;
  199082. }
  199083. break;
  199084. case 2:
  199085. if ((png_ptr->row_number & 0x07) != 4)
  199086. {
  199087. png_write_finish_row(png_ptr);
  199088. return;
  199089. }
  199090. break;
  199091. case 3:
  199092. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199093. {
  199094. png_write_finish_row(png_ptr);
  199095. return;
  199096. }
  199097. break;
  199098. case 4:
  199099. if ((png_ptr->row_number & 0x03) != 2)
  199100. {
  199101. png_write_finish_row(png_ptr);
  199102. return;
  199103. }
  199104. break;
  199105. case 5:
  199106. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199107. {
  199108. png_write_finish_row(png_ptr);
  199109. return;
  199110. }
  199111. break;
  199112. case 6:
  199113. if (!(png_ptr->row_number & 0x01))
  199114. {
  199115. png_write_finish_row(png_ptr);
  199116. return;
  199117. }
  199118. break;
  199119. }
  199120. }
  199121. #endif
  199122. /* set up row info for transformations */
  199123. png_ptr->row_info.color_type = png_ptr->color_type;
  199124. png_ptr->row_info.width = png_ptr->usr_width;
  199125. png_ptr->row_info.channels = png_ptr->usr_channels;
  199126. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199127. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199128. png_ptr->row_info.channels);
  199129. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199130. png_ptr->row_info.width);
  199131. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199132. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199133. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199134. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199135. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199136. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199137. /* Copy user's row into buffer, leaving room for filter byte. */
  199138. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199139. png_ptr->row_info.rowbytes);
  199140. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199141. /* handle interlacing */
  199142. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199143. (png_ptr->transformations & PNG_INTERLACE))
  199144. {
  199145. png_do_write_interlace(&(png_ptr->row_info),
  199146. png_ptr->row_buf + 1, png_ptr->pass);
  199147. /* this should always get caught above, but still ... */
  199148. if (!(png_ptr->row_info.width))
  199149. {
  199150. png_write_finish_row(png_ptr);
  199151. return;
  199152. }
  199153. }
  199154. #endif
  199155. /* handle other transformations */
  199156. if (png_ptr->transformations)
  199157. png_do_write_transformations(png_ptr);
  199158. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199159. /* Write filter_method 64 (intrapixel differencing) only if
  199160. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199161. * 2. Libpng did not write a PNG signature (this filter_method is only
  199162. * used in PNG datastreams that are embedded in MNG datastreams) and
  199163. * 3. The application called png_permit_mng_features with a mask that
  199164. * included PNG_FLAG_MNG_FILTER_64 and
  199165. * 4. The filter_method is 64 and
  199166. * 5. The color_type is RGB or RGBA
  199167. */
  199168. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199169. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199170. {
  199171. /* Intrapixel differencing */
  199172. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199173. }
  199174. #endif
  199175. /* Find a filter if necessary, filter the row and write it out. */
  199176. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199177. if (png_ptr->write_row_fn != NULL)
  199178. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199179. }
  199180. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199181. /* Set the automatic flush interval or 0 to turn flushing off */
  199182. void PNGAPI
  199183. png_set_flush(png_structp png_ptr, int nrows)
  199184. {
  199185. png_debug(1, "in png_set_flush\n");
  199186. if (png_ptr == NULL)
  199187. return;
  199188. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199189. }
  199190. /* flush the current output buffers now */
  199191. void PNGAPI
  199192. png_write_flush(png_structp png_ptr)
  199193. {
  199194. int wrote_IDAT;
  199195. png_debug(1, "in png_write_flush\n");
  199196. if (png_ptr == NULL)
  199197. return;
  199198. /* We have already written out all of the data */
  199199. if (png_ptr->row_number >= png_ptr->num_rows)
  199200. return;
  199201. do
  199202. {
  199203. int ret;
  199204. /* compress the data */
  199205. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199206. wrote_IDAT = 0;
  199207. /* check for compression errors */
  199208. if (ret != Z_OK)
  199209. {
  199210. if (png_ptr->zstream.msg != NULL)
  199211. png_error(png_ptr, png_ptr->zstream.msg);
  199212. else
  199213. png_error(png_ptr, "zlib error");
  199214. }
  199215. if (!(png_ptr->zstream.avail_out))
  199216. {
  199217. /* write the IDAT and reset the zlib output buffer */
  199218. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199219. png_ptr->zbuf_size);
  199220. png_ptr->zstream.next_out = png_ptr->zbuf;
  199221. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199222. wrote_IDAT = 1;
  199223. }
  199224. } while(wrote_IDAT == 1);
  199225. /* If there is any data left to be output, write it into a new IDAT */
  199226. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199227. {
  199228. /* write the IDAT and reset the zlib output buffer */
  199229. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199230. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199231. png_ptr->zstream.next_out = png_ptr->zbuf;
  199232. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199233. }
  199234. png_ptr->flush_rows = 0;
  199235. png_flush(png_ptr);
  199236. }
  199237. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199238. /* free all memory used by the write */
  199239. void PNGAPI
  199240. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199241. {
  199242. png_structp png_ptr = NULL;
  199243. png_infop info_ptr = NULL;
  199244. #ifdef PNG_USER_MEM_SUPPORTED
  199245. png_free_ptr free_fn = NULL;
  199246. png_voidp mem_ptr = NULL;
  199247. #endif
  199248. png_debug(1, "in png_destroy_write_struct\n");
  199249. if (png_ptr_ptr != NULL)
  199250. {
  199251. png_ptr = *png_ptr_ptr;
  199252. #ifdef PNG_USER_MEM_SUPPORTED
  199253. free_fn = png_ptr->free_fn;
  199254. mem_ptr = png_ptr->mem_ptr;
  199255. #endif
  199256. }
  199257. if (info_ptr_ptr != NULL)
  199258. info_ptr = *info_ptr_ptr;
  199259. if (info_ptr != NULL)
  199260. {
  199261. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199262. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199263. if (png_ptr->num_chunk_list)
  199264. {
  199265. png_free(png_ptr, png_ptr->chunk_list);
  199266. png_ptr->chunk_list=NULL;
  199267. png_ptr->num_chunk_list=0;
  199268. }
  199269. #endif
  199270. #ifdef PNG_USER_MEM_SUPPORTED
  199271. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199272. (png_voidp)mem_ptr);
  199273. #else
  199274. png_destroy_struct((png_voidp)info_ptr);
  199275. #endif
  199276. *info_ptr_ptr = NULL;
  199277. }
  199278. if (png_ptr != NULL)
  199279. {
  199280. png_write_destroy(png_ptr);
  199281. #ifdef PNG_USER_MEM_SUPPORTED
  199282. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199283. (png_voidp)mem_ptr);
  199284. #else
  199285. png_destroy_struct((png_voidp)png_ptr);
  199286. #endif
  199287. *png_ptr_ptr = NULL;
  199288. }
  199289. }
  199290. /* Free any memory used in png_ptr struct (old method) */
  199291. void /* PRIVATE */
  199292. png_write_destroy(png_structp png_ptr)
  199293. {
  199294. #ifdef PNG_SETJMP_SUPPORTED
  199295. jmp_buf tmp_jmp; /* save jump buffer */
  199296. #endif
  199297. png_error_ptr error_fn;
  199298. png_error_ptr warning_fn;
  199299. png_voidp error_ptr;
  199300. #ifdef PNG_USER_MEM_SUPPORTED
  199301. png_free_ptr free_fn;
  199302. #endif
  199303. png_debug(1, "in png_write_destroy\n");
  199304. /* free any memory zlib uses */
  199305. deflateEnd(&png_ptr->zstream);
  199306. /* free our memory. png_free checks NULL for us. */
  199307. png_free(png_ptr, png_ptr->zbuf);
  199308. png_free(png_ptr, png_ptr->row_buf);
  199309. png_free(png_ptr, png_ptr->prev_row);
  199310. png_free(png_ptr, png_ptr->sub_row);
  199311. png_free(png_ptr, png_ptr->up_row);
  199312. png_free(png_ptr, png_ptr->avg_row);
  199313. png_free(png_ptr, png_ptr->paeth_row);
  199314. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199315. png_free(png_ptr, png_ptr->time_buffer);
  199316. #endif
  199317. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199318. png_free(png_ptr, png_ptr->prev_filters);
  199319. png_free(png_ptr, png_ptr->filter_weights);
  199320. png_free(png_ptr, png_ptr->inv_filter_weights);
  199321. png_free(png_ptr, png_ptr->filter_costs);
  199322. png_free(png_ptr, png_ptr->inv_filter_costs);
  199323. #endif
  199324. #ifdef PNG_SETJMP_SUPPORTED
  199325. /* reset structure */
  199326. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199327. #endif
  199328. error_fn = png_ptr->error_fn;
  199329. warning_fn = png_ptr->warning_fn;
  199330. error_ptr = png_ptr->error_ptr;
  199331. #ifdef PNG_USER_MEM_SUPPORTED
  199332. free_fn = png_ptr->free_fn;
  199333. #endif
  199334. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199335. png_ptr->error_fn = error_fn;
  199336. png_ptr->warning_fn = warning_fn;
  199337. png_ptr->error_ptr = error_ptr;
  199338. #ifdef PNG_USER_MEM_SUPPORTED
  199339. png_ptr->free_fn = free_fn;
  199340. #endif
  199341. #ifdef PNG_SETJMP_SUPPORTED
  199342. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199343. #endif
  199344. }
  199345. /* Allow the application to select one or more row filters to use. */
  199346. void PNGAPI
  199347. png_set_filter(png_structp png_ptr, int method, int filters)
  199348. {
  199349. png_debug(1, "in png_set_filter\n");
  199350. if (png_ptr == NULL)
  199351. return;
  199352. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199353. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199354. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199355. method = PNG_FILTER_TYPE_BASE;
  199356. #endif
  199357. if (method == PNG_FILTER_TYPE_BASE)
  199358. {
  199359. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199360. {
  199361. #ifndef PNG_NO_WRITE_FILTER
  199362. case 5:
  199363. case 6:
  199364. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199365. #endif /* PNG_NO_WRITE_FILTER */
  199366. case PNG_FILTER_VALUE_NONE:
  199367. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199368. #ifndef PNG_NO_WRITE_FILTER
  199369. case PNG_FILTER_VALUE_SUB:
  199370. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199371. case PNG_FILTER_VALUE_UP:
  199372. png_ptr->do_filter=PNG_FILTER_UP; break;
  199373. case PNG_FILTER_VALUE_AVG:
  199374. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199375. case PNG_FILTER_VALUE_PAETH:
  199376. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199377. default: png_ptr->do_filter = (png_byte)filters; break;
  199378. #else
  199379. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199380. #endif /* PNG_NO_WRITE_FILTER */
  199381. }
  199382. /* If we have allocated the row_buf, this means we have already started
  199383. * with the image and we should have allocated all of the filter buffers
  199384. * that have been selected. If prev_row isn't already allocated, then
  199385. * it is too late to start using the filters that need it, since we
  199386. * will be missing the data in the previous row. If an application
  199387. * wants to start and stop using particular filters during compression,
  199388. * it should start out with all of the filters, and then add and
  199389. * remove them after the start of compression.
  199390. */
  199391. if (png_ptr->row_buf != NULL)
  199392. {
  199393. #ifndef PNG_NO_WRITE_FILTER
  199394. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199395. {
  199396. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199397. (png_ptr->rowbytes + 1));
  199398. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199399. }
  199400. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199401. {
  199402. if (png_ptr->prev_row == NULL)
  199403. {
  199404. png_warning(png_ptr, "Can't add Up filter after starting");
  199405. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199406. }
  199407. else
  199408. {
  199409. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199410. (png_ptr->rowbytes + 1));
  199411. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199412. }
  199413. }
  199414. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199415. {
  199416. if (png_ptr->prev_row == NULL)
  199417. {
  199418. png_warning(png_ptr, "Can't add Average filter after starting");
  199419. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199420. }
  199421. else
  199422. {
  199423. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199424. (png_ptr->rowbytes + 1));
  199425. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199426. }
  199427. }
  199428. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199429. png_ptr->paeth_row == NULL)
  199430. {
  199431. if (png_ptr->prev_row == NULL)
  199432. {
  199433. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199434. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199435. }
  199436. else
  199437. {
  199438. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199439. (png_ptr->rowbytes + 1));
  199440. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199441. }
  199442. }
  199443. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199444. #endif /* PNG_NO_WRITE_FILTER */
  199445. png_ptr->do_filter = PNG_FILTER_NONE;
  199446. }
  199447. }
  199448. else
  199449. png_error(png_ptr, "Unknown custom filter method");
  199450. }
  199451. /* This allows us to influence the way in which libpng chooses the "best"
  199452. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199453. * differences metric is relatively fast and effective, there is some
  199454. * question as to whether it can be improved upon by trying to keep the
  199455. * filtered data going to zlib more consistent, hopefully resulting in
  199456. * better compression.
  199457. */
  199458. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199459. void PNGAPI
  199460. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199461. int num_weights, png_doublep filter_weights,
  199462. png_doublep filter_costs)
  199463. {
  199464. int i;
  199465. png_debug(1, "in png_set_filter_heuristics\n");
  199466. if (png_ptr == NULL)
  199467. return;
  199468. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199469. {
  199470. png_warning(png_ptr, "Unknown filter heuristic method");
  199471. return;
  199472. }
  199473. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199474. {
  199475. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199476. }
  199477. if (num_weights < 0 || filter_weights == NULL ||
  199478. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199479. {
  199480. num_weights = 0;
  199481. }
  199482. png_ptr->num_prev_filters = (png_byte)num_weights;
  199483. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199484. if (num_weights > 0)
  199485. {
  199486. if (png_ptr->prev_filters == NULL)
  199487. {
  199488. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199489. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199490. /* To make sure that the weighting starts out fairly */
  199491. for (i = 0; i < num_weights; i++)
  199492. {
  199493. png_ptr->prev_filters[i] = 255;
  199494. }
  199495. }
  199496. if (png_ptr->filter_weights == NULL)
  199497. {
  199498. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199499. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199500. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199501. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199502. for (i = 0; i < num_weights; i++)
  199503. {
  199504. png_ptr->inv_filter_weights[i] =
  199505. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199506. }
  199507. }
  199508. for (i = 0; i < num_weights; i++)
  199509. {
  199510. if (filter_weights[i] < 0.0)
  199511. {
  199512. png_ptr->inv_filter_weights[i] =
  199513. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199514. }
  199515. else
  199516. {
  199517. png_ptr->inv_filter_weights[i] =
  199518. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199519. png_ptr->filter_weights[i] =
  199520. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199521. }
  199522. }
  199523. }
  199524. /* If, in the future, there are other filter methods, this would
  199525. * need to be based on png_ptr->filter.
  199526. */
  199527. if (png_ptr->filter_costs == NULL)
  199528. {
  199529. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199530. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199531. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199532. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199533. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199534. {
  199535. png_ptr->inv_filter_costs[i] =
  199536. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199537. }
  199538. }
  199539. /* Here is where we set the relative costs of the different filters. We
  199540. * should take the desired compression level into account when setting
  199541. * the costs, so that Paeth, for instance, has a high relative cost at low
  199542. * compression levels, while it has a lower relative cost at higher
  199543. * compression settings. The filter types are in order of increasing
  199544. * relative cost, so it would be possible to do this with an algorithm.
  199545. */
  199546. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199547. {
  199548. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199549. {
  199550. png_ptr->inv_filter_costs[i] =
  199551. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199552. }
  199553. else if (filter_costs[i] >= 1.0)
  199554. {
  199555. png_ptr->inv_filter_costs[i] =
  199556. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199557. png_ptr->filter_costs[i] =
  199558. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199559. }
  199560. }
  199561. }
  199562. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199563. void PNGAPI
  199564. png_set_compression_level(png_structp png_ptr, int level)
  199565. {
  199566. png_debug(1, "in png_set_compression_level\n");
  199567. if (png_ptr == NULL)
  199568. return;
  199569. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199570. png_ptr->zlib_level = level;
  199571. }
  199572. void PNGAPI
  199573. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199574. {
  199575. png_debug(1, "in png_set_compression_mem_level\n");
  199576. if (png_ptr == NULL)
  199577. return;
  199578. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199579. png_ptr->zlib_mem_level = mem_level;
  199580. }
  199581. void PNGAPI
  199582. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199583. {
  199584. png_debug(1, "in png_set_compression_strategy\n");
  199585. if (png_ptr == NULL)
  199586. return;
  199587. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199588. png_ptr->zlib_strategy = strategy;
  199589. }
  199590. void PNGAPI
  199591. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199592. {
  199593. if (png_ptr == NULL)
  199594. return;
  199595. if (window_bits > 15)
  199596. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199597. else if (window_bits < 8)
  199598. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199599. #ifndef WBITS_8_OK
  199600. /* avoid libpng bug with 256-byte windows */
  199601. if (window_bits == 8)
  199602. {
  199603. png_warning(png_ptr, "Compression window is being reset to 512");
  199604. window_bits=9;
  199605. }
  199606. #endif
  199607. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199608. png_ptr->zlib_window_bits = window_bits;
  199609. }
  199610. void PNGAPI
  199611. png_set_compression_method(png_structp png_ptr, int method)
  199612. {
  199613. png_debug(1, "in png_set_compression_method\n");
  199614. if (png_ptr == NULL)
  199615. return;
  199616. if (method != 8)
  199617. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199618. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199619. png_ptr->zlib_method = method;
  199620. }
  199621. void PNGAPI
  199622. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199623. {
  199624. if (png_ptr == NULL)
  199625. return;
  199626. png_ptr->write_row_fn = write_row_fn;
  199627. }
  199628. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199629. void PNGAPI
  199630. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199631. write_user_transform_fn)
  199632. {
  199633. png_debug(1, "in png_set_write_user_transform_fn\n");
  199634. if (png_ptr == NULL)
  199635. return;
  199636. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199637. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199638. }
  199639. #endif
  199640. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199641. void PNGAPI
  199642. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199643. int transforms, voidp params)
  199644. {
  199645. if (png_ptr == NULL || info_ptr == NULL)
  199646. return;
  199647. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199648. /* invert the alpha channel from opacity to transparency */
  199649. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199650. png_set_invert_alpha(png_ptr);
  199651. #endif
  199652. /* Write the file header information. */
  199653. png_write_info(png_ptr, info_ptr);
  199654. /* ------ these transformations don't touch the info structure ------- */
  199655. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199656. /* invert monochrome pixels */
  199657. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199658. png_set_invert_mono(png_ptr);
  199659. #endif
  199660. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199661. /* Shift the pixels up to a legal bit depth and fill in
  199662. * as appropriate to correctly scale the image.
  199663. */
  199664. if ((transforms & PNG_TRANSFORM_SHIFT)
  199665. && (info_ptr->valid & PNG_INFO_sBIT))
  199666. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199667. #endif
  199668. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199669. /* pack pixels into bytes */
  199670. if (transforms & PNG_TRANSFORM_PACKING)
  199671. png_set_packing(png_ptr);
  199672. #endif
  199673. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199674. /* swap location of alpha bytes from ARGB to RGBA */
  199675. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199676. png_set_swap_alpha(png_ptr);
  199677. #endif
  199678. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199679. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199680. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199681. */
  199682. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199683. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199684. #endif
  199685. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199686. /* flip BGR pixels to RGB */
  199687. if (transforms & PNG_TRANSFORM_BGR)
  199688. png_set_bgr(png_ptr);
  199689. #endif
  199690. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199691. /* swap bytes of 16-bit files to most significant byte first */
  199692. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199693. png_set_swap(png_ptr);
  199694. #endif
  199695. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199696. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199697. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199698. png_set_packswap(png_ptr);
  199699. #endif
  199700. /* ----------------------- end of transformations ------------------- */
  199701. /* write the bits */
  199702. if (info_ptr->valid & PNG_INFO_IDAT)
  199703. png_write_image(png_ptr, info_ptr->row_pointers);
  199704. /* It is REQUIRED to call this to finish writing the rest of the file */
  199705. png_write_end(png_ptr, info_ptr);
  199706. transforms = transforms; /* quiet compiler warnings */
  199707. params = params;
  199708. }
  199709. #endif
  199710. #endif /* PNG_WRITE_SUPPORTED */
  199711. /*** End of inlined file: pngwrite.c ***/
  199712. /*** Start of inlined file: pngwtran.c ***/
  199713. /* pngwtran.c - transforms the data in a row for PNG writers
  199714. *
  199715. * Last changed in libpng 1.2.9 April 14, 2006
  199716. * For conditions of distribution and use, see copyright notice in png.h
  199717. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199718. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199719. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199720. */
  199721. #define PNG_INTERNAL
  199722. #ifdef PNG_WRITE_SUPPORTED
  199723. /* Transform the data according to the user's wishes. The order of
  199724. * transformations is significant.
  199725. */
  199726. void /* PRIVATE */
  199727. png_do_write_transformations(png_structp png_ptr)
  199728. {
  199729. png_debug(1, "in png_do_write_transformations\n");
  199730. if (png_ptr == NULL)
  199731. return;
  199732. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199733. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199734. if(png_ptr->write_user_transform_fn != NULL)
  199735. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199736. (png_ptr, /* png_ptr */
  199737. &(png_ptr->row_info), /* row_info: */
  199738. /* png_uint_32 width; width of row */
  199739. /* png_uint_32 rowbytes; number of bytes in row */
  199740. /* png_byte color_type; color type of pixels */
  199741. /* png_byte bit_depth; bit depth of samples */
  199742. /* png_byte channels; number of channels (1-4) */
  199743. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199744. png_ptr->row_buf + 1); /* start of pixel data for row */
  199745. #endif
  199746. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199747. if (png_ptr->transformations & PNG_FILLER)
  199748. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199749. png_ptr->flags);
  199750. #endif
  199751. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199752. if (png_ptr->transformations & PNG_PACKSWAP)
  199753. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199754. #endif
  199755. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199756. if (png_ptr->transformations & PNG_PACK)
  199757. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199758. (png_uint_32)png_ptr->bit_depth);
  199759. #endif
  199760. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199761. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199762. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199763. #endif
  199764. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199765. if (png_ptr->transformations & PNG_SHIFT)
  199766. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199767. &(png_ptr->shift));
  199768. #endif
  199769. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199770. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199771. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199772. #endif
  199773. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199774. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199775. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199776. #endif
  199777. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199778. if (png_ptr->transformations & PNG_BGR)
  199779. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199780. #endif
  199781. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199782. if (png_ptr->transformations & PNG_INVERT_MONO)
  199783. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199784. #endif
  199785. }
  199786. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199787. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199788. * row_info bit depth should be 8 (one pixel per byte). The channels
  199789. * should be 1 (this only happens on grayscale and paletted images).
  199790. */
  199791. void /* PRIVATE */
  199792. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199793. {
  199794. png_debug(1, "in png_do_pack\n");
  199795. if (row_info->bit_depth == 8 &&
  199796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199797. row != NULL && row_info != NULL &&
  199798. #endif
  199799. row_info->channels == 1)
  199800. {
  199801. switch ((int)bit_depth)
  199802. {
  199803. case 1:
  199804. {
  199805. png_bytep sp, dp;
  199806. int mask, v;
  199807. png_uint_32 i;
  199808. png_uint_32 row_width = row_info->width;
  199809. sp = row;
  199810. dp = row;
  199811. mask = 0x80;
  199812. v = 0;
  199813. for (i = 0; i < row_width; i++)
  199814. {
  199815. if (*sp != 0)
  199816. v |= mask;
  199817. sp++;
  199818. if (mask > 1)
  199819. mask >>= 1;
  199820. else
  199821. {
  199822. mask = 0x80;
  199823. *dp = (png_byte)v;
  199824. dp++;
  199825. v = 0;
  199826. }
  199827. }
  199828. if (mask != 0x80)
  199829. *dp = (png_byte)v;
  199830. break;
  199831. }
  199832. case 2:
  199833. {
  199834. png_bytep sp, dp;
  199835. int shift, v;
  199836. png_uint_32 i;
  199837. png_uint_32 row_width = row_info->width;
  199838. sp = row;
  199839. dp = row;
  199840. shift = 6;
  199841. v = 0;
  199842. for (i = 0; i < row_width; i++)
  199843. {
  199844. png_byte value;
  199845. value = (png_byte)(*sp & 0x03);
  199846. v |= (value << shift);
  199847. if (shift == 0)
  199848. {
  199849. shift = 6;
  199850. *dp = (png_byte)v;
  199851. dp++;
  199852. v = 0;
  199853. }
  199854. else
  199855. shift -= 2;
  199856. sp++;
  199857. }
  199858. if (shift != 6)
  199859. *dp = (png_byte)v;
  199860. break;
  199861. }
  199862. case 4:
  199863. {
  199864. png_bytep sp, dp;
  199865. int shift, v;
  199866. png_uint_32 i;
  199867. png_uint_32 row_width = row_info->width;
  199868. sp = row;
  199869. dp = row;
  199870. shift = 4;
  199871. v = 0;
  199872. for (i = 0; i < row_width; i++)
  199873. {
  199874. png_byte value;
  199875. value = (png_byte)(*sp & 0x0f);
  199876. v |= (value << shift);
  199877. if (shift == 0)
  199878. {
  199879. shift = 4;
  199880. *dp = (png_byte)v;
  199881. dp++;
  199882. v = 0;
  199883. }
  199884. else
  199885. shift -= 4;
  199886. sp++;
  199887. }
  199888. if (shift != 4)
  199889. *dp = (png_byte)v;
  199890. break;
  199891. }
  199892. }
  199893. row_info->bit_depth = (png_byte)bit_depth;
  199894. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199895. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199896. row_info->width);
  199897. }
  199898. }
  199899. #endif
  199900. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199901. /* Shift pixel values to take advantage of whole range. Pass the
  199902. * true number of bits in bit_depth. The row should be packed
  199903. * according to row_info->bit_depth. Thus, if you had a row of
  199904. * bit depth 4, but the pixels only had values from 0 to 7, you
  199905. * would pass 3 as bit_depth, and this routine would translate the
  199906. * data to 0 to 15.
  199907. */
  199908. void /* PRIVATE */
  199909. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199910. {
  199911. png_debug(1, "in png_do_shift\n");
  199912. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199913. if (row != NULL && row_info != NULL &&
  199914. #else
  199915. if (
  199916. #endif
  199917. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199918. {
  199919. int shift_start[4], shift_dec[4];
  199920. int channels = 0;
  199921. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199922. {
  199923. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199924. shift_dec[channels] = bit_depth->red;
  199925. channels++;
  199926. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199927. shift_dec[channels] = bit_depth->green;
  199928. channels++;
  199929. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199930. shift_dec[channels] = bit_depth->blue;
  199931. channels++;
  199932. }
  199933. else
  199934. {
  199935. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199936. shift_dec[channels] = bit_depth->gray;
  199937. channels++;
  199938. }
  199939. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199940. {
  199941. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199942. shift_dec[channels] = bit_depth->alpha;
  199943. channels++;
  199944. }
  199945. /* with low row depths, could only be grayscale, so one channel */
  199946. if (row_info->bit_depth < 8)
  199947. {
  199948. png_bytep bp = row;
  199949. png_uint_32 i;
  199950. png_byte mask;
  199951. png_uint_32 row_bytes = row_info->rowbytes;
  199952. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199953. mask = 0x55;
  199954. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199955. mask = 0x11;
  199956. else
  199957. mask = 0xff;
  199958. for (i = 0; i < row_bytes; i++, bp++)
  199959. {
  199960. png_uint_16 v;
  199961. int j;
  199962. v = *bp;
  199963. *bp = 0;
  199964. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199965. {
  199966. if (j > 0)
  199967. *bp |= (png_byte)((v << j) & 0xff);
  199968. else
  199969. *bp |= (png_byte)((v >> (-j)) & mask);
  199970. }
  199971. }
  199972. }
  199973. else if (row_info->bit_depth == 8)
  199974. {
  199975. png_bytep bp = row;
  199976. png_uint_32 i;
  199977. png_uint_32 istop = channels * row_info->width;
  199978. for (i = 0; i < istop; i++, bp++)
  199979. {
  199980. png_uint_16 v;
  199981. int j;
  199982. int c = (int)(i%channels);
  199983. v = *bp;
  199984. *bp = 0;
  199985. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199986. {
  199987. if (j > 0)
  199988. *bp |= (png_byte)((v << j) & 0xff);
  199989. else
  199990. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199991. }
  199992. }
  199993. }
  199994. else
  199995. {
  199996. png_bytep bp;
  199997. png_uint_32 i;
  199998. png_uint_32 istop = channels * row_info->width;
  199999. for (bp = row, i = 0; i < istop; i++)
  200000. {
  200001. int c = (int)(i%channels);
  200002. png_uint_16 value, v;
  200003. int j;
  200004. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200005. value = 0;
  200006. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200007. {
  200008. if (j > 0)
  200009. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200010. else
  200011. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200012. }
  200013. *bp++ = (png_byte)(value >> 8);
  200014. *bp++ = (png_byte)(value & 0xff);
  200015. }
  200016. }
  200017. }
  200018. }
  200019. #endif
  200020. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200021. void /* PRIVATE */
  200022. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200023. {
  200024. png_debug(1, "in png_do_write_swap_alpha\n");
  200025. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200026. if (row != NULL && row_info != NULL)
  200027. #endif
  200028. {
  200029. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200030. {
  200031. /* This converts from ARGB to RGBA */
  200032. if (row_info->bit_depth == 8)
  200033. {
  200034. png_bytep sp, dp;
  200035. png_uint_32 i;
  200036. png_uint_32 row_width = row_info->width;
  200037. for (i = 0, sp = dp = row; i < row_width; i++)
  200038. {
  200039. png_byte save = *(sp++);
  200040. *(dp++) = *(sp++);
  200041. *(dp++) = *(sp++);
  200042. *(dp++) = *(sp++);
  200043. *(dp++) = save;
  200044. }
  200045. }
  200046. /* This converts from AARRGGBB to RRGGBBAA */
  200047. else
  200048. {
  200049. png_bytep sp, dp;
  200050. png_uint_32 i;
  200051. png_uint_32 row_width = row_info->width;
  200052. for (i = 0, sp = dp = row; i < row_width; i++)
  200053. {
  200054. png_byte save[2];
  200055. save[0] = *(sp++);
  200056. save[1] = *(sp++);
  200057. *(dp++) = *(sp++);
  200058. *(dp++) = *(sp++);
  200059. *(dp++) = *(sp++);
  200060. *(dp++) = *(sp++);
  200061. *(dp++) = *(sp++);
  200062. *(dp++) = *(sp++);
  200063. *(dp++) = save[0];
  200064. *(dp++) = save[1];
  200065. }
  200066. }
  200067. }
  200068. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200069. {
  200070. /* This converts from AG to GA */
  200071. if (row_info->bit_depth == 8)
  200072. {
  200073. png_bytep sp, dp;
  200074. png_uint_32 i;
  200075. png_uint_32 row_width = row_info->width;
  200076. for (i = 0, sp = dp = row; i < row_width; i++)
  200077. {
  200078. png_byte save = *(sp++);
  200079. *(dp++) = *(sp++);
  200080. *(dp++) = save;
  200081. }
  200082. }
  200083. /* This converts from AAGG to GGAA */
  200084. else
  200085. {
  200086. png_bytep sp, dp;
  200087. png_uint_32 i;
  200088. png_uint_32 row_width = row_info->width;
  200089. for (i = 0, sp = dp = row; i < row_width; i++)
  200090. {
  200091. png_byte save[2];
  200092. save[0] = *(sp++);
  200093. save[1] = *(sp++);
  200094. *(dp++) = *(sp++);
  200095. *(dp++) = *(sp++);
  200096. *(dp++) = save[0];
  200097. *(dp++) = save[1];
  200098. }
  200099. }
  200100. }
  200101. }
  200102. }
  200103. #endif
  200104. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200105. void /* PRIVATE */
  200106. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200107. {
  200108. png_debug(1, "in png_do_write_invert_alpha\n");
  200109. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200110. if (row != NULL && row_info != NULL)
  200111. #endif
  200112. {
  200113. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200114. {
  200115. /* This inverts the alpha channel in RGBA */
  200116. if (row_info->bit_depth == 8)
  200117. {
  200118. png_bytep sp, dp;
  200119. png_uint_32 i;
  200120. png_uint_32 row_width = row_info->width;
  200121. for (i = 0, sp = dp = row; i < row_width; i++)
  200122. {
  200123. /* does nothing
  200124. *(dp++) = *(sp++);
  200125. *(dp++) = *(sp++);
  200126. *(dp++) = *(sp++);
  200127. */
  200128. sp+=3; dp = sp;
  200129. *(dp++) = (png_byte)(255 - *(sp++));
  200130. }
  200131. }
  200132. /* This inverts the alpha channel in RRGGBBAA */
  200133. else
  200134. {
  200135. png_bytep sp, dp;
  200136. png_uint_32 i;
  200137. png_uint_32 row_width = row_info->width;
  200138. for (i = 0, sp = dp = row; i < row_width; i++)
  200139. {
  200140. /* does nothing
  200141. *(dp++) = *(sp++);
  200142. *(dp++) = *(sp++);
  200143. *(dp++) = *(sp++);
  200144. *(dp++) = *(sp++);
  200145. *(dp++) = *(sp++);
  200146. *(dp++) = *(sp++);
  200147. */
  200148. sp+=6; dp = sp;
  200149. *(dp++) = (png_byte)(255 - *(sp++));
  200150. *(dp++) = (png_byte)(255 - *(sp++));
  200151. }
  200152. }
  200153. }
  200154. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200155. {
  200156. /* This inverts the alpha channel in GA */
  200157. if (row_info->bit_depth == 8)
  200158. {
  200159. png_bytep sp, dp;
  200160. png_uint_32 i;
  200161. png_uint_32 row_width = row_info->width;
  200162. for (i = 0, sp = dp = row; i < row_width; i++)
  200163. {
  200164. *(dp++) = *(sp++);
  200165. *(dp++) = (png_byte)(255 - *(sp++));
  200166. }
  200167. }
  200168. /* This inverts the alpha channel in GGAA */
  200169. else
  200170. {
  200171. png_bytep sp, dp;
  200172. png_uint_32 i;
  200173. png_uint_32 row_width = row_info->width;
  200174. for (i = 0, sp = dp = row; i < row_width; i++)
  200175. {
  200176. /* does nothing
  200177. *(dp++) = *(sp++);
  200178. *(dp++) = *(sp++);
  200179. */
  200180. sp+=2; dp = sp;
  200181. *(dp++) = (png_byte)(255 - *(sp++));
  200182. *(dp++) = (png_byte)(255 - *(sp++));
  200183. }
  200184. }
  200185. }
  200186. }
  200187. }
  200188. #endif
  200189. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200190. /* undoes intrapixel differencing */
  200191. void /* PRIVATE */
  200192. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200193. {
  200194. png_debug(1, "in png_do_write_intrapixel\n");
  200195. if (
  200196. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200197. row != NULL && row_info != NULL &&
  200198. #endif
  200199. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200200. {
  200201. int bytes_per_pixel;
  200202. png_uint_32 row_width = row_info->width;
  200203. if (row_info->bit_depth == 8)
  200204. {
  200205. png_bytep rp;
  200206. png_uint_32 i;
  200207. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200208. bytes_per_pixel = 3;
  200209. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200210. bytes_per_pixel = 4;
  200211. else
  200212. return;
  200213. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200214. {
  200215. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200216. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200217. }
  200218. }
  200219. else if (row_info->bit_depth == 16)
  200220. {
  200221. png_bytep rp;
  200222. png_uint_32 i;
  200223. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200224. bytes_per_pixel = 6;
  200225. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200226. bytes_per_pixel = 8;
  200227. else
  200228. return;
  200229. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200230. {
  200231. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200232. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200233. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200234. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200235. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200236. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200237. *(rp+1) = (png_byte)(red & 0xff);
  200238. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200239. *(rp+5) = (png_byte)(blue & 0xff);
  200240. }
  200241. }
  200242. }
  200243. }
  200244. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200245. #endif /* PNG_WRITE_SUPPORTED */
  200246. /*** End of inlined file: pngwtran.c ***/
  200247. /*** Start of inlined file: pngwutil.c ***/
  200248. /* pngwutil.c - utilities to write a PNG file
  200249. *
  200250. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200251. * For conditions of distribution and use, see copyright notice in png.h
  200252. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200253. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200254. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200255. */
  200256. #define PNG_INTERNAL
  200257. #ifdef PNG_WRITE_SUPPORTED
  200258. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200259. * with unsigned numbers for convenience, although one supported
  200260. * ancillary chunk uses signed (two's complement) numbers.
  200261. */
  200262. void PNGAPI
  200263. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200264. {
  200265. buf[0] = (png_byte)((i >> 24) & 0xff);
  200266. buf[1] = (png_byte)((i >> 16) & 0xff);
  200267. buf[2] = (png_byte)((i >> 8) & 0xff);
  200268. buf[3] = (png_byte)(i & 0xff);
  200269. }
  200270. /* The png_save_int_32 function assumes integers are stored in two's
  200271. * complement format. If this isn't the case, then this routine needs to
  200272. * be modified to write data in two's complement format.
  200273. */
  200274. void PNGAPI
  200275. png_save_int_32(png_bytep buf, png_int_32 i)
  200276. {
  200277. buf[0] = (png_byte)((i >> 24) & 0xff);
  200278. buf[1] = (png_byte)((i >> 16) & 0xff);
  200279. buf[2] = (png_byte)((i >> 8) & 0xff);
  200280. buf[3] = (png_byte)(i & 0xff);
  200281. }
  200282. /* Place a 16-bit number into a buffer in PNG byte order.
  200283. * The parameter is declared unsigned int, not png_uint_16,
  200284. * just to avoid potential problems on pre-ANSI C compilers.
  200285. */
  200286. void PNGAPI
  200287. png_save_uint_16(png_bytep buf, unsigned int i)
  200288. {
  200289. buf[0] = (png_byte)((i >> 8) & 0xff);
  200290. buf[1] = (png_byte)(i & 0xff);
  200291. }
  200292. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200293. * representing the chunk name. The array must be at least 4 bytes in
  200294. * length, and does not need to be null terminated. To be safe, pass the
  200295. * pre-defined chunk names here, and if you need a new one, define it
  200296. * where the others are defined. The length is the length of the data.
  200297. * All the data must be present. If that is not possible, use the
  200298. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200299. * functions instead.
  200300. */
  200301. void PNGAPI
  200302. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200303. png_bytep data, png_size_t length)
  200304. {
  200305. if(png_ptr == NULL) return;
  200306. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200307. png_write_chunk_data(png_ptr, data, length);
  200308. png_write_chunk_end(png_ptr);
  200309. }
  200310. /* Write the start of a PNG chunk. The type is the chunk type.
  200311. * The total_length is the sum of the lengths of all the data you will be
  200312. * passing in png_write_chunk_data().
  200313. */
  200314. void PNGAPI
  200315. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200316. png_uint_32 length)
  200317. {
  200318. png_byte buf[4];
  200319. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200320. if(png_ptr == NULL) return;
  200321. /* write the length */
  200322. png_save_uint_32(buf, length);
  200323. png_write_data(png_ptr, buf, (png_size_t)4);
  200324. /* write the chunk name */
  200325. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200326. /* reset the crc and run it over the chunk name */
  200327. png_reset_crc(png_ptr);
  200328. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200329. }
  200330. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200331. * Note that multiple calls to this function are allowed, and that the
  200332. * sum of the lengths from these calls *must* add up to the total_length
  200333. * given to png_write_chunk_start().
  200334. */
  200335. void PNGAPI
  200336. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200337. {
  200338. /* write the data, and run the CRC over it */
  200339. if(png_ptr == NULL) return;
  200340. if (data != NULL && length > 0)
  200341. {
  200342. png_calculate_crc(png_ptr, data, length);
  200343. png_write_data(png_ptr, data, length);
  200344. }
  200345. }
  200346. /* Finish a chunk started with png_write_chunk_start(). */
  200347. void PNGAPI
  200348. png_write_chunk_end(png_structp png_ptr)
  200349. {
  200350. png_byte buf[4];
  200351. if(png_ptr == NULL) return;
  200352. /* write the crc */
  200353. png_save_uint_32(buf, png_ptr->crc);
  200354. png_write_data(png_ptr, buf, (png_size_t)4);
  200355. }
  200356. /* Simple function to write the signature. If we have already written
  200357. * the magic bytes of the signature, or more likely, the PNG stream is
  200358. * being embedded into another stream and doesn't need its own signature,
  200359. * we should call png_set_sig_bytes() to tell libpng how many of the
  200360. * bytes have already been written.
  200361. */
  200362. void /* PRIVATE */
  200363. png_write_sig(png_structp png_ptr)
  200364. {
  200365. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200366. /* write the rest of the 8 byte signature */
  200367. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200368. (png_size_t)8 - png_ptr->sig_bytes);
  200369. if(png_ptr->sig_bytes < 3)
  200370. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200371. }
  200372. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200373. /*
  200374. * This pair of functions encapsulates the operation of (a) compressing a
  200375. * text string, and (b) issuing it later as a series of chunk data writes.
  200376. * The compression_state structure is shared context for these functions
  200377. * set up by the caller in order to make the whole mess thread-safe.
  200378. */
  200379. typedef struct
  200380. {
  200381. char *input; /* the uncompressed input data */
  200382. int input_len; /* its length */
  200383. int num_output_ptr; /* number of output pointers used */
  200384. int max_output_ptr; /* size of output_ptr */
  200385. png_charpp output_ptr; /* array of pointers to output */
  200386. } compression_state;
  200387. /* compress given text into storage in the png_ptr structure */
  200388. static int /* PRIVATE */
  200389. png_text_compress(png_structp png_ptr,
  200390. png_charp text, png_size_t text_len, int compression,
  200391. compression_state *comp)
  200392. {
  200393. int ret;
  200394. comp->num_output_ptr = 0;
  200395. comp->max_output_ptr = 0;
  200396. comp->output_ptr = NULL;
  200397. comp->input = NULL;
  200398. comp->input_len = 0;
  200399. /* we may just want to pass the text right through */
  200400. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200401. {
  200402. comp->input = text;
  200403. comp->input_len = text_len;
  200404. return((int)text_len);
  200405. }
  200406. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200407. {
  200408. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200409. char msg[50];
  200410. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200411. png_warning(png_ptr, msg);
  200412. #else
  200413. png_warning(png_ptr, "Unknown compression type");
  200414. #endif
  200415. }
  200416. /* We can't write the chunk until we find out how much data we have,
  200417. * which means we need to run the compressor first and save the
  200418. * output. This shouldn't be a problem, as the vast majority of
  200419. * comments should be reasonable, but we will set up an array of
  200420. * malloc'd pointers to be sure.
  200421. *
  200422. * If we knew the application was well behaved, we could simplify this
  200423. * greatly by assuming we can always malloc an output buffer large
  200424. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200425. * and malloc this directly. The only time this would be a bad idea is
  200426. * if we can't malloc more than 64K and we have 64K of random input
  200427. * data, or if the input string is incredibly large (although this
  200428. * wouldn't cause a failure, just a slowdown due to swapping).
  200429. */
  200430. /* set up the compression buffers */
  200431. png_ptr->zstream.avail_in = (uInt)text_len;
  200432. png_ptr->zstream.next_in = (Bytef *)text;
  200433. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200434. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200435. /* this is the same compression loop as in png_write_row() */
  200436. do
  200437. {
  200438. /* compress the data */
  200439. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200440. if (ret != Z_OK)
  200441. {
  200442. /* error */
  200443. if (png_ptr->zstream.msg != NULL)
  200444. png_error(png_ptr, png_ptr->zstream.msg);
  200445. else
  200446. png_error(png_ptr, "zlib error");
  200447. }
  200448. /* check to see if we need more room */
  200449. if (!(png_ptr->zstream.avail_out))
  200450. {
  200451. /* make sure the output array has room */
  200452. if (comp->num_output_ptr >= comp->max_output_ptr)
  200453. {
  200454. int old_max;
  200455. old_max = comp->max_output_ptr;
  200456. comp->max_output_ptr = comp->num_output_ptr + 4;
  200457. if (comp->output_ptr != NULL)
  200458. {
  200459. png_charpp old_ptr;
  200460. old_ptr = comp->output_ptr;
  200461. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200462. (png_uint_32)(comp->max_output_ptr *
  200463. png_sizeof (png_charpp)));
  200464. png_memcpy(comp->output_ptr, old_ptr, old_max
  200465. * png_sizeof (png_charp));
  200466. png_free(png_ptr, old_ptr);
  200467. }
  200468. else
  200469. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200470. (png_uint_32)(comp->max_output_ptr *
  200471. png_sizeof (png_charp)));
  200472. }
  200473. /* save the data */
  200474. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200475. (png_uint_32)png_ptr->zbuf_size);
  200476. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200477. png_ptr->zbuf_size);
  200478. comp->num_output_ptr++;
  200479. /* and reset the buffer */
  200480. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200481. png_ptr->zstream.next_out = png_ptr->zbuf;
  200482. }
  200483. /* continue until we don't have any more to compress */
  200484. } while (png_ptr->zstream.avail_in);
  200485. /* finish the compression */
  200486. do
  200487. {
  200488. /* tell zlib we are finished */
  200489. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200490. if (ret == Z_OK)
  200491. {
  200492. /* check to see if we need more room */
  200493. if (!(png_ptr->zstream.avail_out))
  200494. {
  200495. /* check to make sure our output array has room */
  200496. if (comp->num_output_ptr >= comp->max_output_ptr)
  200497. {
  200498. int old_max;
  200499. old_max = comp->max_output_ptr;
  200500. comp->max_output_ptr = comp->num_output_ptr + 4;
  200501. if (comp->output_ptr != NULL)
  200502. {
  200503. png_charpp old_ptr;
  200504. old_ptr = comp->output_ptr;
  200505. /* This could be optimized to realloc() */
  200506. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200507. (png_uint_32)(comp->max_output_ptr *
  200508. png_sizeof (png_charpp)));
  200509. png_memcpy(comp->output_ptr, old_ptr,
  200510. old_max * png_sizeof (png_charp));
  200511. png_free(png_ptr, old_ptr);
  200512. }
  200513. else
  200514. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200515. (png_uint_32)(comp->max_output_ptr *
  200516. png_sizeof (png_charp)));
  200517. }
  200518. /* save off the data */
  200519. comp->output_ptr[comp->num_output_ptr] =
  200520. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200521. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200522. png_ptr->zbuf_size);
  200523. comp->num_output_ptr++;
  200524. /* and reset the buffer pointers */
  200525. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200526. png_ptr->zstream.next_out = png_ptr->zbuf;
  200527. }
  200528. }
  200529. else if (ret != Z_STREAM_END)
  200530. {
  200531. /* we got an error */
  200532. if (png_ptr->zstream.msg != NULL)
  200533. png_error(png_ptr, png_ptr->zstream.msg);
  200534. else
  200535. png_error(png_ptr, "zlib error");
  200536. }
  200537. } while (ret != Z_STREAM_END);
  200538. /* text length is number of buffers plus last buffer */
  200539. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200540. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200541. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200542. return((int)text_len);
  200543. }
  200544. /* ship the compressed text out via chunk writes */
  200545. static void /* PRIVATE */
  200546. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200547. {
  200548. int i;
  200549. /* handle the no-compression case */
  200550. if (comp->input)
  200551. {
  200552. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200553. (png_size_t)comp->input_len);
  200554. return;
  200555. }
  200556. /* write saved output buffers, if any */
  200557. for (i = 0; i < comp->num_output_ptr; i++)
  200558. {
  200559. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200560. png_ptr->zbuf_size);
  200561. png_free(png_ptr, comp->output_ptr[i]);
  200562. comp->output_ptr[i]=NULL;
  200563. }
  200564. if (comp->max_output_ptr != 0)
  200565. png_free(png_ptr, comp->output_ptr);
  200566. comp->output_ptr=NULL;
  200567. /* write anything left in zbuf */
  200568. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200569. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200570. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200571. /* reset zlib for another zTXt/iTXt or image data */
  200572. deflateReset(&png_ptr->zstream);
  200573. png_ptr->zstream.data_type = Z_BINARY;
  200574. }
  200575. #endif
  200576. /* Write the IHDR chunk, and update the png_struct with the necessary
  200577. * information. Note that the rest of this code depends upon this
  200578. * information being correct.
  200579. */
  200580. void /* PRIVATE */
  200581. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200582. int bit_depth, int color_type, int compression_type, int filter_type,
  200583. int interlace_type)
  200584. {
  200585. #ifdef PNG_USE_LOCAL_ARRAYS
  200586. PNG_IHDR;
  200587. #endif
  200588. png_byte buf[13]; /* buffer to store the IHDR info */
  200589. png_debug(1, "in png_write_IHDR\n");
  200590. /* Check that we have valid input data from the application info */
  200591. switch (color_type)
  200592. {
  200593. case PNG_COLOR_TYPE_GRAY:
  200594. switch (bit_depth)
  200595. {
  200596. case 1:
  200597. case 2:
  200598. case 4:
  200599. case 8:
  200600. case 16: png_ptr->channels = 1; break;
  200601. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200602. }
  200603. break;
  200604. case PNG_COLOR_TYPE_RGB:
  200605. if (bit_depth != 8 && bit_depth != 16)
  200606. png_error(png_ptr, "Invalid bit depth for RGB image");
  200607. png_ptr->channels = 3;
  200608. break;
  200609. case PNG_COLOR_TYPE_PALETTE:
  200610. switch (bit_depth)
  200611. {
  200612. case 1:
  200613. case 2:
  200614. case 4:
  200615. case 8: png_ptr->channels = 1; break;
  200616. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200617. }
  200618. break;
  200619. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200620. if (bit_depth != 8 && bit_depth != 16)
  200621. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200622. png_ptr->channels = 2;
  200623. break;
  200624. case PNG_COLOR_TYPE_RGB_ALPHA:
  200625. if (bit_depth != 8 && bit_depth != 16)
  200626. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200627. png_ptr->channels = 4;
  200628. break;
  200629. default:
  200630. png_error(png_ptr, "Invalid image color type specified");
  200631. }
  200632. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200633. {
  200634. png_warning(png_ptr, "Invalid compression type specified");
  200635. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200636. }
  200637. /* Write filter_method 64 (intrapixel differencing) only if
  200638. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200639. * 2. Libpng did not write a PNG signature (this filter_method is only
  200640. * used in PNG datastreams that are embedded in MNG datastreams) and
  200641. * 3. The application called png_permit_mng_features with a mask that
  200642. * included PNG_FLAG_MNG_FILTER_64 and
  200643. * 4. The filter_method is 64 and
  200644. * 5. The color_type is RGB or RGBA
  200645. */
  200646. if (
  200647. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200648. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200649. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200650. (color_type == PNG_COLOR_TYPE_RGB ||
  200651. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200652. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200653. #endif
  200654. filter_type != PNG_FILTER_TYPE_BASE)
  200655. {
  200656. png_warning(png_ptr, "Invalid filter type specified");
  200657. filter_type = PNG_FILTER_TYPE_BASE;
  200658. }
  200659. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200660. if (interlace_type != PNG_INTERLACE_NONE &&
  200661. interlace_type != PNG_INTERLACE_ADAM7)
  200662. {
  200663. png_warning(png_ptr, "Invalid interlace type specified");
  200664. interlace_type = PNG_INTERLACE_ADAM7;
  200665. }
  200666. #else
  200667. interlace_type=PNG_INTERLACE_NONE;
  200668. #endif
  200669. /* save off the relevent information */
  200670. png_ptr->bit_depth = (png_byte)bit_depth;
  200671. png_ptr->color_type = (png_byte)color_type;
  200672. png_ptr->interlaced = (png_byte)interlace_type;
  200673. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200674. png_ptr->filter_type = (png_byte)filter_type;
  200675. #endif
  200676. png_ptr->compression_type = (png_byte)compression_type;
  200677. png_ptr->width = width;
  200678. png_ptr->height = height;
  200679. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200680. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200681. /* set the usr info, so any transformations can modify it */
  200682. png_ptr->usr_width = png_ptr->width;
  200683. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200684. png_ptr->usr_channels = png_ptr->channels;
  200685. /* pack the header information into the buffer */
  200686. png_save_uint_32(buf, width);
  200687. png_save_uint_32(buf + 4, height);
  200688. buf[8] = (png_byte)bit_depth;
  200689. buf[9] = (png_byte)color_type;
  200690. buf[10] = (png_byte)compression_type;
  200691. buf[11] = (png_byte)filter_type;
  200692. buf[12] = (png_byte)interlace_type;
  200693. /* write the chunk */
  200694. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200695. /* initialize zlib with PNG info */
  200696. png_ptr->zstream.zalloc = png_zalloc;
  200697. png_ptr->zstream.zfree = png_zfree;
  200698. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200699. if (!(png_ptr->do_filter))
  200700. {
  200701. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200702. png_ptr->bit_depth < 8)
  200703. png_ptr->do_filter = PNG_FILTER_NONE;
  200704. else
  200705. png_ptr->do_filter = PNG_ALL_FILTERS;
  200706. }
  200707. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200708. {
  200709. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200710. png_ptr->zlib_strategy = Z_FILTERED;
  200711. else
  200712. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200713. }
  200714. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200715. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200716. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200717. png_ptr->zlib_mem_level = 8;
  200718. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200719. png_ptr->zlib_window_bits = 15;
  200720. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200721. png_ptr->zlib_method = 8;
  200722. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200723. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200724. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200725. png_error(png_ptr, "zlib failed to initialize compressor");
  200726. png_ptr->zstream.next_out = png_ptr->zbuf;
  200727. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200728. /* libpng is not interested in zstream.data_type */
  200729. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200730. png_ptr->zstream.data_type = Z_BINARY;
  200731. png_ptr->mode = PNG_HAVE_IHDR;
  200732. }
  200733. /* write the palette. We are careful not to trust png_color to be in the
  200734. * correct order for PNG, so people can redefine it to any convenient
  200735. * structure.
  200736. */
  200737. void /* PRIVATE */
  200738. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200739. {
  200740. #ifdef PNG_USE_LOCAL_ARRAYS
  200741. PNG_PLTE;
  200742. #endif
  200743. png_uint_32 i;
  200744. png_colorp pal_ptr;
  200745. png_byte buf[3];
  200746. png_debug(1, "in png_write_PLTE\n");
  200747. if ((
  200748. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200749. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200750. #endif
  200751. num_pal == 0) || num_pal > 256)
  200752. {
  200753. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200754. {
  200755. png_error(png_ptr, "Invalid number of colors in palette");
  200756. }
  200757. else
  200758. {
  200759. png_warning(png_ptr, "Invalid number of colors in palette");
  200760. return;
  200761. }
  200762. }
  200763. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200764. {
  200765. png_warning(png_ptr,
  200766. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200767. return;
  200768. }
  200769. png_ptr->num_palette = (png_uint_16)num_pal;
  200770. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200771. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200772. #ifndef PNG_NO_POINTER_INDEXING
  200773. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200774. {
  200775. buf[0] = pal_ptr->red;
  200776. buf[1] = pal_ptr->green;
  200777. buf[2] = pal_ptr->blue;
  200778. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200779. }
  200780. #else
  200781. /* This is a little slower but some buggy compilers need to do this instead */
  200782. pal_ptr=palette;
  200783. for (i = 0; i < num_pal; i++)
  200784. {
  200785. buf[0] = pal_ptr[i].red;
  200786. buf[1] = pal_ptr[i].green;
  200787. buf[2] = pal_ptr[i].blue;
  200788. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200789. }
  200790. #endif
  200791. png_write_chunk_end(png_ptr);
  200792. png_ptr->mode |= PNG_HAVE_PLTE;
  200793. }
  200794. /* write an IDAT chunk */
  200795. void /* PRIVATE */
  200796. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200797. {
  200798. #ifdef PNG_USE_LOCAL_ARRAYS
  200799. PNG_IDAT;
  200800. #endif
  200801. png_debug(1, "in png_write_IDAT\n");
  200802. /* Optimize the CMF field in the zlib stream. */
  200803. /* This hack of the zlib stream is compliant to the stream specification. */
  200804. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200805. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200806. {
  200807. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200808. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200809. {
  200810. /* Avoid memory underflows and multiplication overflows. */
  200811. /* The conditions below are practically always satisfied;
  200812. however, they still must be checked. */
  200813. if (length >= 2 &&
  200814. png_ptr->height < 16384 && png_ptr->width < 16384)
  200815. {
  200816. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200817. ((png_ptr->width *
  200818. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200819. unsigned int z_cinfo = z_cmf >> 4;
  200820. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200821. while (uncompressed_idat_size <= half_z_window_size &&
  200822. half_z_window_size >= 256)
  200823. {
  200824. z_cinfo--;
  200825. half_z_window_size >>= 1;
  200826. }
  200827. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200828. if (data[0] != (png_byte)z_cmf)
  200829. {
  200830. data[0] = (png_byte)z_cmf;
  200831. data[1] &= 0xe0;
  200832. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200833. }
  200834. }
  200835. }
  200836. else
  200837. png_error(png_ptr,
  200838. "Invalid zlib compression method or flags in IDAT");
  200839. }
  200840. png_write_chunk(png_ptr, png_IDAT, data, length);
  200841. png_ptr->mode |= PNG_HAVE_IDAT;
  200842. }
  200843. /* write an IEND chunk */
  200844. void /* PRIVATE */
  200845. png_write_IEND(png_structp png_ptr)
  200846. {
  200847. #ifdef PNG_USE_LOCAL_ARRAYS
  200848. PNG_IEND;
  200849. #endif
  200850. png_debug(1, "in png_write_IEND\n");
  200851. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200852. (png_size_t)0);
  200853. png_ptr->mode |= PNG_HAVE_IEND;
  200854. }
  200855. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200856. /* write a gAMA chunk */
  200857. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200858. void /* PRIVATE */
  200859. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200860. {
  200861. #ifdef PNG_USE_LOCAL_ARRAYS
  200862. PNG_gAMA;
  200863. #endif
  200864. png_uint_32 igamma;
  200865. png_byte buf[4];
  200866. png_debug(1, "in png_write_gAMA\n");
  200867. /* file_gamma is saved in 1/100,000ths */
  200868. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200869. png_save_uint_32(buf, igamma);
  200870. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200871. }
  200872. #endif
  200873. #ifdef PNG_FIXED_POINT_SUPPORTED
  200874. void /* PRIVATE */
  200875. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200876. {
  200877. #ifdef PNG_USE_LOCAL_ARRAYS
  200878. PNG_gAMA;
  200879. #endif
  200880. png_byte buf[4];
  200881. png_debug(1, "in png_write_gAMA\n");
  200882. /* file_gamma is saved in 1/100,000ths */
  200883. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200884. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200885. }
  200886. #endif
  200887. #endif
  200888. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200889. /* write a sRGB chunk */
  200890. void /* PRIVATE */
  200891. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200892. {
  200893. #ifdef PNG_USE_LOCAL_ARRAYS
  200894. PNG_sRGB;
  200895. #endif
  200896. png_byte buf[1];
  200897. png_debug(1, "in png_write_sRGB\n");
  200898. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200899. png_warning(png_ptr,
  200900. "Invalid sRGB rendering intent specified");
  200901. buf[0]=(png_byte)srgb_intent;
  200902. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200903. }
  200904. #endif
  200905. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200906. /* write an iCCP chunk */
  200907. void /* PRIVATE */
  200908. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200909. png_charp profile, int profile_len)
  200910. {
  200911. #ifdef PNG_USE_LOCAL_ARRAYS
  200912. PNG_iCCP;
  200913. #endif
  200914. png_size_t name_len;
  200915. png_charp new_name;
  200916. compression_state comp;
  200917. int embedded_profile_len = 0;
  200918. png_debug(1, "in png_write_iCCP\n");
  200919. comp.num_output_ptr = 0;
  200920. comp.max_output_ptr = 0;
  200921. comp.output_ptr = NULL;
  200922. comp.input = NULL;
  200923. comp.input_len = 0;
  200924. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200925. &new_name)) == 0)
  200926. {
  200927. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200928. return;
  200929. }
  200930. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200931. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200932. if (profile == NULL)
  200933. profile_len = 0;
  200934. if (profile_len > 3)
  200935. embedded_profile_len =
  200936. ((*( (png_bytep)profile ))<<24) |
  200937. ((*( (png_bytep)profile+1))<<16) |
  200938. ((*( (png_bytep)profile+2))<< 8) |
  200939. ((*( (png_bytep)profile+3)) );
  200940. if (profile_len < embedded_profile_len)
  200941. {
  200942. png_warning(png_ptr,
  200943. "Embedded profile length too large in iCCP chunk");
  200944. return;
  200945. }
  200946. if (profile_len > embedded_profile_len)
  200947. {
  200948. png_warning(png_ptr,
  200949. "Truncating profile to actual length in iCCP chunk");
  200950. profile_len = embedded_profile_len;
  200951. }
  200952. if (profile_len)
  200953. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200954. PNG_COMPRESSION_TYPE_BASE, &comp);
  200955. /* make sure we include the NULL after the name and the compression type */
  200956. png_write_chunk_start(png_ptr, png_iCCP,
  200957. (png_uint_32)name_len+profile_len+2);
  200958. new_name[name_len+1]=0x00;
  200959. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200960. if (profile_len)
  200961. png_write_compressed_data_out(png_ptr, &comp);
  200962. png_write_chunk_end(png_ptr);
  200963. png_free(png_ptr, new_name);
  200964. }
  200965. #endif
  200966. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200967. /* write a sPLT chunk */
  200968. void /* PRIVATE */
  200969. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200970. {
  200971. #ifdef PNG_USE_LOCAL_ARRAYS
  200972. PNG_sPLT;
  200973. #endif
  200974. png_size_t name_len;
  200975. png_charp new_name;
  200976. png_byte entrybuf[10];
  200977. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200978. int palette_size = entry_size * spalette->nentries;
  200979. png_sPLT_entryp ep;
  200980. #ifdef PNG_NO_POINTER_INDEXING
  200981. int i;
  200982. #endif
  200983. png_debug(1, "in png_write_sPLT\n");
  200984. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200985. spalette->name, &new_name))==0)
  200986. {
  200987. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200988. return;
  200989. }
  200990. /* make sure we include the NULL after the name */
  200991. png_write_chunk_start(png_ptr, png_sPLT,
  200992. (png_uint_32)(name_len + 2 + palette_size));
  200993. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200994. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200995. /* loop through each palette entry, writing appropriately */
  200996. #ifndef PNG_NO_POINTER_INDEXING
  200997. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200998. {
  200999. if (spalette->depth == 8)
  201000. {
  201001. entrybuf[0] = (png_byte)ep->red;
  201002. entrybuf[1] = (png_byte)ep->green;
  201003. entrybuf[2] = (png_byte)ep->blue;
  201004. entrybuf[3] = (png_byte)ep->alpha;
  201005. png_save_uint_16(entrybuf + 4, ep->frequency);
  201006. }
  201007. else
  201008. {
  201009. png_save_uint_16(entrybuf + 0, ep->red);
  201010. png_save_uint_16(entrybuf + 2, ep->green);
  201011. png_save_uint_16(entrybuf + 4, ep->blue);
  201012. png_save_uint_16(entrybuf + 6, ep->alpha);
  201013. png_save_uint_16(entrybuf + 8, ep->frequency);
  201014. }
  201015. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201016. }
  201017. #else
  201018. ep=spalette->entries;
  201019. for (i=0; i>spalette->nentries; i++)
  201020. {
  201021. if (spalette->depth == 8)
  201022. {
  201023. entrybuf[0] = (png_byte)ep[i].red;
  201024. entrybuf[1] = (png_byte)ep[i].green;
  201025. entrybuf[2] = (png_byte)ep[i].blue;
  201026. entrybuf[3] = (png_byte)ep[i].alpha;
  201027. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201028. }
  201029. else
  201030. {
  201031. png_save_uint_16(entrybuf + 0, ep[i].red);
  201032. png_save_uint_16(entrybuf + 2, ep[i].green);
  201033. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201034. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201035. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201036. }
  201037. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201038. }
  201039. #endif
  201040. png_write_chunk_end(png_ptr);
  201041. png_free(png_ptr, new_name);
  201042. }
  201043. #endif
  201044. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201045. /* write the sBIT chunk */
  201046. void /* PRIVATE */
  201047. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201048. {
  201049. #ifdef PNG_USE_LOCAL_ARRAYS
  201050. PNG_sBIT;
  201051. #endif
  201052. png_byte buf[4];
  201053. png_size_t size;
  201054. png_debug(1, "in png_write_sBIT\n");
  201055. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201056. if (color_type & PNG_COLOR_MASK_COLOR)
  201057. {
  201058. png_byte maxbits;
  201059. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201060. png_ptr->usr_bit_depth);
  201061. if (sbit->red == 0 || sbit->red > maxbits ||
  201062. sbit->green == 0 || sbit->green > maxbits ||
  201063. sbit->blue == 0 || sbit->blue > maxbits)
  201064. {
  201065. png_warning(png_ptr, "Invalid sBIT depth specified");
  201066. return;
  201067. }
  201068. buf[0] = sbit->red;
  201069. buf[1] = sbit->green;
  201070. buf[2] = sbit->blue;
  201071. size = 3;
  201072. }
  201073. else
  201074. {
  201075. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201076. {
  201077. png_warning(png_ptr, "Invalid sBIT depth specified");
  201078. return;
  201079. }
  201080. buf[0] = sbit->gray;
  201081. size = 1;
  201082. }
  201083. if (color_type & PNG_COLOR_MASK_ALPHA)
  201084. {
  201085. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201086. {
  201087. png_warning(png_ptr, "Invalid sBIT depth specified");
  201088. return;
  201089. }
  201090. buf[size++] = sbit->alpha;
  201091. }
  201092. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201093. }
  201094. #endif
  201095. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201096. /* write the cHRM chunk */
  201097. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201098. void /* PRIVATE */
  201099. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201100. double red_x, double red_y, double green_x, double green_y,
  201101. double blue_x, double blue_y)
  201102. {
  201103. #ifdef PNG_USE_LOCAL_ARRAYS
  201104. PNG_cHRM;
  201105. #endif
  201106. png_byte buf[32];
  201107. png_uint_32 itemp;
  201108. png_debug(1, "in png_write_cHRM\n");
  201109. /* each value is saved in 1/100,000ths */
  201110. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201111. white_x + white_y > 1.0)
  201112. {
  201113. png_warning(png_ptr, "Invalid cHRM white point specified");
  201114. #if !defined(PNG_NO_CONSOLE_IO)
  201115. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201116. #endif
  201117. return;
  201118. }
  201119. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201120. png_save_uint_32(buf, itemp);
  201121. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201122. png_save_uint_32(buf + 4, itemp);
  201123. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201124. {
  201125. png_warning(png_ptr, "Invalid cHRM red point specified");
  201126. return;
  201127. }
  201128. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201129. png_save_uint_32(buf + 8, itemp);
  201130. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201131. png_save_uint_32(buf + 12, itemp);
  201132. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201133. {
  201134. png_warning(png_ptr, "Invalid cHRM green point specified");
  201135. return;
  201136. }
  201137. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201138. png_save_uint_32(buf + 16, itemp);
  201139. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201140. png_save_uint_32(buf + 20, itemp);
  201141. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201142. {
  201143. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201144. return;
  201145. }
  201146. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201147. png_save_uint_32(buf + 24, itemp);
  201148. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201149. png_save_uint_32(buf + 28, itemp);
  201150. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201151. }
  201152. #endif
  201153. #ifdef PNG_FIXED_POINT_SUPPORTED
  201154. void /* PRIVATE */
  201155. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201156. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201157. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201158. png_fixed_point blue_y)
  201159. {
  201160. #ifdef PNG_USE_LOCAL_ARRAYS
  201161. PNG_cHRM;
  201162. #endif
  201163. png_byte buf[32];
  201164. png_debug(1, "in png_write_cHRM\n");
  201165. /* each value is saved in 1/100,000ths */
  201166. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201167. {
  201168. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201169. #if !defined(PNG_NO_CONSOLE_IO)
  201170. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201171. #endif
  201172. return;
  201173. }
  201174. png_save_uint_32(buf, (png_uint_32)white_x);
  201175. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201176. if (red_x + red_y > 100000L)
  201177. {
  201178. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201179. return;
  201180. }
  201181. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201182. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201183. if (green_x + green_y > 100000L)
  201184. {
  201185. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201186. return;
  201187. }
  201188. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201189. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201190. if (blue_x + blue_y > 100000L)
  201191. {
  201192. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201193. return;
  201194. }
  201195. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201196. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201197. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201198. }
  201199. #endif
  201200. #endif
  201201. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201202. /* write the tRNS chunk */
  201203. void /* PRIVATE */
  201204. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201205. int num_trans, int color_type)
  201206. {
  201207. #ifdef PNG_USE_LOCAL_ARRAYS
  201208. PNG_tRNS;
  201209. #endif
  201210. png_byte buf[6];
  201211. png_debug(1, "in png_write_tRNS\n");
  201212. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201213. {
  201214. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201215. {
  201216. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201217. return;
  201218. }
  201219. /* write the chunk out as it is */
  201220. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201221. }
  201222. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201223. {
  201224. /* one 16 bit value */
  201225. if(tran->gray >= (1 << png_ptr->bit_depth))
  201226. {
  201227. png_warning(png_ptr,
  201228. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201229. return;
  201230. }
  201231. png_save_uint_16(buf, tran->gray);
  201232. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201233. }
  201234. else if (color_type == PNG_COLOR_TYPE_RGB)
  201235. {
  201236. /* three 16 bit values */
  201237. png_save_uint_16(buf, tran->red);
  201238. png_save_uint_16(buf + 2, tran->green);
  201239. png_save_uint_16(buf + 4, tran->blue);
  201240. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201241. {
  201242. png_warning(png_ptr,
  201243. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201244. return;
  201245. }
  201246. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201247. }
  201248. else
  201249. {
  201250. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201251. }
  201252. }
  201253. #endif
  201254. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201255. /* write the background chunk */
  201256. void /* PRIVATE */
  201257. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201258. {
  201259. #ifdef PNG_USE_LOCAL_ARRAYS
  201260. PNG_bKGD;
  201261. #endif
  201262. png_byte buf[6];
  201263. png_debug(1, "in png_write_bKGD\n");
  201264. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201265. {
  201266. if (
  201267. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201268. (png_ptr->num_palette ||
  201269. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201270. #endif
  201271. back->index > png_ptr->num_palette)
  201272. {
  201273. png_warning(png_ptr, "Invalid background palette index");
  201274. return;
  201275. }
  201276. buf[0] = back->index;
  201277. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201278. }
  201279. else if (color_type & PNG_COLOR_MASK_COLOR)
  201280. {
  201281. png_save_uint_16(buf, back->red);
  201282. png_save_uint_16(buf + 2, back->green);
  201283. png_save_uint_16(buf + 4, back->blue);
  201284. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201285. {
  201286. png_warning(png_ptr,
  201287. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201288. return;
  201289. }
  201290. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201291. }
  201292. else
  201293. {
  201294. if(back->gray >= (1 << png_ptr->bit_depth))
  201295. {
  201296. png_warning(png_ptr,
  201297. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201298. return;
  201299. }
  201300. png_save_uint_16(buf, back->gray);
  201301. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201302. }
  201303. }
  201304. #endif
  201305. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201306. /* write the histogram */
  201307. void /* PRIVATE */
  201308. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201309. {
  201310. #ifdef PNG_USE_LOCAL_ARRAYS
  201311. PNG_hIST;
  201312. #endif
  201313. int i;
  201314. png_byte buf[3];
  201315. png_debug(1, "in png_write_hIST\n");
  201316. if (num_hist > (int)png_ptr->num_palette)
  201317. {
  201318. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201319. png_ptr->num_palette);
  201320. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201321. return;
  201322. }
  201323. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201324. for (i = 0; i < num_hist; i++)
  201325. {
  201326. png_save_uint_16(buf, hist[i]);
  201327. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201328. }
  201329. png_write_chunk_end(png_ptr);
  201330. }
  201331. #endif
  201332. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201333. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201334. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201335. * and if invalid, correct the keyword rather than discarding the entire
  201336. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201337. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201338. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201339. *
  201340. * The new_key is allocated to hold the corrected keyword and must be freed
  201341. * by the calling routine. This avoids problems with trying to write to
  201342. * static keywords without having to have duplicate copies of the strings.
  201343. */
  201344. png_size_t /* PRIVATE */
  201345. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201346. {
  201347. png_size_t key_len;
  201348. png_charp kp, dp;
  201349. int kflag;
  201350. int kwarn=0;
  201351. png_debug(1, "in png_check_keyword\n");
  201352. *new_key = NULL;
  201353. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201354. {
  201355. png_warning(png_ptr, "zero length keyword");
  201356. return ((png_size_t)0);
  201357. }
  201358. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201359. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201360. if (*new_key == NULL)
  201361. {
  201362. png_warning(png_ptr, "Out of memory while procesing keyword");
  201363. return ((png_size_t)0);
  201364. }
  201365. /* Replace non-printing characters with a blank and print a warning */
  201366. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201367. {
  201368. if ((png_byte)*kp < 0x20 ||
  201369. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201370. {
  201371. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201372. char msg[40];
  201373. png_snprintf(msg, 40,
  201374. "invalid keyword character 0x%02X", (png_byte)*kp);
  201375. png_warning(png_ptr, msg);
  201376. #else
  201377. png_warning(png_ptr, "invalid character in keyword");
  201378. #endif
  201379. *dp = ' ';
  201380. }
  201381. else
  201382. {
  201383. *dp = *kp;
  201384. }
  201385. }
  201386. *dp = '\0';
  201387. /* Remove any trailing white space. */
  201388. kp = *new_key + key_len - 1;
  201389. if (*kp == ' ')
  201390. {
  201391. png_warning(png_ptr, "trailing spaces removed from keyword");
  201392. while (*kp == ' ')
  201393. {
  201394. *(kp--) = '\0';
  201395. key_len--;
  201396. }
  201397. }
  201398. /* Remove any leading white space. */
  201399. kp = *new_key;
  201400. if (*kp == ' ')
  201401. {
  201402. png_warning(png_ptr, "leading spaces removed from keyword");
  201403. while (*kp == ' ')
  201404. {
  201405. kp++;
  201406. key_len--;
  201407. }
  201408. }
  201409. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201410. /* Remove multiple internal spaces. */
  201411. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201412. {
  201413. if (*kp == ' ' && kflag == 0)
  201414. {
  201415. *(dp++) = *kp;
  201416. kflag = 1;
  201417. }
  201418. else if (*kp == ' ')
  201419. {
  201420. key_len--;
  201421. kwarn=1;
  201422. }
  201423. else
  201424. {
  201425. *(dp++) = *kp;
  201426. kflag = 0;
  201427. }
  201428. }
  201429. *dp = '\0';
  201430. if(kwarn)
  201431. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201432. if (key_len == 0)
  201433. {
  201434. png_free(png_ptr, *new_key);
  201435. *new_key=NULL;
  201436. png_warning(png_ptr, "Zero length keyword");
  201437. }
  201438. if (key_len > 79)
  201439. {
  201440. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201441. new_key[79] = '\0';
  201442. key_len = 79;
  201443. }
  201444. return (key_len);
  201445. }
  201446. #endif
  201447. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201448. /* write a tEXt chunk */
  201449. void /* PRIVATE */
  201450. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201451. png_size_t text_len)
  201452. {
  201453. #ifdef PNG_USE_LOCAL_ARRAYS
  201454. PNG_tEXt;
  201455. #endif
  201456. png_size_t key_len;
  201457. png_charp new_key;
  201458. png_debug(1, "in png_write_tEXt\n");
  201459. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201460. {
  201461. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201462. return;
  201463. }
  201464. if (text == NULL || *text == '\0')
  201465. text_len = 0;
  201466. else
  201467. text_len = png_strlen(text);
  201468. /* make sure we include the 0 after the key */
  201469. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201470. /*
  201471. * We leave it to the application to meet PNG-1.0 requirements on the
  201472. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201473. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201474. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201475. */
  201476. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201477. if (text_len)
  201478. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201479. png_write_chunk_end(png_ptr);
  201480. png_free(png_ptr, new_key);
  201481. }
  201482. #endif
  201483. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201484. /* write a compressed text chunk */
  201485. void /* PRIVATE */
  201486. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201487. png_size_t text_len, int compression)
  201488. {
  201489. #ifdef PNG_USE_LOCAL_ARRAYS
  201490. PNG_zTXt;
  201491. #endif
  201492. png_size_t key_len;
  201493. char buf[1];
  201494. png_charp new_key;
  201495. compression_state comp;
  201496. png_debug(1, "in png_write_zTXt\n");
  201497. comp.num_output_ptr = 0;
  201498. comp.max_output_ptr = 0;
  201499. comp.output_ptr = NULL;
  201500. comp.input = NULL;
  201501. comp.input_len = 0;
  201502. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201503. {
  201504. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201505. return;
  201506. }
  201507. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201508. {
  201509. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201510. png_free(png_ptr, new_key);
  201511. return;
  201512. }
  201513. text_len = png_strlen(text);
  201514. /* compute the compressed data; do it now for the length */
  201515. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201516. &comp);
  201517. /* write start of chunk */
  201518. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201519. (key_len+text_len+2));
  201520. /* write key */
  201521. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201522. png_free(png_ptr, new_key);
  201523. buf[0] = (png_byte)compression;
  201524. /* write compression */
  201525. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201526. /* write the compressed data */
  201527. png_write_compressed_data_out(png_ptr, &comp);
  201528. /* close the chunk */
  201529. png_write_chunk_end(png_ptr);
  201530. }
  201531. #endif
  201532. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201533. /* write an iTXt chunk */
  201534. void /* PRIVATE */
  201535. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201536. png_charp lang, png_charp lang_key, png_charp text)
  201537. {
  201538. #ifdef PNG_USE_LOCAL_ARRAYS
  201539. PNG_iTXt;
  201540. #endif
  201541. png_size_t lang_len, key_len, lang_key_len, text_len;
  201542. png_charp new_lang, new_key;
  201543. png_byte cbuf[2];
  201544. compression_state comp;
  201545. png_debug(1, "in png_write_iTXt\n");
  201546. comp.num_output_ptr = 0;
  201547. comp.max_output_ptr = 0;
  201548. comp.output_ptr = NULL;
  201549. comp.input = NULL;
  201550. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201551. {
  201552. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201553. return;
  201554. }
  201555. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201556. {
  201557. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201558. new_lang = NULL;
  201559. lang_len = 0;
  201560. }
  201561. if (lang_key == NULL)
  201562. lang_key_len = 0;
  201563. else
  201564. lang_key_len = png_strlen(lang_key);
  201565. if (text == NULL)
  201566. text_len = 0;
  201567. else
  201568. text_len = png_strlen(text);
  201569. /* compute the compressed data; do it now for the length */
  201570. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201571. &comp);
  201572. /* make sure we include the compression flag, the compression byte,
  201573. * and the NULs after the key, lang, and lang_key parts */
  201574. png_write_chunk_start(png_ptr, png_iTXt,
  201575. (png_uint_32)(
  201576. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201577. + key_len
  201578. + lang_len
  201579. + lang_key_len
  201580. + text_len));
  201581. /*
  201582. * We leave it to the application to meet PNG-1.0 requirements on the
  201583. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201584. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201585. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201586. */
  201587. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201588. /* set the compression flag */
  201589. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201590. compression == PNG_TEXT_COMPRESSION_NONE)
  201591. cbuf[0] = 0;
  201592. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201593. cbuf[0] = 1;
  201594. /* set the compression method */
  201595. cbuf[1] = 0;
  201596. png_write_chunk_data(png_ptr, cbuf, 2);
  201597. cbuf[0] = 0;
  201598. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201599. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201600. png_write_compressed_data_out(png_ptr, &comp);
  201601. png_write_chunk_end(png_ptr);
  201602. png_free(png_ptr, new_key);
  201603. if (new_lang)
  201604. png_free(png_ptr, new_lang);
  201605. }
  201606. #endif
  201607. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201608. /* write the oFFs chunk */
  201609. void /* PRIVATE */
  201610. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201611. int unit_type)
  201612. {
  201613. #ifdef PNG_USE_LOCAL_ARRAYS
  201614. PNG_oFFs;
  201615. #endif
  201616. png_byte buf[9];
  201617. png_debug(1, "in png_write_oFFs\n");
  201618. if (unit_type >= PNG_OFFSET_LAST)
  201619. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201620. png_save_int_32(buf, x_offset);
  201621. png_save_int_32(buf + 4, y_offset);
  201622. buf[8] = (png_byte)unit_type;
  201623. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201624. }
  201625. #endif
  201626. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201627. /* write the pCAL chunk (described in the PNG extensions document) */
  201628. void /* PRIVATE */
  201629. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201630. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201631. {
  201632. #ifdef PNG_USE_LOCAL_ARRAYS
  201633. PNG_pCAL;
  201634. #endif
  201635. png_size_t purpose_len, units_len, total_len;
  201636. png_uint_32p params_len;
  201637. png_byte buf[10];
  201638. png_charp new_purpose;
  201639. int i;
  201640. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201641. if (type >= PNG_EQUATION_LAST)
  201642. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201643. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201644. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201645. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201646. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201647. total_len = purpose_len + units_len + 10;
  201648. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201649. *png_sizeof(png_uint_32)));
  201650. /* Find the length of each parameter, making sure we don't count the
  201651. null terminator for the last parameter. */
  201652. for (i = 0; i < nparams; i++)
  201653. {
  201654. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201655. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201656. total_len += (png_size_t)params_len[i];
  201657. }
  201658. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201659. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201660. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201661. png_save_int_32(buf, X0);
  201662. png_save_int_32(buf + 4, X1);
  201663. buf[8] = (png_byte)type;
  201664. buf[9] = (png_byte)nparams;
  201665. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201666. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201667. png_free(png_ptr, new_purpose);
  201668. for (i = 0; i < nparams; i++)
  201669. {
  201670. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201671. (png_size_t)params_len[i]);
  201672. }
  201673. png_free(png_ptr, params_len);
  201674. png_write_chunk_end(png_ptr);
  201675. }
  201676. #endif
  201677. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201678. /* write the sCAL chunk */
  201679. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201680. void /* PRIVATE */
  201681. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201682. {
  201683. #ifdef PNG_USE_LOCAL_ARRAYS
  201684. PNG_sCAL;
  201685. #endif
  201686. char buf[64];
  201687. png_size_t total_len;
  201688. png_debug(1, "in png_write_sCAL\n");
  201689. buf[0] = (char)unit;
  201690. #if defined(_WIN32_WCE)
  201691. /* sprintf() function is not supported on WindowsCE */
  201692. {
  201693. wchar_t wc_buf[32];
  201694. size_t wc_len;
  201695. swprintf(wc_buf, TEXT("%12.12e"), width);
  201696. wc_len = wcslen(wc_buf);
  201697. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201698. total_len = wc_len + 2;
  201699. swprintf(wc_buf, TEXT("%12.12e"), height);
  201700. wc_len = wcslen(wc_buf);
  201701. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201702. NULL, NULL);
  201703. total_len += wc_len;
  201704. }
  201705. #else
  201706. png_snprintf(buf + 1, 63, "%12.12e", width);
  201707. total_len = 1 + png_strlen(buf + 1) + 1;
  201708. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201709. total_len += png_strlen(buf + total_len);
  201710. #endif
  201711. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201712. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201713. }
  201714. #else
  201715. #ifdef PNG_FIXED_POINT_SUPPORTED
  201716. void /* PRIVATE */
  201717. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201718. png_charp height)
  201719. {
  201720. #ifdef PNG_USE_LOCAL_ARRAYS
  201721. PNG_sCAL;
  201722. #endif
  201723. png_byte buf[64];
  201724. png_size_t wlen, hlen, total_len;
  201725. png_debug(1, "in png_write_sCAL_s\n");
  201726. wlen = png_strlen(width);
  201727. hlen = png_strlen(height);
  201728. total_len = wlen + hlen + 2;
  201729. if (total_len > 64)
  201730. {
  201731. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201732. return;
  201733. }
  201734. buf[0] = (png_byte)unit;
  201735. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201736. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201737. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201738. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201739. }
  201740. #endif
  201741. #endif
  201742. #endif
  201743. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201744. /* write the pHYs chunk */
  201745. void /* PRIVATE */
  201746. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201747. png_uint_32 y_pixels_per_unit,
  201748. int unit_type)
  201749. {
  201750. #ifdef PNG_USE_LOCAL_ARRAYS
  201751. PNG_pHYs;
  201752. #endif
  201753. png_byte buf[9];
  201754. png_debug(1, "in png_write_pHYs\n");
  201755. if (unit_type >= PNG_RESOLUTION_LAST)
  201756. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201757. png_save_uint_32(buf, x_pixels_per_unit);
  201758. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201759. buf[8] = (png_byte)unit_type;
  201760. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201761. }
  201762. #endif
  201763. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201764. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201765. * or png_convert_from_time_t(), or fill in the structure yourself.
  201766. */
  201767. void /* PRIVATE */
  201768. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201769. {
  201770. #ifdef PNG_USE_LOCAL_ARRAYS
  201771. PNG_tIME;
  201772. #endif
  201773. png_byte buf[7];
  201774. png_debug(1, "in png_write_tIME\n");
  201775. if (mod_time->month > 12 || mod_time->month < 1 ||
  201776. mod_time->day > 31 || mod_time->day < 1 ||
  201777. mod_time->hour > 23 || mod_time->second > 60)
  201778. {
  201779. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201780. return;
  201781. }
  201782. png_save_uint_16(buf, mod_time->year);
  201783. buf[2] = mod_time->month;
  201784. buf[3] = mod_time->day;
  201785. buf[4] = mod_time->hour;
  201786. buf[5] = mod_time->minute;
  201787. buf[6] = mod_time->second;
  201788. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201789. }
  201790. #endif
  201791. /* initializes the row writing capability of libpng */
  201792. void /* PRIVATE */
  201793. png_write_start_row(png_structp png_ptr)
  201794. {
  201795. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201796. #ifdef PNG_USE_LOCAL_ARRAYS
  201797. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201798. /* start of interlace block */
  201799. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201800. /* offset to next interlace block */
  201801. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201802. /* start of interlace block in the y direction */
  201803. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201804. /* offset to next interlace block in the y direction */
  201805. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201806. #endif
  201807. #endif
  201808. png_size_t buf_size;
  201809. png_debug(1, "in png_write_start_row\n");
  201810. buf_size = (png_size_t)(PNG_ROWBYTES(
  201811. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201812. /* set up row buffer */
  201813. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201814. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201815. #ifndef PNG_NO_WRITE_FILTERING
  201816. /* set up filtering buffer, if using this filter */
  201817. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201818. {
  201819. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201820. (png_ptr->rowbytes + 1));
  201821. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201822. }
  201823. /* We only need to keep the previous row if we are using one of these. */
  201824. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201825. {
  201826. /* set up previous row buffer */
  201827. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201828. png_memset(png_ptr->prev_row, 0, buf_size);
  201829. if (png_ptr->do_filter & PNG_FILTER_UP)
  201830. {
  201831. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201832. (png_ptr->rowbytes + 1));
  201833. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201834. }
  201835. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201836. {
  201837. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201838. (png_ptr->rowbytes + 1));
  201839. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201840. }
  201841. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201842. {
  201843. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201844. (png_ptr->rowbytes + 1));
  201845. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201846. }
  201847. #endif /* PNG_NO_WRITE_FILTERING */
  201848. }
  201849. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201850. /* if interlaced, we need to set up width and height of pass */
  201851. if (png_ptr->interlaced)
  201852. {
  201853. if (!(png_ptr->transformations & PNG_INTERLACE))
  201854. {
  201855. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201856. png_pass_ystart[0]) / png_pass_yinc[0];
  201857. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201858. png_pass_start[0]) / png_pass_inc[0];
  201859. }
  201860. else
  201861. {
  201862. png_ptr->num_rows = png_ptr->height;
  201863. png_ptr->usr_width = png_ptr->width;
  201864. }
  201865. }
  201866. else
  201867. #endif
  201868. {
  201869. png_ptr->num_rows = png_ptr->height;
  201870. png_ptr->usr_width = png_ptr->width;
  201871. }
  201872. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201873. png_ptr->zstream.next_out = png_ptr->zbuf;
  201874. }
  201875. /* Internal use only. Called when finished processing a row of data. */
  201876. void /* PRIVATE */
  201877. png_write_finish_row(png_structp png_ptr)
  201878. {
  201879. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201880. #ifdef PNG_USE_LOCAL_ARRAYS
  201881. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201882. /* start of interlace block */
  201883. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201884. /* offset to next interlace block */
  201885. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201886. /* start of interlace block in the y direction */
  201887. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201888. /* offset to next interlace block in the y direction */
  201889. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201890. #endif
  201891. #endif
  201892. int ret;
  201893. png_debug(1, "in png_write_finish_row\n");
  201894. /* next row */
  201895. png_ptr->row_number++;
  201896. /* see if we are done */
  201897. if (png_ptr->row_number < png_ptr->num_rows)
  201898. return;
  201899. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201900. /* if interlaced, go to next pass */
  201901. if (png_ptr->interlaced)
  201902. {
  201903. png_ptr->row_number = 0;
  201904. if (png_ptr->transformations & PNG_INTERLACE)
  201905. {
  201906. png_ptr->pass++;
  201907. }
  201908. else
  201909. {
  201910. /* loop until we find a non-zero width or height pass */
  201911. do
  201912. {
  201913. png_ptr->pass++;
  201914. if (png_ptr->pass >= 7)
  201915. break;
  201916. png_ptr->usr_width = (png_ptr->width +
  201917. png_pass_inc[png_ptr->pass] - 1 -
  201918. png_pass_start[png_ptr->pass]) /
  201919. png_pass_inc[png_ptr->pass];
  201920. png_ptr->num_rows = (png_ptr->height +
  201921. png_pass_yinc[png_ptr->pass] - 1 -
  201922. png_pass_ystart[png_ptr->pass]) /
  201923. png_pass_yinc[png_ptr->pass];
  201924. if (png_ptr->transformations & PNG_INTERLACE)
  201925. break;
  201926. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201927. }
  201928. /* reset the row above the image for the next pass */
  201929. if (png_ptr->pass < 7)
  201930. {
  201931. if (png_ptr->prev_row != NULL)
  201932. png_memset(png_ptr->prev_row, 0,
  201933. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201934. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201935. return;
  201936. }
  201937. }
  201938. #endif
  201939. /* if we get here, we've just written the last row, so we need
  201940. to flush the compressor */
  201941. do
  201942. {
  201943. /* tell the compressor we are done */
  201944. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201945. /* check for an error */
  201946. if (ret == Z_OK)
  201947. {
  201948. /* check to see if we need more room */
  201949. if (!(png_ptr->zstream.avail_out))
  201950. {
  201951. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201952. png_ptr->zstream.next_out = png_ptr->zbuf;
  201953. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201954. }
  201955. }
  201956. else if (ret != Z_STREAM_END)
  201957. {
  201958. if (png_ptr->zstream.msg != NULL)
  201959. png_error(png_ptr, png_ptr->zstream.msg);
  201960. else
  201961. png_error(png_ptr, "zlib error");
  201962. }
  201963. } while (ret != Z_STREAM_END);
  201964. /* write any extra space */
  201965. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201966. {
  201967. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201968. png_ptr->zstream.avail_out);
  201969. }
  201970. deflateReset(&png_ptr->zstream);
  201971. png_ptr->zstream.data_type = Z_BINARY;
  201972. }
  201973. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201974. /* Pick out the correct pixels for the interlace pass.
  201975. * The basic idea here is to go through the row with a source
  201976. * pointer and a destination pointer (sp and dp), and copy the
  201977. * correct pixels for the pass. As the row gets compacted,
  201978. * sp will always be >= dp, so we should never overwrite anything.
  201979. * See the default: case for the easiest code to understand.
  201980. */
  201981. void /* PRIVATE */
  201982. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201983. {
  201984. #ifdef PNG_USE_LOCAL_ARRAYS
  201985. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201986. /* start of interlace block */
  201987. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201988. /* offset to next interlace block */
  201989. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201990. #endif
  201991. png_debug(1, "in png_do_write_interlace\n");
  201992. /* we don't have to do anything on the last pass (6) */
  201993. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201994. if (row != NULL && row_info != NULL && pass < 6)
  201995. #else
  201996. if (pass < 6)
  201997. #endif
  201998. {
  201999. /* each pixel depth is handled separately */
  202000. switch (row_info->pixel_depth)
  202001. {
  202002. case 1:
  202003. {
  202004. png_bytep sp;
  202005. png_bytep dp;
  202006. int shift;
  202007. int d;
  202008. int value;
  202009. png_uint_32 i;
  202010. png_uint_32 row_width = row_info->width;
  202011. dp = row;
  202012. d = 0;
  202013. shift = 7;
  202014. for (i = png_pass_start[pass]; i < row_width;
  202015. i += png_pass_inc[pass])
  202016. {
  202017. sp = row + (png_size_t)(i >> 3);
  202018. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202019. d |= (value << shift);
  202020. if (shift == 0)
  202021. {
  202022. shift = 7;
  202023. *dp++ = (png_byte)d;
  202024. d = 0;
  202025. }
  202026. else
  202027. shift--;
  202028. }
  202029. if (shift != 7)
  202030. *dp = (png_byte)d;
  202031. break;
  202032. }
  202033. case 2:
  202034. {
  202035. png_bytep sp;
  202036. png_bytep dp;
  202037. int shift;
  202038. int d;
  202039. int value;
  202040. png_uint_32 i;
  202041. png_uint_32 row_width = row_info->width;
  202042. dp = row;
  202043. shift = 6;
  202044. d = 0;
  202045. for (i = png_pass_start[pass]; i < row_width;
  202046. i += png_pass_inc[pass])
  202047. {
  202048. sp = row + (png_size_t)(i >> 2);
  202049. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202050. d |= (value << shift);
  202051. if (shift == 0)
  202052. {
  202053. shift = 6;
  202054. *dp++ = (png_byte)d;
  202055. d = 0;
  202056. }
  202057. else
  202058. shift -= 2;
  202059. }
  202060. if (shift != 6)
  202061. *dp = (png_byte)d;
  202062. break;
  202063. }
  202064. case 4:
  202065. {
  202066. png_bytep sp;
  202067. png_bytep dp;
  202068. int shift;
  202069. int d;
  202070. int value;
  202071. png_uint_32 i;
  202072. png_uint_32 row_width = row_info->width;
  202073. dp = row;
  202074. shift = 4;
  202075. d = 0;
  202076. for (i = png_pass_start[pass]; i < row_width;
  202077. i += png_pass_inc[pass])
  202078. {
  202079. sp = row + (png_size_t)(i >> 1);
  202080. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202081. d |= (value << shift);
  202082. if (shift == 0)
  202083. {
  202084. shift = 4;
  202085. *dp++ = (png_byte)d;
  202086. d = 0;
  202087. }
  202088. else
  202089. shift -= 4;
  202090. }
  202091. if (shift != 4)
  202092. *dp = (png_byte)d;
  202093. break;
  202094. }
  202095. default:
  202096. {
  202097. png_bytep sp;
  202098. png_bytep dp;
  202099. png_uint_32 i;
  202100. png_uint_32 row_width = row_info->width;
  202101. png_size_t pixel_bytes;
  202102. /* start at the beginning */
  202103. dp = row;
  202104. /* find out how many bytes each pixel takes up */
  202105. pixel_bytes = (row_info->pixel_depth >> 3);
  202106. /* loop through the row, only looking at the pixels that
  202107. matter */
  202108. for (i = png_pass_start[pass]; i < row_width;
  202109. i += png_pass_inc[pass])
  202110. {
  202111. /* find out where the original pixel is */
  202112. sp = row + (png_size_t)i * pixel_bytes;
  202113. /* move the pixel */
  202114. if (dp != sp)
  202115. png_memcpy(dp, sp, pixel_bytes);
  202116. /* next pixel */
  202117. dp += pixel_bytes;
  202118. }
  202119. break;
  202120. }
  202121. }
  202122. /* set new row width */
  202123. row_info->width = (row_info->width +
  202124. png_pass_inc[pass] - 1 -
  202125. png_pass_start[pass]) /
  202126. png_pass_inc[pass];
  202127. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202128. row_info->width);
  202129. }
  202130. }
  202131. #endif
  202132. /* This filters the row, chooses which filter to use, if it has not already
  202133. * been specified by the application, and then writes the row out with the
  202134. * chosen filter.
  202135. */
  202136. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202137. #define PNG_HISHIFT 10
  202138. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202139. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202140. void /* PRIVATE */
  202141. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202142. {
  202143. png_bytep best_row;
  202144. #ifndef PNG_NO_WRITE_FILTER
  202145. png_bytep prev_row, row_buf;
  202146. png_uint_32 mins, bpp;
  202147. png_byte filter_to_do = png_ptr->do_filter;
  202148. png_uint_32 row_bytes = row_info->rowbytes;
  202149. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202150. int num_p_filters = (int)png_ptr->num_prev_filters;
  202151. #endif
  202152. png_debug(1, "in png_write_find_filter\n");
  202153. /* find out how many bytes offset each pixel is */
  202154. bpp = (row_info->pixel_depth + 7) >> 3;
  202155. prev_row = png_ptr->prev_row;
  202156. #endif
  202157. best_row = png_ptr->row_buf;
  202158. #ifndef PNG_NO_WRITE_FILTER
  202159. row_buf = best_row;
  202160. mins = PNG_MAXSUM;
  202161. /* The prediction method we use is to find which method provides the
  202162. * smallest value when summing the absolute values of the distances
  202163. * from zero, using anything >= 128 as negative numbers. This is known
  202164. * as the "minimum sum of absolute differences" heuristic. Other
  202165. * heuristics are the "weighted minimum sum of absolute differences"
  202166. * (experimental and can in theory improve compression), and the "zlib
  202167. * predictive" method (not implemented yet), which does test compressions
  202168. * of lines using different filter methods, and then chooses the
  202169. * (series of) filter(s) that give minimum compressed data size (VERY
  202170. * computationally expensive).
  202171. *
  202172. * GRR 980525: consider also
  202173. * (1) minimum sum of absolute differences from running average (i.e.,
  202174. * keep running sum of non-absolute differences & count of bytes)
  202175. * [track dispersion, too? restart average if dispersion too large?]
  202176. * (1b) minimum sum of absolute differences from sliding average, probably
  202177. * with window size <= deflate window (usually 32K)
  202178. * (2) minimum sum of squared differences from zero or running average
  202179. * (i.e., ~ root-mean-square approach)
  202180. */
  202181. /* We don't need to test the 'no filter' case if this is the only filter
  202182. * that has been chosen, as it doesn't actually do anything to the data.
  202183. */
  202184. if ((filter_to_do & PNG_FILTER_NONE) &&
  202185. filter_to_do != PNG_FILTER_NONE)
  202186. {
  202187. png_bytep rp;
  202188. png_uint_32 sum = 0;
  202189. png_uint_32 i;
  202190. int v;
  202191. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202192. {
  202193. v = *rp;
  202194. sum += (v < 128) ? v : 256 - v;
  202195. }
  202196. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202197. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202198. {
  202199. png_uint_32 sumhi, sumlo;
  202200. int j;
  202201. sumlo = sum & PNG_LOMASK;
  202202. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202203. /* Reduce the sum if we match any of the previous rows */
  202204. for (j = 0; j < num_p_filters; j++)
  202205. {
  202206. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202207. {
  202208. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202209. PNG_WEIGHT_SHIFT;
  202210. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202211. PNG_WEIGHT_SHIFT;
  202212. }
  202213. }
  202214. /* Factor in the cost of this filter (this is here for completeness,
  202215. * but it makes no sense to have a "cost" for the NONE filter, as
  202216. * it has the minimum possible computational cost - none).
  202217. */
  202218. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202219. PNG_COST_SHIFT;
  202220. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202221. PNG_COST_SHIFT;
  202222. if (sumhi > PNG_HIMASK)
  202223. sum = PNG_MAXSUM;
  202224. else
  202225. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202226. }
  202227. #endif
  202228. mins = sum;
  202229. }
  202230. /* sub filter */
  202231. if (filter_to_do == PNG_FILTER_SUB)
  202232. /* it's the only filter so no testing is needed */
  202233. {
  202234. png_bytep rp, lp, dp;
  202235. png_uint_32 i;
  202236. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202237. i++, rp++, dp++)
  202238. {
  202239. *dp = *rp;
  202240. }
  202241. for (lp = row_buf + 1; i < row_bytes;
  202242. i++, rp++, lp++, dp++)
  202243. {
  202244. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202245. }
  202246. best_row = png_ptr->sub_row;
  202247. }
  202248. else if (filter_to_do & PNG_FILTER_SUB)
  202249. {
  202250. png_bytep rp, dp, lp;
  202251. png_uint_32 sum = 0, lmins = mins;
  202252. png_uint_32 i;
  202253. int v;
  202254. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202255. /* We temporarily increase the "minimum sum" by the factor we
  202256. * would reduce the sum of this filter, so that we can do the
  202257. * early exit comparison without scaling the sum each time.
  202258. */
  202259. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202260. {
  202261. int j;
  202262. png_uint_32 lmhi, lmlo;
  202263. lmlo = lmins & PNG_LOMASK;
  202264. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202265. for (j = 0; j < num_p_filters; j++)
  202266. {
  202267. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202268. {
  202269. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202270. PNG_WEIGHT_SHIFT;
  202271. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202272. PNG_WEIGHT_SHIFT;
  202273. }
  202274. }
  202275. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202276. PNG_COST_SHIFT;
  202277. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202278. PNG_COST_SHIFT;
  202279. if (lmhi > PNG_HIMASK)
  202280. lmins = PNG_MAXSUM;
  202281. else
  202282. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202283. }
  202284. #endif
  202285. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202286. i++, rp++, dp++)
  202287. {
  202288. v = *dp = *rp;
  202289. sum += (v < 128) ? v : 256 - v;
  202290. }
  202291. for (lp = row_buf + 1; i < row_bytes;
  202292. i++, rp++, lp++, dp++)
  202293. {
  202294. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202295. sum += (v < 128) ? v : 256 - v;
  202296. if (sum > lmins) /* We are already worse, don't continue. */
  202297. break;
  202298. }
  202299. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202300. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202301. {
  202302. int j;
  202303. png_uint_32 sumhi, sumlo;
  202304. sumlo = sum & PNG_LOMASK;
  202305. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202306. for (j = 0; j < num_p_filters; j++)
  202307. {
  202308. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202309. {
  202310. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202311. PNG_WEIGHT_SHIFT;
  202312. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202313. PNG_WEIGHT_SHIFT;
  202314. }
  202315. }
  202316. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202317. PNG_COST_SHIFT;
  202318. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202319. PNG_COST_SHIFT;
  202320. if (sumhi > PNG_HIMASK)
  202321. sum = PNG_MAXSUM;
  202322. else
  202323. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202324. }
  202325. #endif
  202326. if (sum < mins)
  202327. {
  202328. mins = sum;
  202329. best_row = png_ptr->sub_row;
  202330. }
  202331. }
  202332. /* up filter */
  202333. if (filter_to_do == PNG_FILTER_UP)
  202334. {
  202335. png_bytep rp, dp, pp;
  202336. png_uint_32 i;
  202337. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202338. pp = prev_row + 1; i < row_bytes;
  202339. i++, rp++, pp++, dp++)
  202340. {
  202341. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202342. }
  202343. best_row = png_ptr->up_row;
  202344. }
  202345. else if (filter_to_do & PNG_FILTER_UP)
  202346. {
  202347. png_bytep rp, dp, pp;
  202348. png_uint_32 sum = 0, lmins = mins;
  202349. png_uint_32 i;
  202350. int v;
  202351. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202352. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202353. {
  202354. int j;
  202355. png_uint_32 lmhi, lmlo;
  202356. lmlo = lmins & PNG_LOMASK;
  202357. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202358. for (j = 0; j < num_p_filters; j++)
  202359. {
  202360. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202361. {
  202362. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202363. PNG_WEIGHT_SHIFT;
  202364. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202365. PNG_WEIGHT_SHIFT;
  202366. }
  202367. }
  202368. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202369. PNG_COST_SHIFT;
  202370. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202371. PNG_COST_SHIFT;
  202372. if (lmhi > PNG_HIMASK)
  202373. lmins = PNG_MAXSUM;
  202374. else
  202375. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202376. }
  202377. #endif
  202378. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202379. pp = prev_row + 1; i < row_bytes; i++)
  202380. {
  202381. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202382. sum += (v < 128) ? v : 256 - v;
  202383. if (sum > lmins) /* We are already worse, don't continue. */
  202384. break;
  202385. }
  202386. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202387. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202388. {
  202389. int j;
  202390. png_uint_32 sumhi, sumlo;
  202391. sumlo = sum & PNG_LOMASK;
  202392. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202393. for (j = 0; j < num_p_filters; j++)
  202394. {
  202395. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202396. {
  202397. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202398. PNG_WEIGHT_SHIFT;
  202399. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202400. PNG_WEIGHT_SHIFT;
  202401. }
  202402. }
  202403. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202404. PNG_COST_SHIFT;
  202405. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202406. PNG_COST_SHIFT;
  202407. if (sumhi > PNG_HIMASK)
  202408. sum = PNG_MAXSUM;
  202409. else
  202410. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202411. }
  202412. #endif
  202413. if (sum < mins)
  202414. {
  202415. mins = sum;
  202416. best_row = png_ptr->up_row;
  202417. }
  202418. }
  202419. /* avg filter */
  202420. if (filter_to_do == PNG_FILTER_AVG)
  202421. {
  202422. png_bytep rp, dp, pp, lp;
  202423. png_uint_32 i;
  202424. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202425. pp = prev_row + 1; i < bpp; i++)
  202426. {
  202427. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202428. }
  202429. for (lp = row_buf + 1; i < row_bytes; i++)
  202430. {
  202431. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202432. & 0xff);
  202433. }
  202434. best_row = png_ptr->avg_row;
  202435. }
  202436. else if (filter_to_do & PNG_FILTER_AVG)
  202437. {
  202438. png_bytep rp, dp, pp, lp;
  202439. png_uint_32 sum = 0, lmins = mins;
  202440. png_uint_32 i;
  202441. int v;
  202442. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202443. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202444. {
  202445. int j;
  202446. png_uint_32 lmhi, lmlo;
  202447. lmlo = lmins & PNG_LOMASK;
  202448. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202449. for (j = 0; j < num_p_filters; j++)
  202450. {
  202451. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202452. {
  202453. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202454. PNG_WEIGHT_SHIFT;
  202455. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202456. PNG_WEIGHT_SHIFT;
  202457. }
  202458. }
  202459. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202460. PNG_COST_SHIFT;
  202461. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202462. PNG_COST_SHIFT;
  202463. if (lmhi > PNG_HIMASK)
  202464. lmins = PNG_MAXSUM;
  202465. else
  202466. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202467. }
  202468. #endif
  202469. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202470. pp = prev_row + 1; i < bpp; i++)
  202471. {
  202472. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202473. sum += (v < 128) ? v : 256 - v;
  202474. }
  202475. for (lp = row_buf + 1; i < row_bytes; i++)
  202476. {
  202477. v = *dp++ =
  202478. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202479. sum += (v < 128) ? v : 256 - v;
  202480. if (sum > lmins) /* We are already worse, don't continue. */
  202481. break;
  202482. }
  202483. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202484. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202485. {
  202486. int j;
  202487. png_uint_32 sumhi, sumlo;
  202488. sumlo = sum & PNG_LOMASK;
  202489. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202490. for (j = 0; j < num_p_filters; j++)
  202491. {
  202492. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202493. {
  202494. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202495. PNG_WEIGHT_SHIFT;
  202496. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202497. PNG_WEIGHT_SHIFT;
  202498. }
  202499. }
  202500. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202501. PNG_COST_SHIFT;
  202502. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202503. PNG_COST_SHIFT;
  202504. if (sumhi > PNG_HIMASK)
  202505. sum = PNG_MAXSUM;
  202506. else
  202507. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202508. }
  202509. #endif
  202510. if (sum < mins)
  202511. {
  202512. mins = sum;
  202513. best_row = png_ptr->avg_row;
  202514. }
  202515. }
  202516. /* Paeth filter */
  202517. if (filter_to_do == PNG_FILTER_PAETH)
  202518. {
  202519. png_bytep rp, dp, pp, cp, lp;
  202520. png_uint_32 i;
  202521. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202522. pp = prev_row + 1; i < bpp; i++)
  202523. {
  202524. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202525. }
  202526. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202527. {
  202528. int a, b, c, pa, pb, pc, p;
  202529. b = *pp++;
  202530. c = *cp++;
  202531. a = *lp++;
  202532. p = b - c;
  202533. pc = a - c;
  202534. #ifdef PNG_USE_ABS
  202535. pa = abs(p);
  202536. pb = abs(pc);
  202537. pc = abs(p + pc);
  202538. #else
  202539. pa = p < 0 ? -p : p;
  202540. pb = pc < 0 ? -pc : pc;
  202541. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202542. #endif
  202543. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202544. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202545. }
  202546. best_row = png_ptr->paeth_row;
  202547. }
  202548. else if (filter_to_do & PNG_FILTER_PAETH)
  202549. {
  202550. png_bytep rp, dp, pp, cp, lp;
  202551. png_uint_32 sum = 0, lmins = mins;
  202552. png_uint_32 i;
  202553. int v;
  202554. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202555. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202556. {
  202557. int j;
  202558. png_uint_32 lmhi, lmlo;
  202559. lmlo = lmins & PNG_LOMASK;
  202560. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202561. for (j = 0; j < num_p_filters; j++)
  202562. {
  202563. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202564. {
  202565. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202566. PNG_WEIGHT_SHIFT;
  202567. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202568. PNG_WEIGHT_SHIFT;
  202569. }
  202570. }
  202571. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202572. PNG_COST_SHIFT;
  202573. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202574. PNG_COST_SHIFT;
  202575. if (lmhi > PNG_HIMASK)
  202576. lmins = PNG_MAXSUM;
  202577. else
  202578. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202579. }
  202580. #endif
  202581. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202582. pp = prev_row + 1; i < bpp; i++)
  202583. {
  202584. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202585. sum += (v < 128) ? v : 256 - v;
  202586. }
  202587. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202588. {
  202589. int a, b, c, pa, pb, pc, p;
  202590. b = *pp++;
  202591. c = *cp++;
  202592. a = *lp++;
  202593. #ifndef PNG_SLOW_PAETH
  202594. p = b - c;
  202595. pc = a - c;
  202596. #ifdef PNG_USE_ABS
  202597. pa = abs(p);
  202598. pb = abs(pc);
  202599. pc = abs(p + pc);
  202600. #else
  202601. pa = p < 0 ? -p : p;
  202602. pb = pc < 0 ? -pc : pc;
  202603. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202604. #endif
  202605. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202606. #else /* PNG_SLOW_PAETH */
  202607. p = a + b - c;
  202608. pa = abs(p - a);
  202609. pb = abs(p - b);
  202610. pc = abs(p - c);
  202611. if (pa <= pb && pa <= pc)
  202612. p = a;
  202613. else if (pb <= pc)
  202614. p = b;
  202615. else
  202616. p = c;
  202617. #endif /* PNG_SLOW_PAETH */
  202618. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202619. sum += (v < 128) ? v : 256 - v;
  202620. if (sum > lmins) /* We are already worse, don't continue. */
  202621. break;
  202622. }
  202623. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202624. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202625. {
  202626. int j;
  202627. png_uint_32 sumhi, sumlo;
  202628. sumlo = sum & PNG_LOMASK;
  202629. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202630. for (j = 0; j < num_p_filters; j++)
  202631. {
  202632. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202633. {
  202634. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202635. PNG_WEIGHT_SHIFT;
  202636. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202637. PNG_WEIGHT_SHIFT;
  202638. }
  202639. }
  202640. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202641. PNG_COST_SHIFT;
  202642. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202643. PNG_COST_SHIFT;
  202644. if (sumhi > PNG_HIMASK)
  202645. sum = PNG_MAXSUM;
  202646. else
  202647. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202648. }
  202649. #endif
  202650. if (sum < mins)
  202651. {
  202652. best_row = png_ptr->paeth_row;
  202653. }
  202654. }
  202655. #endif /* PNG_NO_WRITE_FILTER */
  202656. /* Do the actual writing of the filtered row data from the chosen filter. */
  202657. png_write_filtered_row(png_ptr, best_row);
  202658. #ifndef PNG_NO_WRITE_FILTER
  202659. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202660. /* Save the type of filter we picked this time for future calculations */
  202661. if (png_ptr->num_prev_filters > 0)
  202662. {
  202663. int j;
  202664. for (j = 1; j < num_p_filters; j++)
  202665. {
  202666. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202667. }
  202668. png_ptr->prev_filters[j] = best_row[0];
  202669. }
  202670. #endif
  202671. #endif /* PNG_NO_WRITE_FILTER */
  202672. }
  202673. /* Do the actual writing of a previously filtered row. */
  202674. void /* PRIVATE */
  202675. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202676. {
  202677. png_debug(1, "in png_write_filtered_row\n");
  202678. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202679. /* set up the zlib input buffer */
  202680. png_ptr->zstream.next_in = filtered_row;
  202681. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202682. /* repeat until we have compressed all the data */
  202683. do
  202684. {
  202685. int ret; /* return of zlib */
  202686. /* compress the data */
  202687. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202688. /* check for compression errors */
  202689. if (ret != Z_OK)
  202690. {
  202691. if (png_ptr->zstream.msg != NULL)
  202692. png_error(png_ptr, png_ptr->zstream.msg);
  202693. else
  202694. png_error(png_ptr, "zlib error");
  202695. }
  202696. /* see if it is time to write another IDAT */
  202697. if (!(png_ptr->zstream.avail_out))
  202698. {
  202699. /* write the IDAT and reset the zlib output buffer */
  202700. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202701. png_ptr->zstream.next_out = png_ptr->zbuf;
  202702. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202703. }
  202704. /* repeat until all data has been compressed */
  202705. } while (png_ptr->zstream.avail_in);
  202706. /* swap the current and previous rows */
  202707. if (png_ptr->prev_row != NULL)
  202708. {
  202709. png_bytep tptr;
  202710. tptr = png_ptr->prev_row;
  202711. png_ptr->prev_row = png_ptr->row_buf;
  202712. png_ptr->row_buf = tptr;
  202713. }
  202714. /* finish row - updates counters and flushes zlib if last row */
  202715. png_write_finish_row(png_ptr);
  202716. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202717. png_ptr->flush_rows++;
  202718. if (png_ptr->flush_dist > 0 &&
  202719. png_ptr->flush_rows >= png_ptr->flush_dist)
  202720. {
  202721. png_write_flush(png_ptr);
  202722. }
  202723. #endif
  202724. }
  202725. #endif /* PNG_WRITE_SUPPORTED */
  202726. /*** End of inlined file: pngwutil.c ***/
  202727. #else
  202728. extern "C"
  202729. {
  202730. #include <png.h>
  202731. #include <pngconf.h>
  202732. }
  202733. #endif
  202734. }
  202735. #undef max
  202736. #undef min
  202737. #if JUCE_MSVC
  202738. #pragma warning (pop)
  202739. #endif
  202740. BEGIN_JUCE_NAMESPACE
  202741. using ::calloc;
  202742. using ::malloc;
  202743. using ::free;
  202744. namespace PNGHelpers
  202745. {
  202746. using namespace pnglibNamespace;
  202747. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202748. {
  202749. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202750. }
  202751. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202752. {
  202753. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202754. }
  202755. struct PNGErrorStruct {};
  202756. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  202757. {
  202758. throw PNGErrorStruct();
  202759. }
  202760. }
  202761. PNGImageFormat::PNGImageFormat() {}
  202762. PNGImageFormat::~PNGImageFormat() {}
  202763. const String PNGImageFormat::getFormatName()
  202764. {
  202765. return "PNG";
  202766. }
  202767. bool PNGImageFormat::canUnderstand (InputStream& in)
  202768. {
  202769. const int bytesNeeded = 4;
  202770. char header [bytesNeeded];
  202771. return in.read (header, bytesNeeded) == bytesNeeded
  202772. && header[1] == 'P'
  202773. && header[2] == 'N'
  202774. && header[3] == 'G';
  202775. }
  202776. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202777. const Image juce_loadWithCoreImage (InputStream& input);
  202778. #endif
  202779. const Image PNGImageFormat::decodeImage (InputStream& in)
  202780. {
  202781. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202782. return juce_loadWithCoreImage (in);
  202783. #else
  202784. using namespace pnglibNamespace;
  202785. Image image;
  202786. png_structp pngReadStruct;
  202787. png_infop pngInfoStruct;
  202788. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202789. if (pngReadStruct != 0)
  202790. {
  202791. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202792. if (pngInfoStruct == 0)
  202793. {
  202794. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202795. return Image::null;
  202796. }
  202797. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202798. // read the header..
  202799. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202800. png_uint_32 width, height;
  202801. int bitDepth, colorType, interlaceType;
  202802. png_read_info (pngReadStruct, pngInfoStruct);
  202803. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202804. &width, &height,
  202805. &bitDepth, &colorType,
  202806. &interlaceType, 0, 0);
  202807. if (bitDepth == 16)
  202808. png_set_strip_16 (pngReadStruct);
  202809. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202810. png_set_expand (pngReadStruct);
  202811. if (bitDepth < 8)
  202812. png_set_expand (pngReadStruct);
  202813. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202814. png_set_expand (pngReadStruct);
  202815. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202816. png_set_gray_to_rgb (pngReadStruct);
  202817. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202818. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202819. || pngInfoStruct->num_trans > 0;
  202820. // Load the image into a temp buffer in the pnglib format..
  202821. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202822. {
  202823. HeapBlock <png_bytep> rows (height);
  202824. for (int y = (int) height; --y >= 0;)
  202825. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202826. png_read_image (pngReadStruct, rows);
  202827. png_read_end (pngReadStruct, pngInfoStruct);
  202828. }
  202829. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202830. // now convert the data to a juce image format..
  202831. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202832. (int) width, (int) height, hasAlphaChan);
  202833. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  202834. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202835. const Image::BitmapData destData (image, true);
  202836. uint8* srcRow = tempBuffer;
  202837. uint8* destRow = destData.data;
  202838. for (int y = 0; y < (int) height; ++y)
  202839. {
  202840. const uint8* src = srcRow;
  202841. srcRow += (width << 2);
  202842. uint8* dest = destRow;
  202843. destRow += destData.lineStride;
  202844. if (hasAlphaChan)
  202845. {
  202846. for (int i = (int) width; --i >= 0;)
  202847. {
  202848. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202849. ((PixelARGB*) dest)->premultiply();
  202850. dest += destData.pixelStride;
  202851. src += 4;
  202852. }
  202853. }
  202854. else
  202855. {
  202856. for (int i = (int) width; --i >= 0;)
  202857. {
  202858. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202859. dest += destData.pixelStride;
  202860. src += 4;
  202861. }
  202862. }
  202863. }
  202864. }
  202865. return image;
  202866. #endif
  202867. }
  202868. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202869. {
  202870. using namespace pnglibNamespace;
  202871. const int width = image.getWidth();
  202872. const int height = image.getHeight();
  202873. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202874. if (pngWriteStruct == 0)
  202875. return false;
  202876. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202877. if (pngInfoStruct == 0)
  202878. {
  202879. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202880. return false;
  202881. }
  202882. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202883. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202884. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202885. : PNG_COLOR_TYPE_RGB,
  202886. PNG_INTERLACE_NONE,
  202887. PNG_COMPRESSION_TYPE_BASE,
  202888. PNG_FILTER_TYPE_BASE);
  202889. HeapBlock <uint8> rowData (width * 4);
  202890. png_color_8 sig_bit;
  202891. sig_bit.red = 8;
  202892. sig_bit.green = 8;
  202893. sig_bit.blue = 8;
  202894. sig_bit.alpha = 8;
  202895. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202896. png_write_info (pngWriteStruct, pngInfoStruct);
  202897. png_set_shift (pngWriteStruct, &sig_bit);
  202898. png_set_packing (pngWriteStruct);
  202899. const Image::BitmapData srcData (image, false);
  202900. for (int y = 0; y < height; ++y)
  202901. {
  202902. uint8* dst = rowData;
  202903. const uint8* src = srcData.getLinePointer (y);
  202904. if (image.hasAlphaChannel())
  202905. {
  202906. for (int i = width; --i >= 0;)
  202907. {
  202908. PixelARGB p (*(const PixelARGB*) src);
  202909. p.unpremultiply();
  202910. *dst++ = p.getRed();
  202911. *dst++ = p.getGreen();
  202912. *dst++ = p.getBlue();
  202913. *dst++ = p.getAlpha();
  202914. src += srcData.pixelStride;
  202915. }
  202916. }
  202917. else
  202918. {
  202919. for (int i = width; --i >= 0;)
  202920. {
  202921. *dst++ = ((const PixelRGB*) src)->getRed();
  202922. *dst++ = ((const PixelRGB*) src)->getGreen();
  202923. *dst++ = ((const PixelRGB*) src)->getBlue();
  202924. src += srcData.pixelStride;
  202925. }
  202926. }
  202927. png_bytep rowPtr = rowData;
  202928. png_write_rows (pngWriteStruct, &rowPtr, 1);
  202929. }
  202930. png_write_end (pngWriteStruct, pngInfoStruct);
  202931. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202932. out.flush();
  202933. return true;
  202934. }
  202935. END_JUCE_NAMESPACE
  202936. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202937. #endif
  202938. //==============================================================================
  202939. #if JUCE_BUILD_NATIVE
  202940. // Non-public headers that are needed by more than one platform must be included
  202941. // before the platform-specific sections..
  202942. BEGIN_JUCE_NAMESPACE
  202943. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  202944. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  202945. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  202946. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202947. /**
  202948. Helper class that takes chunks of incoming midi bytes, packages them into
  202949. messages, and dispatches them to a midi callback.
  202950. */
  202951. class MidiDataConcatenator
  202952. {
  202953. public:
  202954. MidiDataConcatenator (const int initialBufferSize)
  202955. : pendingData (initialBufferSize),
  202956. pendingBytes (0), pendingDataTime (0)
  202957. {
  202958. }
  202959. void reset()
  202960. {
  202961. pendingBytes = 0;
  202962. pendingDataTime = 0;
  202963. }
  202964. void pushMidiData (const void* data, int numBytes, double time,
  202965. MidiInput* input, MidiInputCallback& callback)
  202966. {
  202967. const uint8* d = static_cast <const uint8*> (data);
  202968. while (numBytes > 0)
  202969. {
  202970. if (pendingBytes > 0 || d[0] == 0xf0)
  202971. {
  202972. processSysex (d, numBytes, time, input, callback);
  202973. }
  202974. else
  202975. {
  202976. int used = 0;
  202977. const MidiMessage m (d, numBytes, used, 0, time);
  202978. if (used <= 0)
  202979. break; // malformed message..
  202980. callback.handleIncomingMidiMessage (input, m);
  202981. numBytes -= used;
  202982. d += used;
  202983. }
  202984. }
  202985. }
  202986. private:
  202987. void processSysex (const uint8*& d, int& numBytes, double time,
  202988. MidiInput* input, MidiInputCallback& callback)
  202989. {
  202990. if (*d == 0xf0)
  202991. {
  202992. pendingBytes = 0;
  202993. pendingDataTime = time;
  202994. }
  202995. pendingData.ensureSize (pendingBytes + numBytes, false);
  202996. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  202997. uint8* dest = totalMessage + pendingBytes;
  202998. do
  202999. {
  203000. if (pendingBytes > 0 && *d >= 0x80)
  203001. {
  203002. if (*d >= 0xfa || *d == 0xf8)
  203003. {
  203004. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203005. ++d;
  203006. --numBytes;
  203007. }
  203008. else
  203009. {
  203010. if (*d == 0xf7)
  203011. {
  203012. *dest++ = *d++;
  203013. pendingBytes++;
  203014. --numBytes;
  203015. }
  203016. break;
  203017. }
  203018. }
  203019. else
  203020. {
  203021. *dest++ = *d++;
  203022. pendingBytes++;
  203023. --numBytes;
  203024. }
  203025. }
  203026. while (numBytes > 0);
  203027. if (pendingBytes > 0)
  203028. {
  203029. if (totalMessage [pendingBytes - 1] == 0xf7)
  203030. {
  203031. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203032. pendingBytes = 0;
  203033. }
  203034. else
  203035. {
  203036. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203037. }
  203038. }
  203039. }
  203040. MemoryBlock pendingData;
  203041. int pendingBytes;
  203042. double pendingDataTime;
  203043. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203044. };
  203045. #endif
  203046. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203047. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203048. END_JUCE_NAMESPACE
  203049. #if JUCE_WINDOWS
  203050. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203051. /*
  203052. This file wraps together all the win32-specific code, so that
  203053. we can include all the native headers just once, and compile all our
  203054. platform-specific stuff in one big lump, keeping it out of the way of
  203055. the rest of the codebase.
  203056. */
  203057. #if JUCE_WINDOWS
  203058. #undef JUCE_BUILD_NATIVE
  203059. #define JUCE_BUILD_NATIVE 1
  203060. BEGIN_JUCE_NAMESPACE
  203061. #define JUCE_INCLUDED_FILE 1
  203062. // Now include the actual code files..
  203063. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203064. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203065. // compiled on its own).
  203066. #if JUCE_INCLUDED_FILE
  203067. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203068. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203069. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203070. #ifndef DOXYGEN
  203071. // use with DynamicLibraryLoader to simplify importing functions
  203072. //
  203073. // functionName: function to import
  203074. // localFunctionName: name you want to use to actually call it (must be different)
  203075. // returnType: the return type
  203076. // object: the DynamicLibraryLoader to use
  203077. // params: list of params (bracketed)
  203078. //
  203079. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203080. typedef returnType (WINAPI *type##localFunctionName) params; \
  203081. type##localFunctionName localFunctionName \
  203082. = (type##localFunctionName)object.findProcAddress (#functionName);
  203083. // loads and unloads a DLL automatically
  203084. class JUCE_API DynamicLibraryLoader
  203085. {
  203086. public:
  203087. DynamicLibraryLoader (const String& name = String::empty);
  203088. ~DynamicLibraryLoader();
  203089. bool load (const String& libraryName);
  203090. void* findProcAddress (const String& functionName);
  203091. private:
  203092. void* libHandle;
  203093. };
  203094. #endif
  203095. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203096. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203097. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203098. : libHandle (0)
  203099. {
  203100. load (name);
  203101. }
  203102. DynamicLibraryLoader::~DynamicLibraryLoader()
  203103. {
  203104. load (String::empty);
  203105. }
  203106. bool DynamicLibraryLoader::load (const String& name)
  203107. {
  203108. FreeLibrary ((HMODULE) libHandle);
  203109. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203110. return libHandle != 0;
  203111. }
  203112. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203113. {
  203114. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203115. }
  203116. #endif
  203117. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203118. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203119. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203120. // compiled on its own).
  203121. #if JUCE_INCLUDED_FILE
  203122. void Logger::outputDebugString (const String& text)
  203123. {
  203124. OutputDebugString ((text + "\n").toUTF16());
  203125. }
  203126. static int64 hiResTicksPerSecond;
  203127. static double hiResTicksScaleFactor;
  203128. #if JUCE_USE_INTRINSICS
  203129. // CPU info functions using intrinsics...
  203130. #pragma intrinsic (__cpuid)
  203131. #pragma intrinsic (__rdtsc)
  203132. const String SystemStats::getCpuVendor()
  203133. {
  203134. int info [4];
  203135. __cpuid (info, 0);
  203136. char v [12];
  203137. memcpy (v, info + 1, 4);
  203138. memcpy (v + 4, info + 3, 4);
  203139. memcpy (v + 8, info + 2, 4);
  203140. return String (v, 12);
  203141. }
  203142. #else
  203143. // CPU info functions using old fashioned inline asm...
  203144. static void juce_getCpuVendor (char* const v)
  203145. {
  203146. int vendor[4];
  203147. zeromem (vendor, 16);
  203148. #ifdef JUCE_64BIT
  203149. #else
  203150. #ifndef __MINGW32__
  203151. __try
  203152. #endif
  203153. {
  203154. #if JUCE_GCC
  203155. unsigned int dummy = 0;
  203156. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203157. #else
  203158. __asm
  203159. {
  203160. mov eax, 0
  203161. cpuid
  203162. mov [vendor], ebx
  203163. mov [vendor + 4], edx
  203164. mov [vendor + 8], ecx
  203165. }
  203166. #endif
  203167. }
  203168. #ifndef __MINGW32__
  203169. __except (EXCEPTION_EXECUTE_HANDLER)
  203170. {
  203171. *v = 0;
  203172. }
  203173. #endif
  203174. #endif
  203175. memcpy (v, vendor, 16);
  203176. }
  203177. const String SystemStats::getCpuVendor()
  203178. {
  203179. char v [16];
  203180. juce_getCpuVendor (v);
  203181. return String (v, 16);
  203182. }
  203183. #endif
  203184. void SystemStats::initialiseStats()
  203185. {
  203186. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203187. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203188. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203189. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203190. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203191. #else
  203192. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203193. #endif
  203194. {
  203195. SYSTEM_INFO systemInfo;
  203196. GetSystemInfo (&systemInfo);
  203197. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203198. }
  203199. LARGE_INTEGER f;
  203200. QueryPerformanceFrequency (&f);
  203201. hiResTicksPerSecond = f.QuadPart;
  203202. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203203. String s (SystemStats::getJUCEVersion());
  203204. const MMRESULT res = timeBeginPeriod (1);
  203205. (void) res;
  203206. jassert (res == TIMERR_NOERROR);
  203207. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203208. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203209. #endif
  203210. }
  203211. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203212. {
  203213. OSVERSIONINFO info;
  203214. info.dwOSVersionInfoSize = sizeof (info);
  203215. GetVersionEx (&info);
  203216. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203217. {
  203218. switch (info.dwMajorVersion)
  203219. {
  203220. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203221. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203222. default: jassertfalse; break; // !! not a supported OS!
  203223. }
  203224. }
  203225. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203226. {
  203227. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203228. return Win98;
  203229. }
  203230. return UnknownOS;
  203231. }
  203232. const String SystemStats::getOperatingSystemName()
  203233. {
  203234. const char* name = "Unknown OS";
  203235. switch (getOperatingSystemType())
  203236. {
  203237. case Windows7: name = "Windows 7"; break;
  203238. case WinVista: name = "Windows Vista"; break;
  203239. case WinXP: name = "Windows XP"; break;
  203240. case Win2000: name = "Windows 2000"; break;
  203241. case Win98: name = "Windows 98"; break;
  203242. default: jassertfalse; break; // !! new type of OS?
  203243. }
  203244. return name;
  203245. }
  203246. bool SystemStats::isOperatingSystem64Bit()
  203247. {
  203248. #ifdef _WIN64
  203249. return true;
  203250. #else
  203251. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203252. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203253. BOOL isWow64 = FALSE;
  203254. return (fnIsWow64Process != 0)
  203255. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203256. && (isWow64 != FALSE);
  203257. #endif
  203258. }
  203259. int SystemStats::getMemorySizeInMegabytes()
  203260. {
  203261. MEMORYSTATUSEX mem;
  203262. mem.dwLength = sizeof (mem);
  203263. GlobalMemoryStatusEx (&mem);
  203264. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203265. }
  203266. uint32 juce_millisecondsSinceStartup() throw()
  203267. {
  203268. return (uint32) timeGetTime();
  203269. }
  203270. int64 Time::getHighResolutionTicks() throw()
  203271. {
  203272. LARGE_INTEGER ticks;
  203273. QueryPerformanceCounter (&ticks);
  203274. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203275. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203276. // fix for a very obscure PCI hardware bug that can make the counter
  203277. // sometimes jump forwards by a few seconds..
  203278. static int64 hiResTicksOffset = 0;
  203279. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203280. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203281. hiResTicksOffset = newOffset;
  203282. return ticks.QuadPart + hiResTicksOffset;
  203283. }
  203284. double Time::getMillisecondCounterHiRes() throw()
  203285. {
  203286. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203287. }
  203288. int64 Time::getHighResolutionTicksPerSecond() throw()
  203289. {
  203290. return hiResTicksPerSecond;
  203291. }
  203292. static int64 juce_getClockCycleCounter() throw()
  203293. {
  203294. #if JUCE_USE_INTRINSICS
  203295. // MS intrinsics version...
  203296. return __rdtsc();
  203297. #elif JUCE_GCC
  203298. // GNU inline asm version...
  203299. unsigned int hi = 0, lo = 0;
  203300. __asm__ __volatile__ (
  203301. "xor %%eax, %%eax \n\
  203302. xor %%edx, %%edx \n\
  203303. rdtsc \n\
  203304. movl %%eax, %[lo] \n\
  203305. movl %%edx, %[hi]"
  203306. :
  203307. : [hi] "m" (hi),
  203308. [lo] "m" (lo)
  203309. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203310. return (int64) ((((uint64) hi) << 32) | lo);
  203311. #else
  203312. // MSVC inline asm version...
  203313. unsigned int hi = 0, lo = 0;
  203314. __asm
  203315. {
  203316. xor eax, eax
  203317. xor edx, edx
  203318. rdtsc
  203319. mov lo, eax
  203320. mov hi, edx
  203321. }
  203322. return (int64) ((((uint64) hi) << 32) | lo);
  203323. #endif
  203324. }
  203325. int SystemStats::getCpuSpeedInMegaherz()
  203326. {
  203327. const int64 cycles = juce_getClockCycleCounter();
  203328. const uint32 millis = Time::getMillisecondCounter();
  203329. int lastResult = 0;
  203330. for (;;)
  203331. {
  203332. int n = 1000000;
  203333. while (--n > 0) {}
  203334. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203335. const int64 cyclesNow = juce_getClockCycleCounter();
  203336. if (millisElapsed > 80)
  203337. {
  203338. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203339. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203340. return newResult;
  203341. lastResult = newResult;
  203342. }
  203343. }
  203344. }
  203345. bool Time::setSystemTimeToThisTime() const
  203346. {
  203347. SYSTEMTIME st;
  203348. st.wDayOfWeek = 0;
  203349. st.wYear = (WORD) getYear();
  203350. st.wMonth = (WORD) (getMonth() + 1);
  203351. st.wDay = (WORD) getDayOfMonth();
  203352. st.wHour = (WORD) getHours();
  203353. st.wMinute = (WORD) getMinutes();
  203354. st.wSecond = (WORD) getSeconds();
  203355. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203356. // do this twice because of daylight saving conversion problems - the
  203357. // first one sets it up, the second one kicks it in.
  203358. return SetLocalTime (&st) != 0
  203359. && SetLocalTime (&st) != 0;
  203360. }
  203361. int SystemStats::getPageSize()
  203362. {
  203363. SYSTEM_INFO systemInfo;
  203364. GetSystemInfo (&systemInfo);
  203365. return systemInfo.dwPageSize;
  203366. }
  203367. const String SystemStats::getLogonName()
  203368. {
  203369. TCHAR text [256];
  203370. DWORD len = numElementsInArray (text) - 2;
  203371. zerostruct (text);
  203372. GetUserName (text, &len);
  203373. return String (text, len);
  203374. }
  203375. const String SystemStats::getFullUserName()
  203376. {
  203377. return getLogonName();
  203378. }
  203379. #endif
  203380. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203381. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203382. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203383. // compiled on its own).
  203384. #if JUCE_INCLUDED_FILE
  203385. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203386. extern HWND juce_messageWindowHandle;
  203387. #endif
  203388. #if ! JUCE_USE_INTRINSICS
  203389. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203390. // older ones we have to actually call the ops as win32 functions..
  203391. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203392. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203393. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203394. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203395. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203396. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203397. {
  203398. jassertfalse; // This operation isn't available in old MS compiler versions!
  203399. __int64 oldValue = *value;
  203400. if (oldValue == valueToCompare)
  203401. *value = newValue;
  203402. return oldValue;
  203403. }
  203404. #endif
  203405. CriticalSection::CriticalSection() throw()
  203406. {
  203407. // (just to check the MS haven't changed this structure and broken things...)
  203408. #if JUCE_VC7_OR_EARLIER
  203409. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203410. #else
  203411. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203412. #endif
  203413. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203414. }
  203415. CriticalSection::~CriticalSection() throw()
  203416. {
  203417. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203418. }
  203419. void CriticalSection::enter() const throw()
  203420. {
  203421. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203422. }
  203423. bool CriticalSection::tryEnter() const throw()
  203424. {
  203425. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203426. }
  203427. void CriticalSection::exit() const throw()
  203428. {
  203429. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203430. }
  203431. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203432. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203433. {
  203434. }
  203435. WaitableEvent::~WaitableEvent() throw()
  203436. {
  203437. CloseHandle (internal);
  203438. }
  203439. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203440. {
  203441. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203442. }
  203443. void WaitableEvent::signal() const throw()
  203444. {
  203445. SetEvent (internal);
  203446. }
  203447. void WaitableEvent::reset() const throw()
  203448. {
  203449. ResetEvent (internal);
  203450. }
  203451. void JUCE_API juce_threadEntryPoint (void*);
  203452. static unsigned int __stdcall threadEntryProc (void* userData)
  203453. {
  203454. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203455. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203456. GetCurrentThreadId(), TRUE);
  203457. #endif
  203458. juce_threadEntryPoint (userData);
  203459. _endthreadex (0);
  203460. return 0;
  203461. }
  203462. void Thread::launchThread()
  203463. {
  203464. unsigned int newThreadId;
  203465. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203466. threadId_ = (ThreadID) newThreadId;
  203467. }
  203468. void Thread::closeThreadHandle()
  203469. {
  203470. CloseHandle ((HANDLE) threadHandle_);
  203471. threadId_ = 0;
  203472. threadHandle_ = 0;
  203473. }
  203474. void Thread::killThread()
  203475. {
  203476. if (threadHandle_ != 0)
  203477. {
  203478. #if JUCE_DEBUG
  203479. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203480. #endif
  203481. TerminateThread (threadHandle_, 0);
  203482. }
  203483. }
  203484. void Thread::setCurrentThreadName (const String& name)
  203485. {
  203486. #if JUCE_DEBUG && JUCE_MSVC
  203487. struct
  203488. {
  203489. DWORD dwType;
  203490. LPCSTR szName;
  203491. DWORD dwThreadID;
  203492. DWORD dwFlags;
  203493. } info;
  203494. info.dwType = 0x1000;
  203495. info.szName = name.toCString();
  203496. info.dwThreadID = GetCurrentThreadId();
  203497. info.dwFlags = 0;
  203498. __try
  203499. {
  203500. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203501. }
  203502. __except (EXCEPTION_CONTINUE_EXECUTION)
  203503. {}
  203504. #else
  203505. (void) name;
  203506. #endif
  203507. }
  203508. Thread::ThreadID Thread::getCurrentThreadId()
  203509. {
  203510. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203511. }
  203512. bool Thread::setThreadPriority (void* handle, int priority)
  203513. {
  203514. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203515. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203516. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203517. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203518. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203519. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203520. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203521. if (handle == 0)
  203522. handle = GetCurrentThread();
  203523. return SetThreadPriority (handle, pri) != FALSE;
  203524. }
  203525. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203526. {
  203527. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203528. }
  203529. struct SleepEvent
  203530. {
  203531. SleepEvent()
  203532. : handle (CreateEvent (0, 0, 0,
  203533. #if JUCE_DEBUG
  203534. _T("Juce Sleep Event")))
  203535. #else
  203536. 0))
  203537. #endif
  203538. {
  203539. }
  203540. HANDLE handle;
  203541. };
  203542. static SleepEvent sleepEvent;
  203543. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203544. {
  203545. if (millisecs >= 10)
  203546. {
  203547. Sleep (millisecs);
  203548. }
  203549. else
  203550. {
  203551. // unlike Sleep() this is guaranteed to return to the current thread after
  203552. // the time expires, so we'll use this for short waits, which are more likely
  203553. // to need to be accurate
  203554. WaitForSingleObject (sleepEvent.handle, millisecs);
  203555. }
  203556. }
  203557. void Thread::yield()
  203558. {
  203559. Sleep (0);
  203560. }
  203561. static int lastProcessPriority = -1;
  203562. // called by WindowDriver because Windows does wierd things to process priority
  203563. // when you swap apps, and this forces an update when the app is brought to the front.
  203564. void juce_repeatLastProcessPriority()
  203565. {
  203566. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203567. {
  203568. DWORD p;
  203569. switch (lastProcessPriority)
  203570. {
  203571. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203572. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203573. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203574. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203575. default: jassertfalse; return; // bad priority value
  203576. }
  203577. SetPriorityClass (GetCurrentProcess(), p);
  203578. }
  203579. }
  203580. void Process::setPriority (ProcessPriority prior)
  203581. {
  203582. if (lastProcessPriority != (int) prior)
  203583. {
  203584. lastProcessPriority = (int) prior;
  203585. juce_repeatLastProcessPriority();
  203586. }
  203587. }
  203588. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203589. {
  203590. return IsDebuggerPresent() != FALSE;
  203591. }
  203592. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203593. {
  203594. return juce_isRunningUnderDebugger();
  203595. }
  203596. void Process::raisePrivilege()
  203597. {
  203598. jassertfalse; // xxx not implemented
  203599. }
  203600. void Process::lowerPrivilege()
  203601. {
  203602. jassertfalse; // xxx not implemented
  203603. }
  203604. void Process::terminate()
  203605. {
  203606. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203607. _CrtDumpMemoryLeaks();
  203608. #endif
  203609. // bullet in the head in case there's a problem shutting down..
  203610. ExitProcess (0);
  203611. }
  203612. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203613. {
  203614. void* result = 0;
  203615. JUCE_TRY
  203616. {
  203617. result = LoadLibrary (name.toUTF16());
  203618. }
  203619. JUCE_CATCH_ALL
  203620. return result;
  203621. }
  203622. void PlatformUtilities::freeDynamicLibrary (void* h)
  203623. {
  203624. JUCE_TRY
  203625. {
  203626. if (h != 0)
  203627. FreeLibrary ((HMODULE) h);
  203628. }
  203629. JUCE_CATCH_ALL
  203630. }
  203631. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203632. {
  203633. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203634. }
  203635. class InterProcessLock::Pimpl
  203636. {
  203637. public:
  203638. Pimpl (const String& name, const int timeOutMillisecs)
  203639. : handle (0), refCount (1)
  203640. {
  203641. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  203642. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203643. {
  203644. if (timeOutMillisecs == 0)
  203645. {
  203646. close();
  203647. return;
  203648. }
  203649. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203650. {
  203651. case WAIT_OBJECT_0:
  203652. case WAIT_ABANDONED:
  203653. break;
  203654. case WAIT_TIMEOUT:
  203655. default:
  203656. close();
  203657. break;
  203658. }
  203659. }
  203660. }
  203661. ~Pimpl()
  203662. {
  203663. close();
  203664. }
  203665. void close()
  203666. {
  203667. if (handle != 0)
  203668. {
  203669. ReleaseMutex (handle);
  203670. CloseHandle (handle);
  203671. handle = 0;
  203672. }
  203673. }
  203674. HANDLE handle;
  203675. int refCount;
  203676. };
  203677. InterProcessLock::InterProcessLock (const String& name_)
  203678. : name (name_)
  203679. {
  203680. }
  203681. InterProcessLock::~InterProcessLock()
  203682. {
  203683. }
  203684. bool InterProcessLock::enter (const int timeOutMillisecs)
  203685. {
  203686. const ScopedLock sl (lock);
  203687. if (pimpl == 0)
  203688. {
  203689. pimpl = new Pimpl (name, timeOutMillisecs);
  203690. if (pimpl->handle == 0)
  203691. pimpl = 0;
  203692. }
  203693. else
  203694. {
  203695. pimpl->refCount++;
  203696. }
  203697. return pimpl != 0;
  203698. }
  203699. void InterProcessLock::exit()
  203700. {
  203701. const ScopedLock sl (lock);
  203702. // Trying to release the lock too many times!
  203703. jassert (pimpl != 0);
  203704. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203705. pimpl = 0;
  203706. }
  203707. #endif
  203708. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203709. /*** Start of inlined file: juce_win32_Files.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. #ifndef CSIDL_MYMUSIC
  203714. #define CSIDL_MYMUSIC 0x000d
  203715. #endif
  203716. #ifndef CSIDL_MYVIDEO
  203717. #define CSIDL_MYVIDEO 0x000e
  203718. #endif
  203719. #ifndef INVALID_FILE_ATTRIBUTES
  203720. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203721. #endif
  203722. namespace WindowsFileHelpers
  203723. {
  203724. int64 fileTimeToTime (const FILETIME* const ft)
  203725. {
  203726. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203727. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203728. }
  203729. void timeToFileTime (const int64 time, FILETIME* const ft)
  203730. {
  203731. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203732. }
  203733. const String getDriveFromPath (String path)
  203734. {
  203735. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  203736. if (PathStripToRoot (p))
  203737. return String ((const WCHAR*) p);
  203738. return path;
  203739. }
  203740. int64 getDiskSpaceInfo (const String& path, const bool total)
  203741. {
  203742. ULARGE_INTEGER spc, tot, totFree;
  203743. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  203744. return total ? (int64) tot.QuadPart
  203745. : (int64) spc.QuadPart;
  203746. return 0;
  203747. }
  203748. unsigned int getWindowsDriveType (const String& path)
  203749. {
  203750. return GetDriveType (getDriveFromPath (path).toUTF16());
  203751. }
  203752. const File getSpecialFolderPath (int type)
  203753. {
  203754. WCHAR path [MAX_PATH + 256];
  203755. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203756. return File (String (path));
  203757. return File::nonexistent;
  203758. }
  203759. }
  203760. const juce_wchar File::separator = '\\';
  203761. const String File::separatorString ("\\");
  203762. bool File::exists() const
  203763. {
  203764. return fullPath.isNotEmpty()
  203765. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  203766. }
  203767. bool File::existsAsFile() const
  203768. {
  203769. return fullPath.isNotEmpty()
  203770. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203771. }
  203772. bool File::isDirectory() const
  203773. {
  203774. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203775. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203776. }
  203777. bool File::hasWriteAccess() const
  203778. {
  203779. if (exists())
  203780. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  203781. // on windows, it seems that even read-only directories can still be written into,
  203782. // so checking the parent directory's permissions would return the wrong result..
  203783. return true;
  203784. }
  203785. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203786. {
  203787. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203788. if (attr == INVALID_FILE_ATTRIBUTES)
  203789. return false;
  203790. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203791. return true;
  203792. if (shouldBeReadOnly)
  203793. attr |= FILE_ATTRIBUTE_READONLY;
  203794. else
  203795. attr &= ~FILE_ATTRIBUTE_READONLY;
  203796. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  203797. }
  203798. bool File::isHidden() const
  203799. {
  203800. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203801. }
  203802. bool File::deleteFile() const
  203803. {
  203804. if (! exists())
  203805. return true;
  203806. else if (isDirectory())
  203807. return RemoveDirectory (fullPath.toUTF16()) != 0;
  203808. else
  203809. return DeleteFile (fullPath.toUTF16()) != 0;
  203810. }
  203811. bool File::moveToTrash() const
  203812. {
  203813. if (! exists())
  203814. return true;
  203815. SHFILEOPSTRUCT fos;
  203816. zerostruct (fos);
  203817. // The string we pass in must be double null terminated..
  203818. String doubleNullTermPath (getFullPathName() + " ");
  203819. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  203820. p [getFullPathName().length()] = 0;
  203821. fos.wFunc = FO_DELETE;
  203822. fos.pFrom = p;
  203823. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203824. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203825. return SHFileOperation (&fos) == 0;
  203826. }
  203827. bool File::copyInternal (const File& dest) const
  203828. {
  203829. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  203830. }
  203831. bool File::moveInternal (const File& dest) const
  203832. {
  203833. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  203834. }
  203835. void File::createDirectoryInternal (const String& fileName) const
  203836. {
  203837. CreateDirectory (fileName.toUTF16(), 0);
  203838. }
  203839. int64 juce_fileSetPosition (void* handle, int64 pos)
  203840. {
  203841. LARGE_INTEGER li;
  203842. li.QuadPart = pos;
  203843. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203844. return li.QuadPart;
  203845. }
  203846. void FileInputStream::openHandle()
  203847. {
  203848. totalSize = file.getSize();
  203849. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203850. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203851. if (h != INVALID_HANDLE_VALUE)
  203852. fileHandle = (void*) h;
  203853. }
  203854. void FileInputStream::closeHandle()
  203855. {
  203856. CloseHandle ((HANDLE) fileHandle);
  203857. }
  203858. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  203859. {
  203860. if (fileHandle != 0)
  203861. {
  203862. DWORD actualNum = 0;
  203863. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203864. return (size_t) actualNum;
  203865. }
  203866. return 0;
  203867. }
  203868. void FileOutputStream::openHandle()
  203869. {
  203870. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203871. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203872. if (h != INVALID_HANDLE_VALUE)
  203873. {
  203874. LARGE_INTEGER li;
  203875. li.QuadPart = 0;
  203876. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  203877. if (li.LowPart != INVALID_SET_FILE_POINTER)
  203878. {
  203879. fileHandle = (void*) h;
  203880. currentPosition = li.QuadPart;
  203881. }
  203882. }
  203883. }
  203884. void FileOutputStream::closeHandle()
  203885. {
  203886. CloseHandle ((HANDLE) fileHandle);
  203887. }
  203888. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  203889. {
  203890. if (fileHandle != 0)
  203891. {
  203892. DWORD actualNum = 0;
  203893. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203894. return (int) actualNum;
  203895. }
  203896. return 0;
  203897. }
  203898. void FileOutputStream::flushInternal()
  203899. {
  203900. if (fileHandle != 0)
  203901. FlushFileBuffers ((HANDLE) fileHandle);
  203902. }
  203903. int64 File::getSize() const
  203904. {
  203905. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203906. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203907. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203908. return 0;
  203909. }
  203910. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203911. {
  203912. using namespace WindowsFileHelpers;
  203913. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203914. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203915. {
  203916. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203917. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203918. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203919. }
  203920. else
  203921. {
  203922. creationTime = accessTime = modificationTime = 0;
  203923. }
  203924. }
  203925. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203926. {
  203927. using namespace WindowsFileHelpers;
  203928. bool ok = false;
  203929. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203930. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203931. if (h != INVALID_HANDLE_VALUE)
  203932. {
  203933. FILETIME m, a, c;
  203934. timeToFileTime (modificationTime, &m);
  203935. timeToFileTime (accessTime, &a);
  203936. timeToFileTime (creationTime, &c);
  203937. ok = SetFileTime (h,
  203938. creationTime > 0 ? &c : 0,
  203939. accessTime > 0 ? &a : 0,
  203940. modificationTime > 0 ? &m : 0) != 0;
  203941. CloseHandle (h);
  203942. }
  203943. return ok;
  203944. }
  203945. void File::findFileSystemRoots (Array<File>& destArray)
  203946. {
  203947. TCHAR buffer [2048];
  203948. buffer[0] = 0;
  203949. buffer[1] = 0;
  203950. GetLogicalDriveStrings (2048, buffer);
  203951. const TCHAR* n = buffer;
  203952. StringArray roots;
  203953. while (*n != 0)
  203954. {
  203955. roots.add (String (n));
  203956. while (*n++ != 0)
  203957. {}
  203958. }
  203959. roots.sort (true);
  203960. for (int i = 0; i < roots.size(); ++i)
  203961. destArray.add (roots [i]);
  203962. }
  203963. const String File::getVolumeLabel() const
  203964. {
  203965. TCHAR dest[64];
  203966. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  203967. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203968. dest[0] = 0;
  203969. return dest;
  203970. }
  203971. int File::getVolumeSerialNumber() const
  203972. {
  203973. TCHAR dest[64];
  203974. DWORD serialNum;
  203975. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  203976. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203977. return 0;
  203978. return (int) serialNum;
  203979. }
  203980. int64 File::getBytesFreeOnVolume() const
  203981. {
  203982. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  203983. }
  203984. int64 File::getVolumeTotalSize() const
  203985. {
  203986. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  203987. }
  203988. bool File::isOnCDRomDrive() const
  203989. {
  203990. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203991. }
  203992. bool File::isOnHardDisk() const
  203993. {
  203994. if (fullPath.isEmpty())
  203995. return false;
  203996. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  203997. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203998. return n != DRIVE_REMOVABLE;
  203999. else
  204000. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204001. }
  204002. bool File::isOnRemovableDrive() const
  204003. {
  204004. if (fullPath.isEmpty())
  204005. return false;
  204006. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204007. return n == DRIVE_CDROM
  204008. || n == DRIVE_REMOTE
  204009. || n == DRIVE_REMOVABLE
  204010. || n == DRIVE_RAMDISK;
  204011. }
  204012. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204013. {
  204014. int csidlType = 0;
  204015. switch (type)
  204016. {
  204017. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204018. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204019. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204020. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204021. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204022. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204023. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204024. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204025. case tempDirectory:
  204026. {
  204027. WCHAR dest [2048];
  204028. dest[0] = 0;
  204029. GetTempPath (numElementsInArray (dest), dest);
  204030. return File (String (dest));
  204031. }
  204032. case invokedExecutableFile:
  204033. case currentExecutableFile:
  204034. case currentApplicationFile:
  204035. {
  204036. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204037. WCHAR dest [MAX_PATH + 256];
  204038. dest[0] = 0;
  204039. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204040. return File (String (dest));
  204041. }
  204042. case hostApplicationPath:
  204043. {
  204044. WCHAR dest [MAX_PATH + 256];
  204045. dest[0] = 0;
  204046. GetModuleFileName (0, dest, numElementsInArray (dest));
  204047. return File (String (dest));
  204048. }
  204049. default:
  204050. jassertfalse; // unknown type?
  204051. return File::nonexistent;
  204052. }
  204053. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204054. }
  204055. const File File::getCurrentWorkingDirectory()
  204056. {
  204057. WCHAR dest [MAX_PATH + 256];
  204058. dest[0] = 0;
  204059. GetCurrentDirectory (numElementsInArray (dest), dest);
  204060. return File (String (dest));
  204061. }
  204062. bool File::setAsCurrentWorkingDirectory() const
  204063. {
  204064. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204065. }
  204066. const String File::getVersion() const
  204067. {
  204068. String result;
  204069. DWORD handle = 0;
  204070. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204071. HeapBlock<char> buffer;
  204072. buffer.calloc (bufferSize);
  204073. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204074. {
  204075. VS_FIXEDFILEINFO* vffi;
  204076. UINT len = 0;
  204077. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204078. {
  204079. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204080. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204081. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204082. << (int) LOWORD (vffi->dwFileVersionLS);
  204083. }
  204084. }
  204085. return result;
  204086. }
  204087. const File File::getLinkedTarget() const
  204088. {
  204089. File result (*this);
  204090. String p (getFullPathName());
  204091. if (! exists())
  204092. p += ".lnk";
  204093. else if (getFileExtension() != ".lnk")
  204094. return result;
  204095. ComSmartPtr <IShellLink> shellLink;
  204096. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204097. {
  204098. ComSmartPtr <IPersistFile> persistFile;
  204099. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204100. {
  204101. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204102. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204103. {
  204104. WIN32_FIND_DATA winFindData;
  204105. WCHAR resolvedPath [MAX_PATH];
  204106. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204107. result = File (resolvedPath);
  204108. }
  204109. }
  204110. }
  204111. return result;
  204112. }
  204113. class DirectoryIterator::NativeIterator::Pimpl
  204114. {
  204115. public:
  204116. Pimpl (const File& directory, const String& wildCard)
  204117. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204118. handle (INVALID_HANDLE_VALUE)
  204119. {
  204120. }
  204121. ~Pimpl()
  204122. {
  204123. if (handle != INVALID_HANDLE_VALUE)
  204124. FindClose (handle);
  204125. }
  204126. bool next (String& filenameFound,
  204127. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204128. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204129. {
  204130. using namespace WindowsFileHelpers;
  204131. WIN32_FIND_DATA findData;
  204132. if (handle == INVALID_HANDLE_VALUE)
  204133. {
  204134. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204135. if (handle == INVALID_HANDLE_VALUE)
  204136. return false;
  204137. }
  204138. else
  204139. {
  204140. if (FindNextFile (handle, &findData) == 0)
  204141. return false;
  204142. }
  204143. filenameFound = findData.cFileName;
  204144. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204145. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204146. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204147. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204148. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204149. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204150. return true;
  204151. }
  204152. private:
  204153. const String directoryWithWildCard;
  204154. HANDLE handle;
  204155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204156. };
  204157. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204158. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204159. {
  204160. }
  204161. DirectoryIterator::NativeIterator::~NativeIterator()
  204162. {
  204163. }
  204164. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204165. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204166. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204167. {
  204168. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204169. }
  204170. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204171. {
  204172. HINSTANCE hInstance = 0;
  204173. JUCE_TRY
  204174. {
  204175. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204176. }
  204177. JUCE_CATCH_ALL
  204178. return hInstance > (HINSTANCE) 32;
  204179. }
  204180. void File::revealToUser() const
  204181. {
  204182. if (isDirectory())
  204183. startAsProcess();
  204184. else if (getParentDirectory().exists())
  204185. getParentDirectory().startAsProcess();
  204186. }
  204187. class NamedPipeInternal
  204188. {
  204189. public:
  204190. NamedPipeInternal (const String& file, const bool isPipe_)
  204191. : pipeH (0),
  204192. cancelEvent (0),
  204193. connected (false),
  204194. isPipe (isPipe_)
  204195. {
  204196. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204197. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204198. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204199. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204200. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204201. }
  204202. ~NamedPipeInternal()
  204203. {
  204204. disconnectPipe();
  204205. if (pipeH != 0)
  204206. CloseHandle (pipeH);
  204207. CloseHandle (cancelEvent);
  204208. }
  204209. bool connect (const int timeOutMs)
  204210. {
  204211. if (! isPipe)
  204212. return true;
  204213. if (! connected)
  204214. {
  204215. OVERLAPPED over;
  204216. zerostruct (over);
  204217. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204218. if (ConnectNamedPipe (pipeH, &over))
  204219. {
  204220. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204221. }
  204222. else
  204223. {
  204224. const int err = GetLastError();
  204225. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204226. {
  204227. HANDLE handles[] = { over.hEvent, cancelEvent };
  204228. if (WaitForMultipleObjects (2, handles, FALSE,
  204229. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204230. connected = true;
  204231. }
  204232. else if (err == ERROR_PIPE_CONNECTED)
  204233. {
  204234. connected = true;
  204235. }
  204236. }
  204237. CloseHandle (over.hEvent);
  204238. }
  204239. return connected;
  204240. }
  204241. void disconnectPipe()
  204242. {
  204243. if (connected)
  204244. {
  204245. DisconnectNamedPipe (pipeH);
  204246. connected = false;
  204247. }
  204248. }
  204249. HANDLE pipeH;
  204250. HANDLE cancelEvent;
  204251. bool connected, isPipe;
  204252. };
  204253. void NamedPipe::close()
  204254. {
  204255. cancelPendingReads();
  204256. const ScopedLock sl (lock);
  204257. delete static_cast<NamedPipeInternal*> (internal);
  204258. internal = 0;
  204259. }
  204260. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204261. {
  204262. close();
  204263. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204264. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204265. {
  204266. internal = intern.release();
  204267. return true;
  204268. }
  204269. return false;
  204270. }
  204271. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204272. {
  204273. const ScopedLock sl (lock);
  204274. int bytesRead = -1;
  204275. bool waitAgain = true;
  204276. while (waitAgain && internal != 0)
  204277. {
  204278. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204279. waitAgain = false;
  204280. if (! intern->connect (timeOutMilliseconds))
  204281. break;
  204282. if (maxBytesToRead <= 0)
  204283. return 0;
  204284. OVERLAPPED over;
  204285. zerostruct (over);
  204286. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204287. unsigned long numRead;
  204288. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204289. {
  204290. bytesRead = (int) numRead;
  204291. }
  204292. else if (GetLastError() == ERROR_IO_PENDING)
  204293. {
  204294. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204295. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204296. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204297. : INFINITE);
  204298. if (waitResult != WAIT_OBJECT_0)
  204299. {
  204300. // if the operation timed out, let's cancel it...
  204301. CancelIo (intern->pipeH);
  204302. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204303. }
  204304. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204305. {
  204306. bytesRead = (int) numRead;
  204307. }
  204308. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204309. {
  204310. intern->disconnectPipe();
  204311. waitAgain = true;
  204312. }
  204313. }
  204314. else
  204315. {
  204316. waitAgain = internal != 0;
  204317. Sleep (5);
  204318. }
  204319. CloseHandle (over.hEvent);
  204320. }
  204321. return bytesRead;
  204322. }
  204323. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204324. {
  204325. int bytesWritten = -1;
  204326. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204327. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204328. {
  204329. if (numBytesToWrite <= 0)
  204330. return 0;
  204331. OVERLAPPED over;
  204332. zerostruct (over);
  204333. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204334. unsigned long numWritten;
  204335. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204336. {
  204337. bytesWritten = (int) numWritten;
  204338. }
  204339. else if (GetLastError() == ERROR_IO_PENDING)
  204340. {
  204341. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204342. DWORD waitResult;
  204343. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204344. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204345. : INFINITE);
  204346. if (waitResult != WAIT_OBJECT_0)
  204347. {
  204348. CancelIo (intern->pipeH);
  204349. WaitForSingleObject (over.hEvent, INFINITE);
  204350. }
  204351. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204352. {
  204353. bytesWritten = (int) numWritten;
  204354. }
  204355. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204356. {
  204357. intern->disconnectPipe();
  204358. }
  204359. }
  204360. CloseHandle (over.hEvent);
  204361. }
  204362. return bytesWritten;
  204363. }
  204364. void NamedPipe::cancelPendingReads()
  204365. {
  204366. if (internal != 0)
  204367. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204368. }
  204369. #endif
  204370. /*** End of inlined file: juce_win32_Files.cpp ***/
  204371. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204372. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204373. // compiled on its own).
  204374. #if JUCE_INCLUDED_FILE
  204375. #ifndef INTERNET_FLAG_NEED_FILE
  204376. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204377. #endif
  204378. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204379. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204380. #endif
  204381. #ifndef WORKAROUND_TIMEOUT_BUG
  204382. //#define WORKAROUND_TIMEOUT_BUG 1
  204383. #endif
  204384. #if WORKAROUND_TIMEOUT_BUG
  204385. // Required because of a Microsoft bug in setting a timeout
  204386. class InternetConnectThread : public Thread
  204387. {
  204388. public:
  204389. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204390. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204391. {
  204392. startThread();
  204393. }
  204394. ~InternetConnectThread()
  204395. {
  204396. stopThread (60000);
  204397. }
  204398. void run()
  204399. {
  204400. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204401. uc.nPort, _T(""), _T(""),
  204402. isFtp ? INTERNET_SERVICE_FTP
  204403. : INTERNET_SERVICE_HTTP,
  204404. 0, 0);
  204405. notify();
  204406. }
  204407. private:
  204408. URL_COMPONENTS& uc;
  204409. HINTERNET sessionHandle;
  204410. HINTERNET& connection;
  204411. const bool isFtp;
  204412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204413. };
  204414. #endif
  204415. class WebInputStream : public InputStream
  204416. {
  204417. public:
  204418. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204419. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204420. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204421. : connection (0), request (0),
  204422. address (address_), headers (headers_), postData (postData_), position (0),
  204423. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204424. {
  204425. createConnection (progressCallback, progressCallbackContext);
  204426. if (responseHeaders != 0 && ! isError())
  204427. {
  204428. DWORD bufferSizeBytes = 4096;
  204429. for (;;)
  204430. {
  204431. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204432. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204433. {
  204434. StringArray headersArray;
  204435. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204436. for (int i = 0; i < headersArray.size(); ++i)
  204437. {
  204438. const String& header = headersArray[i];
  204439. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204440. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204441. const String previousValue ((*responseHeaders) [key]);
  204442. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204443. }
  204444. break;
  204445. }
  204446. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204447. break;
  204448. }
  204449. }
  204450. }
  204451. ~WebInputStream()
  204452. {
  204453. close();
  204454. }
  204455. bool isError() const { return request == 0; }
  204456. bool isExhausted() { return finished; }
  204457. int64 getPosition() { return position; }
  204458. int64 getTotalLength()
  204459. {
  204460. if (! isError())
  204461. {
  204462. DWORD index = 0, result = 0, size = sizeof (result);
  204463. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204464. return (int64) result;
  204465. }
  204466. return -1;
  204467. }
  204468. int read (void* buffer, int bytesToRead)
  204469. {
  204470. DWORD bytesRead = 0;
  204471. if (! (finished || isError()))
  204472. {
  204473. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204474. position += bytesRead;
  204475. if (bytesRead == 0)
  204476. finished = true;
  204477. }
  204478. return (int) bytesRead;
  204479. }
  204480. bool setPosition (int64 wantedPos)
  204481. {
  204482. if (isError())
  204483. return false;
  204484. if (wantedPos != position)
  204485. {
  204486. finished = false;
  204487. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204488. if (position == wantedPos)
  204489. return true;
  204490. if (wantedPos < position)
  204491. {
  204492. close();
  204493. position = 0;
  204494. createConnection (0, 0);
  204495. }
  204496. skipNextBytes (wantedPos - position);
  204497. }
  204498. return true;
  204499. }
  204500. private:
  204501. HINTERNET connection, request;
  204502. String address, headers;
  204503. MemoryBlock postData;
  204504. int64 position;
  204505. bool finished;
  204506. const bool isPost;
  204507. int timeOutMs;
  204508. void close()
  204509. {
  204510. if (request != 0)
  204511. {
  204512. InternetCloseHandle (request);
  204513. request = 0;
  204514. }
  204515. if (connection != 0)
  204516. {
  204517. InternetCloseHandle (connection);
  204518. connection = 0;
  204519. }
  204520. }
  204521. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204522. void* progressCallbackContext)
  204523. {
  204524. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204525. close();
  204526. if (sessionHandle != 0)
  204527. {
  204528. // break up the url..
  204529. TCHAR file[1024], server[1024];
  204530. URL_COMPONENTS uc;
  204531. zerostruct (uc);
  204532. uc.dwStructSize = sizeof (uc);
  204533. uc.dwUrlPathLength = sizeof (file);
  204534. uc.dwHostNameLength = sizeof (server);
  204535. uc.lpszUrlPath = file;
  204536. uc.lpszHostName = server;
  204537. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  204538. {
  204539. int disable = 1;
  204540. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204541. if (timeOutMs == 0)
  204542. timeOutMs = 30000;
  204543. else if (timeOutMs < 0)
  204544. timeOutMs = -1;
  204545. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204546. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204547. #if WORKAROUND_TIMEOUT_BUG
  204548. connection = 0;
  204549. {
  204550. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  204551. connectThread.wait (timeOutMs);
  204552. if (connection == 0)
  204553. {
  204554. InternetCloseHandle (sessionHandle);
  204555. sessionHandle = 0;
  204556. }
  204557. }
  204558. #else
  204559. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204560. _T(""), _T(""),
  204561. isFtp ? INTERNET_SERVICE_FTP
  204562. : INTERNET_SERVICE_HTTP,
  204563. 0, 0);
  204564. #endif
  204565. if (connection != 0)
  204566. {
  204567. if (isFtp)
  204568. {
  204569. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204570. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204571. }
  204572. else
  204573. {
  204574. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204575. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204576. if (address.startsWithIgnoreCase ("https:"))
  204577. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204578. // IE7 seems to automatically work out when it's https)
  204579. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204580. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204581. if (request != 0)
  204582. {
  204583. INTERNET_BUFFERS buffers;
  204584. zerostruct (buffers);
  204585. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204586. buffers.lpcszHeader = headers.toUTF16();
  204587. buffers.dwHeadersLength = headers.length();
  204588. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204589. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204590. {
  204591. int bytesSent = 0;
  204592. for (;;)
  204593. {
  204594. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204595. DWORD bytesDone = 0;
  204596. if (bytesToDo > 0
  204597. && ! InternetWriteFile (request,
  204598. static_cast <const char*> (postData.getData()) + bytesSent,
  204599. bytesToDo, &bytesDone))
  204600. {
  204601. break;
  204602. }
  204603. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204604. {
  204605. if (HttpEndRequest (request, 0, 0, 0))
  204606. return;
  204607. break;
  204608. }
  204609. bytesSent += bytesDone;
  204610. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204611. break;
  204612. }
  204613. }
  204614. }
  204615. close();
  204616. }
  204617. }
  204618. }
  204619. }
  204620. }
  204621. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204622. };
  204623. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204624. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204625. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204626. {
  204627. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204628. progressCallback, progressCallbackContext,
  204629. headers, timeOutMs, responseHeaders));
  204630. return wi->isError() ? 0 : wi.release();
  204631. }
  204632. namespace MACAddressHelpers
  204633. {
  204634. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204635. {
  204636. DynamicLibraryLoader dll ("iphlpapi.dll");
  204637. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204638. if (getAdaptersInfo != 0)
  204639. {
  204640. ULONG len = sizeof (IP_ADAPTER_INFO);
  204641. MemoryBlock mb;
  204642. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204643. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204644. {
  204645. mb.setSize (len);
  204646. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204647. }
  204648. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204649. {
  204650. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204651. {
  204652. if (adapter->AddressLength >= 6)
  204653. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204654. }
  204655. }
  204656. }
  204657. }
  204658. void getViaNetBios (Array<MACAddress>& result)
  204659. {
  204660. DynamicLibraryLoader dll ("netapi32.dll");
  204661. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204662. if (NetbiosCall != 0)
  204663. {
  204664. NCB ncb;
  204665. zerostruct (ncb);
  204666. struct ASTAT
  204667. {
  204668. ADAPTER_STATUS adapt;
  204669. NAME_BUFFER NameBuff [30];
  204670. };
  204671. ASTAT astat;
  204672. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204673. LANA_ENUM enums;
  204674. zerostruct (enums);
  204675. ncb.ncb_command = NCBENUM;
  204676. ncb.ncb_buffer = (unsigned char*) &enums;
  204677. ncb.ncb_length = sizeof (LANA_ENUM);
  204678. NetbiosCall (&ncb);
  204679. for (int i = 0; i < enums.length; ++i)
  204680. {
  204681. zerostruct (ncb);
  204682. ncb.ncb_command = NCBRESET;
  204683. ncb.ncb_lana_num = enums.lana[i];
  204684. if (NetbiosCall (&ncb) == 0)
  204685. {
  204686. zerostruct (ncb);
  204687. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204688. ncb.ncb_command = NCBASTAT;
  204689. ncb.ncb_lana_num = enums.lana[i];
  204690. ncb.ncb_buffer = (unsigned char*) &astat;
  204691. ncb.ncb_length = sizeof (ASTAT);
  204692. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204693. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204694. }
  204695. }
  204696. }
  204697. }
  204698. }
  204699. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204700. {
  204701. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204702. MACAddressHelpers::getViaNetBios (result);
  204703. }
  204704. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204705. const String& emailSubject,
  204706. const String& bodyText,
  204707. const StringArray& filesToAttach)
  204708. {
  204709. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204710. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204711. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204712. bool ok = false;
  204713. if (mapiSendMail != 0)
  204714. {
  204715. MapiMessage message;
  204716. zerostruct (message);
  204717. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204718. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204719. MapiRecipDesc recip;
  204720. zerostruct (recip);
  204721. recip.ulRecipClass = MAPI_TO;
  204722. String targetEmailAddress_ (targetEmailAddress);
  204723. if (targetEmailAddress_.isEmpty())
  204724. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204725. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204726. message.nRecipCount = 1;
  204727. message.lpRecips = &recip;
  204728. HeapBlock <MapiFileDesc> files;
  204729. files.calloc (filesToAttach.size());
  204730. message.nFileCount = filesToAttach.size();
  204731. message.lpFiles = files;
  204732. for (int i = 0; i < filesToAttach.size(); ++i)
  204733. {
  204734. files[i].nPosition = (ULONG) -1;
  204735. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204736. }
  204737. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204738. }
  204739. FreeLibrary (h);
  204740. return ok;
  204741. }
  204742. #endif
  204743. /*** End of inlined file: juce_win32_Network.cpp ***/
  204744. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204745. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204746. // compiled on its own).
  204747. #if JUCE_INCLUDED_FILE
  204748. namespace
  204749. {
  204750. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204751. {
  204752. HKEY rootKey = 0;
  204753. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204754. rootKey = HKEY_CURRENT_USER;
  204755. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204756. rootKey = HKEY_LOCAL_MACHINE;
  204757. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204758. rootKey = HKEY_CLASSES_ROOT;
  204759. if (rootKey != 0)
  204760. {
  204761. name = name.substring (name.indexOfChar ('\\') + 1);
  204762. const int lastSlash = name.lastIndexOfChar ('\\');
  204763. valueName = name.substring (lastSlash + 1);
  204764. name = name.substring (0, lastSlash);
  204765. HKEY key;
  204766. DWORD result;
  204767. if (createForWriting)
  204768. {
  204769. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  204770. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204771. return key;
  204772. }
  204773. else
  204774. {
  204775. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204776. return key;
  204777. }
  204778. }
  204779. return 0;
  204780. }
  204781. }
  204782. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204783. const String& defaultValue)
  204784. {
  204785. String valueName, result (defaultValue);
  204786. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204787. if (k != 0)
  204788. {
  204789. WCHAR buffer [2048];
  204790. unsigned long bufferSize = sizeof (buffer);
  204791. DWORD type = REG_SZ;
  204792. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204793. {
  204794. if (type == REG_SZ)
  204795. result = buffer;
  204796. else if (type == REG_DWORD)
  204797. result = String ((int) *(DWORD*) buffer);
  204798. }
  204799. RegCloseKey (k);
  204800. }
  204801. return result;
  204802. }
  204803. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204804. const String& value)
  204805. {
  204806. String valueName;
  204807. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204808. if (k != 0)
  204809. {
  204810. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  204811. (const BYTE*) value.toUTF16().getAddress(),
  204812. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  204813. RegCloseKey (k);
  204814. }
  204815. }
  204816. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204817. {
  204818. bool exists = false;
  204819. String valueName;
  204820. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204821. if (k != 0)
  204822. {
  204823. unsigned char buffer [2048];
  204824. unsigned long bufferSize = sizeof (buffer);
  204825. DWORD type = 0;
  204826. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204827. exists = true;
  204828. RegCloseKey (k);
  204829. }
  204830. return exists;
  204831. }
  204832. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204833. {
  204834. String valueName;
  204835. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204836. if (k != 0)
  204837. {
  204838. RegDeleteValue (k, valueName.toUTF16());
  204839. RegCloseKey (k);
  204840. }
  204841. }
  204842. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204843. {
  204844. String valueName;
  204845. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204846. if (k != 0)
  204847. {
  204848. RegDeleteKey (k, valueName.toUTF16());
  204849. RegCloseKey (k);
  204850. }
  204851. }
  204852. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204853. const String& symbolicDescription,
  204854. const String& fullDescription,
  204855. const File& targetExecutable,
  204856. int iconResourceNumber)
  204857. {
  204858. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204859. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204860. if (iconResourceNumber != 0)
  204861. setRegistryValue (key + "\\DefaultIcon\\",
  204862. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204863. setRegistryValue (key + "\\", fullDescription);
  204864. setRegistryValue (key + "\\shell\\open\\command\\",
  204865. targetExecutable.getFullPathName() + " %1");
  204866. }
  204867. bool juce_IsRunningInWine()
  204868. {
  204869. HKEY key;
  204870. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204871. {
  204872. RegCloseKey (key);
  204873. return true;
  204874. }
  204875. return false;
  204876. }
  204877. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204878. {
  204879. String s (::GetCommandLineW());
  204880. StringArray tokens;
  204881. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204882. return tokens.joinIntoString (" ", 1);
  204883. }
  204884. static void* currentModuleHandle = 0;
  204885. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204886. {
  204887. if (currentModuleHandle == 0)
  204888. currentModuleHandle = GetModuleHandle (0);
  204889. return currentModuleHandle;
  204890. }
  204891. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204892. {
  204893. currentModuleHandle = newHandle;
  204894. }
  204895. void PlatformUtilities::fpuReset()
  204896. {
  204897. #if JUCE_MSVC
  204898. _clearfp();
  204899. #endif
  204900. }
  204901. void PlatformUtilities::beep()
  204902. {
  204903. MessageBeep (MB_OK);
  204904. }
  204905. #endif
  204906. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204907. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204908. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204909. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204910. // compiled on its own).
  204911. #if JUCE_INCLUDED_FILE
  204912. static const unsigned int specialId = WM_APP + 0x4400;
  204913. static const unsigned int broadcastId = WM_APP + 0x4403;
  204914. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204915. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204916. HWND juce_messageWindowHandle = 0;
  204917. extern long improbableWindowNumber; // defined in windowing.cpp
  204918. #ifndef WM_APPCOMMAND
  204919. #define WM_APPCOMMAND 0x0319
  204920. #endif
  204921. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204922. const UINT message,
  204923. const WPARAM wParam,
  204924. const LPARAM lParam) throw()
  204925. {
  204926. JUCE_TRY
  204927. {
  204928. if (h == juce_messageWindowHandle)
  204929. {
  204930. if (message == specialCallbackId)
  204931. {
  204932. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204933. return (LRESULT) (*func) ((void*) lParam);
  204934. }
  204935. else if (message == specialId)
  204936. {
  204937. // these are trapped early in the dispatch call, but must also be checked
  204938. // here in case there are windows modal dialog boxes doing their own
  204939. // dispatch loop and not calling our version
  204940. Message* const message = reinterpret_cast <Message*> (lParam);
  204941. MessageManager::getInstance()->deliverMessage (message);
  204942. message->decReferenceCount();
  204943. return 0;
  204944. }
  204945. else if (message == broadcastId)
  204946. {
  204947. const ScopedPointer <String> messageString ((String*) lParam);
  204948. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204949. return 0;
  204950. }
  204951. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204952. {
  204953. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204954. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204955. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204956. return 0;
  204957. }
  204958. }
  204959. }
  204960. JUCE_CATCH_EXCEPTION
  204961. return DefWindowProc (h, message, wParam, lParam);
  204962. }
  204963. static bool isEventBlockedByModalComps (MSG& m)
  204964. {
  204965. if (Component::getNumCurrentlyModalComponents() == 0
  204966. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204967. return false;
  204968. switch (m.message)
  204969. {
  204970. case WM_MOUSEMOVE:
  204971. case WM_NCMOUSEMOVE:
  204972. case 0x020A: /* WM_MOUSEWHEEL */
  204973. case 0x020E: /* WM_MOUSEHWHEEL */
  204974. case WM_KEYUP:
  204975. case WM_SYSKEYUP:
  204976. case WM_CHAR:
  204977. case WM_APPCOMMAND:
  204978. case WM_LBUTTONUP:
  204979. case WM_MBUTTONUP:
  204980. case WM_RBUTTONUP:
  204981. case WM_MOUSEACTIVATE:
  204982. case WM_NCMOUSEHOVER:
  204983. case WM_MOUSEHOVER:
  204984. return true;
  204985. case WM_NCLBUTTONDOWN:
  204986. case WM_NCLBUTTONDBLCLK:
  204987. case WM_NCRBUTTONDOWN:
  204988. case WM_NCRBUTTONDBLCLK:
  204989. case WM_NCMBUTTONDOWN:
  204990. case WM_NCMBUTTONDBLCLK:
  204991. case WM_LBUTTONDOWN:
  204992. case WM_LBUTTONDBLCLK:
  204993. case WM_MBUTTONDOWN:
  204994. case WM_MBUTTONDBLCLK:
  204995. case WM_RBUTTONDOWN:
  204996. case WM_RBUTTONDBLCLK:
  204997. case WM_KEYDOWN:
  204998. case WM_SYSKEYDOWN:
  204999. {
  205000. Component* const modal = Component::getCurrentlyModalComponent (0);
  205001. if (modal != 0)
  205002. modal->inputAttemptWhenModal();
  205003. return true;
  205004. }
  205005. default:
  205006. break;
  205007. }
  205008. return false;
  205009. }
  205010. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205011. {
  205012. MSG m;
  205013. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205014. return false;
  205015. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205016. {
  205017. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205018. {
  205019. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205020. MessageManager::getInstance()->deliverMessage (message);
  205021. message->decReferenceCount();
  205022. }
  205023. else if (m.message == WM_QUIT)
  205024. {
  205025. if (JUCEApplication::getInstance() != 0)
  205026. JUCEApplication::getInstance()->systemRequestedQuit();
  205027. }
  205028. else if (! isEventBlockedByModalComps (m))
  205029. {
  205030. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205031. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205032. {
  205033. // if it's someone else's window being clicked on, and the focus is
  205034. // currently on a juce window, pass the kb focus over..
  205035. HWND currentFocus = GetFocus();
  205036. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205037. SetFocus (m.hwnd);
  205038. }
  205039. TranslateMessage (&m);
  205040. DispatchMessage (&m);
  205041. }
  205042. }
  205043. return true;
  205044. }
  205045. bool juce_postMessageToSystemQueue (Message* message)
  205046. {
  205047. message->incReferenceCount();
  205048. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205049. }
  205050. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205051. void* userData)
  205052. {
  205053. if (MessageManager::getInstance()->isThisTheMessageThread())
  205054. {
  205055. return (*callback) (userData);
  205056. }
  205057. else
  205058. {
  205059. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205060. // deadlock because the message manager is blocked from running, and can't
  205061. // call your function..
  205062. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205063. return (void*) SendMessage (juce_messageWindowHandle,
  205064. specialCallbackId,
  205065. (WPARAM) callback,
  205066. (LPARAM) userData);
  205067. }
  205068. }
  205069. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205070. {
  205071. if (hwnd != juce_messageWindowHandle)
  205072. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205073. return TRUE;
  205074. }
  205075. void MessageManager::broadcastMessage (const String& value)
  205076. {
  205077. Array<void*> windows;
  205078. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205079. const String localCopy (value);
  205080. COPYDATASTRUCT data;
  205081. data.dwData = broadcastId;
  205082. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205083. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205084. for (int i = windows.size(); --i >= 0;)
  205085. {
  205086. HWND hwnd = (HWND) windows.getUnchecked(i);
  205087. TCHAR windowName [64]; // no need to read longer strings than this
  205088. GetWindowText (hwnd, windowName, 64);
  205089. windowName [63] = 0;
  205090. if (String (windowName) == messageWindowName)
  205091. {
  205092. DWORD_PTR result;
  205093. SendMessageTimeout (hwnd, WM_COPYDATA,
  205094. (WPARAM) juce_messageWindowHandle,
  205095. (LPARAM) &data,
  205096. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205097. 8000,
  205098. &result);
  205099. }
  205100. }
  205101. }
  205102. static const String getMessageWindowClassName()
  205103. {
  205104. // this name has to be different for each app/dll instance because otherwise
  205105. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205106. // window class).
  205107. static int number = 0;
  205108. if (number == 0)
  205109. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205110. return "JUCEcs_" + String (number);
  205111. }
  205112. void MessageManager::doPlatformSpecificInitialisation()
  205113. {
  205114. OleInitialize (0);
  205115. const String className (getMessageWindowClassName());
  205116. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205117. WNDCLASSEX wc;
  205118. zerostruct (wc);
  205119. wc.cbSize = sizeof (wc);
  205120. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205121. wc.cbWndExtra = 4;
  205122. wc.hInstance = hmod;
  205123. wc.lpszClassName = className.toUTF16();
  205124. RegisterClassEx (&wc);
  205125. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205126. messageWindowName,
  205127. 0, 0, 0, 0, 0, 0, 0,
  205128. hmod, 0);
  205129. }
  205130. void MessageManager::doPlatformSpecificShutdown()
  205131. {
  205132. DestroyWindow (juce_messageWindowHandle);
  205133. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205134. OleUninitialize();
  205135. }
  205136. #endif
  205137. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205138. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205139. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205140. // compiled on its own).
  205141. #if JUCE_INCLUDED_FILE
  205142. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205143. NEWTEXTMETRICEXW*,
  205144. int type,
  205145. LPARAM lParam)
  205146. {
  205147. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205148. {
  205149. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205150. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205151. }
  205152. return 1;
  205153. }
  205154. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205155. NEWTEXTMETRICEXW*,
  205156. int type,
  205157. LPARAM lParam)
  205158. {
  205159. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205160. {
  205161. LOGFONTW lf;
  205162. zerostruct (lf);
  205163. lf.lfWeight = FW_DONTCARE;
  205164. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205165. lf.lfQuality = DEFAULT_QUALITY;
  205166. lf.lfCharSet = DEFAULT_CHARSET;
  205167. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205168. lf.lfPitchAndFamily = FF_DONTCARE;
  205169. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205170. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205171. HDC dc = CreateCompatibleDC (0);
  205172. EnumFontFamiliesEx (dc, &lf,
  205173. (FONTENUMPROCW) &wfontEnum2,
  205174. lParam, 0);
  205175. DeleteDC (dc);
  205176. }
  205177. return 1;
  205178. }
  205179. const StringArray Font::findAllTypefaceNames()
  205180. {
  205181. StringArray results;
  205182. HDC dc = CreateCompatibleDC (0);
  205183. {
  205184. LOGFONTW lf;
  205185. zerostruct (lf);
  205186. lf.lfWeight = FW_DONTCARE;
  205187. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205188. lf.lfQuality = DEFAULT_QUALITY;
  205189. lf.lfCharSet = DEFAULT_CHARSET;
  205190. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205191. lf.lfPitchAndFamily = FF_DONTCARE;
  205192. lf.lfFaceName[0] = 0;
  205193. EnumFontFamiliesEx (dc, &lf,
  205194. (FONTENUMPROCW) &wfontEnum1,
  205195. (LPARAM) &results, 0);
  205196. }
  205197. DeleteDC (dc);
  205198. results.sort (true);
  205199. return results;
  205200. }
  205201. extern bool juce_IsRunningInWine();
  205202. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205203. {
  205204. if (juce_IsRunningInWine())
  205205. {
  205206. // If we're running in Wine, then use fonts that might be available on Linux..
  205207. defaultSans = "Bitstream Vera Sans";
  205208. defaultSerif = "Bitstream Vera Serif";
  205209. defaultFixed = "Bitstream Vera Sans Mono";
  205210. }
  205211. else
  205212. {
  205213. defaultSans = "Verdana";
  205214. defaultSerif = "Times";
  205215. defaultFixed = "Lucida Console";
  205216. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205217. }
  205218. }
  205219. class FontDCHolder : private DeletedAtShutdown
  205220. {
  205221. public:
  205222. FontDCHolder()
  205223. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205224. bold (false), italic (false)
  205225. {
  205226. }
  205227. ~FontDCHolder()
  205228. {
  205229. deleteDCAndFont();
  205230. clearSingletonInstance();
  205231. }
  205232. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205233. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205234. {
  205235. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205236. {
  205237. fontName = fontName_;
  205238. bold = bold_;
  205239. italic = italic_;
  205240. size = size_;
  205241. deleteDCAndFont();
  205242. dc = CreateCompatibleDC (0);
  205243. SetMapperFlags (dc, 0);
  205244. SetMapMode (dc, MM_TEXT);
  205245. LOGFONTW lfw;
  205246. zerostruct (lfw);
  205247. lfw.lfCharSet = DEFAULT_CHARSET;
  205248. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205249. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205250. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205251. lfw.lfQuality = PROOF_QUALITY;
  205252. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205253. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205254. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205255. lfw.lfHeight = size > 0 ? size : -256;
  205256. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205257. if (standardSizedFont != 0)
  205258. {
  205259. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205260. {
  205261. fontH = standardSizedFont;
  205262. if (size == 0)
  205263. {
  205264. OUTLINETEXTMETRIC otm;
  205265. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205266. {
  205267. lfw.lfHeight = -(int) otm.otmEMSquare;
  205268. fontH = CreateFontIndirect (&lfw);
  205269. SelectObject (dc, fontH);
  205270. DeleteObject (standardSizedFont);
  205271. }
  205272. }
  205273. }
  205274. }
  205275. }
  205276. return dc;
  205277. }
  205278. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205279. {
  205280. if (kps == 0)
  205281. {
  205282. numKPs = GetKerningPairs (dc, 0, 0);
  205283. kps.calloc (numKPs);
  205284. GetKerningPairs (dc, numKPs, kps);
  205285. }
  205286. numKPs_ = numKPs;
  205287. return kps;
  205288. }
  205289. private:
  205290. HFONT fontH;
  205291. HGDIOBJ previousFontH;
  205292. HDC dc;
  205293. String fontName;
  205294. HeapBlock <KERNINGPAIR> kps;
  205295. int numKPs, size;
  205296. bool bold, italic;
  205297. void deleteDCAndFont()
  205298. {
  205299. if (dc != 0)
  205300. {
  205301. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205302. DeleteDC (dc);
  205303. dc = 0;
  205304. }
  205305. if (fontH != 0)
  205306. {
  205307. DeleteObject (fontH);
  205308. fontH = 0;
  205309. }
  205310. kps.free();
  205311. }
  205312. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205313. };
  205314. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205315. class WindowsTypeface : public CustomTypeface
  205316. {
  205317. public:
  205318. WindowsTypeface (const Font& font)
  205319. {
  205320. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205321. font.isBold(), font.isItalic(), 0);
  205322. TEXTMETRIC tm;
  205323. tm.tmAscent = tm.tmHeight = 1;
  205324. tm.tmDefaultChar = 0;
  205325. GetTextMetrics (dc, &tm);
  205326. setCharacteristics (font.getTypefaceName(),
  205327. tm.tmAscent / (float) tm.tmHeight,
  205328. font.isBold(), font.isItalic(),
  205329. tm.tmDefaultChar);
  205330. }
  205331. bool loadGlyphIfPossible (juce_wchar character)
  205332. {
  205333. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205334. GLYPHMETRICS gm;
  205335. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205336. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205337. // gets correctly created later on.
  205338. if (! isFallbackFont)
  205339. {
  205340. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205341. WORD index = 0;
  205342. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205343. && index == 0xffff)
  205344. {
  205345. return false;
  205346. }
  205347. }
  205348. Path glyphPath;
  205349. TEXTMETRIC tm;
  205350. if (! GetTextMetrics (dc, &tm))
  205351. {
  205352. addGlyph (character, glyphPath, 0);
  205353. return true;
  205354. }
  205355. const float height = (float) tm.tmHeight;
  205356. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205357. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205358. &gm, 0, 0, &identityMatrix);
  205359. if (bufSize > 0)
  205360. {
  205361. HeapBlock<char> data (bufSize);
  205362. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205363. bufSize, data, &identityMatrix);
  205364. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205365. const float scaleX = 1.0f / height;
  205366. const float scaleY = -1.0f / height;
  205367. while ((char*) pheader < data + bufSize)
  205368. {
  205369. float x = scaleX * pheader->pfxStart.x.value;
  205370. float y = scaleY * pheader->pfxStart.y.value;
  205371. glyphPath.startNewSubPath (x, y);
  205372. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205373. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205374. while ((const char*) curve < curveEnd)
  205375. {
  205376. if (curve->wType == TT_PRIM_LINE)
  205377. {
  205378. for (int i = 0; i < curve->cpfx; ++i)
  205379. {
  205380. x = scaleX * curve->apfx[i].x.value;
  205381. y = scaleY * curve->apfx[i].y.value;
  205382. glyphPath.lineTo (x, y);
  205383. }
  205384. }
  205385. else if (curve->wType == TT_PRIM_QSPLINE)
  205386. {
  205387. for (int i = 0; i < curve->cpfx - 1; ++i)
  205388. {
  205389. const float x2 = scaleX * curve->apfx[i].x.value;
  205390. const float y2 = scaleY * curve->apfx[i].y.value;
  205391. float x3, y3;
  205392. if (i < curve->cpfx - 2)
  205393. {
  205394. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205395. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205396. }
  205397. else
  205398. {
  205399. x3 = scaleX * curve->apfx[i + 1].x.value;
  205400. y3 = scaleY * curve->apfx[i + 1].y.value;
  205401. }
  205402. glyphPath.quadraticTo (x2, y2, x3, y3);
  205403. x = x3;
  205404. y = y3;
  205405. }
  205406. }
  205407. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205408. }
  205409. pheader = (const TTPOLYGONHEADER*) curve;
  205410. glyphPath.closeSubPath();
  205411. }
  205412. }
  205413. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205414. int numKPs;
  205415. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205416. for (int i = 0; i < numKPs; ++i)
  205417. {
  205418. if (kps[i].wFirst == character)
  205419. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205420. kps[i].iKernAmount / height);
  205421. }
  205422. return true;
  205423. }
  205424. private:
  205425. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205426. };
  205427. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205428. {
  205429. return new WindowsTypeface (font);
  205430. }
  205431. #endif
  205432. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205433. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205434. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205435. // compiled on its own).
  205436. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205437. class SharedD2DFactory : public DeletedAtShutdown
  205438. {
  205439. public:
  205440. SharedD2DFactory()
  205441. {
  205442. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  205443. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  205444. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  205445. if (directWriteFactory != 0)
  205446. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  205447. }
  205448. ~SharedD2DFactory()
  205449. {
  205450. clearSingletonInstance();
  205451. }
  205452. juce_DeclareSingleton (SharedD2DFactory, false);
  205453. ComSmartPtr <ID2D1Factory> d2dFactory;
  205454. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205455. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205456. };
  205457. juce_ImplementSingleton (SharedD2DFactory)
  205458. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205459. {
  205460. public:
  205461. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205462. : hwnd (hwnd_),
  205463. currentState (0)
  205464. {
  205465. RECT windowRect;
  205466. GetClientRect (hwnd, &windowRect);
  205467. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205468. bounds.setSize (size.width, size.height);
  205469. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205470. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205471. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  205472. // xxx check for error
  205473. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  205474. }
  205475. ~Direct2DLowLevelGraphicsContext()
  205476. {
  205477. states.clear();
  205478. }
  205479. void resized()
  205480. {
  205481. RECT windowRect;
  205482. GetClientRect (hwnd, &windowRect);
  205483. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205484. renderingTarget->Resize (size);
  205485. bounds.setSize (size.width, size.height);
  205486. }
  205487. void clear()
  205488. {
  205489. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205490. }
  205491. void start()
  205492. {
  205493. renderingTarget->BeginDraw();
  205494. saveState();
  205495. }
  205496. void end()
  205497. {
  205498. states.clear();
  205499. currentState = 0;
  205500. renderingTarget->EndDraw();
  205501. renderingTarget->CheckWindowState();
  205502. }
  205503. bool isVectorDevice() const { return false; }
  205504. void setOrigin (int x, int y)
  205505. {
  205506. currentState->origin.addXY (x, y);
  205507. }
  205508. void addTransform (const AffineTransform& transform)
  205509. {
  205510. //xxx todo
  205511. jassertfalse;
  205512. }
  205513. float getScaleFactor()
  205514. {
  205515. jassertfalse; //xxx
  205516. return 1.0f;
  205517. }
  205518. bool clipToRectangle (const Rectangle<int>& r)
  205519. {
  205520. currentState->clipToRectangle (r);
  205521. return ! isClipEmpty();
  205522. }
  205523. bool clipToRectangleList (const RectangleList& clipRegion)
  205524. {
  205525. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205526. return ! isClipEmpty();
  205527. }
  205528. void excludeClipRectangle (const Rectangle<int>&)
  205529. {
  205530. //xxx
  205531. }
  205532. void clipToPath (const Path& path, const AffineTransform& transform)
  205533. {
  205534. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205535. }
  205536. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205537. {
  205538. currentState->clipToImage (sourceImage,transform);
  205539. }
  205540. bool clipRegionIntersects (const Rectangle<int>& r)
  205541. {
  205542. const Rectangle<int> r2 (r + currentState->origin);
  205543. return currentState->clipRect.intersects (r2);
  205544. }
  205545. const Rectangle<int> getClipBounds() const
  205546. {
  205547. // xxx could this take into account complex clip regions?
  205548. return currentState->clipRect - currentState->origin;
  205549. }
  205550. bool isClipEmpty() const
  205551. {
  205552. return currentState->clipRect.isEmpty();
  205553. }
  205554. void saveState()
  205555. {
  205556. states.add (new SavedState (*this));
  205557. currentState = states.getLast();
  205558. }
  205559. void restoreState()
  205560. {
  205561. jassert (states.size() > 1) //you should never pop the last state!
  205562. states.removeLast (1);
  205563. currentState = states.getLast();
  205564. }
  205565. void beginTransparencyLayer (float opacity)
  205566. {
  205567. jassertfalse; //xxx todo
  205568. }
  205569. void endTransparencyLayer()
  205570. {
  205571. jassertfalse; //xxx todo
  205572. }
  205573. void setFill (const FillType& fillType)
  205574. {
  205575. currentState->setFill (fillType);
  205576. }
  205577. void setOpacity (float newOpacity)
  205578. {
  205579. currentState->setOpacity (newOpacity);
  205580. }
  205581. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205582. {
  205583. }
  205584. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205585. {
  205586. currentState->createBrush();
  205587. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205588. }
  205589. void fillPath (const Path& p, const AffineTransform& transform)
  205590. {
  205591. currentState->createBrush();
  205592. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205593. if (renderingTarget != 0)
  205594. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205595. }
  205596. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205597. {
  205598. const int x = currentState->origin.getX();
  205599. const int y = currentState->origin.getY();
  205600. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205601. D2D1_SIZE_U size;
  205602. size.width = image.getWidth();
  205603. size.height = image.getHeight();
  205604. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205605. Image img (image.convertedToFormat (Image::ARGB));
  205606. Image::BitmapData bd (img, false);
  205607. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205608. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205609. {
  205610. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205611. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  205612. if (tempBitmap != 0)
  205613. renderingTarget->DrawBitmap (tempBitmap);
  205614. }
  205615. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205616. }
  205617. void drawLine (const Line <float>& line)
  205618. {
  205619. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205620. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205621. line.getEnd() + currentState->origin.toFloat());
  205622. currentState->createBrush();
  205623. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205624. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205625. currentState->currentBrush);
  205626. }
  205627. void drawVerticalLine (int x, float top, float bottom)
  205628. {
  205629. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205630. currentState->createBrush();
  205631. x += currentState->origin.getX();
  205632. const int y = currentState->origin.getY();
  205633. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205634. D2D1::Point2F (x, y + bottom),
  205635. currentState->currentBrush);
  205636. }
  205637. void drawHorizontalLine (int y, float left, float right)
  205638. {
  205639. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205640. currentState->createBrush();
  205641. y += currentState->origin.getY();
  205642. const int x = currentState->origin.getX();
  205643. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205644. D2D1::Point2F (x + right, y),
  205645. currentState->currentBrush);
  205646. }
  205647. void setFont (const Font& newFont)
  205648. {
  205649. currentState->setFont (newFont);
  205650. }
  205651. const Font getFont()
  205652. {
  205653. return currentState->font;
  205654. }
  205655. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205656. {
  205657. const float x = currentState->origin.getX();
  205658. const float y = currentState->origin.getY();
  205659. currentState->createBrush();
  205660. currentState->createFont();
  205661. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205662. float hScale = currentState->font.getHorizontalScale();
  205663. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205664. float dpiX = 0, dpiY = 0;
  205665. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205666. UINT32 glyphNum = glyphNumber;
  205667. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205668. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205669. DWRITE_GLYPH_OFFSET offset;
  205670. offset.advanceOffset = 0;
  205671. offset.ascenderOffset = 0;
  205672. float glyphAdvances = 0;
  205673. DWRITE_GLYPH_RUN glyph;
  205674. glyph.fontFace = currentState->currentFontFace;
  205675. glyph.glyphCount = 1;
  205676. glyph.glyphIndices = &glyphNum1;
  205677. glyph.isSideways = FALSE;
  205678. glyph.glyphAdvances = &glyphAdvances;
  205679. glyph.glyphOffsets = &offset;
  205680. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205681. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205682. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205683. }
  205684. class SavedState
  205685. {
  205686. public:
  205687. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205688. : owner (owner_), currentBrush (0),
  205689. fontScaling (1.0f), currentFontFace (0),
  205690. clipsRect (false), shouldClipRect (false),
  205691. clipsRectList (false), shouldClipRectList (false),
  205692. clipsComplex (false), shouldClipComplex (false),
  205693. clipsBitmap (false), shouldClipBitmap (false)
  205694. {
  205695. if (owner.currentState != 0)
  205696. {
  205697. // xxx seems like a very slow way to create one of these, and this is a performance
  205698. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205699. setFill (owner.currentState->fillType);
  205700. currentBrush = owner.currentState->currentBrush;
  205701. origin = owner.currentState->origin;
  205702. clipRect = owner.currentState->clipRect;
  205703. font = owner.currentState->font;
  205704. currentFontFace = owner.currentState->currentFontFace;
  205705. }
  205706. else
  205707. {
  205708. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205709. clipRect.setSize (size.width, size.height);
  205710. setFill (FillType (Colours::black));
  205711. }
  205712. }
  205713. ~SavedState()
  205714. {
  205715. clearClip();
  205716. clearFont();
  205717. clearFill();
  205718. clearPathClip();
  205719. clearImageClip();
  205720. complexClipLayer = 0;
  205721. bitmapMaskLayer = 0;
  205722. }
  205723. void clearClip()
  205724. {
  205725. popClips();
  205726. shouldClipRect = false;
  205727. }
  205728. void clipToRectangle (const Rectangle<int>& r)
  205729. {
  205730. clearClip();
  205731. clipRect = r + origin;
  205732. shouldClipRect = true;
  205733. pushClips();
  205734. }
  205735. void clearPathClip()
  205736. {
  205737. popClips();
  205738. if (shouldClipComplex)
  205739. {
  205740. complexClipGeometry = 0;
  205741. shouldClipComplex = false;
  205742. }
  205743. }
  205744. void clipToPath (ID2D1Geometry* geometry)
  205745. {
  205746. clearPathClip();
  205747. if (complexClipLayer == 0)
  205748. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  205749. complexClipGeometry = geometry;
  205750. shouldClipComplex = true;
  205751. pushClips();
  205752. }
  205753. void clearRectListClip()
  205754. {
  205755. popClips();
  205756. if (shouldClipRectList)
  205757. {
  205758. rectListGeometry = 0;
  205759. shouldClipRectList = false;
  205760. }
  205761. }
  205762. void clipToRectList (ID2D1Geometry* geometry)
  205763. {
  205764. clearRectListClip();
  205765. if (rectListLayer == 0)
  205766. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  205767. rectListGeometry = geometry;
  205768. shouldClipRectList = true;
  205769. pushClips();
  205770. }
  205771. void clearImageClip()
  205772. {
  205773. popClips();
  205774. if (shouldClipBitmap)
  205775. {
  205776. maskBitmap = 0;
  205777. bitmapMaskBrush = 0;
  205778. shouldClipBitmap = false;
  205779. }
  205780. }
  205781. void clipToImage (const Image& image, const AffineTransform& transform)
  205782. {
  205783. clearImageClip();
  205784. if (bitmapMaskLayer == 0)
  205785. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  205786. D2D1_BRUSH_PROPERTIES brushProps;
  205787. brushProps.opacity = 1;
  205788. brushProps.transform = transformToMatrix (transform);
  205789. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205790. D2D1_SIZE_U size;
  205791. size.width = image.getWidth();
  205792. size.height = image.getHeight();
  205793. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205794. maskImage = image.convertedToFormat (Image::ARGB);
  205795. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205796. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205797. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205798. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  205799. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  205800. imageMaskLayerParams = D2D1::LayerParameters();
  205801. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205802. shouldClipBitmap = true;
  205803. pushClips();
  205804. }
  205805. void popClips()
  205806. {
  205807. if (clipsBitmap)
  205808. {
  205809. owner.renderingTarget->PopLayer();
  205810. clipsBitmap = false;
  205811. }
  205812. if (clipsComplex)
  205813. {
  205814. owner.renderingTarget->PopLayer();
  205815. clipsComplex = false;
  205816. }
  205817. if (clipsRectList)
  205818. {
  205819. owner.renderingTarget->PopLayer();
  205820. clipsRectList = false;
  205821. }
  205822. if (clipsRect)
  205823. {
  205824. owner.renderingTarget->PopAxisAlignedClip();
  205825. clipsRect = false;
  205826. }
  205827. }
  205828. void pushClips()
  205829. {
  205830. if (shouldClipRect && ! clipsRect)
  205831. {
  205832. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205833. clipsRect = true;
  205834. }
  205835. if (shouldClipRectList && ! clipsRectList)
  205836. {
  205837. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205838. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205839. layerParams.geometricMask = rectListGeometry;
  205840. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205841. clipsRectList = true;
  205842. }
  205843. if (shouldClipComplex && ! clipsComplex)
  205844. {
  205845. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205846. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205847. layerParams.geometricMask = complexClipGeometry;
  205848. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  205849. clipsComplex = true;
  205850. }
  205851. if (shouldClipBitmap && ! clipsBitmap)
  205852. {
  205853. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  205854. clipsBitmap = true;
  205855. }
  205856. }
  205857. void setFill (const FillType& newFillType)
  205858. {
  205859. if (fillType != newFillType)
  205860. {
  205861. fillType = newFillType;
  205862. clearFill();
  205863. }
  205864. }
  205865. void clearFont()
  205866. {
  205867. currentFontFace = localFontFace = 0;
  205868. }
  205869. void setFont (const Font& newFont)
  205870. {
  205871. if (font != newFont)
  205872. {
  205873. font = newFont;
  205874. clearFont();
  205875. }
  205876. }
  205877. void createFont()
  205878. {
  205879. // xxx The font shouldn't be managed by the graphics context.
  205880. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  205881. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  205882. // WindowsTypeface class.
  205883. if (currentFontFace == 0)
  205884. {
  205885. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  205886. fontScaling = systemType->getAscent();
  205887. BOOL fontFound;
  205888. uint32 fontIndex;
  205889. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  205890. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  205891. if (! fontFound)
  205892. fontIndex = 0;
  205893. ComSmartPtr <IDWriteFontFamily> fontFam;
  205894. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  205895. ComSmartPtr <IDWriteFont> font;
  205896. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  205897. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  205898. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  205899. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  205900. currentFontFace = localFontFace;
  205901. }
  205902. }
  205903. void setOpacity (float newOpacity)
  205904. {
  205905. fillType.setOpacity (newOpacity);
  205906. if (currentBrush != 0)
  205907. currentBrush->SetOpacity (newOpacity);
  205908. }
  205909. void clearFill()
  205910. {
  205911. gradientStops = 0;
  205912. linearGradient = 0;
  205913. radialGradient = 0;
  205914. bitmap = 0;
  205915. bitmapBrush = 0;
  205916. currentBrush = 0;
  205917. }
  205918. void createBrush()
  205919. {
  205920. if (currentBrush == 0)
  205921. {
  205922. const int x = origin.getX();
  205923. const int y = origin.getY();
  205924. if (fillType.isColour())
  205925. {
  205926. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  205927. owner.colourBrush->SetColor (colour);
  205928. currentBrush = owner.colourBrush;
  205929. }
  205930. else if (fillType.isTiledImage())
  205931. {
  205932. D2D1_BRUSH_PROPERTIES brushProps;
  205933. brushProps.opacity = fillType.getOpacity();
  205934. brushProps.transform = transformToMatrix (fillType.transform);
  205935. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  205936. image = fillType.image;
  205937. D2D1_SIZE_U size;
  205938. size.width = image.getWidth();
  205939. size.height = image.getHeight();
  205940. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205941. this->image = image.convertedToFormat (Image::ARGB);
  205942. Image::BitmapData bd (this->image, false);
  205943. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205944. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205945. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  205946. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  205947. currentBrush = bitmapBrush;
  205948. }
  205949. else if (fillType.isGradient())
  205950. {
  205951. gradientStops = 0;
  205952. D2D1_BRUSH_PROPERTIES brushProps;
  205953. brushProps.opacity = fillType.getOpacity();
  205954. brushProps.transform = transformToMatrix (fillType.transform);
  205955. const int numColors = fillType.gradient->getNumColours();
  205956. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  205957. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  205958. {
  205959. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  205960. stops[i].position = fillType.gradient->getColourPosition(i);
  205961. }
  205962. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  205963. if (fillType.gradient->isRadial)
  205964. {
  205965. radialGradient = 0;
  205966. const Point<float>& p1 = fillType.gradient->point1;
  205967. const Point<float>& p2 = fillType.gradient->point2;
  205968. float r = p1.getDistanceFrom (p2);
  205969. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  205970. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  205971. D2D1::Point2F (0, 0),
  205972. r, r);
  205973. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  205974. currentBrush = radialGradient;
  205975. }
  205976. else
  205977. {
  205978. linearGradient = 0;
  205979. const Point<float>& p1 = fillType.gradient->point1;
  205980. const Point<float>& p2 = fillType.gradient->point2;
  205981. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  205982. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  205983. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  205984. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  205985. currentBrush = linearGradient;
  205986. }
  205987. }
  205988. }
  205989. }
  205990. //xxx most of these members should probably be private...
  205991. Direct2DLowLevelGraphicsContext& owner;
  205992. Point<int> origin;
  205993. Font font;
  205994. float fontScaling;
  205995. IDWriteFontFace* currentFontFace;
  205996. ComSmartPtr <IDWriteFontFace> localFontFace;
  205997. FillType fillType;
  205998. Image image;
  205999. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206000. Rectangle<int> clipRect;
  206001. bool clipsRect, shouldClipRect;
  206002. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206003. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206004. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206005. bool clipsComplex, shouldClipComplex;
  206006. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206007. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206008. ComSmartPtr <ID2D1Layer> rectListLayer;
  206009. bool clipsRectList, shouldClipRectList;
  206010. Image maskImage;
  206011. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206012. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206013. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206014. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206015. bool clipsBitmap, shouldClipBitmap;
  206016. ID2D1Brush* currentBrush;
  206017. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206018. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206019. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206020. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206021. private:
  206022. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206023. };
  206024. private:
  206025. HWND hwnd;
  206026. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206027. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206028. Rectangle<int> bounds;
  206029. SavedState* currentState;
  206030. OwnedArray<SavedState> states;
  206031. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206032. {
  206033. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206034. }
  206035. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206036. {
  206037. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206038. }
  206039. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206040. {
  206041. transform.transformPoint (x, y);
  206042. return D2D1::Point2F (x, y);
  206043. }
  206044. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206045. {
  206046. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206047. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206048. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206049. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206050. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206051. }
  206052. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206053. {
  206054. ID2D1PathGeometry* p = 0;
  206055. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206056. ComSmartPtr <ID2D1GeometrySink> sink;
  206057. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206058. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206059. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206060. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206061. hr = sink->Close();
  206062. return p;
  206063. }
  206064. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206065. {
  206066. Path::Iterator it (path);
  206067. while (it.next())
  206068. {
  206069. switch (it.elementType)
  206070. {
  206071. case Path::Iterator::cubicTo:
  206072. {
  206073. D2D1_BEZIER_SEGMENT seg;
  206074. transform.transformPoint (it.x1, it.y1);
  206075. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206076. transform.transformPoint (it.x2, it.y2);
  206077. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206078. transform.transformPoint(it.x3, it.y3);
  206079. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206080. sink->AddBezier (seg);
  206081. break;
  206082. }
  206083. case Path::Iterator::lineTo:
  206084. {
  206085. transform.transformPoint (it.x1, it.y1);
  206086. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206087. break;
  206088. }
  206089. case Path::Iterator::quadraticTo:
  206090. {
  206091. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206092. transform.transformPoint (it.x1, it.y1);
  206093. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206094. transform.transformPoint (it.x2, it.y2);
  206095. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206096. sink->AddQuadraticBezier (seg);
  206097. break;
  206098. }
  206099. case Path::Iterator::closePath:
  206100. {
  206101. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206102. break;
  206103. }
  206104. case Path::Iterator::startNewSubPath:
  206105. {
  206106. transform.transformPoint (it.x1, it.y1);
  206107. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206108. break;
  206109. }
  206110. }
  206111. }
  206112. }
  206113. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206114. {
  206115. ID2D1PathGeometry* p = 0;
  206116. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206117. ComSmartPtr <ID2D1GeometrySink> sink;
  206118. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206119. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206120. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206121. hr = sink->Close();
  206122. return p;
  206123. }
  206124. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206125. {
  206126. D2D1::Matrix3x2F matrix;
  206127. matrix._11 = transform.mat00;
  206128. matrix._12 = transform.mat10;
  206129. matrix._21 = transform.mat01;
  206130. matrix._22 = transform.mat11;
  206131. matrix._31 = transform.mat02;
  206132. matrix._32 = transform.mat12;
  206133. return matrix;
  206134. }
  206135. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206136. };
  206137. #endif
  206138. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206139. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206140. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206141. // compiled on its own).
  206142. #if JUCE_INCLUDED_FILE
  206143. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206144. // these are in the windows SDK, but need to be repeated here for GCC..
  206145. #ifndef GET_APPCOMMAND_LPARAM
  206146. #define FAPPCOMMAND_MASK 0xF000
  206147. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206148. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206149. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206150. #define APPCOMMAND_MEDIA_STOP 13
  206151. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206152. #define WM_APPCOMMAND 0x0319
  206153. #endif
  206154. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206155. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206156. extern bool juce_IsRunningInWine();
  206157. #ifndef ULW_ALPHA
  206158. #define ULW_ALPHA 0x00000002
  206159. #endif
  206160. #ifndef AC_SRC_ALPHA
  206161. #define AC_SRC_ALPHA 0x01
  206162. #endif
  206163. static bool shouldDeactivateTitleBar = true;
  206164. #define WM_TRAYNOTIFY WM_USER + 100
  206165. using ::abs;
  206166. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206167. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206168. bool Desktop::canUseSemiTransparentWindows() throw()
  206169. {
  206170. if (updateLayeredWindow == 0)
  206171. {
  206172. if (! juce_IsRunningInWine())
  206173. {
  206174. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206175. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206176. }
  206177. }
  206178. return updateLayeredWindow != 0;
  206179. }
  206180. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206181. {
  206182. return upright;
  206183. }
  206184. const int extendedKeyModifier = 0x10000;
  206185. const int KeyPress::spaceKey = VK_SPACE;
  206186. const int KeyPress::returnKey = VK_RETURN;
  206187. const int KeyPress::escapeKey = VK_ESCAPE;
  206188. const int KeyPress::backspaceKey = VK_BACK;
  206189. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206190. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206191. const int KeyPress::tabKey = VK_TAB;
  206192. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206193. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206194. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206195. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206196. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206197. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206198. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206199. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206200. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206201. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206202. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206203. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206204. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206205. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206206. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206207. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206208. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206209. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206210. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206211. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206212. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206213. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206214. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206215. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206216. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206217. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206218. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206219. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206220. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206221. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206222. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206223. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206224. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206225. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206226. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206227. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206228. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206229. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206230. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206231. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206232. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206233. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206234. const int KeyPress::playKey = 0x30000;
  206235. const int KeyPress::stopKey = 0x30001;
  206236. const int KeyPress::fastForwardKey = 0x30002;
  206237. const int KeyPress::rewindKey = 0x30003;
  206238. class WindowsBitmapImage : public Image::SharedImage
  206239. {
  206240. public:
  206241. HBITMAP hBitmap;
  206242. HGDIOBJ previousBitmap;
  206243. BITMAPV4HEADER bitmapInfo;
  206244. HDC hdc;
  206245. unsigned char* bitmapData;
  206246. WindowsBitmapImage (const Image::PixelFormat format_,
  206247. const int w, const int h, const bool clearImage)
  206248. : Image::SharedImage (format_, w, h)
  206249. {
  206250. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206251. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206252. zerostruct (bitmapInfo);
  206253. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206254. bitmapInfo.bV4Width = w;
  206255. bitmapInfo.bV4Height = h;
  206256. bitmapInfo.bV4Planes = 1;
  206257. bitmapInfo.bV4CSType = 1;
  206258. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206259. if (format_ == Image::ARGB)
  206260. {
  206261. bitmapInfo.bV4AlphaMask = 0xff000000;
  206262. bitmapInfo.bV4RedMask = 0xff0000;
  206263. bitmapInfo.bV4GreenMask = 0xff00;
  206264. bitmapInfo.bV4BlueMask = 0xff;
  206265. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206266. }
  206267. else
  206268. {
  206269. bitmapInfo.bV4V4Compression = BI_RGB;
  206270. }
  206271. lineStride = -((w * pixelStride + 3) & ~3);
  206272. HDC dc = GetDC (0);
  206273. hdc = CreateCompatibleDC (dc);
  206274. ReleaseDC (0, dc);
  206275. SetMapMode (hdc, MM_TEXT);
  206276. hBitmap = CreateDIBSection (hdc,
  206277. (BITMAPINFO*) &(bitmapInfo),
  206278. DIB_RGB_COLORS,
  206279. (void**) &bitmapData,
  206280. 0, 0);
  206281. previousBitmap = SelectObject (hdc, hBitmap);
  206282. if (format_ == Image::ARGB && clearImage)
  206283. zeromem (bitmapData, abs (h * lineStride));
  206284. imageData = bitmapData - (lineStride * (h - 1));
  206285. }
  206286. ~WindowsBitmapImage()
  206287. {
  206288. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206289. DeleteDC (hdc);
  206290. DeleteObject (hBitmap);
  206291. }
  206292. Image::ImageType getType() const { return Image::NativeImage; }
  206293. LowLevelGraphicsContext* createLowLevelContext()
  206294. {
  206295. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206296. }
  206297. Image::SharedImage* clone()
  206298. {
  206299. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206300. for (int i = 0; i < height; ++i)
  206301. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206302. return im;
  206303. }
  206304. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206305. const int x, const int y,
  206306. const RectangleList& maskedRegion,
  206307. const uint8 updateLayeredWindowAlpha) throw()
  206308. {
  206309. static HDRAWDIB hdd = 0;
  206310. static bool needToCreateDrawDib = true;
  206311. if (needToCreateDrawDib)
  206312. {
  206313. needToCreateDrawDib = false;
  206314. HDC dc = GetDC (0);
  206315. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206316. ReleaseDC (0, dc);
  206317. // only open if we're not palettised
  206318. if (n > 8)
  206319. hdd = DrawDibOpen();
  206320. }
  206321. SetMapMode (dc, MM_TEXT);
  206322. if (transparent)
  206323. {
  206324. POINT p, pos;
  206325. SIZE size;
  206326. RECT windowBounds;
  206327. GetWindowRect (hwnd, &windowBounds);
  206328. p.x = -x;
  206329. p.y = -y;
  206330. pos.x = windowBounds.left;
  206331. pos.y = windowBounds.top;
  206332. size.cx = windowBounds.right - windowBounds.left;
  206333. size.cy = windowBounds.bottom - windowBounds.top;
  206334. BLENDFUNCTION bf;
  206335. bf.AlphaFormat = AC_SRC_ALPHA;
  206336. bf.BlendFlags = 0;
  206337. bf.BlendOp = AC_SRC_OVER;
  206338. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206339. if (! maskedRegion.isEmpty())
  206340. {
  206341. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206342. {
  206343. const Rectangle<int>& r = *i.getRectangle();
  206344. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206345. }
  206346. }
  206347. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206348. }
  206349. else
  206350. {
  206351. int savedDC = 0;
  206352. if (! maskedRegion.isEmpty())
  206353. {
  206354. savedDC = SaveDC (dc);
  206355. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206356. {
  206357. const Rectangle<int>& r = *i.getRectangle();
  206358. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206359. }
  206360. }
  206361. if (hdd == 0)
  206362. {
  206363. StretchDIBits (dc,
  206364. x, y, width, height,
  206365. 0, 0, width, height,
  206366. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206367. DIB_RGB_COLORS, SRCCOPY);
  206368. }
  206369. else
  206370. {
  206371. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206372. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206373. 0, 0, width, height, 0);
  206374. }
  206375. if (! maskedRegion.isEmpty())
  206376. RestoreDC (dc, savedDC);
  206377. }
  206378. }
  206379. private:
  206380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206381. };
  206382. namespace IconConverters
  206383. {
  206384. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206385. {
  206386. Image im;
  206387. if (bitmap != 0)
  206388. {
  206389. BITMAP bm;
  206390. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206391. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206392. {
  206393. HDC tempDC = GetDC (0);
  206394. HDC dc = CreateCompatibleDC (tempDC);
  206395. ReleaseDC (0, tempDC);
  206396. SelectObject (dc, bitmap);
  206397. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206398. Image::BitmapData imageData (im, true);
  206399. for (int y = bm.bmHeight; --y >= 0;)
  206400. {
  206401. for (int x = bm.bmWidth; --x >= 0;)
  206402. {
  206403. COLORREF col = GetPixel (dc, x, y);
  206404. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206405. (uint8) GetGValue (col),
  206406. (uint8) GetBValue (col)));
  206407. }
  206408. }
  206409. DeleteDC (dc);
  206410. }
  206411. }
  206412. return im;
  206413. }
  206414. const Image createImageFromHICON (HICON icon)
  206415. {
  206416. ICONINFO info;
  206417. if (GetIconInfo (icon, &info))
  206418. {
  206419. Image mask (createImageFromHBITMAP (info.hbmMask));
  206420. Image image (createImageFromHBITMAP (info.hbmColor));
  206421. if (mask.isValid() && image.isValid())
  206422. {
  206423. for (int y = image.getHeight(); --y >= 0;)
  206424. {
  206425. for (int x = image.getWidth(); --x >= 0;)
  206426. {
  206427. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206428. if (brightness > 0.0f)
  206429. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206430. }
  206431. }
  206432. return image;
  206433. }
  206434. }
  206435. return Image::null;
  206436. }
  206437. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206438. {
  206439. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206440. Image bitmap (nativeBitmap);
  206441. {
  206442. Graphics g (bitmap);
  206443. g.drawImageAt (image, 0, 0);
  206444. }
  206445. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206446. ICONINFO info;
  206447. info.fIcon = isIcon;
  206448. info.xHotspot = hotspotX;
  206449. info.yHotspot = hotspotY;
  206450. info.hbmMask = mask;
  206451. info.hbmColor = nativeBitmap->hBitmap;
  206452. HICON hi = CreateIconIndirect (&info);
  206453. DeleteObject (mask);
  206454. return hi;
  206455. }
  206456. }
  206457. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206458. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206459. {
  206460. SHORT k = (SHORT) keyCode;
  206461. if ((keyCode & extendedKeyModifier) == 0
  206462. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206463. k += (SHORT) 'A' - (SHORT) 'a';
  206464. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206465. (SHORT) '+', VK_OEM_PLUS,
  206466. (SHORT) '-', VK_OEM_MINUS,
  206467. (SHORT) '.', VK_OEM_PERIOD,
  206468. (SHORT) ';', VK_OEM_1,
  206469. (SHORT) ':', VK_OEM_1,
  206470. (SHORT) '/', VK_OEM_2,
  206471. (SHORT) '?', VK_OEM_2,
  206472. (SHORT) '[', VK_OEM_4,
  206473. (SHORT) ']', VK_OEM_6 };
  206474. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206475. if (k == translatedValues [i])
  206476. k = translatedValues [i + 1];
  206477. return (GetKeyState (k) & 0x8000) != 0;
  206478. }
  206479. class Win32ComponentPeer : public ComponentPeer
  206480. {
  206481. public:
  206482. enum RenderingEngineType
  206483. {
  206484. softwareRenderingEngine = 0,
  206485. direct2DRenderingEngine
  206486. };
  206487. Win32ComponentPeer (Component* const component,
  206488. const int windowStyleFlags,
  206489. HWND parentToAddTo_)
  206490. : ComponentPeer (component, windowStyleFlags),
  206491. dontRepaint (false),
  206492. #if JUCE_DIRECT2D
  206493. currentRenderingEngine (direct2DRenderingEngine),
  206494. #else
  206495. currentRenderingEngine (softwareRenderingEngine),
  206496. #endif
  206497. fullScreen (false),
  206498. isDragging (false),
  206499. isMouseOver (false),
  206500. hasCreatedCaret (false),
  206501. constrainerIsResizing (false),
  206502. currentWindowIcon (0),
  206503. dropTarget (0),
  206504. parentToAddTo (parentToAddTo_),
  206505. updateLayeredWindowAlpha (255)
  206506. {
  206507. callFunctionIfNotLocked (&createWindowCallback, this);
  206508. setTitle (component->getName());
  206509. if ((windowStyleFlags & windowHasDropShadow) != 0
  206510. && Desktop::canUseSemiTransparentWindows())
  206511. {
  206512. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206513. if (shadower != 0)
  206514. shadower->setOwner (component);
  206515. }
  206516. }
  206517. ~Win32ComponentPeer()
  206518. {
  206519. setTaskBarIcon (Image());
  206520. shadower = 0;
  206521. // do this before the next bit to avoid messages arriving for this window
  206522. // before it's destroyed
  206523. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206524. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206525. if (currentWindowIcon != 0)
  206526. DestroyIcon (currentWindowIcon);
  206527. if (dropTarget != 0)
  206528. {
  206529. dropTarget->Release();
  206530. dropTarget = 0;
  206531. }
  206532. #if JUCE_DIRECT2D
  206533. direct2DContext = 0;
  206534. #endif
  206535. }
  206536. void* getNativeHandle() const
  206537. {
  206538. return hwnd;
  206539. }
  206540. void setVisible (bool shouldBeVisible)
  206541. {
  206542. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206543. if (shouldBeVisible)
  206544. InvalidateRect (hwnd, 0, 0);
  206545. else
  206546. lastPaintTime = 0;
  206547. }
  206548. void setTitle (const String& title)
  206549. {
  206550. SetWindowText (hwnd, title.toUTF16());
  206551. }
  206552. void setPosition (int x, int y)
  206553. {
  206554. offsetWithinParent (x, y);
  206555. SetWindowPos (hwnd, 0,
  206556. x - windowBorder.getLeft(),
  206557. y - windowBorder.getTop(),
  206558. 0, 0,
  206559. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206560. }
  206561. void repaintNowIfTransparent()
  206562. {
  206563. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206564. handlePaintMessage();
  206565. }
  206566. void updateBorderSize()
  206567. {
  206568. WINDOWINFO info;
  206569. info.cbSize = sizeof (info);
  206570. if (GetWindowInfo (hwnd, &info))
  206571. {
  206572. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  206573. info.rcClient.left - info.rcWindow.left,
  206574. info.rcWindow.bottom - info.rcClient.bottom,
  206575. info.rcWindow.right - info.rcClient.right);
  206576. }
  206577. #if JUCE_DIRECT2D
  206578. if (direct2DContext != 0)
  206579. direct2DContext->resized();
  206580. #endif
  206581. }
  206582. void setSize (int w, int h)
  206583. {
  206584. SetWindowPos (hwnd, 0, 0, 0,
  206585. w + windowBorder.getLeftAndRight(),
  206586. h + windowBorder.getTopAndBottom(),
  206587. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206588. updateBorderSize();
  206589. repaintNowIfTransparent();
  206590. }
  206591. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206592. {
  206593. fullScreen = isNowFullScreen;
  206594. offsetWithinParent (x, y);
  206595. SetWindowPos (hwnd, 0,
  206596. x - windowBorder.getLeft(),
  206597. y - windowBorder.getTop(),
  206598. w + windowBorder.getLeftAndRight(),
  206599. h + windowBorder.getTopAndBottom(),
  206600. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206601. updateBorderSize();
  206602. repaintNowIfTransparent();
  206603. }
  206604. const Rectangle<int> getBounds() const
  206605. {
  206606. RECT r;
  206607. GetWindowRect (hwnd, &r);
  206608. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206609. HWND parentH = GetParent (hwnd);
  206610. if (parentH != 0)
  206611. {
  206612. GetWindowRect (parentH, &r);
  206613. bounds.translate (-r.left, -r.top);
  206614. }
  206615. return windowBorder.subtractedFrom (bounds);
  206616. }
  206617. const Point<int> getScreenPosition() const
  206618. {
  206619. RECT r;
  206620. GetWindowRect (hwnd, &r);
  206621. return Point<int> (r.left + windowBorder.getLeft(),
  206622. r.top + windowBorder.getTop());
  206623. }
  206624. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206625. {
  206626. return relativePosition + getScreenPosition();
  206627. }
  206628. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206629. {
  206630. return screenPosition - getScreenPosition();
  206631. }
  206632. void setAlpha (float newAlpha)
  206633. {
  206634. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206635. if (component->isOpaque())
  206636. {
  206637. if (newAlpha < 1.0f)
  206638. {
  206639. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206640. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206641. }
  206642. else
  206643. {
  206644. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206645. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206646. }
  206647. }
  206648. else
  206649. {
  206650. updateLayeredWindowAlpha = intAlpha;
  206651. component->repaint();
  206652. }
  206653. }
  206654. void setMinimised (bool shouldBeMinimised)
  206655. {
  206656. if (shouldBeMinimised != isMinimised())
  206657. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206658. }
  206659. bool isMinimised() const
  206660. {
  206661. WINDOWPLACEMENT wp;
  206662. wp.length = sizeof (WINDOWPLACEMENT);
  206663. GetWindowPlacement (hwnd, &wp);
  206664. return wp.showCmd == SW_SHOWMINIMIZED;
  206665. }
  206666. void setFullScreen (bool shouldBeFullScreen)
  206667. {
  206668. setMinimised (false);
  206669. if (fullScreen != shouldBeFullScreen)
  206670. {
  206671. fullScreen = shouldBeFullScreen;
  206672. const WeakReference<Component> deletionChecker (component);
  206673. if (! fullScreen)
  206674. {
  206675. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206676. if (hasTitleBar())
  206677. ShowWindow (hwnd, SW_SHOWNORMAL);
  206678. if (! boundsCopy.isEmpty())
  206679. {
  206680. setBounds (boundsCopy.getX(),
  206681. boundsCopy.getY(),
  206682. boundsCopy.getWidth(),
  206683. boundsCopy.getHeight(),
  206684. false);
  206685. }
  206686. }
  206687. else
  206688. {
  206689. if (hasTitleBar())
  206690. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206691. else
  206692. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206693. }
  206694. if (deletionChecker != 0)
  206695. handleMovedOrResized();
  206696. }
  206697. }
  206698. bool isFullScreen() const
  206699. {
  206700. if (! hasTitleBar())
  206701. return fullScreen;
  206702. WINDOWPLACEMENT wp;
  206703. wp.length = sizeof (wp);
  206704. GetWindowPlacement (hwnd, &wp);
  206705. return wp.showCmd == SW_SHOWMAXIMIZED;
  206706. }
  206707. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206708. {
  206709. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  206710. && isPositiveAndBelow (position.getY(), component->getHeight())))
  206711. return false;
  206712. RECT r;
  206713. GetWindowRect (hwnd, &r);
  206714. POINT p;
  206715. p.x = position.getX() + r.left + windowBorder.getLeft();
  206716. p.y = position.getY() + r.top + windowBorder.getTop();
  206717. HWND w = WindowFromPoint (p);
  206718. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206719. }
  206720. const BorderSize<int> getFrameSize() const
  206721. {
  206722. return windowBorder;
  206723. }
  206724. bool setAlwaysOnTop (bool alwaysOnTop)
  206725. {
  206726. const bool oldDeactivate = shouldDeactivateTitleBar;
  206727. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206728. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206729. 0, 0, 0, 0,
  206730. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206731. shouldDeactivateTitleBar = oldDeactivate;
  206732. if (shadower != 0)
  206733. shadower->componentBroughtToFront (*component);
  206734. return true;
  206735. }
  206736. void toFront (bool makeActive)
  206737. {
  206738. setMinimised (false);
  206739. const bool oldDeactivate = shouldDeactivateTitleBar;
  206740. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206741. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206742. shouldDeactivateTitleBar = oldDeactivate;
  206743. if (! makeActive)
  206744. {
  206745. // in this case a broughttofront call won't have occured, so do it now..
  206746. handleBroughtToFront();
  206747. }
  206748. }
  206749. void toBehind (ComponentPeer* other)
  206750. {
  206751. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206752. jassert (otherPeer != 0); // wrong type of window?
  206753. if (otherPeer != 0)
  206754. {
  206755. setMinimised (false);
  206756. // must be careful not to try to put a topmost window behind a normal one, or win32
  206757. // promotes the normal one to be topmost!
  206758. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206759. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206760. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206761. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206762. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206763. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206764. }
  206765. }
  206766. bool isFocused() const
  206767. {
  206768. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206769. }
  206770. void grabFocus()
  206771. {
  206772. const bool oldDeactivate = shouldDeactivateTitleBar;
  206773. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206774. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206775. shouldDeactivateTitleBar = oldDeactivate;
  206776. }
  206777. void textInputRequired (const Point<int>&)
  206778. {
  206779. if (! hasCreatedCaret)
  206780. {
  206781. hasCreatedCaret = true;
  206782. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206783. }
  206784. ShowCaret (hwnd);
  206785. SetCaretPos (0, 0);
  206786. }
  206787. void repaint (const Rectangle<int>& area)
  206788. {
  206789. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206790. InvalidateRect (hwnd, &r, FALSE);
  206791. }
  206792. void performAnyPendingRepaintsNow()
  206793. {
  206794. MSG m;
  206795. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206796. DispatchMessage (&m);
  206797. }
  206798. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206799. {
  206800. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206801. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206802. return 0;
  206803. }
  206804. void setTaskBarIcon (const Image& image)
  206805. {
  206806. if (image.isValid())
  206807. {
  206808. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  206809. if (taskBarIcon == 0)
  206810. {
  206811. taskBarIcon = new NOTIFYICONDATA();
  206812. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  206813. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206814. taskBarIcon->hWnd = (HWND) hwnd;
  206815. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206816. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206817. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206818. taskBarIcon->hIcon = hicon;
  206819. taskBarIcon->szTip[0] = 0;
  206820. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206821. }
  206822. else
  206823. {
  206824. HICON oldIcon = taskBarIcon->hIcon;
  206825. taskBarIcon->hIcon = hicon;
  206826. taskBarIcon->uFlags = NIF_ICON;
  206827. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206828. DestroyIcon (oldIcon);
  206829. }
  206830. }
  206831. else if (taskBarIcon != 0)
  206832. {
  206833. taskBarIcon->uFlags = 0;
  206834. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206835. DestroyIcon (taskBarIcon->hIcon);
  206836. taskBarIcon = 0;
  206837. }
  206838. }
  206839. void setTaskBarIconToolTip (const String& toolTip) const
  206840. {
  206841. if (taskBarIcon != 0)
  206842. {
  206843. taskBarIcon->uFlags = NIF_TIP;
  206844. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206845. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206846. }
  206847. }
  206848. void handleTaskBarEvent (const LPARAM lParam)
  206849. {
  206850. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206851. {
  206852. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206853. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206854. {
  206855. Component* const current = Component::getCurrentlyModalComponent();
  206856. if (current != 0)
  206857. current->inputAttemptWhenModal();
  206858. }
  206859. }
  206860. else
  206861. {
  206862. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206863. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206864. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206865. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206866. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206867. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206868. eventMods = eventMods.withoutMouseButtons();
  206869. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206870. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  206871. Point<int>(), Time (getMouseEventTime()), 1, false);
  206872. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206873. {
  206874. SetFocus (hwnd);
  206875. SetForegroundWindow (hwnd);
  206876. component->mouseDown (e);
  206877. }
  206878. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206879. {
  206880. component->mouseUp (e);
  206881. }
  206882. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206883. {
  206884. component->mouseDoubleClick (e);
  206885. }
  206886. else if (lParam == WM_MOUSEMOVE)
  206887. {
  206888. component->mouseMove (e);
  206889. }
  206890. }
  206891. }
  206892. bool isInside (HWND h) const
  206893. {
  206894. return GetAncestor (hwnd, GA_ROOT) == h;
  206895. }
  206896. static void updateKeyModifiers() throw()
  206897. {
  206898. int keyMods = 0;
  206899. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206900. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206901. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206902. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206903. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206904. }
  206905. static void updateModifiersFromWParam (const WPARAM wParam)
  206906. {
  206907. int mouseMods = 0;
  206908. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206909. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206910. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206911. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206912. updateKeyModifiers();
  206913. }
  206914. static int64 getMouseEventTime()
  206915. {
  206916. static int64 eventTimeOffset = 0;
  206917. static DWORD lastMessageTime = 0;
  206918. const DWORD thisMessageTime = GetMessageTime();
  206919. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206920. {
  206921. lastMessageTime = thisMessageTime;
  206922. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206923. }
  206924. return eventTimeOffset + thisMessageTime;
  206925. }
  206926. bool dontRepaint;
  206927. static ModifierKeys currentModifiers;
  206928. static ModifierKeys modifiersAtLastCallback;
  206929. private:
  206930. HWND hwnd, parentToAddTo;
  206931. ScopedPointer<DropShadower> shadower;
  206932. RenderingEngineType currentRenderingEngine;
  206933. #if JUCE_DIRECT2D
  206934. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  206935. #endif
  206936. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  206937. BorderSize<int> windowBorder;
  206938. HICON currentWindowIcon;
  206939. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  206940. IDropTarget* dropTarget;
  206941. uint8 updateLayeredWindowAlpha;
  206942. class TemporaryImage : public Timer
  206943. {
  206944. public:
  206945. TemporaryImage() {}
  206946. ~TemporaryImage() {}
  206947. const Image& getImage (const bool transparent, const int w, const int h)
  206948. {
  206949. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206950. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  206951. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  206952. startTimer (3000);
  206953. return image;
  206954. }
  206955. void timerCallback()
  206956. {
  206957. stopTimer();
  206958. image = Image::null;
  206959. }
  206960. private:
  206961. Image image;
  206962. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  206963. };
  206964. TemporaryImage offscreenImageGenerator;
  206965. class WindowClassHolder : public DeletedAtShutdown
  206966. {
  206967. public:
  206968. WindowClassHolder()
  206969. : windowClassName ("JUCE_")
  206970. {
  206971. // this name has to be different for each app/dll instance because otherwise
  206972. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206973. // window class).
  206974. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  206975. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206976. TCHAR moduleFile [1024];
  206977. moduleFile[0] = 0;
  206978. GetModuleFileName (moduleHandle, moduleFile, 1024);
  206979. WORD iconNum = 0;
  206980. WNDCLASSEX wcex;
  206981. wcex.cbSize = sizeof (wcex);
  206982. wcex.style = CS_OWNDC;
  206983. wcex.lpfnWndProc = (WNDPROC) windowProc;
  206984. wcex.lpszClassName = windowClassName.toUTF16();
  206985. wcex.cbClsExtra = 0;
  206986. wcex.cbWndExtra = 32;
  206987. wcex.hInstance = moduleHandle;
  206988. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206989. iconNum = 1;
  206990. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206991. wcex.hCursor = 0;
  206992. wcex.hbrBackground = 0;
  206993. wcex.lpszMenuName = 0;
  206994. RegisterClassEx (&wcex);
  206995. }
  206996. ~WindowClassHolder()
  206997. {
  206998. if (ComponentPeer::getNumPeers() == 0)
  206999. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207000. clearSingletonInstance();
  207001. }
  207002. String windowClassName;
  207003. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207004. };
  207005. static void* createWindowCallback (void* userData)
  207006. {
  207007. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207008. return 0;
  207009. }
  207010. void createWindow()
  207011. {
  207012. DWORD exstyle = WS_EX_ACCEPTFILES;
  207013. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207014. if (hasTitleBar())
  207015. {
  207016. type |= WS_OVERLAPPED;
  207017. if ((styleFlags & windowHasCloseButton) != 0)
  207018. {
  207019. type |= WS_SYSMENU;
  207020. }
  207021. else
  207022. {
  207023. // annoyingly, windows won't let you have a min/max button without a close button
  207024. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207025. }
  207026. if ((styleFlags & windowIsResizable) != 0)
  207027. type |= WS_THICKFRAME;
  207028. }
  207029. else if (parentToAddTo != 0)
  207030. {
  207031. type |= WS_CHILD;
  207032. }
  207033. else
  207034. {
  207035. type |= WS_POPUP | WS_SYSMENU;
  207036. }
  207037. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207038. exstyle |= WS_EX_TOOLWINDOW;
  207039. else
  207040. exstyle |= WS_EX_APPWINDOW;
  207041. if ((styleFlags & windowHasMinimiseButton) != 0)
  207042. type |= WS_MINIMIZEBOX;
  207043. if ((styleFlags & windowHasMaximiseButton) != 0)
  207044. type |= WS_MAXIMIZEBOX;
  207045. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207046. exstyle |= WS_EX_TRANSPARENT;
  207047. if ((styleFlags & windowIsSemiTransparent) != 0
  207048. && Desktop::canUseSemiTransparentWindows())
  207049. exstyle |= WS_EX_LAYERED;
  207050. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207051. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207052. #if JUCE_DIRECT2D
  207053. updateDirect2DContext();
  207054. #endif
  207055. if (hwnd != 0)
  207056. {
  207057. SetWindowLongPtr (hwnd, 0, 0);
  207058. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207059. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207060. if (dropTarget == 0)
  207061. dropTarget = new JuceDropTarget (this);
  207062. RegisterDragDrop (hwnd, dropTarget);
  207063. updateBorderSize();
  207064. // Calling this function here is (for some reason) necessary to make Windows
  207065. // correctly enable the menu items that we specify in the wm_initmenu message.
  207066. GetSystemMenu (hwnd, false);
  207067. const float alpha = component->getAlpha();
  207068. if (alpha < 1.0f)
  207069. setAlpha (alpha);
  207070. }
  207071. else
  207072. {
  207073. jassertfalse;
  207074. }
  207075. }
  207076. static void* destroyWindowCallback (void* handle)
  207077. {
  207078. RevokeDragDrop ((HWND) handle);
  207079. DestroyWindow ((HWND) handle);
  207080. return 0;
  207081. }
  207082. static void* toFrontCallback1 (void* h)
  207083. {
  207084. SetForegroundWindow ((HWND) h);
  207085. return 0;
  207086. }
  207087. static void* toFrontCallback2 (void* h)
  207088. {
  207089. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207090. return 0;
  207091. }
  207092. static void* setFocusCallback (void* h)
  207093. {
  207094. SetFocus ((HWND) h);
  207095. return 0;
  207096. }
  207097. static void* getFocusCallback (void*)
  207098. {
  207099. return GetFocus();
  207100. }
  207101. void offsetWithinParent (int& x, int& y) const
  207102. {
  207103. if (isUsingUpdateLayeredWindow())
  207104. {
  207105. HWND parentHwnd = GetParent (hwnd);
  207106. if (parentHwnd != 0)
  207107. {
  207108. RECT parentRect;
  207109. GetWindowRect (parentHwnd, &parentRect);
  207110. x += parentRect.left;
  207111. y += parentRect.top;
  207112. }
  207113. }
  207114. }
  207115. bool isUsingUpdateLayeredWindow() const
  207116. {
  207117. return ! component->isOpaque();
  207118. }
  207119. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207120. void setIcon (const Image& newIcon)
  207121. {
  207122. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207123. if (hicon != 0)
  207124. {
  207125. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207126. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207127. if (currentWindowIcon != 0)
  207128. DestroyIcon (currentWindowIcon);
  207129. currentWindowIcon = hicon;
  207130. }
  207131. }
  207132. void handlePaintMessage()
  207133. {
  207134. #if JUCE_DIRECT2D
  207135. if (direct2DContext != 0)
  207136. {
  207137. RECT r;
  207138. if (GetUpdateRect (hwnd, &r, false))
  207139. {
  207140. direct2DContext->start();
  207141. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207142. handlePaint (*direct2DContext);
  207143. direct2DContext->end();
  207144. }
  207145. }
  207146. else
  207147. #endif
  207148. {
  207149. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207150. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207151. PAINTSTRUCT paintStruct;
  207152. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207153. // message and become re-entrant, but that's OK
  207154. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207155. // corrupt the image it's using to paint into, so do a check here.
  207156. static bool reentrant = false;
  207157. if (reentrant)
  207158. {
  207159. DeleteObject (rgn);
  207160. EndPaint (hwnd, &paintStruct);
  207161. return;
  207162. }
  207163. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207164. // this is the rectangle to update..
  207165. int x = paintStruct.rcPaint.left;
  207166. int y = paintStruct.rcPaint.top;
  207167. int w = paintStruct.rcPaint.right - x;
  207168. int h = paintStruct.rcPaint.bottom - y;
  207169. const bool transparent = isUsingUpdateLayeredWindow();
  207170. if (transparent)
  207171. {
  207172. // it's not possible to have a transparent window with a title bar at the moment!
  207173. jassert (! hasTitleBar());
  207174. RECT r;
  207175. GetWindowRect (hwnd, &r);
  207176. x = y = 0;
  207177. w = r.right - r.left;
  207178. h = r.bottom - r.top;
  207179. }
  207180. if (w > 0 && h > 0)
  207181. {
  207182. clearMaskedRegion();
  207183. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207184. RectangleList contextClip;
  207185. const Rectangle<int> clipBounds (0, 0, w, h);
  207186. bool needToPaintAll = true;
  207187. if (regionType == COMPLEXREGION && ! transparent)
  207188. {
  207189. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207190. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207191. DeleteObject (clipRgn);
  207192. char rgnData [8192];
  207193. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207194. if (res > 0 && res <= sizeof (rgnData))
  207195. {
  207196. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207197. if (hdr->iType == RDH_RECTANGLES
  207198. && hdr->rcBound.right - hdr->rcBound.left >= w
  207199. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207200. {
  207201. needToPaintAll = false;
  207202. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207203. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207204. while (--num >= 0)
  207205. {
  207206. if (rects->right <= x + w && rects->bottom <= y + h)
  207207. {
  207208. const int cx = jmax (x, (int) rects->left);
  207209. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207210. .getIntersection (clipBounds));
  207211. }
  207212. else
  207213. {
  207214. needToPaintAll = true;
  207215. break;
  207216. }
  207217. ++rects;
  207218. }
  207219. }
  207220. }
  207221. }
  207222. if (needToPaintAll)
  207223. {
  207224. contextClip.clear();
  207225. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207226. }
  207227. if (transparent)
  207228. {
  207229. RectangleList::Iterator i (contextClip);
  207230. while (i.next())
  207231. offscreenImage.clear (*i.getRectangle());
  207232. }
  207233. // if the component's not opaque, this won't draw properly unless the platform can support this
  207234. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207235. updateCurrentModifiers();
  207236. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207237. handlePaint (context);
  207238. if (! dontRepaint)
  207239. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207240. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207241. }
  207242. DeleteObject (rgn);
  207243. EndPaint (hwnd, &paintStruct);
  207244. }
  207245. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207246. _fpreset(); // because some graphics cards can unmask FP exceptions
  207247. #endif
  207248. lastPaintTime = Time::getMillisecondCounter();
  207249. }
  207250. void doMouseEvent (const Point<int>& position)
  207251. {
  207252. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207253. }
  207254. const StringArray getAvailableRenderingEngines()
  207255. {
  207256. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207257. #if JUCE_DIRECT2D
  207258. // xxx is this correct? Seems to enable it on Vista too??
  207259. OSVERSIONINFO info;
  207260. zerostruct (info);
  207261. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207262. GetVersionEx (&info);
  207263. if (info.dwMajorVersion >= 6)
  207264. s.add ("Direct2D");
  207265. #endif
  207266. return s;
  207267. }
  207268. int getCurrentRenderingEngine() throw()
  207269. {
  207270. return currentRenderingEngine;
  207271. }
  207272. #if JUCE_DIRECT2D
  207273. void updateDirect2DContext()
  207274. {
  207275. if (currentRenderingEngine != direct2DRenderingEngine)
  207276. direct2DContext = 0;
  207277. else if (direct2DContext == 0)
  207278. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207279. }
  207280. #endif
  207281. void setCurrentRenderingEngine (int index)
  207282. {
  207283. (void) index;
  207284. #if JUCE_DIRECT2D
  207285. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207286. updateDirect2DContext();
  207287. repaint (component->getLocalBounds());
  207288. #endif
  207289. }
  207290. void doMouseMove (const Point<int>& position)
  207291. {
  207292. if (! isMouseOver)
  207293. {
  207294. isMouseOver = true;
  207295. updateKeyModifiers();
  207296. TRACKMOUSEEVENT tme;
  207297. tme.cbSize = sizeof (tme);
  207298. tme.dwFlags = TME_LEAVE;
  207299. tme.hwndTrack = hwnd;
  207300. tme.dwHoverTime = 0;
  207301. if (! TrackMouseEvent (&tme))
  207302. jassertfalse;
  207303. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207304. }
  207305. else if (! isDragging)
  207306. {
  207307. if (! contains (position, false))
  207308. return;
  207309. }
  207310. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207311. static uint32 lastMouseTime = 0;
  207312. const uint32 now = Time::getMillisecondCounter();
  207313. const int maxMouseMovesPerSecond = 60;
  207314. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207315. {
  207316. lastMouseTime = now;
  207317. doMouseEvent (position);
  207318. }
  207319. }
  207320. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207321. {
  207322. if (GetCapture() != hwnd)
  207323. SetCapture (hwnd);
  207324. doMouseMove (position);
  207325. updateModifiersFromWParam (wParam);
  207326. isDragging = true;
  207327. doMouseEvent (position);
  207328. }
  207329. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207330. {
  207331. updateModifiersFromWParam (wParam);
  207332. isDragging = false;
  207333. // release the mouse capture if the user has released all buttons
  207334. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207335. ReleaseCapture();
  207336. doMouseEvent (position);
  207337. }
  207338. void doCaptureChanged()
  207339. {
  207340. if (constrainerIsResizing)
  207341. {
  207342. if (constrainer != 0)
  207343. constrainer->resizeEnd();
  207344. constrainerIsResizing = false;
  207345. }
  207346. if (isDragging)
  207347. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207348. }
  207349. void doMouseExit()
  207350. {
  207351. isMouseOver = false;
  207352. doMouseEvent (getCurrentMousePos());
  207353. }
  207354. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207355. {
  207356. updateKeyModifiers();
  207357. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207358. handleMouseWheel (0, position, getMouseEventTime(),
  207359. isVertical ? 0.0f : amount,
  207360. isVertical ? amount : 0.0f);
  207361. }
  207362. void sendModifierKeyChangeIfNeeded()
  207363. {
  207364. if (modifiersAtLastCallback != currentModifiers)
  207365. {
  207366. modifiersAtLastCallback = currentModifiers;
  207367. handleModifierKeysChange();
  207368. }
  207369. }
  207370. bool doKeyUp (const WPARAM key)
  207371. {
  207372. updateKeyModifiers();
  207373. switch (key)
  207374. {
  207375. case VK_SHIFT:
  207376. case VK_CONTROL:
  207377. case VK_MENU:
  207378. case VK_CAPITAL:
  207379. case VK_LWIN:
  207380. case VK_RWIN:
  207381. case VK_APPS:
  207382. case VK_NUMLOCK:
  207383. case VK_SCROLL:
  207384. case VK_LSHIFT:
  207385. case VK_RSHIFT:
  207386. case VK_LCONTROL:
  207387. case VK_LMENU:
  207388. case VK_RCONTROL:
  207389. case VK_RMENU:
  207390. sendModifierKeyChangeIfNeeded();
  207391. }
  207392. return handleKeyUpOrDown (false)
  207393. || Component::getCurrentlyModalComponent() != 0;
  207394. }
  207395. bool doKeyDown (const WPARAM key)
  207396. {
  207397. updateKeyModifiers();
  207398. bool used = false;
  207399. switch (key)
  207400. {
  207401. case VK_SHIFT:
  207402. case VK_LSHIFT:
  207403. case VK_RSHIFT:
  207404. case VK_CONTROL:
  207405. case VK_LCONTROL:
  207406. case VK_RCONTROL:
  207407. case VK_MENU:
  207408. case VK_LMENU:
  207409. case VK_RMENU:
  207410. case VK_LWIN:
  207411. case VK_RWIN:
  207412. case VK_CAPITAL:
  207413. case VK_NUMLOCK:
  207414. case VK_SCROLL:
  207415. case VK_APPS:
  207416. sendModifierKeyChangeIfNeeded();
  207417. break;
  207418. case VK_LEFT:
  207419. case VK_RIGHT:
  207420. case VK_UP:
  207421. case VK_DOWN:
  207422. case VK_PRIOR:
  207423. case VK_NEXT:
  207424. case VK_HOME:
  207425. case VK_END:
  207426. case VK_DELETE:
  207427. case VK_INSERT:
  207428. case VK_F1:
  207429. case VK_F2:
  207430. case VK_F3:
  207431. case VK_F4:
  207432. case VK_F5:
  207433. case VK_F6:
  207434. case VK_F7:
  207435. case VK_F8:
  207436. case VK_F9:
  207437. case VK_F10:
  207438. case VK_F11:
  207439. case VK_F12:
  207440. case VK_F13:
  207441. case VK_F14:
  207442. case VK_F15:
  207443. case VK_F16:
  207444. used = handleKeyUpOrDown (true);
  207445. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207446. break;
  207447. case VK_ADD:
  207448. case VK_SUBTRACT:
  207449. case VK_MULTIPLY:
  207450. case VK_DIVIDE:
  207451. case VK_SEPARATOR:
  207452. case VK_DECIMAL:
  207453. used = handleKeyUpOrDown (true);
  207454. break;
  207455. default:
  207456. used = handleKeyUpOrDown (true);
  207457. {
  207458. MSG msg;
  207459. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207460. {
  207461. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207462. // manually generate the key-press event that matches this key-down.
  207463. const UINT keyChar = MapVirtualKey (key, 2);
  207464. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207465. }
  207466. }
  207467. break;
  207468. }
  207469. if (Component::getCurrentlyModalComponent() != 0)
  207470. used = true;
  207471. return used;
  207472. }
  207473. bool doKeyChar (int key, const LPARAM flags)
  207474. {
  207475. updateKeyModifiers();
  207476. juce_wchar textChar = (juce_wchar) key;
  207477. const int virtualScanCode = (flags >> 16) & 0xff;
  207478. if (key >= '0' && key <= '9')
  207479. {
  207480. switch (virtualScanCode) // check for a numeric keypad scan-code
  207481. {
  207482. case 0x52:
  207483. case 0x4f:
  207484. case 0x50:
  207485. case 0x51:
  207486. case 0x4b:
  207487. case 0x4c:
  207488. case 0x4d:
  207489. case 0x47:
  207490. case 0x48:
  207491. case 0x49:
  207492. key = (key - '0') + KeyPress::numberPad0;
  207493. break;
  207494. default:
  207495. break;
  207496. }
  207497. }
  207498. else
  207499. {
  207500. // convert the scan code to an unmodified character code..
  207501. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207502. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207503. keyChar = LOWORD (keyChar);
  207504. if (keyChar != 0)
  207505. key = (int) keyChar;
  207506. // avoid sending junk text characters for some control-key combinations
  207507. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207508. textChar = 0;
  207509. }
  207510. return handleKeyPress (key, textChar);
  207511. }
  207512. bool doAppCommand (const LPARAM lParam)
  207513. {
  207514. int key = 0;
  207515. switch (GET_APPCOMMAND_LPARAM (lParam))
  207516. {
  207517. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207518. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207519. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207520. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207521. default: break;
  207522. }
  207523. if (key != 0)
  207524. {
  207525. updateKeyModifiers();
  207526. if (hwnd == GetActiveWindow())
  207527. {
  207528. handleKeyPress (key, 0);
  207529. return true;
  207530. }
  207531. }
  207532. return false;
  207533. }
  207534. bool isConstrainedNativeWindow() const
  207535. {
  207536. return constrainer != 0
  207537. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  207538. }
  207539. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207540. {
  207541. if (isConstrainedNativeWindow())
  207542. {
  207543. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207544. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207545. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207546. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207547. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207548. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207549. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207550. r->left = pos.getX();
  207551. r->top = pos.getY();
  207552. r->right = pos.getRight();
  207553. r->bottom = pos.getBottom();
  207554. }
  207555. return TRUE;
  207556. }
  207557. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207558. {
  207559. if (isConstrainedNativeWindow())
  207560. {
  207561. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207562. && ! Component::isMouseButtonDownAnywhere())
  207563. {
  207564. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207565. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207566. constrainer->checkBounds (pos, current,
  207567. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207568. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207569. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207570. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207571. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207572. wp->x = pos.getX();
  207573. wp->y = pos.getY();
  207574. wp->cx = pos.getWidth();
  207575. wp->cy = pos.getHeight();
  207576. }
  207577. }
  207578. return 0;
  207579. }
  207580. void handleAppActivation (const WPARAM wParam)
  207581. {
  207582. modifiersAtLastCallback = -1;
  207583. updateKeyModifiers();
  207584. if (isMinimised())
  207585. {
  207586. component->repaint();
  207587. handleMovedOrResized();
  207588. if (! ComponentPeer::isValidPeer (this))
  207589. return;
  207590. }
  207591. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207592. {
  207593. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207594. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207595. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207596. }
  207597. else
  207598. {
  207599. handleBroughtToFront();
  207600. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207601. Component::getCurrentlyModalComponent()->toFront (true);
  207602. }
  207603. }
  207604. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207605. {
  207606. public:
  207607. JuceDropTarget (Win32ComponentPeer* const owner_)
  207608. : owner (owner_)
  207609. {
  207610. }
  207611. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207612. {
  207613. updateFileList (pDataObject);
  207614. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207615. *pdwEffect = DROPEFFECT_COPY;
  207616. return S_OK;
  207617. }
  207618. HRESULT __stdcall DragLeave()
  207619. {
  207620. owner->handleFileDragExit (files);
  207621. return S_OK;
  207622. }
  207623. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207624. {
  207625. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207626. *pdwEffect = DROPEFFECT_COPY;
  207627. return S_OK;
  207628. }
  207629. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207630. {
  207631. updateFileList (pDataObject);
  207632. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207633. *pdwEffect = DROPEFFECT_COPY;
  207634. return S_OK;
  207635. }
  207636. private:
  207637. Win32ComponentPeer* const owner;
  207638. StringArray files;
  207639. void updateFileList (IDataObject* const pDataObject)
  207640. {
  207641. files.clear();
  207642. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207643. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207644. if (pDataObject->GetData (&format, &medium) == S_OK)
  207645. {
  207646. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207647. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207648. unsigned int i = 0;
  207649. if (pDropFiles->fWide)
  207650. {
  207651. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207652. for (;;)
  207653. {
  207654. unsigned int len = 0;
  207655. while (i + len < totalLen && fname [i + len] != 0)
  207656. ++len;
  207657. if (len == 0)
  207658. break;
  207659. files.add (String (fname + i, len));
  207660. i += len + 1;
  207661. }
  207662. }
  207663. else
  207664. {
  207665. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207666. for (;;)
  207667. {
  207668. unsigned int len = 0;
  207669. while (i + len < totalLen && fname [i + len] != 0)
  207670. ++len;
  207671. if (len == 0)
  207672. break;
  207673. files.add (String (fname + i, len));
  207674. i += len + 1;
  207675. }
  207676. }
  207677. GlobalUnlock (medium.hGlobal);
  207678. }
  207679. }
  207680. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207681. };
  207682. void doSettingChange()
  207683. {
  207684. Desktop::getInstance().refreshMonitorSizes();
  207685. if (fullScreen && ! isMinimised())
  207686. {
  207687. const Rectangle<int> r (component->getParentMonitorArea());
  207688. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207689. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207690. }
  207691. }
  207692. public:
  207693. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207694. {
  207695. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207696. if (peer != 0)
  207697. {
  207698. jassert (isValidPeer (peer));
  207699. return peer->peerWindowProc (h, message, wParam, lParam);
  207700. }
  207701. return DefWindowProcW (h, message, wParam, lParam);
  207702. }
  207703. private:
  207704. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207705. {
  207706. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207707. return callback (userData);
  207708. else
  207709. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207710. }
  207711. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207712. {
  207713. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207714. }
  207715. const Point<int> getCurrentMousePos() throw()
  207716. {
  207717. RECT wr;
  207718. GetWindowRect (hwnd, &wr);
  207719. const DWORD mp = GetMessagePos();
  207720. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207721. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207722. }
  207723. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207724. {
  207725. switch (message)
  207726. {
  207727. case WM_NCHITTEST:
  207728. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207729. return HTTRANSPARENT;
  207730. else if (! hasTitleBar())
  207731. return HTCLIENT;
  207732. break;
  207733. case WM_PAINT:
  207734. handlePaintMessage();
  207735. return 0;
  207736. case WM_NCPAINT:
  207737. if (hasTitleBar())
  207738. break;
  207739. else if (wParam != 1)
  207740. handlePaintMessage();
  207741. return 0;
  207742. case WM_ERASEBKGND:
  207743. case WM_NCCALCSIZE:
  207744. if (hasTitleBar())
  207745. break;
  207746. return 1;
  207747. case WM_MOUSEMOVE:
  207748. doMouseMove (getPointFromLParam (lParam));
  207749. return 0;
  207750. case WM_MOUSELEAVE:
  207751. doMouseExit();
  207752. return 0;
  207753. case WM_LBUTTONDOWN:
  207754. case WM_MBUTTONDOWN:
  207755. case WM_RBUTTONDOWN:
  207756. doMouseDown (getPointFromLParam (lParam), wParam);
  207757. return 0;
  207758. case WM_LBUTTONUP:
  207759. case WM_MBUTTONUP:
  207760. case WM_RBUTTONUP:
  207761. doMouseUp (getPointFromLParam (lParam), wParam);
  207762. return 0;
  207763. case WM_CAPTURECHANGED:
  207764. doCaptureChanged();
  207765. return 0;
  207766. case WM_NCMOUSEMOVE:
  207767. if (hasTitleBar())
  207768. break;
  207769. return 0;
  207770. case 0x020A: /* WM_MOUSEWHEEL */
  207771. case 0x020E: /* WM_MOUSEHWHEEL */
  207772. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  207773. return 0;
  207774. case WM_SIZING:
  207775. return handleSizeConstraining ((RECT*) lParam, wParam);
  207776. case WM_WINDOWPOSCHANGING:
  207777. return handlePositionChanging ((WINDOWPOS*) lParam);
  207778. case WM_WINDOWPOSCHANGED:
  207779. {
  207780. const Point<int> pos (getCurrentMousePos());
  207781. if (contains (pos, false))
  207782. doMouseEvent (pos);
  207783. }
  207784. handleMovedOrResized();
  207785. if (dontRepaint)
  207786. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207787. return 0;
  207788. case WM_KEYDOWN:
  207789. case WM_SYSKEYDOWN:
  207790. if (doKeyDown (wParam))
  207791. return 0;
  207792. break;
  207793. case WM_KEYUP:
  207794. case WM_SYSKEYUP:
  207795. if (doKeyUp (wParam))
  207796. return 0;
  207797. break;
  207798. case WM_CHAR:
  207799. if (doKeyChar ((int) wParam, lParam))
  207800. return 0;
  207801. break;
  207802. case WM_APPCOMMAND:
  207803. if (doAppCommand (lParam))
  207804. return TRUE;
  207805. break;
  207806. case WM_SETFOCUS:
  207807. updateKeyModifiers();
  207808. handleFocusGain();
  207809. break;
  207810. case WM_KILLFOCUS:
  207811. if (hasCreatedCaret)
  207812. {
  207813. hasCreatedCaret = false;
  207814. DestroyCaret();
  207815. }
  207816. handleFocusLoss();
  207817. break;
  207818. case WM_ACTIVATEAPP:
  207819. // Windows does weird things to process priority when you swap apps,
  207820. // so this forces an update when the app is brought to the front
  207821. if (wParam != FALSE)
  207822. juce_repeatLastProcessPriority();
  207823. else
  207824. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207825. juce_CheckCurrentlyFocusedTopLevelWindow();
  207826. modifiersAtLastCallback = -1;
  207827. return 0;
  207828. case WM_ACTIVATE:
  207829. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207830. {
  207831. handleAppActivation (wParam);
  207832. return 0;
  207833. }
  207834. break;
  207835. case WM_NCACTIVATE:
  207836. // while a temporary window is being shown, prevent Windows from deactivating the
  207837. // title bars of our main windows.
  207838. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207839. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207840. break;
  207841. case WM_MOUSEACTIVATE:
  207842. if (! component->getMouseClickGrabsKeyboardFocus())
  207843. return MA_NOACTIVATE;
  207844. break;
  207845. case WM_SHOWWINDOW:
  207846. if (wParam != 0)
  207847. handleBroughtToFront();
  207848. break;
  207849. case WM_CLOSE:
  207850. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207851. handleUserClosingWindow();
  207852. return 0;
  207853. case WM_QUERYENDSESSION:
  207854. if (JUCEApplication::getInstance() != 0)
  207855. {
  207856. JUCEApplication::getInstance()->systemRequestedQuit();
  207857. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207858. }
  207859. return TRUE;
  207860. case WM_TRAYNOTIFY:
  207861. handleTaskBarEvent (lParam);
  207862. break;
  207863. case WM_SYNCPAINT:
  207864. return 0;
  207865. case WM_DISPLAYCHANGE:
  207866. InvalidateRect (h, 0, 0);
  207867. // intentional fall-through...
  207868. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207869. doSettingChange();
  207870. break;
  207871. case WM_INITMENU:
  207872. if (! hasTitleBar())
  207873. {
  207874. if (isFullScreen())
  207875. {
  207876. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207877. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207878. }
  207879. else if (! isMinimised())
  207880. {
  207881. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207882. }
  207883. }
  207884. break;
  207885. case WM_SYSCOMMAND:
  207886. switch (wParam & 0xfff0)
  207887. {
  207888. case SC_CLOSE:
  207889. if (sendInputAttemptWhenModalMessage())
  207890. return 0;
  207891. if (hasTitleBar())
  207892. {
  207893. PostMessage (h, WM_CLOSE, 0, 0);
  207894. return 0;
  207895. }
  207896. break;
  207897. case SC_KEYMENU:
  207898. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  207899. // situations that can arise if a modal loop is started from an alt-key keypress).
  207900. if (hasTitleBar() && h == GetCapture())
  207901. ReleaseCapture();
  207902. break;
  207903. case SC_MAXIMIZE:
  207904. if (! sendInputAttemptWhenModalMessage())
  207905. setFullScreen (true);
  207906. return 0;
  207907. case SC_MINIMIZE:
  207908. if (sendInputAttemptWhenModalMessage())
  207909. return 0;
  207910. if (! hasTitleBar())
  207911. {
  207912. setMinimised (true);
  207913. return 0;
  207914. }
  207915. break;
  207916. case SC_RESTORE:
  207917. if (sendInputAttemptWhenModalMessage())
  207918. return 0;
  207919. if (hasTitleBar())
  207920. {
  207921. if (isFullScreen())
  207922. {
  207923. setFullScreen (false);
  207924. return 0;
  207925. }
  207926. }
  207927. else
  207928. {
  207929. if (isMinimised())
  207930. setMinimised (false);
  207931. else if (isFullScreen())
  207932. setFullScreen (false);
  207933. return 0;
  207934. }
  207935. break;
  207936. }
  207937. break;
  207938. case WM_NCLBUTTONDOWN:
  207939. if (! sendInputAttemptWhenModalMessage())
  207940. {
  207941. switch (wParam)
  207942. {
  207943. case HTBOTTOM:
  207944. case HTBOTTOMLEFT:
  207945. case HTBOTTOMRIGHT:
  207946. case HTGROWBOX:
  207947. case HTLEFT:
  207948. case HTRIGHT:
  207949. case HTTOP:
  207950. case HTTOPLEFT:
  207951. case HTTOPRIGHT:
  207952. if (isConstrainedNativeWindow())
  207953. {
  207954. constrainerIsResizing = true;
  207955. constrainer->resizeStart();
  207956. }
  207957. break;
  207958. default:
  207959. break;
  207960. };
  207961. }
  207962. break;
  207963. case WM_NCRBUTTONDOWN:
  207964. case WM_NCMBUTTONDOWN:
  207965. sendInputAttemptWhenModalMessage();
  207966. break;
  207967. //case WM_IME_STARTCOMPOSITION;
  207968. // return 0;
  207969. case WM_GETDLGCODE:
  207970. return DLGC_WANTALLKEYS;
  207971. default:
  207972. if (taskBarIcon != 0)
  207973. {
  207974. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  207975. if (message == taskbarCreatedMessage)
  207976. {
  207977. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207978. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207979. }
  207980. }
  207981. break;
  207982. }
  207983. return DefWindowProcW (h, message, wParam, lParam);
  207984. }
  207985. bool sendInputAttemptWhenModalMessage()
  207986. {
  207987. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207988. {
  207989. Component* const current = Component::getCurrentlyModalComponent();
  207990. if (current != 0)
  207991. current->inputAttemptWhenModal();
  207992. return true;
  207993. }
  207994. return false;
  207995. }
  207996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  207997. };
  207998. ModifierKeys Win32ComponentPeer::currentModifiers;
  207999. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208000. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208001. {
  208002. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208003. }
  208004. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208005. void ModifierKeys::updateCurrentModifiers() throw()
  208006. {
  208007. currentModifiers = Win32ComponentPeer::currentModifiers;
  208008. }
  208009. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208010. {
  208011. Win32ComponentPeer::updateKeyModifiers();
  208012. int mouseMods = 0;
  208013. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208014. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208015. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208016. Win32ComponentPeer::currentModifiers
  208017. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208018. return Win32ComponentPeer::currentModifiers;
  208019. }
  208020. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208021. {
  208022. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208023. if (wp != 0)
  208024. wp->setTaskBarIcon (newImage);
  208025. }
  208026. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208027. {
  208028. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208029. if (wp != 0)
  208030. wp->setTaskBarIconToolTip (tooltip);
  208031. }
  208032. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208033. {
  208034. DWORD val = GetWindowLong (h, styleType);
  208035. if (bitIsSet)
  208036. val |= feature;
  208037. else
  208038. val &= ~feature;
  208039. SetWindowLongPtr (h, styleType, val);
  208040. SetWindowPos (h, 0, 0, 0, 0, 0,
  208041. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208042. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208043. }
  208044. bool Process::isForegroundProcess()
  208045. {
  208046. HWND fg = GetForegroundWindow();
  208047. if (fg == 0)
  208048. return true;
  208049. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208050. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208051. // have to see if any of our windows are children of the foreground window
  208052. fg = GetAncestor (fg, GA_ROOT);
  208053. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208054. {
  208055. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208056. if (wp != 0 && wp->isInside (fg))
  208057. return true;
  208058. }
  208059. return false;
  208060. }
  208061. bool AlertWindow::showNativeDialogBox (const String& title,
  208062. const String& bodyText,
  208063. bool isOkCancel)
  208064. {
  208065. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208066. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208067. : MB_OK)) == IDOK;
  208068. }
  208069. void Desktop::createMouseInputSources()
  208070. {
  208071. mouseSources.add (new MouseInputSource (0, true));
  208072. }
  208073. const Point<int> MouseInputSource::getCurrentMousePosition()
  208074. {
  208075. POINT mousePos;
  208076. GetCursorPos (&mousePos);
  208077. return Point<int> (mousePos.x, mousePos.y);
  208078. }
  208079. void Desktop::setMousePosition (const Point<int>& newPosition)
  208080. {
  208081. SetCursorPos (newPosition.getX(), newPosition.getY());
  208082. }
  208083. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208084. {
  208085. return createSoftwareImage (format, width, height, clearImage);
  208086. }
  208087. class ScreenSaverDefeater : public Timer,
  208088. public DeletedAtShutdown
  208089. {
  208090. public:
  208091. ScreenSaverDefeater()
  208092. {
  208093. startTimer (10000);
  208094. timerCallback();
  208095. }
  208096. ~ScreenSaverDefeater() {}
  208097. void timerCallback()
  208098. {
  208099. if (Process::isForegroundProcess())
  208100. {
  208101. // simulate a shift key getting pressed..
  208102. INPUT input[2];
  208103. input[0].type = INPUT_KEYBOARD;
  208104. input[0].ki.wVk = VK_SHIFT;
  208105. input[0].ki.dwFlags = 0;
  208106. input[0].ki.dwExtraInfo = 0;
  208107. input[1].type = INPUT_KEYBOARD;
  208108. input[1].ki.wVk = VK_SHIFT;
  208109. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208110. input[1].ki.dwExtraInfo = 0;
  208111. SendInput (2, input, sizeof (INPUT));
  208112. }
  208113. }
  208114. };
  208115. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208116. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208117. {
  208118. if (isEnabled)
  208119. deleteAndZero (screenSaverDefeater);
  208120. else if (screenSaverDefeater == 0)
  208121. screenSaverDefeater = new ScreenSaverDefeater();
  208122. }
  208123. bool Desktop::isScreenSaverEnabled()
  208124. {
  208125. return screenSaverDefeater == 0;
  208126. }
  208127. /* (The code below is the "correct" way to disable the screen saver, but it
  208128. completely fails on winXP when the saver is password-protected...)
  208129. static bool juce_screenSaverEnabled = true;
  208130. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208131. {
  208132. juce_screenSaverEnabled = isEnabled;
  208133. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208134. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208135. }
  208136. bool Desktop::isScreenSaverEnabled() throw()
  208137. {
  208138. return juce_screenSaverEnabled;
  208139. }
  208140. */
  208141. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208142. {
  208143. if (enableOrDisable)
  208144. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208145. }
  208146. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208147. {
  208148. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208149. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208150. return TRUE;
  208151. }
  208152. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208153. {
  208154. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208155. // make sure the first in the list is the main monitor
  208156. for (int i = 1; i < monitorCoords.size(); ++i)
  208157. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208158. monitorCoords.swap (i, 0);
  208159. if (monitorCoords.size() == 0)
  208160. {
  208161. RECT r;
  208162. GetWindowRect (GetDesktopWindow(), &r);
  208163. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208164. }
  208165. if (clipToWorkArea)
  208166. {
  208167. // clip the main monitor to the active non-taskbar area
  208168. RECT r;
  208169. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208170. Rectangle<int>& screen = monitorCoords.getReference (0);
  208171. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208172. jmax (screen.getY(), (int) r.top));
  208173. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208174. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208175. }
  208176. }
  208177. const Image juce_createIconForFile (const File& file)
  208178. {
  208179. Image image;
  208180. WORD iconNum = 0;
  208181. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208182. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208183. if (icon != 0)
  208184. {
  208185. image = IconConverters::createImageFromHICON (icon);
  208186. DestroyIcon (icon);
  208187. }
  208188. return image;
  208189. }
  208190. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208191. {
  208192. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208193. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208194. Image im (image);
  208195. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208196. {
  208197. im = im.rescaled (maxW, maxH);
  208198. hotspotX = (hotspotX * maxW) / image.getWidth();
  208199. hotspotY = (hotspotY * maxH) / image.getHeight();
  208200. }
  208201. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208202. }
  208203. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208204. {
  208205. if (cursorHandle != 0 && ! isStandard)
  208206. DestroyCursor ((HCURSOR) cursorHandle);
  208207. }
  208208. enum
  208209. {
  208210. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208211. };
  208212. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208213. {
  208214. LPCTSTR cursorName = IDC_ARROW;
  208215. switch (type)
  208216. {
  208217. case NormalCursor: break;
  208218. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208219. case WaitCursor: cursorName = IDC_WAIT; break;
  208220. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208221. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208222. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208223. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208224. case LeftRightResizeCursor:
  208225. case LeftEdgeResizeCursor:
  208226. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208227. case UpDownResizeCursor:
  208228. case TopEdgeResizeCursor:
  208229. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208230. case TopLeftCornerResizeCursor:
  208231. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208232. case TopRightCornerResizeCursor:
  208233. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208234. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208235. case DraggingHandCursor:
  208236. {
  208237. static void* dragHandCursor = 0;
  208238. if (dragHandCursor == 0)
  208239. {
  208240. static const unsigned char dragHandData[] =
  208241. { 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,
  208242. 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,
  208243. 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 };
  208244. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208245. }
  208246. return dragHandCursor;
  208247. }
  208248. default:
  208249. jassertfalse; break;
  208250. }
  208251. HCURSOR cursorH = LoadCursor (0, cursorName);
  208252. if (cursorH == 0)
  208253. cursorH = LoadCursor (0, IDC_ARROW);
  208254. return cursorH;
  208255. }
  208256. void MouseCursor::showInWindow (ComponentPeer*) const
  208257. {
  208258. HCURSOR c = (HCURSOR) getHandle();
  208259. if (c == 0)
  208260. c = LoadCursor (0, IDC_ARROW);
  208261. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208262. c = 0;
  208263. SetCursor (c);
  208264. }
  208265. void MouseCursor::showInAllWindows() const
  208266. {
  208267. showInWindow (0);
  208268. }
  208269. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208270. {
  208271. public:
  208272. JuceDropSource() {}
  208273. ~JuceDropSource() {}
  208274. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208275. {
  208276. if (escapePressed)
  208277. return DRAGDROP_S_CANCEL;
  208278. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208279. return DRAGDROP_S_DROP;
  208280. return S_OK;
  208281. }
  208282. HRESULT __stdcall GiveFeedback (DWORD)
  208283. {
  208284. return DRAGDROP_S_USEDEFAULTCURSORS;
  208285. }
  208286. };
  208287. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208288. {
  208289. public:
  208290. JuceEnumFormatEtc (const FORMATETC* const format_)
  208291. : format (format_),
  208292. index (0)
  208293. {
  208294. }
  208295. ~JuceEnumFormatEtc() {}
  208296. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208297. {
  208298. if (result == 0)
  208299. return E_POINTER;
  208300. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208301. newOne->index = index;
  208302. *result = newOne;
  208303. return S_OK;
  208304. }
  208305. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208306. {
  208307. if (pceltFetched != 0)
  208308. *pceltFetched = 0;
  208309. else if (celt != 1)
  208310. return S_FALSE;
  208311. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208312. {
  208313. copyFormatEtc (lpFormatEtc [0], *format);
  208314. ++index;
  208315. if (pceltFetched != 0)
  208316. *pceltFetched = 1;
  208317. return S_OK;
  208318. }
  208319. return S_FALSE;
  208320. }
  208321. HRESULT __stdcall Skip (ULONG celt)
  208322. {
  208323. if (index + (int) celt >= 1)
  208324. return S_FALSE;
  208325. index += celt;
  208326. return S_OK;
  208327. }
  208328. HRESULT __stdcall Reset()
  208329. {
  208330. index = 0;
  208331. return S_OK;
  208332. }
  208333. private:
  208334. const FORMATETC* const format;
  208335. int index;
  208336. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208337. {
  208338. dest = source;
  208339. if (source.ptd != 0)
  208340. {
  208341. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208342. *(dest.ptd) = *(source.ptd);
  208343. }
  208344. }
  208345. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208346. };
  208347. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208348. {
  208349. public:
  208350. JuceDataObject (JuceDropSource* const dropSource_,
  208351. const FORMATETC* const format_,
  208352. const STGMEDIUM* const medium_)
  208353. : dropSource (dropSource_),
  208354. format (format_),
  208355. medium (medium_)
  208356. {
  208357. }
  208358. ~JuceDataObject()
  208359. {
  208360. jassert (refCount == 0);
  208361. }
  208362. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208363. {
  208364. if ((pFormatEtc->tymed & format->tymed) != 0
  208365. && pFormatEtc->cfFormat == format->cfFormat
  208366. && pFormatEtc->dwAspect == format->dwAspect)
  208367. {
  208368. pMedium->tymed = format->tymed;
  208369. pMedium->pUnkForRelease = 0;
  208370. if (format->tymed == TYMED_HGLOBAL)
  208371. {
  208372. const SIZE_T len = GlobalSize (medium->hGlobal);
  208373. void* const src = GlobalLock (medium->hGlobal);
  208374. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208375. memcpy (dst, src, len);
  208376. GlobalUnlock (medium->hGlobal);
  208377. pMedium->hGlobal = dst;
  208378. return S_OK;
  208379. }
  208380. }
  208381. return DV_E_FORMATETC;
  208382. }
  208383. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208384. {
  208385. if (f == 0)
  208386. return E_INVALIDARG;
  208387. if (f->tymed == format->tymed
  208388. && f->cfFormat == format->cfFormat
  208389. && f->dwAspect == format->dwAspect)
  208390. return S_OK;
  208391. return DV_E_FORMATETC;
  208392. }
  208393. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208394. {
  208395. pFormatEtcOut->ptd = 0;
  208396. return E_NOTIMPL;
  208397. }
  208398. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208399. {
  208400. if (result == 0)
  208401. return E_POINTER;
  208402. if (direction == DATADIR_GET)
  208403. {
  208404. *result = new JuceEnumFormatEtc (format);
  208405. return S_OK;
  208406. }
  208407. *result = 0;
  208408. return E_NOTIMPL;
  208409. }
  208410. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208411. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208412. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208413. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208414. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208415. private:
  208416. JuceDropSource* const dropSource;
  208417. const FORMATETC* const format;
  208418. const STGMEDIUM* const medium;
  208419. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208420. };
  208421. static HDROP createHDrop (const StringArray& fileNames)
  208422. {
  208423. int totalBytes = 0;
  208424. for (int i = fileNames.size(); --i >= 0;)
  208425. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  208426. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  208427. if (hDrop != 0)
  208428. {
  208429. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208430. pDropFiles->pFiles = sizeof (DROPFILES);
  208431. pDropFiles->fWide = true;
  208432. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208433. for (int i = 0; i < fileNames.size(); ++i)
  208434. {
  208435. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  208436. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  208437. }
  208438. *fname = 0;
  208439. GlobalUnlock (hDrop);
  208440. }
  208441. return hDrop;
  208442. }
  208443. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208444. {
  208445. JuceDropSource* const source = new JuceDropSource();
  208446. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208447. DWORD effect;
  208448. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208449. data->Release();
  208450. source->Release();
  208451. return res == DRAGDROP_S_DROP;
  208452. }
  208453. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208454. {
  208455. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208456. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208457. medium.hGlobal = createHDrop (files);
  208458. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208459. : DROPEFFECT_COPY);
  208460. }
  208461. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208462. {
  208463. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208464. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208465. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  208466. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  208467. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208468. text.copyToUTF16 (data, numBytes);
  208469. format.cfFormat = CF_UNICODETEXT;
  208470. GlobalUnlock (medium.hGlobal);
  208471. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208472. }
  208473. #endif
  208474. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208475. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208476. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208477. // compiled on its own).
  208478. #if JUCE_INCLUDED_FILE
  208479. namespace FileChooserHelpers
  208480. {
  208481. static bool areThereAnyAlwaysOnTopWindows()
  208482. {
  208483. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208484. {
  208485. Component* c = Desktop::getInstance().getComponent (i);
  208486. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208487. return true;
  208488. }
  208489. return false;
  208490. }
  208491. struct FileChooserCallbackInfo
  208492. {
  208493. String initialPath;
  208494. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208495. ScopedPointer<Component> customComponent;
  208496. };
  208497. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208498. {
  208499. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208500. if (msg == BFFM_INITIALIZED)
  208501. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  208502. else if (msg == BFFM_VALIDATEFAILEDW)
  208503. info->returnedString = (LPCWSTR) lParam;
  208504. else if (msg == BFFM_VALIDATEFAILEDA)
  208505. info->returnedString = (const char*) lParam;
  208506. return 0;
  208507. }
  208508. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208509. {
  208510. if (uiMsg == WM_INITDIALOG)
  208511. {
  208512. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208513. HWND dialogH = GetParent (hdlg);
  208514. jassert (dialogH != 0);
  208515. if (dialogH == 0)
  208516. dialogH = hdlg;
  208517. RECT r, cr;
  208518. GetWindowRect (dialogH, &r);
  208519. GetClientRect (dialogH, &cr);
  208520. SetWindowPos (dialogH, 0,
  208521. r.left, r.top,
  208522. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208523. jmax (150, (int) (r.bottom - r.top)),
  208524. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208525. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208526. customComp->addToDesktop (0, dialogH);
  208527. }
  208528. else if (uiMsg == WM_NOTIFY)
  208529. {
  208530. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208531. if (ofn->hdr.code == CDN_SELCHANGE)
  208532. {
  208533. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208534. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208535. if (comp != 0)
  208536. {
  208537. WCHAR path [MAX_PATH * 2];
  208538. zerostruct (path);
  208539. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208540. comp->selectedFileChanged (File (path));
  208541. }
  208542. }
  208543. }
  208544. return 0;
  208545. }
  208546. class CustomComponentHolder : public Component
  208547. {
  208548. public:
  208549. CustomComponentHolder (Component* customComp)
  208550. {
  208551. setVisible (true);
  208552. setOpaque (true);
  208553. addAndMakeVisible (customComp);
  208554. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208555. }
  208556. void paint (Graphics& g)
  208557. {
  208558. g.fillAll (Colours::lightgrey);
  208559. }
  208560. void resized()
  208561. {
  208562. if (getNumChildComponents() > 0)
  208563. getChildComponent(0)->setBounds (getLocalBounds());
  208564. }
  208565. private:
  208566. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208567. };
  208568. }
  208569. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208570. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208571. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208572. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208573. {
  208574. using namespace FileChooserHelpers;
  208575. HeapBlock<WCHAR> files;
  208576. const int charsAvailableForResult = 32768;
  208577. files.calloc (charsAvailableForResult + 1);
  208578. int filenameOffset = 0;
  208579. FileChooserCallbackInfo info;
  208580. // use a modal window as the parent for this dialog box
  208581. // to block input from other app windows
  208582. Component parentWindow (String::empty);
  208583. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208584. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208585. mainMon.getY() + mainMon.getHeight() / 4,
  208586. 0, 0);
  208587. parentWindow.setOpaque (true);
  208588. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208589. parentWindow.addToDesktop (0);
  208590. if (extraInfoComponent == 0)
  208591. parentWindow.enterModalState();
  208592. if (currentFileOrDirectory.isDirectory())
  208593. {
  208594. info.initialPath = currentFileOrDirectory.getFullPathName();
  208595. }
  208596. else
  208597. {
  208598. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  208599. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208600. }
  208601. if (selectsDirectory)
  208602. {
  208603. BROWSEINFO bi;
  208604. zerostruct (bi);
  208605. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208606. bi.pszDisplayName = files;
  208607. bi.lpszTitle = title.toUTF16();
  208608. bi.lParam = (LPARAM) &info;
  208609. bi.lpfn = browseCallbackProc;
  208610. #ifdef BIF_USENEWUI
  208611. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208612. #else
  208613. bi.ulFlags = 0x50;
  208614. #endif
  208615. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208616. if (! SHGetPathFromIDListW (list, files))
  208617. {
  208618. files[0] = 0;
  208619. info.returnedString = String::empty;
  208620. }
  208621. LPMALLOC al;
  208622. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208623. al->Free (list);
  208624. if (info.returnedString.isNotEmpty())
  208625. {
  208626. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208627. return;
  208628. }
  208629. }
  208630. else
  208631. {
  208632. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208633. if (warnAboutOverwritingExistingFiles)
  208634. flags |= OFN_OVERWRITEPROMPT;
  208635. if (selectMultipleFiles)
  208636. flags |= OFN_ALLOWMULTISELECT;
  208637. if (extraInfoComponent != 0)
  208638. {
  208639. flags |= OFN_ENABLEHOOK;
  208640. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208641. info.customComponent->enterModalState();
  208642. }
  208643. const int filterSpace = 2048;
  208644. HeapBlock<char> filters;
  208645. filters.calloc (filterSpace * 2);
  208646. const int bytesWritten = filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters.getData()), filterSpace);
  208647. filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters + bytesWritten), filterSpace);
  208648. OPENFILENAMEW of;
  208649. zerostruct (of);
  208650. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208651. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208652. #else
  208653. of.lStructSize = sizeof (of);
  208654. #endif
  208655. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208656. of.lpstrFilter = reinterpret_cast <WCHAR*> (filters.getData());
  208657. of.nFilterIndex = 1;
  208658. of.lpstrFile = files;
  208659. of.nMaxFile = charsAvailableForResult;
  208660. of.lpstrInitialDir = info.initialPath.toUTF16();
  208661. of.lpstrTitle = title.toUTF16();
  208662. of.Flags = flags;
  208663. of.lCustData = (LPARAM) &info;
  208664. if (extraInfoComponent != 0)
  208665. of.lpfnHook = &openCallback;
  208666. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208667. : GetOpenFileName (&of)))
  208668. return;
  208669. filenameOffset = of.nFileOffset;
  208670. }
  208671. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208672. {
  208673. const WCHAR* filename = files + filenameOffset;
  208674. while (*filename != 0)
  208675. {
  208676. results.add (File (String (files) + "\\" + String (filename)));
  208677. filename += wcslen (filename) + 1;
  208678. }
  208679. }
  208680. else if (files[0] != 0)
  208681. {
  208682. results.add (File (String (files)));
  208683. }
  208684. }
  208685. #endif
  208686. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208687. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208688. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208689. // compiled on its own).
  208690. #if JUCE_INCLUDED_FILE
  208691. void SystemClipboard::copyTextToClipboard (const String& text)
  208692. {
  208693. if (OpenClipboard (0) != 0)
  208694. {
  208695. if (EmptyClipboard() != 0)
  208696. {
  208697. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  208698. if (bytesNeeded > 0)
  208699. {
  208700. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  208701. if (bufH != 0)
  208702. {
  208703. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208704. text.copyToUTF16 (data, bytesNeeded);
  208705. GlobalUnlock (bufH);
  208706. SetClipboardData (CF_UNICODETEXT, bufH);
  208707. }
  208708. }
  208709. }
  208710. CloseClipboard();
  208711. }
  208712. }
  208713. const String SystemClipboard::getTextFromClipboard()
  208714. {
  208715. String result;
  208716. if (OpenClipboard (0) != 0)
  208717. {
  208718. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208719. if (bufH != 0)
  208720. {
  208721. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  208722. if (data != 0)
  208723. {
  208724. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  208725. GlobalUnlock (bufH);
  208726. }
  208727. }
  208728. CloseClipboard();
  208729. }
  208730. return result;
  208731. }
  208732. #endif
  208733. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208734. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208735. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208736. // compiled on its own).
  208737. #if JUCE_INCLUDED_FILE
  208738. namespace ActiveXHelpers
  208739. {
  208740. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208741. {
  208742. public:
  208743. JuceIStorage() {}
  208744. ~JuceIStorage() {}
  208745. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208746. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208747. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208748. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208749. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208750. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208751. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208752. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208753. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208754. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208755. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208756. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208757. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208758. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208759. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208760. };
  208761. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208762. {
  208763. HWND window;
  208764. public:
  208765. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208766. ~JuceOleInPlaceFrame() {}
  208767. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208768. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208769. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208770. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208771. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208772. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208773. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208774. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208775. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208776. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208777. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208778. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208779. };
  208780. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208781. {
  208782. HWND window;
  208783. JuceOleInPlaceFrame* frame;
  208784. public:
  208785. JuceIOleInPlaceSite (HWND window_)
  208786. : window (window_),
  208787. frame (new JuceOleInPlaceFrame (window))
  208788. {}
  208789. ~JuceIOleInPlaceSite()
  208790. {
  208791. frame->Release();
  208792. }
  208793. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208794. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208795. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208796. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208797. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208798. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208799. {
  208800. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208801. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  208802. */
  208803. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  208804. if (lplpDoc != 0) *lplpDoc = 0;
  208805. lpFrameInfo->fMDIApp = FALSE;
  208806. lpFrameInfo->hwndFrame = window;
  208807. lpFrameInfo->haccel = 0;
  208808. lpFrameInfo->cAccelEntries = 0;
  208809. return S_OK;
  208810. }
  208811. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208812. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208813. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208814. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208815. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208816. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208817. };
  208818. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208819. {
  208820. JuceIOleInPlaceSite* inplaceSite;
  208821. public:
  208822. JuceIOleClientSite (HWND window)
  208823. : inplaceSite (new JuceIOleInPlaceSite (window))
  208824. {}
  208825. ~JuceIOleClientSite()
  208826. {
  208827. inplaceSite->Release();
  208828. }
  208829. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  208830. {
  208831. if (type == IID_IOleInPlaceSite)
  208832. {
  208833. inplaceSite->AddRef();
  208834. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208835. return S_OK;
  208836. }
  208837. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208838. }
  208839. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208840. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208841. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208842. HRESULT __stdcall ShowObject() { return S_OK; }
  208843. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208844. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208845. };
  208846. static Array<ActiveXControlComponent*> activeXComps;
  208847. static HWND getHWND (const ActiveXControlComponent* const component)
  208848. {
  208849. HWND hwnd = 0;
  208850. const IID iid = IID_IOleWindow;
  208851. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208852. if (window != 0)
  208853. {
  208854. window->GetWindow (&hwnd);
  208855. window->Release();
  208856. }
  208857. return hwnd;
  208858. }
  208859. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208860. {
  208861. RECT activeXRect, peerRect;
  208862. GetWindowRect (hwnd, &activeXRect);
  208863. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208864. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208865. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208866. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208867. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208868. switch (message)
  208869. {
  208870. case WM_MOUSEMOVE:
  208871. case WM_LBUTTONDOWN:
  208872. case WM_MBUTTONDOWN:
  208873. case WM_RBUTTONDOWN:
  208874. case WM_LBUTTONUP:
  208875. case WM_MBUTTONUP:
  208876. case WM_RBUTTONUP:
  208877. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  208878. break;
  208879. default:
  208880. break;
  208881. }
  208882. }
  208883. }
  208884. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  208885. {
  208886. public:
  208887. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  208888. : ComponentMovementWatcher (&owner_),
  208889. owner (owner_),
  208890. controlHWND (0),
  208891. storage (new ActiveXHelpers::JuceIStorage()),
  208892. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  208893. control (0)
  208894. {
  208895. }
  208896. ~Pimpl()
  208897. {
  208898. if (control != 0)
  208899. {
  208900. control->Close (OLECLOSE_NOSAVE);
  208901. control->Release();
  208902. }
  208903. clientSite->Release();
  208904. storage->Release();
  208905. }
  208906. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208907. {
  208908. Component* const topComp = owner.getTopLevelComponent();
  208909. if (topComp->getPeer() != 0)
  208910. {
  208911. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  208912. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  208913. }
  208914. }
  208915. void componentPeerChanged()
  208916. {
  208917. componentMovedOrResized (true, true);
  208918. }
  208919. void componentVisibilityChanged()
  208920. {
  208921. owner.setControlVisible (owner.isShowing());
  208922. componentPeerChanged();
  208923. }
  208924. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208925. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208926. {
  208927. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  208928. {
  208929. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  208930. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  208931. {
  208932. switch (message)
  208933. {
  208934. case WM_MOUSEMOVE:
  208935. case WM_LBUTTONDOWN:
  208936. case WM_MBUTTONDOWN:
  208937. case WM_RBUTTONDOWN:
  208938. case WM_LBUTTONUP:
  208939. case WM_MBUTTONUP:
  208940. case WM_RBUTTONUP:
  208941. case WM_LBUTTONDBLCLK:
  208942. case WM_MBUTTONDBLCLK:
  208943. case WM_RBUTTONDBLCLK:
  208944. if (ax->isShowing())
  208945. {
  208946. ComponentPeer* const peer = ax->getPeer();
  208947. if (peer != 0)
  208948. {
  208949. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  208950. if (! ax->areMouseEventsAllowed())
  208951. return 0;
  208952. }
  208953. }
  208954. break;
  208955. default:
  208956. break;
  208957. }
  208958. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  208959. }
  208960. }
  208961. return DefWindowProc (hwnd, message, wParam, lParam);
  208962. }
  208963. private:
  208964. ActiveXControlComponent& owner;
  208965. public:
  208966. HWND controlHWND;
  208967. IStorage* storage;
  208968. IOleClientSite* clientSite;
  208969. IOleObject* control;
  208970. };
  208971. ActiveXControlComponent::ActiveXControlComponent()
  208972. : originalWndProc (0),
  208973. mouseEventsAllowed (true)
  208974. {
  208975. ActiveXHelpers::activeXComps.add (this);
  208976. }
  208977. ActiveXControlComponent::~ActiveXControlComponent()
  208978. {
  208979. deleteControl();
  208980. ActiveXHelpers::activeXComps.removeValue (this);
  208981. }
  208982. void ActiveXControlComponent::paint (Graphics& g)
  208983. {
  208984. if (control == 0)
  208985. g.fillAll (Colours::lightgrey);
  208986. }
  208987. bool ActiveXControlComponent::createControl (const void* controlIID)
  208988. {
  208989. deleteControl();
  208990. ComponentPeer* const peer = getPeer();
  208991. // the component must have already been added to a real window when you call this!
  208992. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  208993. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  208994. {
  208995. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  208996. HWND hwnd = (HWND) peer->getNativeHandle();
  208997. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  208998. HRESULT hr;
  208999. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209000. newControl->clientSite, newControl->storage,
  209001. (void**) &(newControl->control))) == S_OK)
  209002. {
  209003. newControl->control->SetHostNames (L"Juce", 0);
  209004. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209005. {
  209006. RECT rect;
  209007. rect.left = pos.getX();
  209008. rect.top = pos.getY();
  209009. rect.right = pos.getX() + getWidth();
  209010. rect.bottom = pos.getY() + getHeight();
  209011. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209012. {
  209013. control = newControl;
  209014. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209015. control->controlHWND = ActiveXHelpers::getHWND (this);
  209016. if (control->controlHWND != 0)
  209017. {
  209018. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209019. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209020. }
  209021. return true;
  209022. }
  209023. }
  209024. }
  209025. }
  209026. return false;
  209027. }
  209028. void ActiveXControlComponent::deleteControl()
  209029. {
  209030. control = 0;
  209031. originalWndProc = 0;
  209032. }
  209033. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209034. {
  209035. void* result = 0;
  209036. if (control != 0 && control->control != 0
  209037. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209038. return result;
  209039. return 0;
  209040. }
  209041. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209042. {
  209043. if (control->controlHWND != 0)
  209044. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209045. }
  209046. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209047. {
  209048. if (control->controlHWND != 0)
  209049. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209050. }
  209051. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209052. {
  209053. mouseEventsAllowed = eventsCanReachControl;
  209054. }
  209055. #endif
  209056. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209057. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209058. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209059. // compiled on its own).
  209060. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209061. using namespace QTOLibrary;
  209062. using namespace QTOControlLib;
  209063. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209064. static bool isQTAvailable = false;
  209065. class QuickTimeMovieComponent::Pimpl
  209066. {
  209067. public:
  209068. Pimpl() : dataHandle (0)
  209069. {
  209070. }
  209071. ~Pimpl()
  209072. {
  209073. clearHandle();
  209074. }
  209075. void clearHandle()
  209076. {
  209077. if (dataHandle != 0)
  209078. {
  209079. DisposeHandle (dataHandle);
  209080. dataHandle = 0;
  209081. }
  209082. }
  209083. IQTControlPtr qtControl;
  209084. IQTMoviePtr qtMovie;
  209085. Handle dataHandle;
  209086. };
  209087. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209088. : movieLoaded (false),
  209089. controllerVisible (true)
  209090. {
  209091. pimpl = new Pimpl();
  209092. setMouseEventsAllowed (false);
  209093. }
  209094. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209095. {
  209096. closeMovie();
  209097. pimpl->qtControl = 0;
  209098. deleteControl();
  209099. pimpl = 0;
  209100. }
  209101. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209102. {
  209103. if (! isQTAvailable)
  209104. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209105. return isQTAvailable;
  209106. }
  209107. void QuickTimeMovieComponent::createControlIfNeeded()
  209108. {
  209109. if (isShowing() && ! isControlCreated())
  209110. {
  209111. const IID qtIID = __uuidof (QTControl);
  209112. if (createControl (&qtIID))
  209113. {
  209114. const IID qtInterfaceIID = __uuidof (IQTControl);
  209115. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209116. if (pimpl->qtControl != 0)
  209117. {
  209118. pimpl->qtControl->Release(); // it has one ref too many at this point
  209119. pimpl->qtControl->QuickTimeInitialize();
  209120. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209121. if (movieFile != File::nonexistent)
  209122. loadMovie (movieFile, controllerVisible);
  209123. }
  209124. }
  209125. }
  209126. }
  209127. bool QuickTimeMovieComponent::isControlCreated() const
  209128. {
  209129. return isControlOpen();
  209130. }
  209131. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209132. const bool isControllerVisible)
  209133. {
  209134. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209135. movieFile = File::nonexistent;
  209136. movieLoaded = false;
  209137. pimpl->qtMovie = 0;
  209138. controllerVisible = isControllerVisible;
  209139. createControlIfNeeded();
  209140. if (isControlCreated())
  209141. {
  209142. if (pimpl->qtControl != 0)
  209143. {
  209144. pimpl->qtControl->Put_MovieHandle (0);
  209145. pimpl->clearHandle();
  209146. Movie movie;
  209147. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209148. {
  209149. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209150. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209151. if (pimpl->qtMovie != 0)
  209152. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209153. : qtMovieControllerTypeNone);
  209154. }
  209155. if (movie == 0)
  209156. pimpl->clearHandle();
  209157. }
  209158. movieLoaded = (pimpl->qtMovie != 0);
  209159. }
  209160. else
  209161. {
  209162. // You're trying to open a movie when the control hasn't yet been created, probably because
  209163. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209164. jassertfalse;
  209165. }
  209166. return movieLoaded;
  209167. }
  209168. void QuickTimeMovieComponent::closeMovie()
  209169. {
  209170. stop();
  209171. movieFile = File::nonexistent;
  209172. movieLoaded = false;
  209173. pimpl->qtMovie = 0;
  209174. if (pimpl->qtControl != 0)
  209175. pimpl->qtControl->Put_MovieHandle (0);
  209176. pimpl->clearHandle();
  209177. }
  209178. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209179. {
  209180. return movieFile;
  209181. }
  209182. bool QuickTimeMovieComponent::isMovieOpen() const
  209183. {
  209184. return movieLoaded;
  209185. }
  209186. double QuickTimeMovieComponent::getMovieDuration() const
  209187. {
  209188. if (pimpl->qtMovie != 0)
  209189. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209190. return 0.0;
  209191. }
  209192. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209193. {
  209194. if (pimpl->qtMovie != 0)
  209195. {
  209196. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209197. width = r.right - r.left;
  209198. height = r.bottom - r.top;
  209199. }
  209200. else
  209201. {
  209202. width = height = 0;
  209203. }
  209204. }
  209205. void QuickTimeMovieComponent::play()
  209206. {
  209207. if (pimpl->qtMovie != 0)
  209208. pimpl->qtMovie->Play();
  209209. }
  209210. void QuickTimeMovieComponent::stop()
  209211. {
  209212. if (pimpl->qtMovie != 0)
  209213. pimpl->qtMovie->Stop();
  209214. }
  209215. bool QuickTimeMovieComponent::isPlaying() const
  209216. {
  209217. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209218. }
  209219. void QuickTimeMovieComponent::setPosition (const double seconds)
  209220. {
  209221. if (pimpl->qtMovie != 0)
  209222. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209223. }
  209224. double QuickTimeMovieComponent::getPosition() const
  209225. {
  209226. if (pimpl->qtMovie != 0)
  209227. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209228. return 0.0;
  209229. }
  209230. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209231. {
  209232. if (pimpl->qtMovie != 0)
  209233. pimpl->qtMovie->PutRate (newSpeed);
  209234. }
  209235. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209236. {
  209237. if (pimpl->qtMovie != 0)
  209238. {
  209239. pimpl->qtMovie->PutAudioVolume (newVolume);
  209240. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209241. }
  209242. }
  209243. float QuickTimeMovieComponent::getMovieVolume() const
  209244. {
  209245. if (pimpl->qtMovie != 0)
  209246. return pimpl->qtMovie->GetAudioVolume();
  209247. return 0.0f;
  209248. }
  209249. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209250. {
  209251. if (pimpl->qtMovie != 0)
  209252. pimpl->qtMovie->PutLoop (shouldLoop);
  209253. }
  209254. bool QuickTimeMovieComponent::isLooping() const
  209255. {
  209256. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209257. }
  209258. bool QuickTimeMovieComponent::isControllerVisible() const
  209259. {
  209260. return controllerVisible;
  209261. }
  209262. void QuickTimeMovieComponent::parentHierarchyChanged()
  209263. {
  209264. createControlIfNeeded();
  209265. QTCompBaseClass::parentHierarchyChanged();
  209266. }
  209267. void QuickTimeMovieComponent::visibilityChanged()
  209268. {
  209269. createControlIfNeeded();
  209270. QTCompBaseClass::visibilityChanged();
  209271. }
  209272. void QuickTimeMovieComponent::paint (Graphics& g)
  209273. {
  209274. if (! isControlCreated())
  209275. g.fillAll (Colours::black);
  209276. }
  209277. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209278. {
  209279. Handle dataRef = 0;
  209280. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209281. if (err == noErr)
  209282. {
  209283. Str255 suffix;
  209284. strncpy ((char*) suffix, fileName, 128);
  209285. StringPtr name = suffix;
  209286. err = PtrAndHand (name, dataRef, name[0] + 1);
  209287. if (err == noErr)
  209288. {
  209289. long atoms[3];
  209290. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209291. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209292. atoms[2] = EndianU32_NtoB (MovieFileType);
  209293. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209294. if (err == noErr)
  209295. return dataRef;
  209296. }
  209297. DisposeHandle (dataRef);
  209298. }
  209299. return 0;
  209300. }
  209301. static CFStringRef juceStringToCFString (const String& s)
  209302. {
  209303. const int len = s.length();
  209304. const juce_wchar* const t = s;
  209305. HeapBlock <UniChar> temp (len + 2);
  209306. for (int i = 0; i <= len; ++i)
  209307. temp[i] = t[i];
  209308. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209309. }
  209310. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209311. {
  209312. Boolean trueBool = true;
  209313. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209314. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209315. props[prop].propValueSize = sizeof (trueBool);
  209316. props[prop].propValueAddress = &trueBool;
  209317. ++prop;
  209318. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209319. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209320. props[prop].propValueSize = sizeof (trueBool);
  209321. props[prop].propValueAddress = &trueBool;
  209322. ++prop;
  209323. Boolean isActive = true;
  209324. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209325. props[prop].propID = kQTNewMoviePropertyID_Active;
  209326. props[prop].propValueSize = sizeof (isActive);
  209327. props[prop].propValueAddress = &isActive;
  209328. ++prop;
  209329. MacSetPort (0);
  209330. jassert (prop <= 5);
  209331. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209332. return err == noErr;
  209333. }
  209334. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209335. {
  209336. if (input == 0)
  209337. return false;
  209338. dataHandle = 0;
  209339. bool ok = false;
  209340. QTNewMoviePropertyElement props[5];
  209341. zeromem (props, sizeof (props));
  209342. int prop = 0;
  209343. DataReferenceRecord dr;
  209344. props[prop].propClass = kQTPropertyClass_DataLocation;
  209345. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209346. props[prop].propValueSize = sizeof (dr);
  209347. props[prop].propValueAddress = &dr;
  209348. ++prop;
  209349. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209350. if (fin != 0)
  209351. {
  209352. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209353. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209354. &dr.dataRef, &dr.dataRefType);
  209355. ok = openMovie (props, prop, movie);
  209356. DisposeHandle (dr.dataRef);
  209357. CFRelease (filePath);
  209358. }
  209359. else
  209360. {
  209361. // sanity-check because this currently needs to load the whole stream into memory..
  209362. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209363. dataHandle = NewHandle ((Size) input->getTotalLength());
  209364. HLock (dataHandle);
  209365. // read the entire stream into memory - this is a pain, but can't get it to work
  209366. // properly using a custom callback to supply the data.
  209367. input->read (*dataHandle, (int) input->getTotalLength());
  209368. HUnlock (dataHandle);
  209369. // different types to get QT to try. (We should really be a bit smarter here by
  209370. // working out in advance which one the stream contains, rather than just trying
  209371. // each one)
  209372. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209373. "\04.avi", "\04.m4a" };
  209374. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209375. {
  209376. /* // this fails for some bizarre reason - it can be bodged to work with
  209377. // movies, but can't seem to do it for other file types..
  209378. QTNewMovieUserProcRecord procInfo;
  209379. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209380. procInfo.getMovieUserProcRefcon = this;
  209381. procInfo.defaultDataRef.dataRef = dataRef;
  209382. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209383. props[prop].propClass = kQTPropertyClass_DataLocation;
  209384. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209385. props[prop].propValueSize = sizeof (procInfo);
  209386. props[prop].propValueAddress = (void*) &procInfo;
  209387. ++prop; */
  209388. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209389. dr.dataRefType = HandleDataHandlerSubType;
  209390. ok = openMovie (props, prop, movie);
  209391. DisposeHandle (dr.dataRef);
  209392. }
  209393. }
  209394. return ok;
  209395. }
  209396. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209397. const bool isControllerVisible)
  209398. {
  209399. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209400. movieFile = movieFile_;
  209401. return ok;
  209402. }
  209403. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209404. const bool isControllerVisible)
  209405. {
  209406. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209407. }
  209408. void QuickTimeMovieComponent::goToStart()
  209409. {
  209410. setPosition (0.0);
  209411. }
  209412. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209413. const RectanglePlacement& placement)
  209414. {
  209415. int normalWidth, normalHeight;
  209416. getMovieNormalSize (normalWidth, normalHeight);
  209417. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209418. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209419. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209420. else
  209421. setBounds (spaceToFitWithin);
  209422. }
  209423. #endif
  209424. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209425. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209426. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209427. // compiled on its own).
  209428. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209429. class WebBrowserComponentInternal : public ActiveXControlComponent
  209430. {
  209431. public:
  209432. WebBrowserComponentInternal()
  209433. : browser (0),
  209434. connectionPoint (0),
  209435. adviseCookie (0)
  209436. {
  209437. }
  209438. ~WebBrowserComponentInternal()
  209439. {
  209440. if (connectionPoint != 0)
  209441. connectionPoint->Unadvise (adviseCookie);
  209442. if (browser != 0)
  209443. browser->Release();
  209444. }
  209445. void createBrowser()
  209446. {
  209447. createControl (&CLSID_WebBrowser);
  209448. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209449. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209450. if (connectionPointContainer != 0)
  209451. {
  209452. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209453. &connectionPoint);
  209454. if (connectionPoint != 0)
  209455. {
  209456. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209457. jassert (owner != 0);
  209458. EventHandler* handler = new EventHandler (*owner);
  209459. connectionPoint->Advise (handler, &adviseCookie);
  209460. handler->Release();
  209461. }
  209462. }
  209463. }
  209464. void goToURL (const String& url,
  209465. const StringArray* headers,
  209466. const MemoryBlock* postData)
  209467. {
  209468. if (browser != 0)
  209469. {
  209470. LPSAFEARRAY sa = 0;
  209471. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209472. VariantInit (&flags);
  209473. VariantInit (&frame);
  209474. VariantInit (&postDataVar);
  209475. VariantInit (&headersVar);
  209476. if (headers != 0)
  209477. {
  209478. V_VT (&headersVar) = VT_BSTR;
  209479. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  209480. }
  209481. if (postData != 0 && postData->getSize() > 0)
  209482. {
  209483. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209484. if (sa != 0)
  209485. {
  209486. void* data = 0;
  209487. SafeArrayAccessData (sa, &data);
  209488. jassert (data != 0);
  209489. if (data != 0)
  209490. {
  209491. postData->copyTo (data, 0, postData->getSize());
  209492. SafeArrayUnaccessData (sa);
  209493. VARIANT postDataVar2;
  209494. VariantInit (&postDataVar2);
  209495. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209496. V_ARRAY (&postDataVar2) = sa;
  209497. postDataVar = postDataVar2;
  209498. }
  209499. }
  209500. }
  209501. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  209502. &flags, &frame,
  209503. &postDataVar, &headersVar);
  209504. if (sa != 0)
  209505. SafeArrayDestroy (sa);
  209506. VariantClear (&flags);
  209507. VariantClear (&frame);
  209508. VariantClear (&postDataVar);
  209509. VariantClear (&headersVar);
  209510. }
  209511. }
  209512. IWebBrowser2* browser;
  209513. private:
  209514. IConnectionPoint* connectionPoint;
  209515. DWORD adviseCookie;
  209516. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209517. public ComponentMovementWatcher
  209518. {
  209519. public:
  209520. EventHandler (WebBrowserComponent& owner_)
  209521. : ComponentMovementWatcher (&owner_),
  209522. owner (owner_)
  209523. {
  209524. }
  209525. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209526. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209527. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209528. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209529. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209530. {
  209531. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  209532. {
  209533. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209534. String url;
  209535. if ((vurl->vt & VT_BYREF) != 0)
  209536. url = *vurl->pbstrVal;
  209537. else
  209538. url = vurl->bstrVal;
  209539. *pDispParams->rgvarg->pboolVal
  209540. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  209541. : VARIANT_TRUE;
  209542. return S_OK;
  209543. }
  209544. return E_NOTIMPL;
  209545. }
  209546. void componentMovedOrResized (bool, bool ) {}
  209547. void componentPeerChanged() {}
  209548. void componentVisibilityChanged() { owner.visibilityChanged(); }
  209549. private:
  209550. WebBrowserComponent& owner;
  209551. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209552. };
  209553. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209554. };
  209555. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209556. : browser (0),
  209557. blankPageShown (false),
  209558. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209559. {
  209560. setOpaque (true);
  209561. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209562. }
  209563. WebBrowserComponent::~WebBrowserComponent()
  209564. {
  209565. delete browser;
  209566. }
  209567. void WebBrowserComponent::goToURL (const String& url,
  209568. const StringArray* headers,
  209569. const MemoryBlock* postData)
  209570. {
  209571. lastURL = url;
  209572. lastHeaders.clear();
  209573. if (headers != 0)
  209574. lastHeaders = *headers;
  209575. lastPostData.setSize (0);
  209576. if (postData != 0)
  209577. lastPostData = *postData;
  209578. blankPageShown = false;
  209579. browser->goToURL (url, headers, postData);
  209580. }
  209581. void WebBrowserComponent::stop()
  209582. {
  209583. if (browser->browser != 0)
  209584. browser->browser->Stop();
  209585. }
  209586. void WebBrowserComponent::goBack()
  209587. {
  209588. lastURL = String::empty;
  209589. blankPageShown = false;
  209590. if (browser->browser != 0)
  209591. browser->browser->GoBack();
  209592. }
  209593. void WebBrowserComponent::goForward()
  209594. {
  209595. lastURL = String::empty;
  209596. if (browser->browser != 0)
  209597. browser->browser->GoForward();
  209598. }
  209599. void WebBrowserComponent::refresh()
  209600. {
  209601. if (browser->browser != 0)
  209602. browser->browser->Refresh();
  209603. }
  209604. void WebBrowserComponent::paint (Graphics& g)
  209605. {
  209606. if (browser->browser == 0)
  209607. g.fillAll (Colours::white);
  209608. }
  209609. void WebBrowserComponent::checkWindowAssociation()
  209610. {
  209611. if (isShowing())
  209612. {
  209613. if (browser->browser == 0 && getPeer() != 0)
  209614. {
  209615. browser->createBrowser();
  209616. reloadLastURL();
  209617. }
  209618. else
  209619. {
  209620. if (blankPageShown)
  209621. goBack();
  209622. }
  209623. }
  209624. else
  209625. {
  209626. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209627. {
  209628. // when the component becomes invisible, some stuff like flash
  209629. // carries on playing audio, so we need to force it onto a blank
  209630. // page to avoid this..
  209631. blankPageShown = true;
  209632. browser->goToURL ("about:blank", 0, 0);
  209633. }
  209634. }
  209635. }
  209636. void WebBrowserComponent::reloadLastURL()
  209637. {
  209638. if (lastURL.isNotEmpty())
  209639. {
  209640. goToURL (lastURL, &lastHeaders, &lastPostData);
  209641. lastURL = String::empty;
  209642. }
  209643. }
  209644. void WebBrowserComponent::parentHierarchyChanged()
  209645. {
  209646. checkWindowAssociation();
  209647. }
  209648. void WebBrowserComponent::resized()
  209649. {
  209650. browser->setSize (getWidth(), getHeight());
  209651. }
  209652. void WebBrowserComponent::visibilityChanged()
  209653. {
  209654. checkWindowAssociation();
  209655. }
  209656. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209657. {
  209658. return true;
  209659. }
  209660. #endif
  209661. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209662. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209663. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209664. // compiled on its own).
  209665. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209666. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209667. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209668. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209669. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209670. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209671. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209672. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209673. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209674. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209675. #define WGL_ACCELERATION_ARB 0x2003
  209676. #define WGL_SWAP_METHOD_ARB 0x2007
  209677. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209678. #define WGL_PIXEL_TYPE_ARB 0x2013
  209679. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209680. #define WGL_COLOR_BITS_ARB 0x2014
  209681. #define WGL_RED_BITS_ARB 0x2015
  209682. #define WGL_GREEN_BITS_ARB 0x2017
  209683. #define WGL_BLUE_BITS_ARB 0x2019
  209684. #define WGL_ALPHA_BITS_ARB 0x201B
  209685. #define WGL_DEPTH_BITS_ARB 0x2022
  209686. #define WGL_STENCIL_BITS_ARB 0x2023
  209687. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209688. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209689. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209690. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209691. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209692. #define WGL_STEREO_ARB 0x2012
  209693. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209694. #define WGL_SAMPLES_ARB 0x2042
  209695. #define WGL_TYPE_RGBA_ARB 0x202B
  209696. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209697. {
  209698. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209699. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209700. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209701. else
  209702. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209703. }
  209704. class WindowedGLContext : public OpenGLContext
  209705. {
  209706. public:
  209707. WindowedGLContext (Component* const component_,
  209708. HGLRC contextToShareWith,
  209709. const OpenGLPixelFormat& pixelFormat)
  209710. : renderContext (0),
  209711. component (component_),
  209712. dc (0)
  209713. {
  209714. jassert (component != 0);
  209715. createNativeWindow();
  209716. // Use a default pixel format that should be supported everywhere
  209717. PIXELFORMATDESCRIPTOR pfd;
  209718. zerostruct (pfd);
  209719. pfd.nSize = sizeof (pfd);
  209720. pfd.nVersion = 1;
  209721. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209722. pfd.iPixelType = PFD_TYPE_RGBA;
  209723. pfd.cColorBits = 24;
  209724. pfd.cDepthBits = 16;
  209725. const int format = ChoosePixelFormat (dc, &pfd);
  209726. if (format != 0)
  209727. SetPixelFormat (dc, format, &pfd);
  209728. renderContext = wglCreateContext (dc);
  209729. makeActive();
  209730. setPixelFormat (pixelFormat);
  209731. if (contextToShareWith != 0 && renderContext != 0)
  209732. wglShareLists (contextToShareWith, renderContext);
  209733. }
  209734. ~WindowedGLContext()
  209735. {
  209736. deleteContext();
  209737. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209738. nativeWindow = 0;
  209739. }
  209740. void deleteContext()
  209741. {
  209742. makeInactive();
  209743. if (renderContext != 0)
  209744. {
  209745. wglDeleteContext (renderContext);
  209746. renderContext = 0;
  209747. }
  209748. }
  209749. bool makeActive() const throw()
  209750. {
  209751. jassert (renderContext != 0);
  209752. return wglMakeCurrent (dc, renderContext) != 0;
  209753. }
  209754. bool makeInactive() const throw()
  209755. {
  209756. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209757. }
  209758. bool isActive() const throw()
  209759. {
  209760. return wglGetCurrentContext() == renderContext;
  209761. }
  209762. const OpenGLPixelFormat getPixelFormat() const
  209763. {
  209764. OpenGLPixelFormat pf;
  209765. makeActive();
  209766. StringArray availableExtensions;
  209767. getWglExtensions (dc, availableExtensions);
  209768. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209769. return pf;
  209770. }
  209771. void* getRawContext() const throw()
  209772. {
  209773. return renderContext;
  209774. }
  209775. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209776. {
  209777. makeActive();
  209778. PIXELFORMATDESCRIPTOR pfd;
  209779. zerostruct (pfd);
  209780. pfd.nSize = sizeof (pfd);
  209781. pfd.nVersion = 1;
  209782. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209783. pfd.iPixelType = PFD_TYPE_RGBA;
  209784. pfd.iLayerType = PFD_MAIN_PLANE;
  209785. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209786. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209787. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209788. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209789. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209790. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209791. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209792. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209793. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209794. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209795. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209796. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209797. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209798. int format = 0;
  209799. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209800. StringArray availableExtensions;
  209801. getWglExtensions (dc, availableExtensions);
  209802. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209803. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209804. {
  209805. int attributes[64];
  209806. int n = 0;
  209807. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209808. attributes[n++] = GL_TRUE;
  209809. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209810. attributes[n++] = GL_TRUE;
  209811. attributes[n++] = WGL_ACCELERATION_ARB;
  209812. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209813. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209814. attributes[n++] = GL_TRUE;
  209815. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209816. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209817. attributes[n++] = WGL_COLOR_BITS_ARB;
  209818. attributes[n++] = pfd.cColorBits;
  209819. attributes[n++] = WGL_RED_BITS_ARB;
  209820. attributes[n++] = pixelFormat.redBits;
  209821. attributes[n++] = WGL_GREEN_BITS_ARB;
  209822. attributes[n++] = pixelFormat.greenBits;
  209823. attributes[n++] = WGL_BLUE_BITS_ARB;
  209824. attributes[n++] = pixelFormat.blueBits;
  209825. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209826. attributes[n++] = pixelFormat.alphaBits;
  209827. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209828. attributes[n++] = pixelFormat.depthBufferBits;
  209829. if (pixelFormat.stencilBufferBits > 0)
  209830. {
  209831. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209832. attributes[n++] = pixelFormat.stencilBufferBits;
  209833. }
  209834. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209835. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209836. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209837. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209838. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209839. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209840. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209841. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209842. if (availableExtensions.contains ("WGL_ARB_multisample")
  209843. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209844. {
  209845. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  209846. attributes[n++] = 1;
  209847. attributes[n++] = WGL_SAMPLES_ARB;
  209848. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  209849. }
  209850. attributes[n++] = 0;
  209851. UINT formatsCount;
  209852. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  209853. (void) ok;
  209854. jassert (ok);
  209855. }
  209856. else
  209857. {
  209858. format = ChoosePixelFormat (dc, &pfd);
  209859. }
  209860. if (format != 0)
  209861. {
  209862. makeInactive();
  209863. // win32 can't change the pixel format of a window, so need to delete the
  209864. // old one and create a new one..
  209865. jassert (nativeWindow != 0);
  209866. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209867. nativeWindow = 0;
  209868. createNativeWindow();
  209869. if (SetPixelFormat (dc, format, &pfd))
  209870. {
  209871. wglDeleteContext (renderContext);
  209872. renderContext = wglCreateContext (dc);
  209873. jassert (renderContext != 0);
  209874. return renderContext != 0;
  209875. }
  209876. }
  209877. return false;
  209878. }
  209879. void updateWindowPosition (int x, int y, int w, int h, int)
  209880. {
  209881. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  209882. x, y, w, h,
  209883. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  209884. }
  209885. void repaint()
  209886. {
  209887. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  209888. }
  209889. void swapBuffers()
  209890. {
  209891. SwapBuffers (dc);
  209892. }
  209893. bool setSwapInterval (int numFramesPerSwap)
  209894. {
  209895. makeActive();
  209896. StringArray availableExtensions;
  209897. getWglExtensions (dc, availableExtensions);
  209898. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  209899. return availableExtensions.contains ("WGL_EXT_swap_control")
  209900. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  209901. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  209902. }
  209903. int getSwapInterval() const
  209904. {
  209905. makeActive();
  209906. StringArray availableExtensions;
  209907. getWglExtensions (dc, availableExtensions);
  209908. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  209909. if (availableExtensions.contains ("WGL_EXT_swap_control")
  209910. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  209911. return wglGetSwapIntervalEXT();
  209912. return 0;
  209913. }
  209914. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  209915. {
  209916. jassert (isActive());
  209917. StringArray availableExtensions;
  209918. getWglExtensions (dc, availableExtensions);
  209919. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  209920. int numTypes = 0;
  209921. if (availableExtensions.contains("WGL_ARB_pixel_format")
  209922. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  209923. {
  209924. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  209925. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  209926. jassertfalse;
  209927. }
  209928. else
  209929. {
  209930. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  209931. }
  209932. OpenGLPixelFormat pf;
  209933. for (int i = 0; i < numTypes; ++i)
  209934. {
  209935. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  209936. {
  209937. bool alreadyListed = false;
  209938. for (int j = results.size(); --j >= 0;)
  209939. if (pf == *results.getUnchecked(j))
  209940. alreadyListed = true;
  209941. if (! alreadyListed)
  209942. results.add (new OpenGLPixelFormat (pf));
  209943. }
  209944. }
  209945. }
  209946. void* getNativeWindowHandle() const
  209947. {
  209948. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  209949. }
  209950. HGLRC renderContext;
  209951. private:
  209952. ScopedPointer<Win32ComponentPeer> nativeWindow;
  209953. Component* const component;
  209954. HDC dc;
  209955. void createNativeWindow()
  209956. {
  209957. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  209958. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  209959. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  209960. nativeWindow->dontRepaint = true;
  209961. nativeWindow->setVisible (true);
  209962. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  209963. }
  209964. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  209965. OpenGLPixelFormat& result,
  209966. const StringArray& availableExtensions) const throw()
  209967. {
  209968. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  209969. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209970. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  209971. {
  209972. int attributes[32];
  209973. int numAttributes = 0;
  209974. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  209975. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  209976. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  209977. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  209978. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  209979. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  209980. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  209981. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  209982. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  209983. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  209984. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  209985. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  209986. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  209987. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  209988. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209989. if (availableExtensions.contains ("WGL_ARB_multisample"))
  209990. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  209991. int values[32];
  209992. zeromem (values, sizeof (values));
  209993. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  209994. {
  209995. int n = 0;
  209996. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  209997. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  209998. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  209999. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210000. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210001. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210002. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210003. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210004. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210005. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210006. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210007. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210008. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210009. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210010. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210011. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210012. return isValidFormat;
  210013. }
  210014. else
  210015. {
  210016. jassertfalse;
  210017. }
  210018. }
  210019. else
  210020. {
  210021. PIXELFORMATDESCRIPTOR pfd;
  210022. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210023. {
  210024. result.redBits = pfd.cRedBits;
  210025. result.greenBits = pfd.cGreenBits;
  210026. result.blueBits = pfd.cBlueBits;
  210027. result.alphaBits = pfd.cAlphaBits;
  210028. result.depthBufferBits = pfd.cDepthBits;
  210029. result.stencilBufferBits = pfd.cStencilBits;
  210030. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210031. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210032. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210033. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210034. result.fullSceneAntiAliasingNumSamples = 0;
  210035. return true;
  210036. }
  210037. else
  210038. {
  210039. jassertfalse;
  210040. }
  210041. }
  210042. return false;
  210043. }
  210044. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210045. };
  210046. OpenGLContext* OpenGLComponent::createContext()
  210047. {
  210048. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210049. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210050. preferredPixelFormat));
  210051. return (c->renderContext != 0) ? c.release() : 0;
  210052. }
  210053. void* OpenGLComponent::getNativeWindowHandle() const
  210054. {
  210055. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210056. }
  210057. void juce_glViewport (const int w, const int h)
  210058. {
  210059. glViewport (0, 0, w, h);
  210060. }
  210061. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210062. OwnedArray <OpenGLPixelFormat>& results)
  210063. {
  210064. Component tempComp;
  210065. {
  210066. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210067. wc.makeActive();
  210068. wc.findAlternativeOpenGLPixelFormats (results);
  210069. }
  210070. }
  210071. #endif
  210072. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210073. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210074. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210075. // compiled on its own).
  210076. #if JUCE_INCLUDED_FILE
  210077. #if JUCE_USE_CDREADER
  210078. namespace CDReaderHelpers
  210079. {
  210080. #define FILE_ANY_ACCESS 0
  210081. #ifndef FILE_READ_ACCESS
  210082. #define FILE_READ_ACCESS 1
  210083. #endif
  210084. #ifndef FILE_WRITE_ACCESS
  210085. #define FILE_WRITE_ACCESS 2
  210086. #endif
  210087. #define METHOD_BUFFERED 0
  210088. #define IOCTL_SCSI_BASE 4
  210089. #define SCSI_IOCTL_DATA_OUT 0
  210090. #define SCSI_IOCTL_DATA_IN 1
  210091. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210092. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210093. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210094. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210095. #define SENSE_LEN 14
  210096. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210097. #define SRB_DIR_IN 0x08
  210098. #define SRB_DIR_OUT 0x10
  210099. #define SRB_EVENT_NOTIFY 0x40
  210100. #define SC_HA_INQUIRY 0x00
  210101. #define SC_GET_DEV_TYPE 0x01
  210102. #define SC_EXEC_SCSI_CMD 0x02
  210103. #define SS_PENDING 0x00
  210104. #define SS_COMP 0x01
  210105. #define SS_ERR 0x04
  210106. enum
  210107. {
  210108. READTYPE_ANY = 0,
  210109. READTYPE_ATAPI1 = 1,
  210110. READTYPE_ATAPI2 = 2,
  210111. READTYPE_READ6 = 3,
  210112. READTYPE_READ10 = 4,
  210113. READTYPE_READ_D8 = 5,
  210114. READTYPE_READ_D4 = 6,
  210115. READTYPE_READ_D4_1 = 7,
  210116. READTYPE_READ10_2 = 8
  210117. };
  210118. struct SCSI_PASS_THROUGH
  210119. {
  210120. USHORT Length;
  210121. UCHAR ScsiStatus;
  210122. UCHAR PathId;
  210123. UCHAR TargetId;
  210124. UCHAR Lun;
  210125. UCHAR CdbLength;
  210126. UCHAR SenseInfoLength;
  210127. UCHAR DataIn;
  210128. ULONG DataTransferLength;
  210129. ULONG TimeOutValue;
  210130. ULONG DataBufferOffset;
  210131. ULONG SenseInfoOffset;
  210132. UCHAR Cdb[16];
  210133. };
  210134. struct SCSI_PASS_THROUGH_DIRECT
  210135. {
  210136. USHORT Length;
  210137. UCHAR ScsiStatus;
  210138. UCHAR PathId;
  210139. UCHAR TargetId;
  210140. UCHAR Lun;
  210141. UCHAR CdbLength;
  210142. UCHAR SenseInfoLength;
  210143. UCHAR DataIn;
  210144. ULONG DataTransferLength;
  210145. ULONG TimeOutValue;
  210146. PVOID DataBuffer;
  210147. ULONG SenseInfoOffset;
  210148. UCHAR Cdb[16];
  210149. };
  210150. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210151. {
  210152. SCSI_PASS_THROUGH_DIRECT spt;
  210153. ULONG Filler;
  210154. UCHAR ucSenseBuf[32];
  210155. };
  210156. struct SCSI_ADDRESS
  210157. {
  210158. ULONG Length;
  210159. UCHAR PortNumber;
  210160. UCHAR PathId;
  210161. UCHAR TargetId;
  210162. UCHAR Lun;
  210163. };
  210164. #pragma pack(1)
  210165. struct SRB_GDEVBlock
  210166. {
  210167. BYTE SRB_Cmd;
  210168. BYTE SRB_Status;
  210169. BYTE SRB_HaID;
  210170. BYTE SRB_Flags;
  210171. DWORD SRB_Hdr_Rsvd;
  210172. BYTE SRB_Target;
  210173. BYTE SRB_Lun;
  210174. BYTE SRB_DeviceType;
  210175. BYTE SRB_Rsvd1;
  210176. BYTE pad[68];
  210177. };
  210178. struct SRB_ExecSCSICmd
  210179. {
  210180. BYTE SRB_Cmd;
  210181. BYTE SRB_Status;
  210182. BYTE SRB_HaID;
  210183. BYTE SRB_Flags;
  210184. DWORD SRB_Hdr_Rsvd;
  210185. BYTE SRB_Target;
  210186. BYTE SRB_Lun;
  210187. WORD SRB_Rsvd1;
  210188. DWORD SRB_BufLen;
  210189. BYTE *SRB_BufPointer;
  210190. BYTE SRB_SenseLen;
  210191. BYTE SRB_CDBLen;
  210192. BYTE SRB_HaStat;
  210193. BYTE SRB_TargStat;
  210194. VOID *SRB_PostProc;
  210195. BYTE SRB_Rsvd2[20];
  210196. BYTE CDBByte[16];
  210197. BYTE SenseArea[SENSE_LEN + 2];
  210198. };
  210199. struct SRB
  210200. {
  210201. BYTE SRB_Cmd;
  210202. BYTE SRB_Status;
  210203. BYTE SRB_HaId;
  210204. BYTE SRB_Flags;
  210205. DWORD SRB_Hdr_Rsvd;
  210206. };
  210207. struct TOCTRACK
  210208. {
  210209. BYTE rsvd;
  210210. BYTE ADR;
  210211. BYTE trackNumber;
  210212. BYTE rsvd2;
  210213. BYTE addr[4];
  210214. };
  210215. struct TOC
  210216. {
  210217. WORD tocLen;
  210218. BYTE firstTrack;
  210219. BYTE lastTrack;
  210220. TOCTRACK tracks[100];
  210221. };
  210222. #pragma pack()
  210223. struct CDDeviceDescription
  210224. {
  210225. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210226. {
  210227. }
  210228. void createDescription (const char* data)
  210229. {
  210230. description << String (data + 8, 8).trim() // vendor
  210231. << ' ' << String (data + 16, 16).trim() // product id
  210232. << ' ' << String (data + 32, 4).trim(); // rev
  210233. }
  210234. String description;
  210235. BYTE ha, tgt, lun;
  210236. char scsiDriveLetter; // will be 0 if not using scsi
  210237. };
  210238. class CDReadBuffer
  210239. {
  210240. public:
  210241. CDReadBuffer (const int numberOfFrames)
  210242. : startFrame (0), numFrames (0), dataStartOffset (0),
  210243. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210244. buffer (bufferSize), wantsIndex (false)
  210245. {
  210246. }
  210247. bool isZero() const throw()
  210248. {
  210249. for (int i = 0; i < dataLength; ++i)
  210250. if (buffer [dataStartOffset + i] != 0)
  210251. return false;
  210252. return true;
  210253. }
  210254. int startFrame, numFrames, dataStartOffset;
  210255. int dataLength, bufferSize, index;
  210256. HeapBlock<BYTE> buffer;
  210257. bool wantsIndex;
  210258. };
  210259. class CDDeviceHandle;
  210260. class CDController
  210261. {
  210262. public:
  210263. CDController() : initialised (false) {}
  210264. virtual ~CDController() {}
  210265. virtual bool read (CDReadBuffer&) = 0;
  210266. virtual void shutDown() {}
  210267. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210268. int getLastIndex();
  210269. public:
  210270. CDDeviceHandle* deviceInfo;
  210271. int framesToCheck, framesOverlap;
  210272. bool initialised;
  210273. void prepare (SRB_ExecSCSICmd& s);
  210274. void perform (SRB_ExecSCSICmd& s);
  210275. void setPaused (bool paused);
  210276. };
  210277. class CDDeviceHandle
  210278. {
  210279. public:
  210280. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210281. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210282. {
  210283. }
  210284. ~CDDeviceHandle()
  210285. {
  210286. if (controller != 0)
  210287. {
  210288. controller->shutDown();
  210289. controller = 0;
  210290. }
  210291. if (scsiHandle != 0)
  210292. CloseHandle (scsiHandle);
  210293. }
  210294. bool readTOC (TOC* lpToc);
  210295. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210296. void openDrawer (bool shouldBeOpen);
  210297. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210298. CDDeviceDescription info;
  210299. HANDLE scsiHandle;
  210300. BYTE readType;
  210301. private:
  210302. ScopedPointer<CDController> controller;
  210303. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210304. };
  210305. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210306. {
  210307. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210308. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210309. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210310. if (h == INVALID_HANDLE_VALUE)
  210311. {
  210312. flags ^= GENERIC_WRITE;
  210313. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210314. }
  210315. return h;
  210316. }
  210317. void findCDDevices (Array<CDDeviceDescription>& list)
  210318. {
  210319. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210320. {
  210321. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210322. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210323. {
  210324. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210325. if (h != INVALID_HANDLE_VALUE)
  210326. {
  210327. char buffer[100];
  210328. zeromem (buffer, sizeof (buffer));
  210329. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210330. zerostruct (p);
  210331. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210332. p.spt.CdbLength = 6;
  210333. p.spt.SenseInfoLength = 24;
  210334. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210335. p.spt.DataTransferLength = sizeof (buffer);
  210336. p.spt.TimeOutValue = 2;
  210337. p.spt.DataBuffer = buffer;
  210338. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210339. p.spt.Cdb[0] = 0x12;
  210340. p.spt.Cdb[4] = 100;
  210341. DWORD bytesReturned = 0;
  210342. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210343. &p, sizeof (p), &p, sizeof (p),
  210344. &bytesReturned, 0) != 0)
  210345. {
  210346. CDDeviceDescription dev;
  210347. dev.scsiDriveLetter = driveLetter;
  210348. dev.createDescription (buffer);
  210349. SCSI_ADDRESS scsiAddr;
  210350. zerostruct (scsiAddr);
  210351. scsiAddr.Length = sizeof (scsiAddr);
  210352. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210353. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210354. &bytesReturned, 0) != 0)
  210355. {
  210356. dev.ha = scsiAddr.PortNumber;
  210357. dev.tgt = scsiAddr.TargetId;
  210358. dev.lun = scsiAddr.Lun;
  210359. list.add (dev);
  210360. }
  210361. }
  210362. CloseHandle (h);
  210363. }
  210364. }
  210365. }
  210366. }
  210367. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210368. HANDLE& deviceHandle, const bool retryOnFailure)
  210369. {
  210370. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210371. zerostruct (s);
  210372. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210373. s.spt.CdbLength = srb->SRB_CDBLen;
  210374. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210375. ? SCSI_IOCTL_DATA_IN
  210376. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210377. ? SCSI_IOCTL_DATA_OUT
  210378. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210379. s.spt.DataTransferLength = srb->SRB_BufLen;
  210380. s.spt.TimeOutValue = 5;
  210381. s.spt.DataBuffer = srb->SRB_BufPointer;
  210382. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210383. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210384. srb->SRB_Status = SS_ERR;
  210385. srb->SRB_TargStat = 0x0004;
  210386. DWORD bytesReturned = 0;
  210387. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210388. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210389. {
  210390. srb->SRB_Status = SS_COMP;
  210391. }
  210392. else if (retryOnFailure)
  210393. {
  210394. const DWORD error = GetLastError();
  210395. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210396. {
  210397. if (error != ERROR_INVALID_HANDLE)
  210398. CloseHandle (deviceHandle);
  210399. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210400. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210401. }
  210402. }
  210403. return srb->SRB_Status;
  210404. }
  210405. // Controller types..
  210406. class ControllerType1 : public CDController
  210407. {
  210408. public:
  210409. ControllerType1() {}
  210410. bool read (CDReadBuffer& rb)
  210411. {
  210412. if (rb.numFrames * 2352 > rb.bufferSize)
  210413. return false;
  210414. SRB_ExecSCSICmd s;
  210415. prepare (s);
  210416. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210417. s.SRB_BufLen = rb.bufferSize;
  210418. s.SRB_BufPointer = rb.buffer;
  210419. s.SRB_CDBLen = 12;
  210420. s.CDBByte[0] = 0xBE;
  210421. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210422. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210423. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210424. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210425. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210426. perform (s);
  210427. if (s.SRB_Status != SS_COMP)
  210428. return false;
  210429. rb.dataLength = rb.numFrames * 2352;
  210430. rb.dataStartOffset = 0;
  210431. return true;
  210432. }
  210433. };
  210434. class ControllerType2 : public CDController
  210435. {
  210436. public:
  210437. ControllerType2() {}
  210438. void shutDown()
  210439. {
  210440. if (initialised)
  210441. {
  210442. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210443. SRB_ExecSCSICmd s;
  210444. prepare (s);
  210445. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210446. s.SRB_BufLen = 0x0C;
  210447. s.SRB_BufPointer = bufPointer;
  210448. s.SRB_CDBLen = 6;
  210449. s.CDBByte[0] = 0x15;
  210450. s.CDBByte[4] = 0x0C;
  210451. perform (s);
  210452. }
  210453. }
  210454. bool init()
  210455. {
  210456. SRB_ExecSCSICmd s;
  210457. s.SRB_Status = SS_ERR;
  210458. if (deviceInfo->readType == READTYPE_READ10_2)
  210459. {
  210460. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210461. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210462. for (int i = 0; i < 2; ++i)
  210463. {
  210464. prepare (s);
  210465. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210466. s.SRB_BufLen = 0x14;
  210467. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210468. s.SRB_CDBLen = 6;
  210469. s.CDBByte[0] = 0x15;
  210470. s.CDBByte[1] = 0x10;
  210471. s.CDBByte[4] = 0x14;
  210472. perform (s);
  210473. if (s.SRB_Status != SS_COMP)
  210474. return false;
  210475. }
  210476. }
  210477. else
  210478. {
  210479. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210480. prepare (s);
  210481. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210482. s.SRB_BufLen = 0x0C;
  210483. s.SRB_BufPointer = bufPointer;
  210484. s.SRB_CDBLen = 6;
  210485. s.CDBByte[0] = 0x15;
  210486. s.CDBByte[4] = 0x0C;
  210487. perform (s);
  210488. }
  210489. return s.SRB_Status == SS_COMP;
  210490. }
  210491. bool read (CDReadBuffer& rb)
  210492. {
  210493. if (rb.numFrames * 2352 > rb.bufferSize)
  210494. return false;
  210495. if (! initialised)
  210496. {
  210497. initialised = init();
  210498. if (! initialised)
  210499. return false;
  210500. }
  210501. SRB_ExecSCSICmd s;
  210502. prepare (s);
  210503. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210504. s.SRB_BufLen = rb.bufferSize;
  210505. s.SRB_BufPointer = rb.buffer;
  210506. s.SRB_CDBLen = 10;
  210507. s.CDBByte[0] = 0x28;
  210508. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210509. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210510. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210511. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210512. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210513. perform (s);
  210514. if (s.SRB_Status != SS_COMP)
  210515. return false;
  210516. rb.dataLength = rb.numFrames * 2352;
  210517. rb.dataStartOffset = 0;
  210518. return true;
  210519. }
  210520. };
  210521. class ControllerType3 : public CDController
  210522. {
  210523. public:
  210524. ControllerType3() {}
  210525. bool read (CDReadBuffer& rb)
  210526. {
  210527. if (rb.numFrames * 2352 > rb.bufferSize)
  210528. return false;
  210529. if (! initialised)
  210530. {
  210531. setPaused (false);
  210532. initialised = true;
  210533. }
  210534. SRB_ExecSCSICmd s;
  210535. prepare (s);
  210536. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210537. s.SRB_BufLen = rb.numFrames * 2352;
  210538. s.SRB_BufPointer = rb.buffer;
  210539. s.SRB_CDBLen = 12;
  210540. s.CDBByte[0] = 0xD8;
  210541. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210542. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210543. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210544. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210545. perform (s);
  210546. if (s.SRB_Status != SS_COMP)
  210547. return false;
  210548. rb.dataLength = rb.numFrames * 2352;
  210549. rb.dataStartOffset = 0;
  210550. return true;
  210551. }
  210552. };
  210553. class ControllerType4 : public CDController
  210554. {
  210555. public:
  210556. ControllerType4() {}
  210557. bool selectD4Mode()
  210558. {
  210559. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210560. SRB_ExecSCSICmd s;
  210561. prepare (s);
  210562. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210563. s.SRB_CDBLen = 6;
  210564. s.SRB_BufLen = 12;
  210565. s.SRB_BufPointer = bufPointer;
  210566. s.CDBByte[0] = 0x15;
  210567. s.CDBByte[1] = 0x10;
  210568. s.CDBByte[4] = 0x08;
  210569. perform (s);
  210570. return s.SRB_Status == SS_COMP;
  210571. }
  210572. bool read (CDReadBuffer& rb)
  210573. {
  210574. if (rb.numFrames * 2352 > rb.bufferSize)
  210575. return false;
  210576. if (! initialised)
  210577. {
  210578. setPaused (true);
  210579. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210580. selectD4Mode();
  210581. initialised = true;
  210582. }
  210583. SRB_ExecSCSICmd s;
  210584. prepare (s);
  210585. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210586. s.SRB_BufLen = rb.bufferSize;
  210587. s.SRB_BufPointer = rb.buffer;
  210588. s.SRB_CDBLen = 10;
  210589. s.CDBByte[0] = 0xD4;
  210590. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210591. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210592. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210593. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210594. perform (s);
  210595. if (s.SRB_Status != SS_COMP)
  210596. return false;
  210597. rb.dataLength = rb.numFrames * 2352;
  210598. rb.dataStartOffset = 0;
  210599. return true;
  210600. }
  210601. };
  210602. void CDController::prepare (SRB_ExecSCSICmd& s)
  210603. {
  210604. zerostruct (s);
  210605. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210606. s.SRB_HaID = deviceInfo->info.ha;
  210607. s.SRB_Target = deviceInfo->info.tgt;
  210608. s.SRB_Lun = deviceInfo->info.lun;
  210609. s.SRB_SenseLen = SENSE_LEN;
  210610. }
  210611. void CDController::perform (SRB_ExecSCSICmd& s)
  210612. {
  210613. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210614. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210615. }
  210616. void CDController::setPaused (bool paused)
  210617. {
  210618. SRB_ExecSCSICmd s;
  210619. prepare (s);
  210620. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210621. s.SRB_CDBLen = 10;
  210622. s.CDBByte[0] = 0x4B;
  210623. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210624. perform (s);
  210625. }
  210626. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210627. {
  210628. if (overlapBuffer != 0)
  210629. {
  210630. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210631. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210632. if (doJitter
  210633. && overlapBuffer->startFrame > 0
  210634. && overlapBuffer->numFrames > 0
  210635. && overlapBuffer->dataLength > 0)
  210636. {
  210637. const int numFrames = rb.numFrames;
  210638. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210639. {
  210640. rb.startFrame -= framesOverlap;
  210641. if (framesToCheck < framesOverlap
  210642. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210643. rb.numFrames += framesOverlap;
  210644. }
  210645. else
  210646. {
  210647. overlapBuffer->dataLength = 0;
  210648. overlapBuffer->startFrame = 0;
  210649. overlapBuffer->numFrames = 0;
  210650. }
  210651. }
  210652. if (! read (rb))
  210653. return false;
  210654. if (doJitter)
  210655. {
  210656. const int checkLen = framesToCheck * 2352;
  210657. const int maxToCheck = rb.dataLength - checkLen;
  210658. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210659. return true;
  210660. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210661. bool found = false;
  210662. for (int i = 0; i < maxToCheck; ++i)
  210663. {
  210664. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210665. {
  210666. i += checkLen;
  210667. rb.dataStartOffset = i;
  210668. rb.dataLength -= i;
  210669. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210670. found = true;
  210671. break;
  210672. }
  210673. }
  210674. rb.numFrames = rb.dataLength / 2352;
  210675. rb.dataLength = 2352 * rb.numFrames;
  210676. if (! found)
  210677. return false;
  210678. }
  210679. if (canDoJitter)
  210680. {
  210681. memcpy (overlapBuffer->buffer,
  210682. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210683. 2352 * framesToCheck);
  210684. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210685. overlapBuffer->numFrames = framesToCheck;
  210686. overlapBuffer->dataLength = 2352 * framesToCheck;
  210687. overlapBuffer->dataStartOffset = 0;
  210688. }
  210689. else
  210690. {
  210691. overlapBuffer->startFrame = 0;
  210692. overlapBuffer->numFrames = 0;
  210693. overlapBuffer->dataLength = 0;
  210694. }
  210695. return true;
  210696. }
  210697. return read (rb);
  210698. }
  210699. int CDController::getLastIndex()
  210700. {
  210701. char qdata[100];
  210702. SRB_ExecSCSICmd s;
  210703. prepare (s);
  210704. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210705. s.SRB_BufLen = sizeof (qdata);
  210706. s.SRB_BufPointer = (BYTE*) qdata;
  210707. s.SRB_CDBLen = 12;
  210708. s.CDBByte[0] = 0x42;
  210709. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210710. s.CDBByte[2] = 64;
  210711. s.CDBByte[3] = 1; // get current position
  210712. s.CDBByte[7] = 0;
  210713. s.CDBByte[8] = (BYTE) sizeof (qdata);
  210714. perform (s);
  210715. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  210716. }
  210717. bool CDDeviceHandle::readTOC (TOC* lpToc)
  210718. {
  210719. SRB_ExecSCSICmd s;
  210720. zerostruct (s);
  210721. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210722. s.SRB_HaID = info.ha;
  210723. s.SRB_Target = info.tgt;
  210724. s.SRB_Lun = info.lun;
  210725. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210726. s.SRB_BufLen = 0x324;
  210727. s.SRB_BufPointer = (BYTE*) lpToc;
  210728. s.SRB_SenseLen = 0x0E;
  210729. s.SRB_CDBLen = 0x0A;
  210730. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210731. s.CDBByte[0] = 0x43;
  210732. s.CDBByte[1] = 0x00;
  210733. s.CDBByte[7] = 0x03;
  210734. s.CDBByte[8] = 0x24;
  210735. performScsiCommand (s.SRB_PostProc, s);
  210736. return (s.SRB_Status == SS_COMP);
  210737. }
  210738. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  210739. {
  210740. ResetEvent (event);
  210741. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  210742. if (status == SS_PENDING)
  210743. WaitForSingleObject (event, 4000);
  210744. CloseHandle (event);
  210745. }
  210746. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  210747. {
  210748. if (controller == 0)
  210749. {
  210750. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210751. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210752. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210753. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210754. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210755. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210756. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210757. }
  210758. buffer.index = 0;
  210759. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  210760. {
  210761. if (buffer.wantsIndex)
  210762. buffer.index = controller->getLastIndex();
  210763. return true;
  210764. }
  210765. return false;
  210766. }
  210767. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210768. {
  210769. if (shouldBeOpen)
  210770. {
  210771. if (controller != 0)
  210772. {
  210773. controller->shutDown();
  210774. controller = 0;
  210775. }
  210776. if (scsiHandle != 0)
  210777. {
  210778. CloseHandle (scsiHandle);
  210779. scsiHandle = 0;
  210780. }
  210781. }
  210782. SRB_ExecSCSICmd s;
  210783. zerostruct (s);
  210784. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210785. s.SRB_HaID = info.ha;
  210786. s.SRB_Target = info.tgt;
  210787. s.SRB_Lun = info.lun;
  210788. s.SRB_SenseLen = SENSE_LEN;
  210789. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210790. s.SRB_BufLen = 0;
  210791. s.SRB_BufPointer = 0;
  210792. s.SRB_CDBLen = 12;
  210793. s.CDBByte[0] = 0x1b;
  210794. s.CDBByte[1] = (BYTE) (info.lun << 5);
  210795. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  210796. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210797. performScsiCommand (s.SRB_PostProc, s);
  210798. }
  210799. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  210800. {
  210801. controller = newController;
  210802. readType = (BYTE) type;
  210803. controller->deviceInfo = this;
  210804. controller->framesToCheck = 1;
  210805. controller->framesOverlap = 3;
  210806. bool passed = false;
  210807. memset (rb.buffer, 0xcd, rb.bufferSize);
  210808. if (controller->read (rb))
  210809. {
  210810. passed = true;
  210811. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  210812. int wrong = 0;
  210813. for (int i = rb.dataLength / 4; --i >= 0;)
  210814. {
  210815. if (*p++ == (int) 0xcdcdcdcd)
  210816. {
  210817. if (++wrong == 4)
  210818. {
  210819. passed = false;
  210820. break;
  210821. }
  210822. }
  210823. else
  210824. {
  210825. wrong = 0;
  210826. }
  210827. }
  210828. }
  210829. if (! passed)
  210830. {
  210831. controller->shutDown();
  210832. controller = 0;
  210833. }
  210834. return passed;
  210835. }
  210836. struct CDDeviceWrapper
  210837. {
  210838. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  210839. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  210840. {
  210841. // xxx jitter never seemed to actually be enabled (??)
  210842. }
  210843. CDDeviceHandle deviceHandle;
  210844. CDReadBuffer overlapBuffer;
  210845. bool jitter;
  210846. };
  210847. int getAddressOfTrack (const TOCTRACK& t) throw()
  210848. {
  210849. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  210850. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  210851. }
  210852. const int samplesPerFrame = 44100 / 75;
  210853. const int bytesPerFrame = samplesPerFrame * 4;
  210854. const int framesPerIndexRead = 4;
  210855. }
  210856. const StringArray AudioCDReader::getAvailableCDNames()
  210857. {
  210858. using namespace CDReaderHelpers;
  210859. StringArray results;
  210860. Array<CDDeviceDescription> list;
  210861. findCDDevices (list);
  210862. for (int i = 0; i < list.size(); ++i)
  210863. {
  210864. String s;
  210865. if (list[i].scsiDriveLetter > 0)
  210866. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210867. s << list[i].description;
  210868. results.add (s);
  210869. }
  210870. return results;
  210871. }
  210872. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210873. {
  210874. using namespace CDReaderHelpers;
  210875. Array<CDDeviceDescription> list;
  210876. findCDDevices (list);
  210877. if (isPositiveAndBelow (deviceIndex, list.size()))
  210878. {
  210879. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  210880. if (h != INVALID_HANDLE_VALUE)
  210881. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  210882. }
  210883. return 0;
  210884. }
  210885. AudioCDReader::AudioCDReader (void* handle_)
  210886. : AudioFormatReader (0, "CD Audio"),
  210887. handle (handle_),
  210888. indexingEnabled (false),
  210889. lastIndex (0),
  210890. firstFrameInBuffer (0),
  210891. samplesInBuffer (0)
  210892. {
  210893. using namespace CDReaderHelpers;
  210894. jassert (handle_ != 0);
  210895. refreshTrackLengths();
  210896. sampleRate = 44100.0;
  210897. bitsPerSample = 16;
  210898. numChannels = 2;
  210899. usesFloatingPointData = false;
  210900. buffer.setSize (4 * bytesPerFrame, true);
  210901. }
  210902. AudioCDReader::~AudioCDReader()
  210903. {
  210904. using namespace CDReaderHelpers;
  210905. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210906. delete device;
  210907. }
  210908. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210909. int64 startSampleInFile, int numSamples)
  210910. {
  210911. using namespace CDReaderHelpers;
  210912. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210913. bool ok = true;
  210914. while (numSamples > 0)
  210915. {
  210916. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210917. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210918. if (startSampleInFile >= bufferStartSample
  210919. && startSampleInFile < bufferEndSample)
  210920. {
  210921. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210922. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210923. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210924. const short* src = (const short*) buffer.getData();
  210925. src += 2 * (startSampleInFile - bufferStartSample);
  210926. for (int i = 0; i < toDo; ++i)
  210927. {
  210928. l[i] = src [i << 1] << 16;
  210929. if (r != 0)
  210930. r[i] = src [(i << 1) + 1] << 16;
  210931. }
  210932. startOffsetInDestBuffer += toDo;
  210933. startSampleInFile += toDo;
  210934. numSamples -= toDo;
  210935. }
  210936. else
  210937. {
  210938. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210939. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210940. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210941. {
  210942. device->overlapBuffer.dataLength = 0;
  210943. device->overlapBuffer.startFrame = 0;
  210944. device->overlapBuffer.numFrames = 0;
  210945. device->jitter = false;
  210946. }
  210947. firstFrameInBuffer = frameNeeded;
  210948. lastIndex = 0;
  210949. CDReadBuffer readBuffer (framesInBuffer + 4);
  210950. readBuffer.wantsIndex = indexingEnabled;
  210951. int i;
  210952. for (i = 5; --i >= 0;)
  210953. {
  210954. readBuffer.startFrame = frameNeeded;
  210955. readBuffer.numFrames = framesInBuffer;
  210956. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  210957. break;
  210958. else
  210959. device->overlapBuffer.dataLength = 0;
  210960. }
  210961. if (i >= 0)
  210962. {
  210963. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  210964. samplesInBuffer = readBuffer.dataLength >> 2;
  210965. lastIndex = readBuffer.index;
  210966. }
  210967. else
  210968. {
  210969. int* l = destSamples[0] + startOffsetInDestBuffer;
  210970. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210971. while (--numSamples >= 0)
  210972. {
  210973. *l++ = 0;
  210974. if (r != 0)
  210975. *r++ = 0;
  210976. }
  210977. // sometimes the read fails for just the very last couple of blocks, so
  210978. // we'll ignore and errors in the last half-second of the disk..
  210979. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  210980. break;
  210981. }
  210982. }
  210983. }
  210984. return ok;
  210985. }
  210986. bool AudioCDReader::isCDStillPresent() const
  210987. {
  210988. using namespace CDReaderHelpers;
  210989. TOC toc;
  210990. zerostruct (toc);
  210991. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  210992. }
  210993. void AudioCDReader::refreshTrackLengths()
  210994. {
  210995. using namespace CDReaderHelpers;
  210996. trackStartSamples.clear();
  210997. zeromem (audioTracks, sizeof (audioTracks));
  210998. TOC toc;
  210999. zerostruct (toc);
  211000. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211001. {
  211002. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211003. for (int i = 0; i <= numTracks; ++i)
  211004. {
  211005. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211006. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211007. }
  211008. }
  211009. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211010. }
  211011. bool AudioCDReader::isTrackAudio (int trackNum) const
  211012. {
  211013. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211014. }
  211015. void AudioCDReader::enableIndexScanning (bool b)
  211016. {
  211017. indexingEnabled = b;
  211018. }
  211019. int AudioCDReader::getLastIndex() const
  211020. {
  211021. return lastIndex;
  211022. }
  211023. int AudioCDReader::getIndexAt (int samplePos)
  211024. {
  211025. using namespace CDReaderHelpers;
  211026. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211027. const int frameNeeded = samplePos / samplesPerFrame;
  211028. device->overlapBuffer.dataLength = 0;
  211029. device->overlapBuffer.startFrame = 0;
  211030. device->overlapBuffer.numFrames = 0;
  211031. device->jitter = false;
  211032. firstFrameInBuffer = 0;
  211033. lastIndex = 0;
  211034. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211035. readBuffer.wantsIndex = true;
  211036. int i;
  211037. for (i = 5; --i >= 0;)
  211038. {
  211039. readBuffer.startFrame = frameNeeded;
  211040. readBuffer.numFrames = framesPerIndexRead;
  211041. if (device->deviceHandle.readAudio (readBuffer))
  211042. break;
  211043. }
  211044. if (i >= 0)
  211045. return readBuffer.index;
  211046. return -1;
  211047. }
  211048. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211049. {
  211050. using namespace CDReaderHelpers;
  211051. Array <int> indexes;
  211052. const int trackStart = getPositionOfTrackStart (trackNumber);
  211053. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211054. bool needToScan = true;
  211055. if (trackEnd - trackStart > 20 * 44100)
  211056. {
  211057. // check the end of the track for indexes before scanning the whole thing
  211058. needToScan = false;
  211059. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211060. bool seenAnIndex = false;
  211061. while (pos <= trackEnd - samplesPerFrame)
  211062. {
  211063. const int index = getIndexAt (pos);
  211064. if (index == 0)
  211065. {
  211066. // lead-out, so skip back a bit if we've not found any indexes yet..
  211067. if (seenAnIndex)
  211068. break;
  211069. pos -= 44100 * 5;
  211070. if (pos < trackStart)
  211071. break;
  211072. }
  211073. else
  211074. {
  211075. if (index > 0)
  211076. seenAnIndex = true;
  211077. if (index > 1)
  211078. {
  211079. needToScan = true;
  211080. break;
  211081. }
  211082. pos += samplesPerFrame * framesPerIndexRead;
  211083. }
  211084. }
  211085. }
  211086. if (needToScan)
  211087. {
  211088. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211089. int pos = trackStart;
  211090. int last = -1;
  211091. while (pos < trackEnd - samplesPerFrame * 10)
  211092. {
  211093. const int frameNeeded = pos / samplesPerFrame;
  211094. device->overlapBuffer.dataLength = 0;
  211095. device->overlapBuffer.startFrame = 0;
  211096. device->overlapBuffer.numFrames = 0;
  211097. device->jitter = false;
  211098. firstFrameInBuffer = 0;
  211099. CDReadBuffer readBuffer (4);
  211100. readBuffer.wantsIndex = true;
  211101. int i;
  211102. for (i = 5; --i >= 0;)
  211103. {
  211104. readBuffer.startFrame = frameNeeded;
  211105. readBuffer.numFrames = framesPerIndexRead;
  211106. if (device->deviceHandle.readAudio (readBuffer))
  211107. break;
  211108. }
  211109. if (i < 0)
  211110. break;
  211111. if (readBuffer.index > last && readBuffer.index > 1)
  211112. {
  211113. last = readBuffer.index;
  211114. indexes.add (pos);
  211115. }
  211116. pos += samplesPerFrame * framesPerIndexRead;
  211117. }
  211118. indexes.removeValue (trackStart);
  211119. }
  211120. return indexes;
  211121. }
  211122. void AudioCDReader::ejectDisk()
  211123. {
  211124. using namespace CDReaderHelpers;
  211125. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211126. }
  211127. #endif
  211128. #if JUCE_USE_CDBURNER
  211129. namespace CDBurnerHelpers
  211130. {
  211131. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211132. {
  211133. CoInitialize (0);
  211134. IDiscMaster* dm;
  211135. IDiscRecorder* result = 0;
  211136. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211137. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211138. IID_IDiscMaster,
  211139. (void**) &dm)))
  211140. {
  211141. if (SUCCEEDED (dm->Open()))
  211142. {
  211143. IEnumDiscRecorders* drEnum = 0;
  211144. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211145. {
  211146. IDiscRecorder* dr = 0;
  211147. DWORD dummy;
  211148. int index = 0;
  211149. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211150. {
  211151. if (indexToOpen == index)
  211152. {
  211153. result = dr;
  211154. break;
  211155. }
  211156. else if (list != 0)
  211157. {
  211158. BSTR path;
  211159. if (SUCCEEDED (dr->GetPath (&path)))
  211160. list->add ((const WCHAR*) path);
  211161. }
  211162. ++index;
  211163. dr->Release();
  211164. }
  211165. drEnum->Release();
  211166. }
  211167. if (master == 0)
  211168. dm->Close();
  211169. }
  211170. if (master != 0)
  211171. *master = dm;
  211172. else
  211173. dm->Release();
  211174. }
  211175. return result;
  211176. }
  211177. }
  211178. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211179. public Timer
  211180. {
  211181. public:
  211182. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211183. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211184. listener (0), progress (0), shouldCancel (false)
  211185. {
  211186. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211187. jassert (SUCCEEDED (hr));
  211188. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211189. //jassert (SUCCEEDED (hr));
  211190. lastState = getDiskState();
  211191. startTimer (2000);
  211192. }
  211193. ~Pimpl() {}
  211194. void releaseObjects()
  211195. {
  211196. discRecorder->Close();
  211197. if (redbook != 0)
  211198. redbook->Release();
  211199. discRecorder->Release();
  211200. discMaster->Release();
  211201. Release();
  211202. }
  211203. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211204. {
  211205. if (listener != 0 && ! shouldCancel)
  211206. shouldCancel = listener->audioCDBurnProgress (progress);
  211207. *pbCancel = shouldCancel;
  211208. return S_OK;
  211209. }
  211210. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211211. {
  211212. progress = nCompleted / (float) nTotal;
  211213. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211214. return E_NOTIMPL;
  211215. }
  211216. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211217. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211218. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211219. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211220. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211221. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211222. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211223. class ScopedDiscOpener
  211224. {
  211225. public:
  211226. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211227. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211228. private:
  211229. Pimpl& pimpl;
  211230. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211231. };
  211232. DiskState getDiskState()
  211233. {
  211234. const ScopedDiscOpener opener (*this);
  211235. long type, flags;
  211236. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211237. if (FAILED (hr))
  211238. return unknown;
  211239. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211240. return writableDiskPresent;
  211241. if (type == 0)
  211242. return noDisc;
  211243. else
  211244. return readOnlyDiskPresent;
  211245. }
  211246. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211247. {
  211248. ComSmartPtr<IPropertyStorage> prop;
  211249. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211250. return defaultReturn;
  211251. PROPSPEC iPropSpec;
  211252. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211253. iPropSpec.lpwstr = name;
  211254. PROPVARIANT iPropVariant;
  211255. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211256. ? defaultReturn : (int) iPropVariant.lVal;
  211257. }
  211258. bool setIntProperty (const LPOLESTR name, const int value) const
  211259. {
  211260. ComSmartPtr<IPropertyStorage> prop;
  211261. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211262. return false;
  211263. PROPSPEC iPropSpec;
  211264. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211265. iPropSpec.lpwstr = name;
  211266. PROPVARIANT iPropVariant;
  211267. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211268. return false;
  211269. iPropVariant.lVal = (long) value;
  211270. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211271. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211272. }
  211273. void timerCallback()
  211274. {
  211275. const DiskState state = getDiskState();
  211276. if (state != lastState)
  211277. {
  211278. lastState = state;
  211279. owner.sendChangeMessage();
  211280. }
  211281. }
  211282. AudioCDBurner& owner;
  211283. DiskState lastState;
  211284. IDiscMaster* discMaster;
  211285. IDiscRecorder* discRecorder;
  211286. IRedbookDiscMaster* redbook;
  211287. AudioCDBurner::BurnProgressListener* listener;
  211288. float progress;
  211289. bool shouldCancel;
  211290. };
  211291. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211292. {
  211293. IDiscMaster* discMaster = 0;
  211294. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211295. if (discRecorder != 0)
  211296. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211297. }
  211298. AudioCDBurner::~AudioCDBurner()
  211299. {
  211300. if (pimpl != 0)
  211301. pimpl.release()->releaseObjects();
  211302. }
  211303. const StringArray AudioCDBurner::findAvailableDevices()
  211304. {
  211305. StringArray devs;
  211306. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211307. return devs;
  211308. }
  211309. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211310. {
  211311. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211312. if (b->pimpl == 0)
  211313. b = 0;
  211314. return b.release();
  211315. }
  211316. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211317. {
  211318. return pimpl->getDiskState();
  211319. }
  211320. bool AudioCDBurner::isDiskPresent() const
  211321. {
  211322. return getDiskState() == writableDiskPresent;
  211323. }
  211324. bool AudioCDBurner::openTray()
  211325. {
  211326. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211327. return SUCCEEDED (pimpl->discRecorder->Eject());
  211328. }
  211329. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211330. {
  211331. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211332. DiskState oldState = getDiskState();
  211333. DiskState newState = oldState;
  211334. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211335. {
  211336. newState = getDiskState();
  211337. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211338. }
  211339. return newState;
  211340. }
  211341. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211342. {
  211343. Array<int> results;
  211344. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211345. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211346. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211347. if (speeds[i] <= maxSpeed)
  211348. results.add (speeds[i]);
  211349. results.addIfNotAlreadyThere (maxSpeed);
  211350. return results;
  211351. }
  211352. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211353. {
  211354. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211355. return false;
  211356. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211357. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211358. }
  211359. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211360. {
  211361. long blocksFree = 0;
  211362. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211363. return blocksFree;
  211364. }
  211365. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211366. bool performFakeBurnForTesting, int writeSpeed)
  211367. {
  211368. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211369. pimpl->listener = listener;
  211370. pimpl->progress = 0;
  211371. pimpl->shouldCancel = false;
  211372. UINT_PTR cookie;
  211373. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211374. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211375. ejectDiscAfterwards);
  211376. String error;
  211377. if (hr != S_OK)
  211378. {
  211379. const char* e = "Couldn't open or write to the CD device";
  211380. if (hr == IMAPI_E_USERABORT)
  211381. e = "User cancelled the write operation";
  211382. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211383. e = "No Disk present";
  211384. error = e;
  211385. }
  211386. pimpl->discMaster->ProgressUnadvise (cookie);
  211387. pimpl->listener = 0;
  211388. return error;
  211389. }
  211390. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211391. {
  211392. if (audioSource == 0)
  211393. return false;
  211394. ScopedPointer<AudioSource> source (audioSource);
  211395. long bytesPerBlock;
  211396. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211397. const int samplesPerBlock = bytesPerBlock / 4;
  211398. bool ok = true;
  211399. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211400. HeapBlock <byte> buffer (bytesPerBlock);
  211401. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211402. int samplesDone = 0;
  211403. source->prepareToPlay (samplesPerBlock, 44100.0);
  211404. while (ok)
  211405. {
  211406. {
  211407. AudioSourceChannelInfo info;
  211408. info.buffer = &sourceBuffer;
  211409. info.numSamples = samplesPerBlock;
  211410. info.startSample = 0;
  211411. sourceBuffer.clear();
  211412. source->getNextAudioBlock (info);
  211413. }
  211414. zeromem (buffer, bytesPerBlock);
  211415. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211416. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211417. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211418. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211419. CDSampleFormat left (buffer, 2);
  211420. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211421. CDSampleFormat right (buffer + 2, 2);
  211422. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211423. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211424. if (FAILED (hr))
  211425. ok = false;
  211426. samplesDone += samplesPerBlock;
  211427. if (samplesDone >= numSamples)
  211428. break;
  211429. }
  211430. hr = pimpl->redbook->CloseAudioTrack();
  211431. return ok && hr == S_OK;
  211432. }
  211433. #endif
  211434. #endif
  211435. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211436. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211437. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211438. // compiled on its own).
  211439. #if JUCE_INCLUDED_FILE
  211440. class MidiInCollector
  211441. {
  211442. public:
  211443. MidiInCollector (MidiInput* const input_,
  211444. MidiInputCallback& callback_)
  211445. : deviceHandle (0),
  211446. input (input_),
  211447. callback (callback_),
  211448. concatenator (4096),
  211449. isStarted (false),
  211450. startTime (0)
  211451. {
  211452. }
  211453. ~MidiInCollector()
  211454. {
  211455. stop();
  211456. if (deviceHandle != 0)
  211457. {
  211458. int count = 5;
  211459. while (--count >= 0)
  211460. {
  211461. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211462. break;
  211463. Sleep (20);
  211464. }
  211465. }
  211466. }
  211467. void handleMessage (const uint32 message, const uint32 timeStamp)
  211468. {
  211469. if ((message & 0xff) >= 0x80 && isStarted)
  211470. {
  211471. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211472. writeFinishedBlocks();
  211473. }
  211474. }
  211475. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211476. {
  211477. if (isStarted)
  211478. {
  211479. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211480. writeFinishedBlocks();
  211481. }
  211482. }
  211483. void start()
  211484. {
  211485. jassert (deviceHandle != 0);
  211486. if (deviceHandle != 0 && ! isStarted)
  211487. {
  211488. activeMidiCollectors.addIfNotAlreadyThere (this);
  211489. for (int i = 0; i < (int) numHeaders; ++i)
  211490. headers[i].write (deviceHandle);
  211491. startTime = Time::getMillisecondCounter();
  211492. MMRESULT res = midiInStart (deviceHandle);
  211493. if (res == MMSYSERR_NOERROR)
  211494. {
  211495. concatenator.reset();
  211496. isStarted = true;
  211497. }
  211498. else
  211499. {
  211500. unprepareAllHeaders();
  211501. }
  211502. }
  211503. }
  211504. void stop()
  211505. {
  211506. if (isStarted)
  211507. {
  211508. isStarted = false;
  211509. midiInReset (deviceHandle);
  211510. midiInStop (deviceHandle);
  211511. activeMidiCollectors.removeValue (this);
  211512. unprepareAllHeaders();
  211513. concatenator.reset();
  211514. }
  211515. }
  211516. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211517. {
  211518. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211519. if (activeMidiCollectors.contains (collector))
  211520. {
  211521. if (uMsg == MIM_DATA)
  211522. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211523. else if (uMsg == MIM_LONGDATA)
  211524. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211525. }
  211526. }
  211527. HMIDIIN deviceHandle;
  211528. private:
  211529. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211530. MidiInput* input;
  211531. MidiInputCallback& callback;
  211532. MidiDataConcatenator concatenator;
  211533. bool volatile isStarted;
  211534. uint32 startTime;
  211535. class MidiHeader
  211536. {
  211537. public:
  211538. MidiHeader()
  211539. {
  211540. zerostruct (hdr);
  211541. hdr.lpData = data;
  211542. hdr.dwBufferLength = numElementsInArray (data);
  211543. }
  211544. void write (HMIDIIN deviceHandle)
  211545. {
  211546. hdr.dwBytesRecorded = 0;
  211547. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211548. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211549. }
  211550. void writeIfFinished (HMIDIIN deviceHandle)
  211551. {
  211552. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211553. {
  211554. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211555. (void) res;
  211556. write (deviceHandle);
  211557. }
  211558. }
  211559. void unprepare (HMIDIIN deviceHandle)
  211560. {
  211561. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211562. {
  211563. int c = 10;
  211564. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211565. Thread::sleep (20);
  211566. jassert (c >= 0);
  211567. }
  211568. }
  211569. private:
  211570. MIDIHDR hdr;
  211571. char data [256];
  211572. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211573. };
  211574. enum { numHeaders = 32 };
  211575. MidiHeader headers [numHeaders];
  211576. void writeFinishedBlocks()
  211577. {
  211578. for (int i = 0; i < (int) numHeaders; ++i)
  211579. headers[i].writeIfFinished (deviceHandle);
  211580. }
  211581. void unprepareAllHeaders()
  211582. {
  211583. for (int i = 0; i < (int) numHeaders; ++i)
  211584. headers[i].unprepare (deviceHandle);
  211585. }
  211586. double convertTimeStamp (uint32 timeStamp)
  211587. {
  211588. timeStamp += startTime;
  211589. const uint32 now = Time::getMillisecondCounter();
  211590. if (timeStamp > now)
  211591. {
  211592. if (timeStamp > now + 2)
  211593. --startTime;
  211594. timeStamp = now;
  211595. }
  211596. return timeStamp * 0.001;
  211597. }
  211598. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211599. };
  211600. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211601. const StringArray MidiInput::getDevices()
  211602. {
  211603. StringArray s;
  211604. const int num = midiInGetNumDevs();
  211605. for (int i = 0; i < num; ++i)
  211606. {
  211607. MIDIINCAPS mc;
  211608. zerostruct (mc);
  211609. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211610. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211611. }
  211612. return s;
  211613. }
  211614. int MidiInput::getDefaultDeviceIndex()
  211615. {
  211616. return 0;
  211617. }
  211618. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211619. {
  211620. if (callback == 0)
  211621. return 0;
  211622. UINT deviceId = MIDI_MAPPER;
  211623. int n = 0;
  211624. String name;
  211625. const int num = midiInGetNumDevs();
  211626. for (int i = 0; i < num; ++i)
  211627. {
  211628. MIDIINCAPS mc;
  211629. zerostruct (mc);
  211630. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211631. {
  211632. if (index == n)
  211633. {
  211634. deviceId = i;
  211635. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211636. break;
  211637. }
  211638. ++n;
  211639. }
  211640. }
  211641. ScopedPointer <MidiInput> in (new MidiInput (name));
  211642. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211643. HMIDIIN h;
  211644. HRESULT err = midiInOpen (&h, deviceId,
  211645. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211646. (DWORD_PTR) (MidiInCollector*) collector,
  211647. CALLBACK_FUNCTION);
  211648. if (err == MMSYSERR_NOERROR)
  211649. {
  211650. collector->deviceHandle = h;
  211651. in->internal = collector.release();
  211652. return in.release();
  211653. }
  211654. return 0;
  211655. }
  211656. MidiInput::MidiInput (const String& name_)
  211657. : name (name_),
  211658. internal (0)
  211659. {
  211660. }
  211661. MidiInput::~MidiInput()
  211662. {
  211663. delete static_cast <MidiInCollector*> (internal);
  211664. }
  211665. void MidiInput::start()
  211666. {
  211667. static_cast <MidiInCollector*> (internal)->start();
  211668. }
  211669. void MidiInput::stop()
  211670. {
  211671. static_cast <MidiInCollector*> (internal)->stop();
  211672. }
  211673. struct MidiOutHandle
  211674. {
  211675. int refCount;
  211676. UINT deviceId;
  211677. HMIDIOUT handle;
  211678. static Array<MidiOutHandle*> activeHandles;
  211679. private:
  211680. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211681. };
  211682. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211683. const StringArray MidiOutput::getDevices()
  211684. {
  211685. StringArray s;
  211686. const int num = midiOutGetNumDevs();
  211687. for (int i = 0; i < num; ++i)
  211688. {
  211689. MIDIOUTCAPS mc;
  211690. zerostruct (mc);
  211691. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211692. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211693. }
  211694. return s;
  211695. }
  211696. int MidiOutput::getDefaultDeviceIndex()
  211697. {
  211698. const int num = midiOutGetNumDevs();
  211699. int n = 0;
  211700. for (int i = 0; i < num; ++i)
  211701. {
  211702. MIDIOUTCAPS mc;
  211703. zerostruct (mc);
  211704. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211705. {
  211706. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211707. return n;
  211708. ++n;
  211709. }
  211710. }
  211711. return 0;
  211712. }
  211713. MidiOutput* MidiOutput::openDevice (int index)
  211714. {
  211715. UINT deviceId = MIDI_MAPPER;
  211716. const int num = midiOutGetNumDevs();
  211717. int i, n = 0;
  211718. for (i = 0; i < num; ++i)
  211719. {
  211720. MIDIOUTCAPS mc;
  211721. zerostruct (mc);
  211722. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211723. {
  211724. // use the microsoft sw synth as a default - best not to allow deviceId
  211725. // to be MIDI_MAPPER, or else device sharing breaks
  211726. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211727. deviceId = i;
  211728. if (index == n)
  211729. {
  211730. deviceId = i;
  211731. break;
  211732. }
  211733. ++n;
  211734. }
  211735. }
  211736. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211737. {
  211738. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211739. if (han != 0 && han->deviceId == deviceId)
  211740. {
  211741. han->refCount++;
  211742. MidiOutput* const out = new MidiOutput();
  211743. out->internal = han;
  211744. return out;
  211745. }
  211746. }
  211747. for (i = 4; --i >= 0;)
  211748. {
  211749. HMIDIOUT h = 0;
  211750. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211751. if (res == MMSYSERR_NOERROR)
  211752. {
  211753. MidiOutHandle* const han = new MidiOutHandle();
  211754. han->deviceId = deviceId;
  211755. han->refCount = 1;
  211756. han->handle = h;
  211757. MidiOutHandle::activeHandles.add (han);
  211758. MidiOutput* const out = new MidiOutput();
  211759. out->internal = han;
  211760. return out;
  211761. }
  211762. else if (res == MMSYSERR_ALLOCATED)
  211763. {
  211764. Sleep (100);
  211765. }
  211766. else
  211767. {
  211768. break;
  211769. }
  211770. }
  211771. return 0;
  211772. }
  211773. MidiOutput::~MidiOutput()
  211774. {
  211775. stopBackgroundThread();
  211776. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211777. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211778. {
  211779. midiOutClose (h->handle);
  211780. MidiOutHandle::activeHandles.removeValue (h);
  211781. delete h;
  211782. }
  211783. }
  211784. void MidiOutput::reset()
  211785. {
  211786. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211787. midiOutReset (h->handle);
  211788. }
  211789. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211790. {
  211791. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211792. DWORD n;
  211793. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211794. {
  211795. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  211796. rightVol = nn[0] / (float) 0xffff;
  211797. leftVol = nn[1] / (float) 0xffff;
  211798. return true;
  211799. }
  211800. else
  211801. {
  211802. rightVol = leftVol = 1.0f;
  211803. return false;
  211804. }
  211805. }
  211806. void MidiOutput::setVolume (float leftVol, float rightVol)
  211807. {
  211808. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211809. DWORD n;
  211810. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  211811. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211812. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211813. midiOutSetVolume (handle->handle, n);
  211814. }
  211815. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211816. {
  211817. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211818. if (message.getRawDataSize() > 3
  211819. || message.isSysEx())
  211820. {
  211821. MIDIHDR h;
  211822. zerostruct (h);
  211823. h.lpData = (char*) message.getRawData();
  211824. h.dwBufferLength = message.getRawDataSize();
  211825. h.dwBytesRecorded = message.getRawDataSize();
  211826. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211827. {
  211828. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211829. if (res == MMSYSERR_NOERROR)
  211830. {
  211831. while ((h.dwFlags & MHDR_DONE) == 0)
  211832. Sleep (1);
  211833. int count = 500; // 1 sec timeout
  211834. while (--count >= 0)
  211835. {
  211836. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211837. if (res == MIDIERR_STILLPLAYING)
  211838. Sleep (2);
  211839. else
  211840. break;
  211841. }
  211842. }
  211843. }
  211844. }
  211845. else
  211846. {
  211847. midiOutShortMsg (handle->handle,
  211848. *(unsigned int*) message.getRawData());
  211849. }
  211850. }
  211851. #endif
  211852. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211853. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211854. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211855. // compiled on its own).
  211856. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211857. #undef WINDOWS
  211858. // #define ASIO_DEBUGGING 1
  211859. #undef log
  211860. #if ASIO_DEBUGGING
  211861. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211862. #else
  211863. #define log(a) {}
  211864. #endif
  211865. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  211866. to be pretty random about whether or not they do this. If you hit an error using these functions
  211867. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  211868. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  211869. */
  211870. #define JUCE_ASIOCALLBACK __cdecl
  211871. namespace ASIODebugging
  211872. {
  211873. #if ASIO_DEBUGGING
  211874. static void log (const String& context, long error)
  211875. {
  211876. String err ("unknown error");
  211877. if (error == ASE_NotPresent) err = "Not Present";
  211878. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  211879. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  211880. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  211881. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  211882. else if (error == ASE_NoClock) err = "No Clock";
  211883. else if (error == ASE_NoMemory) err = "Out of memory";
  211884. log ("!!error: " + context + " - " + err);
  211885. }
  211886. #define logError(a, b) ASIODebugging::log ((a), (b))
  211887. #else
  211888. #define logError(a, b) {}
  211889. #endif
  211890. }
  211891. class ASIOAudioIODevice;
  211892. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211893. static const int maxASIOChannels = 160;
  211894. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211895. private Timer
  211896. {
  211897. public:
  211898. Component ourWindow;
  211899. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211900. const String& optionalDllForDirectLoading_)
  211901. : AudioIODevice (name_, "ASIO"),
  211902. asioObject (0),
  211903. classId (classId_),
  211904. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211905. currentBitDepth (16),
  211906. currentSampleRate (0),
  211907. isOpen_ (false),
  211908. isStarted (false),
  211909. postOutput (true),
  211910. insideControlPanelModalLoop (false),
  211911. shouldUsePreferredSize (false)
  211912. {
  211913. name = name_;
  211914. ourWindow.addToDesktop (0);
  211915. windowHandle = ourWindow.getWindowHandle();
  211916. jassert (currentASIODev [slotNumber] == 0);
  211917. currentASIODev [slotNumber] = this;
  211918. openDevice();
  211919. }
  211920. ~ASIOAudioIODevice()
  211921. {
  211922. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211923. if (currentASIODev[i] == this)
  211924. currentASIODev[i] = 0;
  211925. close();
  211926. log ("ASIO - exiting");
  211927. removeCurrentDriver();
  211928. }
  211929. void updateSampleRates()
  211930. {
  211931. // find a list of sample rates..
  211932. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211933. sampleRates.clear();
  211934. if (asioObject != 0)
  211935. {
  211936. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211937. {
  211938. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211939. if (err == 0)
  211940. {
  211941. sampleRates.add ((int) possibleSampleRates[index]);
  211942. log ("rate: " + String ((int) possibleSampleRates[index]));
  211943. }
  211944. else if (err != ASE_NoClock)
  211945. {
  211946. logError ("CanSampleRate", err);
  211947. }
  211948. }
  211949. if (sampleRates.size() == 0)
  211950. {
  211951. double cr = 0;
  211952. const long err = asioObject->getSampleRate (&cr);
  211953. log ("No sample rates supported - current rate: " + String ((int) cr));
  211954. if (err == 0)
  211955. sampleRates.add ((int) cr);
  211956. }
  211957. }
  211958. }
  211959. const StringArray getOutputChannelNames() { return outputChannelNames; }
  211960. const StringArray getInputChannelNames() { return inputChannelNames; }
  211961. int getNumSampleRates() { return sampleRates.size(); }
  211962. double getSampleRate (int index) { return sampleRates [index]; }
  211963. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211964. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211965. int getDefaultBufferSize() { return preferredSize; }
  211966. const String open (const BigInteger& inputChannels,
  211967. const BigInteger& outputChannels,
  211968. double sr,
  211969. int bufferSizeSamples)
  211970. {
  211971. close();
  211972. currentCallback = 0;
  211973. if (bufferSizeSamples <= 0)
  211974. shouldUsePreferredSize = true;
  211975. if (asioObject == 0 || ! isASIOOpen)
  211976. {
  211977. log ("Warning: device not open");
  211978. const String err (openDevice());
  211979. if (asioObject == 0 || ! isASIOOpen)
  211980. return err;
  211981. }
  211982. isStarted = false;
  211983. bufferIndex = -1;
  211984. long err = 0;
  211985. long newPreferredSize = 0;
  211986. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211987. minSize = 0;
  211988. maxSize = 0;
  211989. newPreferredSize = 0;
  211990. granularity = 0;
  211991. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211992. {
  211993. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211994. shouldUsePreferredSize = true;
  211995. preferredSize = newPreferredSize;
  211996. }
  211997. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211998. // dynamic changes to the buffer size...
  211999. shouldUsePreferredSize = shouldUsePreferredSize
  212000. || getName().containsIgnoreCase ("Digidesign");
  212001. if (shouldUsePreferredSize)
  212002. {
  212003. log ("Using preferred size for buffer..");
  212004. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212005. {
  212006. bufferSizeSamples = preferredSize;
  212007. }
  212008. else
  212009. {
  212010. bufferSizeSamples = 1024;
  212011. logError ("GetBufferSize1", err);
  212012. }
  212013. shouldUsePreferredSize = false;
  212014. }
  212015. int sampleRate = roundDoubleToInt (sr);
  212016. currentSampleRate = sampleRate;
  212017. currentBlockSizeSamples = bufferSizeSamples;
  212018. currentChansOut.clear();
  212019. currentChansIn.clear();
  212020. zeromem (inBuffers, sizeof (inBuffers));
  212021. zeromem (outBuffers, sizeof (outBuffers));
  212022. updateSampleRates();
  212023. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212024. sampleRate = sampleRates[0];
  212025. jassert (sampleRate != 0);
  212026. if (sampleRate == 0)
  212027. sampleRate = 44100;
  212028. long numSources = 32;
  212029. ASIOClockSource clocks[32];
  212030. zeromem (clocks, sizeof (clocks));
  212031. asioObject->getClockSources (clocks, &numSources);
  212032. bool isSourceSet = false;
  212033. // careful not to remove this loop because it does more than just logging!
  212034. int i;
  212035. for (i = 0; i < numSources; ++i)
  212036. {
  212037. String s ("clock: ");
  212038. s += clocks[i].name;
  212039. if (clocks[i].isCurrentSource)
  212040. {
  212041. isSourceSet = true;
  212042. s << " (cur)";
  212043. }
  212044. log (s);
  212045. }
  212046. if (numSources > 1 && ! isSourceSet)
  212047. {
  212048. log ("setting clock source");
  212049. asioObject->setClockSource (clocks[0].index);
  212050. Thread::sleep (20);
  212051. }
  212052. else
  212053. {
  212054. if (numSources == 0)
  212055. {
  212056. log ("ASIO - no clock sources!");
  212057. }
  212058. }
  212059. double cr = 0;
  212060. err = asioObject->getSampleRate (&cr);
  212061. if (err == 0)
  212062. {
  212063. currentSampleRate = cr;
  212064. }
  212065. else
  212066. {
  212067. logError ("GetSampleRate", err);
  212068. currentSampleRate = 0;
  212069. }
  212070. error = String::empty;
  212071. needToReset = false;
  212072. isReSync = false;
  212073. err = 0;
  212074. bool buffersCreated = false;
  212075. if (currentSampleRate != sampleRate)
  212076. {
  212077. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212078. err = asioObject->setSampleRate (sampleRate);
  212079. if (err == ASE_NoClock && numSources > 0)
  212080. {
  212081. log ("trying to set a clock source..");
  212082. Thread::sleep (10);
  212083. err = asioObject->setClockSource (clocks[0].index);
  212084. if (err != 0)
  212085. {
  212086. logError ("SetClock", err);
  212087. }
  212088. Thread::sleep (10);
  212089. err = asioObject->setSampleRate (sampleRate);
  212090. }
  212091. }
  212092. if (err == 0)
  212093. {
  212094. currentSampleRate = sampleRate;
  212095. if (needToReset)
  212096. {
  212097. if (isReSync)
  212098. {
  212099. log ("Resync request");
  212100. }
  212101. log ("! Resetting ASIO after sample rate change");
  212102. removeCurrentDriver();
  212103. loadDriver();
  212104. const String error (initDriver());
  212105. if (error.isNotEmpty())
  212106. {
  212107. log ("ASIOInit: " + error);
  212108. }
  212109. needToReset = false;
  212110. isReSync = false;
  212111. }
  212112. numActiveInputChans = 0;
  212113. numActiveOutputChans = 0;
  212114. ASIOBufferInfo* info = bufferInfos;
  212115. int i;
  212116. for (i = 0; i < totalNumInputChans; ++i)
  212117. {
  212118. if (inputChannels[i])
  212119. {
  212120. currentChansIn.setBit (i);
  212121. info->isInput = 1;
  212122. info->channelNum = i;
  212123. info->buffers[0] = info->buffers[1] = 0;
  212124. ++info;
  212125. ++numActiveInputChans;
  212126. }
  212127. }
  212128. for (i = 0; i < totalNumOutputChans; ++i)
  212129. {
  212130. if (outputChannels[i])
  212131. {
  212132. currentChansOut.setBit (i);
  212133. info->isInput = 0;
  212134. info->channelNum = i;
  212135. info->buffers[0] = info->buffers[1] = 0;
  212136. ++info;
  212137. ++numActiveOutputChans;
  212138. }
  212139. }
  212140. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212141. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212142. if (currentASIODev[0] == this)
  212143. {
  212144. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212145. callbacks.asioMessage = &asioMessagesCallback0;
  212146. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212147. }
  212148. else if (currentASIODev[1] == this)
  212149. {
  212150. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212151. callbacks.asioMessage = &asioMessagesCallback1;
  212152. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212153. }
  212154. else if (currentASIODev[2] == this)
  212155. {
  212156. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212157. callbacks.asioMessage = &asioMessagesCallback2;
  212158. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212159. }
  212160. else
  212161. {
  212162. jassertfalse;
  212163. }
  212164. log ("disposing buffers");
  212165. err = asioObject->disposeBuffers();
  212166. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212167. err = asioObject->createBuffers (bufferInfos,
  212168. totalBuffers,
  212169. currentBlockSizeSamples,
  212170. &callbacks);
  212171. if (err != 0)
  212172. {
  212173. currentBlockSizeSamples = preferredSize;
  212174. logError ("create buffers 2", err);
  212175. asioObject->disposeBuffers();
  212176. err = asioObject->createBuffers (bufferInfos,
  212177. totalBuffers,
  212178. currentBlockSizeSamples,
  212179. &callbacks);
  212180. }
  212181. if (err == 0)
  212182. {
  212183. buffersCreated = true;
  212184. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212185. int n = 0;
  212186. Array <int> types;
  212187. currentBitDepth = 16;
  212188. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212189. {
  212190. if (inputChannels[i])
  212191. {
  212192. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212193. ASIOChannelInfo channelInfo;
  212194. zerostruct (channelInfo);
  212195. channelInfo.channel = i;
  212196. channelInfo.isInput = 1;
  212197. asioObject->getChannelInfo (&channelInfo);
  212198. types.addIfNotAlreadyThere (channelInfo.type);
  212199. typeToFormatParameters (channelInfo.type,
  212200. inputChannelBitDepths[n],
  212201. inputChannelBytesPerSample[n],
  212202. inputChannelIsFloat[n],
  212203. inputChannelLittleEndian[n]);
  212204. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212205. ++n;
  212206. }
  212207. }
  212208. jassert (numActiveInputChans == n);
  212209. n = 0;
  212210. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212211. {
  212212. if (outputChannels[i])
  212213. {
  212214. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212215. ASIOChannelInfo channelInfo;
  212216. zerostruct (channelInfo);
  212217. channelInfo.channel = i;
  212218. channelInfo.isInput = 0;
  212219. asioObject->getChannelInfo (&channelInfo);
  212220. types.addIfNotAlreadyThere (channelInfo.type);
  212221. typeToFormatParameters (channelInfo.type,
  212222. outputChannelBitDepths[n],
  212223. outputChannelBytesPerSample[n],
  212224. outputChannelIsFloat[n],
  212225. outputChannelLittleEndian[n]);
  212226. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212227. ++n;
  212228. }
  212229. }
  212230. jassert (numActiveOutputChans == n);
  212231. for (i = types.size(); --i >= 0;)
  212232. {
  212233. log ("channel format: " + String (types[i]));
  212234. }
  212235. jassert (n <= totalBuffers);
  212236. for (i = 0; i < numActiveOutputChans; ++i)
  212237. {
  212238. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212239. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212240. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212241. {
  212242. log ("!! Null buffers");
  212243. }
  212244. else
  212245. {
  212246. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212247. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212248. }
  212249. }
  212250. inputLatency = outputLatency = 0;
  212251. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212252. {
  212253. log ("ASIO - no latencies");
  212254. }
  212255. else
  212256. {
  212257. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212258. }
  212259. isOpen_ = true;
  212260. log ("starting ASIO");
  212261. calledback = false;
  212262. err = asioObject->start();
  212263. if (err != 0)
  212264. {
  212265. isOpen_ = false;
  212266. log ("ASIO - stop on failure");
  212267. Thread::sleep (10);
  212268. asioObject->stop();
  212269. error = "Can't start device";
  212270. Thread::sleep (10);
  212271. }
  212272. else
  212273. {
  212274. int count = 300;
  212275. while (--count > 0 && ! calledback)
  212276. Thread::sleep (10);
  212277. isStarted = true;
  212278. if (! calledback)
  212279. {
  212280. error = "Device didn't start correctly";
  212281. log ("ASIO didn't callback - stopping..");
  212282. asioObject->stop();
  212283. }
  212284. }
  212285. }
  212286. else
  212287. {
  212288. error = "Can't create i/o buffers";
  212289. }
  212290. }
  212291. else
  212292. {
  212293. error = "Can't set sample rate: ";
  212294. error << sampleRate;
  212295. }
  212296. if (error.isNotEmpty())
  212297. {
  212298. logError (error, err);
  212299. if (asioObject != 0 && buffersCreated)
  212300. asioObject->disposeBuffers();
  212301. Thread::sleep (20);
  212302. isStarted = false;
  212303. isOpen_ = false;
  212304. const String errorCopy (error);
  212305. close(); // (this resets the error string)
  212306. error = errorCopy;
  212307. }
  212308. needToReset = false;
  212309. isReSync = false;
  212310. return error;
  212311. }
  212312. void close()
  212313. {
  212314. error = String::empty;
  212315. stopTimer();
  212316. stop();
  212317. if (isASIOOpen && isOpen_)
  212318. {
  212319. const ScopedLock sl (callbackLock);
  212320. isOpen_ = false;
  212321. isStarted = false;
  212322. needToReset = false;
  212323. isReSync = false;
  212324. log ("ASIO - stopping");
  212325. if (asioObject != 0)
  212326. {
  212327. Thread::sleep (20);
  212328. asioObject->stop();
  212329. Thread::sleep (10);
  212330. asioObject->disposeBuffers();
  212331. }
  212332. Thread::sleep (10);
  212333. }
  212334. }
  212335. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212336. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212337. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212338. double getCurrentSampleRate() { return currentSampleRate; }
  212339. int getCurrentBitDepth() { return currentBitDepth; }
  212340. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212341. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212342. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212343. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212344. void start (AudioIODeviceCallback* callback)
  212345. {
  212346. if (callback != 0)
  212347. {
  212348. callback->audioDeviceAboutToStart (this);
  212349. const ScopedLock sl (callbackLock);
  212350. currentCallback = callback;
  212351. }
  212352. }
  212353. void stop()
  212354. {
  212355. AudioIODeviceCallback* const lastCallback = currentCallback;
  212356. {
  212357. const ScopedLock sl (callbackLock);
  212358. currentCallback = 0;
  212359. }
  212360. if (lastCallback != 0)
  212361. lastCallback->audioDeviceStopped();
  212362. }
  212363. const String getLastError() { return error; }
  212364. bool hasControlPanel() const { return true; }
  212365. bool showControlPanel()
  212366. {
  212367. log ("ASIO - showing control panel");
  212368. Component modalWindow (String::empty);
  212369. modalWindow.setOpaque (true);
  212370. modalWindow.addToDesktop (0);
  212371. modalWindow.enterModalState();
  212372. bool done = false;
  212373. JUCE_TRY
  212374. {
  212375. // are there are devices that need to be closed before showing their control panel?
  212376. // close();
  212377. insideControlPanelModalLoop = true;
  212378. const uint32 started = Time::getMillisecondCounter();
  212379. if (asioObject != 0)
  212380. {
  212381. asioObject->controlPanel();
  212382. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212383. log ("spent: " + String (spent));
  212384. if (spent > 300)
  212385. {
  212386. shouldUsePreferredSize = true;
  212387. done = true;
  212388. }
  212389. }
  212390. }
  212391. JUCE_CATCH_ALL
  212392. insideControlPanelModalLoop = false;
  212393. return done;
  212394. }
  212395. void resetRequest() throw()
  212396. {
  212397. needToReset = true;
  212398. }
  212399. void resyncRequest() throw()
  212400. {
  212401. needToReset = true;
  212402. isReSync = true;
  212403. }
  212404. void timerCallback()
  212405. {
  212406. if (! insideControlPanelModalLoop)
  212407. {
  212408. stopTimer();
  212409. // used to cause a reset
  212410. log ("! ASIO restart request!");
  212411. if (isOpen_)
  212412. {
  212413. AudioIODeviceCallback* const oldCallback = currentCallback;
  212414. close();
  212415. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212416. currentSampleRate, currentBlockSizeSamples);
  212417. if (oldCallback != 0)
  212418. start (oldCallback);
  212419. }
  212420. }
  212421. else
  212422. {
  212423. startTimer (100);
  212424. }
  212425. }
  212426. private:
  212427. IASIO* volatile asioObject;
  212428. ASIOCallbacks callbacks;
  212429. void* windowHandle;
  212430. CLSID classId;
  212431. const String optionalDllForDirectLoading;
  212432. String error;
  212433. long totalNumInputChans, totalNumOutputChans;
  212434. StringArray inputChannelNames, outputChannelNames;
  212435. Array<int> sampleRates, bufferSizes;
  212436. long inputLatency, outputLatency;
  212437. long minSize, maxSize, preferredSize, granularity;
  212438. int volatile currentBlockSizeSamples;
  212439. int volatile currentBitDepth;
  212440. double volatile currentSampleRate;
  212441. BigInteger currentChansOut, currentChansIn;
  212442. AudioIODeviceCallback* volatile currentCallback;
  212443. CriticalSection callbackLock;
  212444. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212445. float* inBuffers [maxASIOChannels];
  212446. float* outBuffers [maxASIOChannels];
  212447. int inputChannelBitDepths [maxASIOChannels];
  212448. int outputChannelBitDepths [maxASIOChannels];
  212449. int inputChannelBytesPerSample [maxASIOChannels];
  212450. int outputChannelBytesPerSample [maxASIOChannels];
  212451. bool inputChannelIsFloat [maxASIOChannels];
  212452. bool outputChannelIsFloat [maxASIOChannels];
  212453. bool inputChannelLittleEndian [maxASIOChannels];
  212454. bool outputChannelLittleEndian [maxASIOChannels];
  212455. WaitableEvent event1;
  212456. HeapBlock <float> tempBuffer;
  212457. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212458. bool isOpen_, isStarted;
  212459. bool volatile isASIOOpen;
  212460. bool volatile calledback;
  212461. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212462. bool volatile insideControlPanelModalLoop;
  212463. bool volatile shouldUsePreferredSize;
  212464. void removeCurrentDriver()
  212465. {
  212466. if (asioObject != 0)
  212467. {
  212468. asioObject->Release();
  212469. asioObject = 0;
  212470. }
  212471. }
  212472. bool loadDriver()
  212473. {
  212474. removeCurrentDriver();
  212475. JUCE_TRY
  212476. {
  212477. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212478. classId, (void**) &asioObject) == S_OK)
  212479. {
  212480. return true;
  212481. }
  212482. // If a class isn't registered but we have a path for it, we can fallback to
  212483. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212484. if (optionalDllForDirectLoading.isNotEmpty())
  212485. {
  212486. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212487. if (h != 0)
  212488. {
  212489. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212490. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212491. if (dllGetClassObject != 0)
  212492. {
  212493. IClassFactory* classFactory = 0;
  212494. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212495. if (classFactory != 0)
  212496. {
  212497. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212498. classFactory->Release();
  212499. }
  212500. return asioObject != 0;
  212501. }
  212502. }
  212503. }
  212504. }
  212505. JUCE_CATCH_ALL
  212506. asioObject = 0;
  212507. return false;
  212508. }
  212509. const String initDriver()
  212510. {
  212511. if (asioObject != 0)
  212512. {
  212513. char buffer [256];
  212514. zeromem (buffer, sizeof (buffer));
  212515. if (! asioObject->init (windowHandle))
  212516. {
  212517. asioObject->getErrorMessage (buffer);
  212518. return String (buffer, sizeof (buffer) - 1);
  212519. }
  212520. // just in case any daft drivers expect this to be called..
  212521. asioObject->getDriverName (buffer);
  212522. return String::empty;
  212523. }
  212524. return "No Driver";
  212525. }
  212526. const String openDevice()
  212527. {
  212528. // use this in case the driver starts opening dialog boxes..
  212529. Component modalWindow (String::empty);
  212530. modalWindow.setOpaque (true);
  212531. modalWindow.addToDesktop (0);
  212532. modalWindow.enterModalState();
  212533. // open the device and get its info..
  212534. log ("opening ASIO device: " + getName());
  212535. needToReset = false;
  212536. isReSync = false;
  212537. outputChannelNames.clear();
  212538. inputChannelNames.clear();
  212539. bufferSizes.clear();
  212540. sampleRates.clear();
  212541. isASIOOpen = false;
  212542. isOpen_ = false;
  212543. totalNumInputChans = 0;
  212544. totalNumOutputChans = 0;
  212545. numActiveInputChans = 0;
  212546. numActiveOutputChans = 0;
  212547. currentCallback = 0;
  212548. error = String::empty;
  212549. if (getName().isEmpty())
  212550. return error;
  212551. long err = 0;
  212552. if (loadDriver())
  212553. {
  212554. if ((error = initDriver()).isEmpty())
  212555. {
  212556. numActiveInputChans = 0;
  212557. numActiveOutputChans = 0;
  212558. totalNumInputChans = 0;
  212559. totalNumOutputChans = 0;
  212560. if (asioObject != 0
  212561. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212562. {
  212563. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212564. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212565. {
  212566. // find a list of buffer sizes..
  212567. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212568. if (granularity >= 0)
  212569. {
  212570. granularity = jmax (1, (int) granularity);
  212571. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212572. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212573. }
  212574. else if (granularity < 0)
  212575. {
  212576. for (int i = 0; i < 18; ++i)
  212577. {
  212578. const int s = (1 << i);
  212579. if (s >= minSize && s <= maxSize)
  212580. bufferSizes.add (s);
  212581. }
  212582. }
  212583. if (! bufferSizes.contains (preferredSize))
  212584. bufferSizes.insert (0, preferredSize);
  212585. double currentRate = 0;
  212586. asioObject->getSampleRate (&currentRate);
  212587. if (currentRate <= 0.0 || currentRate > 192001.0)
  212588. {
  212589. log ("setting sample rate");
  212590. err = asioObject->setSampleRate (44100.0);
  212591. if (err != 0)
  212592. {
  212593. logError ("setting sample rate", err);
  212594. }
  212595. asioObject->getSampleRate (&currentRate);
  212596. }
  212597. currentSampleRate = currentRate;
  212598. postOutput = (asioObject->outputReady() == 0);
  212599. if (postOutput)
  212600. {
  212601. log ("ASIO outputReady = ok");
  212602. }
  212603. updateSampleRates();
  212604. // ..because cubase does it at this point
  212605. inputLatency = outputLatency = 0;
  212606. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212607. {
  212608. log ("ASIO - no latencies");
  212609. }
  212610. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212611. // create some dummy buffers now.. because cubase does..
  212612. numActiveInputChans = 0;
  212613. numActiveOutputChans = 0;
  212614. ASIOBufferInfo* info = bufferInfos;
  212615. int i, numChans = 0;
  212616. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212617. {
  212618. info->isInput = 1;
  212619. info->channelNum = i;
  212620. info->buffers[0] = info->buffers[1] = 0;
  212621. ++info;
  212622. ++numChans;
  212623. }
  212624. const int outputBufferIndex = numChans;
  212625. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212626. {
  212627. info->isInput = 0;
  212628. info->channelNum = i;
  212629. info->buffers[0] = info->buffers[1] = 0;
  212630. ++info;
  212631. ++numChans;
  212632. }
  212633. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212634. if (currentASIODev[0] == this)
  212635. {
  212636. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212637. callbacks.asioMessage = &asioMessagesCallback0;
  212638. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212639. }
  212640. else if (currentASIODev[1] == this)
  212641. {
  212642. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212643. callbacks.asioMessage = &asioMessagesCallback1;
  212644. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212645. }
  212646. else if (currentASIODev[2] == this)
  212647. {
  212648. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212649. callbacks.asioMessage = &asioMessagesCallback2;
  212650. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212651. }
  212652. else
  212653. {
  212654. jassertfalse;
  212655. }
  212656. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212657. if (preferredSize > 0)
  212658. {
  212659. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212660. if (err != 0)
  212661. {
  212662. logError ("dummy buffers", err);
  212663. }
  212664. }
  212665. long newInps = 0, newOuts = 0;
  212666. asioObject->getChannels (&newInps, &newOuts);
  212667. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212668. {
  212669. totalNumInputChans = newInps;
  212670. totalNumOutputChans = newOuts;
  212671. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212672. }
  212673. updateSampleRates();
  212674. ASIOChannelInfo channelInfo;
  212675. channelInfo.type = 0;
  212676. for (i = 0; i < totalNumInputChans; ++i)
  212677. {
  212678. zerostruct (channelInfo);
  212679. channelInfo.channel = i;
  212680. channelInfo.isInput = 1;
  212681. asioObject->getChannelInfo (&channelInfo);
  212682. inputChannelNames.add (String (channelInfo.name));
  212683. }
  212684. for (i = 0; i < totalNumOutputChans; ++i)
  212685. {
  212686. zerostruct (channelInfo);
  212687. channelInfo.channel = i;
  212688. channelInfo.isInput = 0;
  212689. asioObject->getChannelInfo (&channelInfo);
  212690. outputChannelNames.add (String (channelInfo.name));
  212691. typeToFormatParameters (channelInfo.type,
  212692. outputChannelBitDepths[i],
  212693. outputChannelBytesPerSample[i],
  212694. outputChannelIsFloat[i],
  212695. outputChannelLittleEndian[i]);
  212696. if (i < 2)
  212697. {
  212698. // clear the channels that are used with the dummy stuff
  212699. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212700. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212701. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212702. }
  212703. }
  212704. outputChannelNames.trim();
  212705. inputChannelNames.trim();
  212706. outputChannelNames.appendNumbersToDuplicates (false, true);
  212707. inputChannelNames.appendNumbersToDuplicates (false, true);
  212708. // start and stop because cubase does it..
  212709. asioObject->getLatencies (&inputLatency, &outputLatency);
  212710. if ((err = asioObject->start()) != 0)
  212711. {
  212712. // ignore an error here, as it might start later after setting other stuff up
  212713. logError ("ASIO start", err);
  212714. }
  212715. Thread::sleep (100);
  212716. asioObject->stop();
  212717. }
  212718. else
  212719. {
  212720. error = "Can't detect buffer sizes";
  212721. }
  212722. }
  212723. else
  212724. {
  212725. error = "Can't detect asio channels";
  212726. }
  212727. }
  212728. }
  212729. else
  212730. {
  212731. error = "No such device";
  212732. }
  212733. if (error.isNotEmpty())
  212734. {
  212735. logError (error, err);
  212736. if (asioObject != 0)
  212737. asioObject->disposeBuffers();
  212738. removeCurrentDriver();
  212739. isASIOOpen = false;
  212740. }
  212741. else
  212742. {
  212743. isASIOOpen = true;
  212744. log ("ASIO device open");
  212745. }
  212746. isOpen_ = false;
  212747. needToReset = false;
  212748. isReSync = false;
  212749. return error;
  212750. }
  212751. void JUCE_ASIOCALLBACK callback (const long index)
  212752. {
  212753. if (isStarted)
  212754. {
  212755. bufferIndex = index;
  212756. processBuffer();
  212757. }
  212758. else
  212759. {
  212760. if (postOutput && (asioObject != 0))
  212761. asioObject->outputReady();
  212762. }
  212763. calledback = true;
  212764. }
  212765. void processBuffer()
  212766. {
  212767. const ASIOBufferInfo* const infos = bufferInfos;
  212768. const int bi = bufferIndex;
  212769. const ScopedLock sl (callbackLock);
  212770. if (needToReset)
  212771. {
  212772. needToReset = false;
  212773. if (isReSync)
  212774. {
  212775. log ("! ASIO resync");
  212776. isReSync = false;
  212777. }
  212778. else
  212779. {
  212780. startTimer (20);
  212781. }
  212782. }
  212783. if (bi >= 0)
  212784. {
  212785. const int samps = currentBlockSizeSamples;
  212786. if (currentCallback != 0)
  212787. {
  212788. int i;
  212789. for (i = 0; i < numActiveInputChans; ++i)
  212790. {
  212791. float* const dst = inBuffers[i];
  212792. jassert (dst != 0);
  212793. const char* const src = (const char*) (infos[i].buffers[bi]);
  212794. if (inputChannelIsFloat[i])
  212795. {
  212796. memcpy (dst, src, samps * sizeof (float));
  212797. }
  212798. else
  212799. {
  212800. jassert (dst == tempBuffer + (samps * i));
  212801. switch (inputChannelBitDepths[i])
  212802. {
  212803. case 16:
  212804. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212805. samps, inputChannelLittleEndian[i]);
  212806. break;
  212807. case 24:
  212808. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212809. samps, inputChannelLittleEndian[i]);
  212810. break;
  212811. case 32:
  212812. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212813. samps, inputChannelLittleEndian[i]);
  212814. break;
  212815. case 64:
  212816. jassertfalse;
  212817. break;
  212818. }
  212819. }
  212820. }
  212821. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  212822. outBuffers, numActiveOutputChans, samps);
  212823. for (i = 0; i < numActiveOutputChans; ++i)
  212824. {
  212825. float* const src = outBuffers[i];
  212826. jassert (src != 0);
  212827. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212828. if (outputChannelIsFloat[i])
  212829. {
  212830. memcpy (dst, src, samps * sizeof (float));
  212831. }
  212832. else
  212833. {
  212834. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212835. switch (outputChannelBitDepths[i])
  212836. {
  212837. case 16:
  212838. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212839. samps, outputChannelLittleEndian[i]);
  212840. break;
  212841. case 24:
  212842. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212843. samps, outputChannelLittleEndian[i]);
  212844. break;
  212845. case 32:
  212846. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212847. samps, outputChannelLittleEndian[i]);
  212848. break;
  212849. case 64:
  212850. jassertfalse;
  212851. break;
  212852. }
  212853. }
  212854. }
  212855. }
  212856. else
  212857. {
  212858. for (int i = 0; i < numActiveOutputChans; ++i)
  212859. {
  212860. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212861. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212862. }
  212863. }
  212864. }
  212865. if (postOutput)
  212866. asioObject->outputReady();
  212867. }
  212868. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212869. {
  212870. if (currentASIODev[0] != 0)
  212871. currentASIODev[0]->callback (index);
  212872. return 0;
  212873. }
  212874. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212875. {
  212876. if (currentASIODev[1] != 0)
  212877. currentASIODev[1]->callback (index);
  212878. return 0;
  212879. }
  212880. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212881. {
  212882. if (currentASIODev[2] != 0)
  212883. currentASIODev[2]->callback (index);
  212884. return 0;
  212885. }
  212886. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  212887. {
  212888. if (currentASIODev[0] != 0)
  212889. currentASIODev[0]->callback (index);
  212890. }
  212891. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  212892. {
  212893. if (currentASIODev[1] != 0)
  212894. currentASIODev[1]->callback (index);
  212895. }
  212896. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  212897. {
  212898. if (currentASIODev[2] != 0)
  212899. currentASIODev[2]->callback (index);
  212900. }
  212901. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  212902. {
  212903. return asioMessagesCallback (selector, value, 0);
  212904. }
  212905. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  212906. {
  212907. return asioMessagesCallback (selector, value, 1);
  212908. }
  212909. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  212910. {
  212911. return asioMessagesCallback (selector, value, 2);
  212912. }
  212913. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  212914. {
  212915. switch (selector)
  212916. {
  212917. case kAsioSelectorSupported:
  212918. if (value == kAsioResetRequest
  212919. || value == kAsioEngineVersion
  212920. || value == kAsioResyncRequest
  212921. || value == kAsioLatenciesChanged
  212922. || value == kAsioSupportsInputMonitor)
  212923. return 1;
  212924. break;
  212925. case kAsioBufferSizeChange:
  212926. break;
  212927. case kAsioResetRequest:
  212928. if (currentASIODev[deviceIndex] != 0)
  212929. currentASIODev[deviceIndex]->resetRequest();
  212930. return 1;
  212931. case kAsioResyncRequest:
  212932. if (currentASIODev[deviceIndex] != 0)
  212933. currentASIODev[deviceIndex]->resyncRequest();
  212934. return 1;
  212935. case kAsioLatenciesChanged:
  212936. return 1;
  212937. case kAsioEngineVersion:
  212938. return 2;
  212939. case kAsioSupportsTimeInfo:
  212940. case kAsioSupportsTimeCode:
  212941. return 0;
  212942. }
  212943. return 0;
  212944. }
  212945. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  212946. {
  212947. }
  212948. static void convertInt16ToFloat (const char* src,
  212949. float* dest,
  212950. const int srcStrideBytes,
  212951. int numSamples,
  212952. const bool littleEndian) throw()
  212953. {
  212954. const double g = 1.0 / 32768.0;
  212955. if (littleEndian)
  212956. {
  212957. while (--numSamples >= 0)
  212958. {
  212959. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212960. src += srcStrideBytes;
  212961. }
  212962. }
  212963. else
  212964. {
  212965. while (--numSamples >= 0)
  212966. {
  212967. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212968. src += srcStrideBytes;
  212969. }
  212970. }
  212971. }
  212972. static void convertFloatToInt16 (const float* src,
  212973. char* dest,
  212974. const int dstStrideBytes,
  212975. int numSamples,
  212976. const bool littleEndian) throw()
  212977. {
  212978. const double maxVal = (double) 0x7fff;
  212979. if (littleEndian)
  212980. {
  212981. while (--numSamples >= 0)
  212982. {
  212983. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212984. dest += dstStrideBytes;
  212985. }
  212986. }
  212987. else
  212988. {
  212989. while (--numSamples >= 0)
  212990. {
  212991. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212992. dest += dstStrideBytes;
  212993. }
  212994. }
  212995. }
  212996. static void convertInt24ToFloat (const char* src,
  212997. float* dest,
  212998. const int srcStrideBytes,
  212999. int numSamples,
  213000. const bool littleEndian) throw()
  213001. {
  213002. const double g = 1.0 / 0x7fffff;
  213003. if (littleEndian)
  213004. {
  213005. while (--numSamples >= 0)
  213006. {
  213007. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213008. src += srcStrideBytes;
  213009. }
  213010. }
  213011. else
  213012. {
  213013. while (--numSamples >= 0)
  213014. {
  213015. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213016. src += srcStrideBytes;
  213017. }
  213018. }
  213019. }
  213020. static void convertFloatToInt24 (const float* src,
  213021. char* dest,
  213022. const int dstStrideBytes,
  213023. int numSamples,
  213024. const bool littleEndian) throw()
  213025. {
  213026. const double maxVal = (double) 0x7fffff;
  213027. if (littleEndian)
  213028. {
  213029. while (--numSamples >= 0)
  213030. {
  213031. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213032. dest += dstStrideBytes;
  213033. }
  213034. }
  213035. else
  213036. {
  213037. while (--numSamples >= 0)
  213038. {
  213039. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213040. dest += dstStrideBytes;
  213041. }
  213042. }
  213043. }
  213044. static void convertInt32ToFloat (const char* src,
  213045. float* dest,
  213046. const int srcStrideBytes,
  213047. int numSamples,
  213048. const bool littleEndian) throw()
  213049. {
  213050. const double g = 1.0 / 0x7fffffff;
  213051. if (littleEndian)
  213052. {
  213053. while (--numSamples >= 0)
  213054. {
  213055. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213056. src += srcStrideBytes;
  213057. }
  213058. }
  213059. else
  213060. {
  213061. while (--numSamples >= 0)
  213062. {
  213063. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213064. src += srcStrideBytes;
  213065. }
  213066. }
  213067. }
  213068. static void convertFloatToInt32 (const float* src,
  213069. char* dest,
  213070. const int dstStrideBytes,
  213071. int numSamples,
  213072. const bool littleEndian) throw()
  213073. {
  213074. const double maxVal = (double) 0x7fffffff;
  213075. if (littleEndian)
  213076. {
  213077. while (--numSamples >= 0)
  213078. {
  213079. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213080. dest += dstStrideBytes;
  213081. }
  213082. }
  213083. else
  213084. {
  213085. while (--numSamples >= 0)
  213086. {
  213087. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213088. dest += dstStrideBytes;
  213089. }
  213090. }
  213091. }
  213092. static void typeToFormatParameters (const long type,
  213093. int& bitDepth,
  213094. int& byteStride,
  213095. bool& formatIsFloat,
  213096. bool& littleEndian) throw()
  213097. {
  213098. bitDepth = 0;
  213099. littleEndian = false;
  213100. formatIsFloat = false;
  213101. switch (type)
  213102. {
  213103. case ASIOSTInt16MSB:
  213104. case ASIOSTInt16LSB:
  213105. case ASIOSTInt32MSB16:
  213106. case ASIOSTInt32LSB16:
  213107. bitDepth = 16; break;
  213108. case ASIOSTFloat32MSB:
  213109. case ASIOSTFloat32LSB:
  213110. formatIsFloat = true;
  213111. bitDepth = 32; break;
  213112. case ASIOSTInt32MSB:
  213113. case ASIOSTInt32LSB:
  213114. bitDepth = 32; break;
  213115. case ASIOSTInt24MSB:
  213116. case ASIOSTInt24LSB:
  213117. case ASIOSTInt32MSB24:
  213118. case ASIOSTInt32LSB24:
  213119. case ASIOSTInt32MSB18:
  213120. case ASIOSTInt32MSB20:
  213121. case ASIOSTInt32LSB18:
  213122. case ASIOSTInt32LSB20:
  213123. bitDepth = 24; break;
  213124. case ASIOSTFloat64MSB:
  213125. case ASIOSTFloat64LSB:
  213126. default:
  213127. bitDepth = 64;
  213128. break;
  213129. }
  213130. switch (type)
  213131. {
  213132. case ASIOSTInt16MSB:
  213133. case ASIOSTInt32MSB16:
  213134. case ASIOSTFloat32MSB:
  213135. case ASIOSTFloat64MSB:
  213136. case ASIOSTInt32MSB:
  213137. case ASIOSTInt32MSB18:
  213138. case ASIOSTInt32MSB20:
  213139. case ASIOSTInt32MSB24:
  213140. case ASIOSTInt24MSB:
  213141. littleEndian = false; break;
  213142. case ASIOSTInt16LSB:
  213143. case ASIOSTInt32LSB16:
  213144. case ASIOSTFloat32LSB:
  213145. case ASIOSTFloat64LSB:
  213146. case ASIOSTInt32LSB:
  213147. case ASIOSTInt32LSB18:
  213148. case ASIOSTInt32LSB20:
  213149. case ASIOSTInt32LSB24:
  213150. case ASIOSTInt24LSB:
  213151. littleEndian = true; break;
  213152. default:
  213153. break;
  213154. }
  213155. switch (type)
  213156. {
  213157. case ASIOSTInt16LSB:
  213158. case ASIOSTInt16MSB:
  213159. byteStride = 2; break;
  213160. case ASIOSTInt24LSB:
  213161. case ASIOSTInt24MSB:
  213162. byteStride = 3; break;
  213163. case ASIOSTInt32MSB16:
  213164. case ASIOSTInt32LSB16:
  213165. case ASIOSTInt32MSB:
  213166. case ASIOSTInt32MSB18:
  213167. case ASIOSTInt32MSB20:
  213168. case ASIOSTInt32MSB24:
  213169. case ASIOSTInt32LSB:
  213170. case ASIOSTInt32LSB18:
  213171. case ASIOSTInt32LSB20:
  213172. case ASIOSTInt32LSB24:
  213173. case ASIOSTFloat32LSB:
  213174. case ASIOSTFloat32MSB:
  213175. byteStride = 4; break;
  213176. case ASIOSTFloat64MSB:
  213177. case ASIOSTFloat64LSB:
  213178. byteStride = 8; break;
  213179. default:
  213180. break;
  213181. }
  213182. }
  213183. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213184. };
  213185. class ASIOAudioIODeviceType : public AudioIODeviceType
  213186. {
  213187. public:
  213188. ASIOAudioIODeviceType()
  213189. : AudioIODeviceType ("ASIO"),
  213190. hasScanned (false)
  213191. {
  213192. CoInitialize (0);
  213193. }
  213194. ~ASIOAudioIODeviceType()
  213195. {
  213196. }
  213197. void scanForDevices()
  213198. {
  213199. hasScanned = true;
  213200. deviceNames.clear();
  213201. classIds.clear();
  213202. HKEY hk = 0;
  213203. int index = 0;
  213204. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213205. {
  213206. for (;;)
  213207. {
  213208. char name [256];
  213209. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213210. {
  213211. addDriverInfo (name, hk);
  213212. }
  213213. else
  213214. {
  213215. break;
  213216. }
  213217. }
  213218. RegCloseKey (hk);
  213219. }
  213220. }
  213221. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213222. {
  213223. jassert (hasScanned); // need to call scanForDevices() before doing this
  213224. return deviceNames;
  213225. }
  213226. int getDefaultDeviceIndex (bool) const
  213227. {
  213228. jassert (hasScanned); // need to call scanForDevices() before doing this
  213229. for (int i = deviceNames.size(); --i >= 0;)
  213230. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213231. return i; // asio4all is a safe choice for a default..
  213232. #if JUCE_DEBUG
  213233. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213234. return 1; // (the digi m-box driver crashes the app when you run
  213235. // it in the debugger, which can be a bit annoying)
  213236. #endif
  213237. return 0;
  213238. }
  213239. static int findFreeSlot()
  213240. {
  213241. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213242. if (currentASIODev[i] == 0)
  213243. return i;
  213244. jassertfalse; // unfortunately you can only have a finite number
  213245. // of ASIO devices open at the same time..
  213246. return -1;
  213247. }
  213248. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213249. {
  213250. jassert (hasScanned); // need to call scanForDevices() before doing this
  213251. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213252. }
  213253. bool hasSeparateInputsAndOutputs() const { return false; }
  213254. AudioIODevice* createDevice (const String& outputDeviceName,
  213255. const String& inputDeviceName)
  213256. {
  213257. // ASIO can't open two different devices for input and output - they must be the same one.
  213258. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213259. jassert (hasScanned); // need to call scanForDevices() before doing this
  213260. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213261. : inputDeviceName);
  213262. if (index >= 0)
  213263. {
  213264. const int freeSlot = findFreeSlot();
  213265. if (freeSlot >= 0)
  213266. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213267. }
  213268. return 0;
  213269. }
  213270. private:
  213271. StringArray deviceNames;
  213272. OwnedArray <CLSID> classIds;
  213273. bool hasScanned;
  213274. static bool checkClassIsOk (const String& classId)
  213275. {
  213276. HKEY hk = 0;
  213277. bool ok = false;
  213278. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213279. {
  213280. int index = 0;
  213281. for (;;)
  213282. {
  213283. WCHAR buf [512];
  213284. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213285. {
  213286. if (classId.equalsIgnoreCase (buf))
  213287. {
  213288. HKEY subKey, pathKey;
  213289. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213290. {
  213291. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213292. {
  213293. WCHAR pathName [1024];
  213294. DWORD dtype = REG_SZ;
  213295. DWORD dsize = sizeof (pathName);
  213296. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213297. ok = File (pathName).exists();
  213298. RegCloseKey (pathKey);
  213299. }
  213300. RegCloseKey (subKey);
  213301. }
  213302. break;
  213303. }
  213304. }
  213305. else
  213306. {
  213307. break;
  213308. }
  213309. }
  213310. RegCloseKey (hk);
  213311. }
  213312. return ok;
  213313. }
  213314. void addDriverInfo (const String& keyName, HKEY hk)
  213315. {
  213316. HKEY subKey;
  213317. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213318. {
  213319. WCHAR buf [256];
  213320. zerostruct (buf);
  213321. DWORD dtype = REG_SZ;
  213322. DWORD dsize = sizeof (buf);
  213323. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213324. {
  213325. if (dsize > 0 && checkClassIsOk (buf))
  213326. {
  213327. CLSID classId;
  213328. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213329. {
  213330. dtype = REG_SZ;
  213331. dsize = sizeof (buf);
  213332. String deviceName;
  213333. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213334. deviceName = buf;
  213335. else
  213336. deviceName = keyName;
  213337. log ("found " + deviceName);
  213338. deviceNames.add (deviceName);
  213339. classIds.add (new CLSID (classId));
  213340. }
  213341. }
  213342. RegCloseKey (subKey);
  213343. }
  213344. }
  213345. }
  213346. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213347. };
  213348. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213349. {
  213350. return new ASIOAudioIODeviceType();
  213351. }
  213352. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213353. void* guid,
  213354. const String& optionalDllForDirectLoading)
  213355. {
  213356. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213357. if (freeSlot < 0)
  213358. return 0;
  213359. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213360. }
  213361. #undef logError
  213362. #undef log
  213363. #endif
  213364. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213365. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213366. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213367. // compiled on its own).
  213368. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213369. END_JUCE_NAMESPACE
  213370. extern "C"
  213371. {
  213372. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213373. typedef struct typeDSBUFFERDESC
  213374. {
  213375. DWORD dwSize;
  213376. DWORD dwFlags;
  213377. DWORD dwBufferBytes;
  213378. DWORD dwReserved;
  213379. LPWAVEFORMATEX lpwfxFormat;
  213380. GUID guid3DAlgorithm;
  213381. } DSBUFFERDESC;
  213382. struct IDirectSoundBuffer;
  213383. #undef INTERFACE
  213384. #define INTERFACE IDirectSound
  213385. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213386. {
  213387. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213388. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213389. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213390. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213391. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213392. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213393. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213394. STDMETHOD(Compact) (THIS) PURE;
  213395. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213396. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213397. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213398. };
  213399. #undef INTERFACE
  213400. #define INTERFACE IDirectSoundBuffer
  213401. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213402. {
  213403. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213404. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213405. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213406. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213407. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213408. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213409. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213410. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213411. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213412. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213413. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213414. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213415. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213416. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213417. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213418. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213419. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213420. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213421. STDMETHOD(Stop) (THIS) PURE;
  213422. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213423. STDMETHOD(Restore) (THIS) PURE;
  213424. };
  213425. typedef struct typeDSCBUFFERDESC
  213426. {
  213427. DWORD dwSize;
  213428. DWORD dwFlags;
  213429. DWORD dwBufferBytes;
  213430. DWORD dwReserved;
  213431. LPWAVEFORMATEX lpwfxFormat;
  213432. } DSCBUFFERDESC;
  213433. struct IDirectSoundCaptureBuffer;
  213434. #undef INTERFACE
  213435. #define INTERFACE IDirectSoundCapture
  213436. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213437. {
  213438. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213439. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213440. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213441. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213442. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213443. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213444. };
  213445. #undef INTERFACE
  213446. #define INTERFACE IDirectSoundCaptureBuffer
  213447. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213448. {
  213449. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213450. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213451. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213452. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213453. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213454. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213455. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213456. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213457. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213458. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213459. STDMETHOD(Stop) (THIS) PURE;
  213460. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213461. };
  213462. };
  213463. BEGIN_JUCE_NAMESPACE
  213464. namespace
  213465. {
  213466. const String getDSErrorMessage (HRESULT hr)
  213467. {
  213468. const char* result = 0;
  213469. switch (hr)
  213470. {
  213471. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213472. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213473. case E_INVALIDARG: result = "Invalid parameter"; break;
  213474. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213475. case E_FAIL: result = "Generic error"; break;
  213476. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213477. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213478. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213479. case E_NOTIMPL: result = "Unsupported function"; break;
  213480. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213481. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213482. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213483. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213484. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213485. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213486. case E_NOINTERFACE: result = "No interface"; break;
  213487. case S_OK: result = "No error"; break;
  213488. default: return "Unknown error: " + String ((int) hr);
  213489. }
  213490. return result;
  213491. }
  213492. #define DS_DEBUGGING 1
  213493. #ifdef DS_DEBUGGING
  213494. #define CATCH JUCE_CATCH_EXCEPTION
  213495. #undef log
  213496. #define log(a) Logger::writeToLog(a);
  213497. #undef logError
  213498. #define logError(a) logDSError(a, __LINE__);
  213499. static void logDSError (HRESULT hr, int lineNum)
  213500. {
  213501. if (hr != S_OK)
  213502. {
  213503. String error ("DS error at line ");
  213504. error << lineNum << " - " << getDSErrorMessage (hr);
  213505. log (error);
  213506. }
  213507. }
  213508. #else
  213509. #define CATCH JUCE_CATCH_ALL
  213510. #define log(a)
  213511. #define logError(a)
  213512. #endif
  213513. #define DSOUND_FUNCTION(functionName, params) \
  213514. typedef HRESULT (WINAPI *type##functionName) params; \
  213515. static type##functionName ds##functionName = 0;
  213516. #define DSOUND_FUNCTION_LOAD(functionName) \
  213517. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213518. jassert (ds##functionName != 0);
  213519. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213520. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213521. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213522. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213523. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213524. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213525. void initialiseDSoundFunctions()
  213526. {
  213527. if (dsDirectSoundCreate == 0)
  213528. {
  213529. HMODULE h = LoadLibraryA ("dsound.dll");
  213530. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213531. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213532. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213533. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213534. }
  213535. }
  213536. }
  213537. class DSoundInternalOutChannel
  213538. {
  213539. public:
  213540. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213541. int bufferSize, float* left, float* right)
  213542. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213543. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213544. pDirectSound (0), pOutputBuffer (0)
  213545. {
  213546. }
  213547. ~DSoundInternalOutChannel()
  213548. {
  213549. close();
  213550. }
  213551. void close()
  213552. {
  213553. HRESULT hr;
  213554. if (pOutputBuffer != 0)
  213555. {
  213556. log ("closing dsound out: " + name);
  213557. hr = pOutputBuffer->Stop();
  213558. logError (hr);
  213559. hr = pOutputBuffer->Release();
  213560. pOutputBuffer = 0;
  213561. logError (hr);
  213562. }
  213563. if (pDirectSound != 0)
  213564. {
  213565. hr = pDirectSound->Release();
  213566. pDirectSound = 0;
  213567. logError (hr);
  213568. }
  213569. }
  213570. const String open()
  213571. {
  213572. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213573. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213574. pDirectSound = 0;
  213575. pOutputBuffer = 0;
  213576. writeOffset = 0;
  213577. String error;
  213578. HRESULT hr = E_NOINTERFACE;
  213579. if (dsDirectSoundCreate != 0)
  213580. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213581. if (hr == S_OK)
  213582. {
  213583. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213584. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213585. const int numChannels = 2;
  213586. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213587. logError (hr);
  213588. if (hr == S_OK)
  213589. {
  213590. IDirectSoundBuffer* pPrimaryBuffer;
  213591. DSBUFFERDESC primaryDesc;
  213592. zerostruct (primaryDesc);
  213593. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213594. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213595. primaryDesc.dwBufferBytes = 0;
  213596. primaryDesc.lpwfxFormat = 0;
  213597. log ("opening dsound out step 2");
  213598. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213599. logError (hr);
  213600. if (hr == S_OK)
  213601. {
  213602. WAVEFORMATEX wfFormat;
  213603. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213604. wfFormat.nChannels = (unsigned short) numChannels;
  213605. wfFormat.nSamplesPerSec = sampleRate;
  213606. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213607. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213608. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213609. wfFormat.cbSize = 0;
  213610. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213611. logError (hr);
  213612. if (hr == S_OK)
  213613. {
  213614. DSBUFFERDESC secondaryDesc;
  213615. zerostruct (secondaryDesc);
  213616. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213617. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213618. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213619. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213620. secondaryDesc.lpwfxFormat = &wfFormat;
  213621. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213622. logError (hr);
  213623. if (hr == S_OK)
  213624. {
  213625. log ("opening dsound out step 3");
  213626. DWORD dwDataLen;
  213627. unsigned char* pDSBuffData;
  213628. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213629. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213630. logError (hr);
  213631. if (hr == S_OK)
  213632. {
  213633. zeromem (pDSBuffData, dwDataLen);
  213634. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213635. if (hr == S_OK)
  213636. {
  213637. hr = pOutputBuffer->SetCurrentPosition (0);
  213638. if (hr == S_OK)
  213639. {
  213640. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213641. if (hr == S_OK)
  213642. return String::empty;
  213643. }
  213644. }
  213645. }
  213646. }
  213647. }
  213648. }
  213649. }
  213650. }
  213651. error = getDSErrorMessage (hr);
  213652. close();
  213653. return error;
  213654. }
  213655. void synchronisePosition()
  213656. {
  213657. if (pOutputBuffer != 0)
  213658. {
  213659. DWORD playCursor;
  213660. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213661. }
  213662. }
  213663. bool service()
  213664. {
  213665. if (pOutputBuffer == 0)
  213666. return true;
  213667. DWORD playCursor, writeCursor;
  213668. for (;;)
  213669. {
  213670. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213671. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213672. {
  213673. pOutputBuffer->Restore();
  213674. continue;
  213675. }
  213676. if (hr == S_OK)
  213677. break;
  213678. logError (hr);
  213679. jassertfalse;
  213680. return true;
  213681. }
  213682. int playWriteGap = writeCursor - playCursor;
  213683. if (playWriteGap < 0)
  213684. playWriteGap += totalBytesPerBuffer;
  213685. int bytesEmpty = playCursor - writeOffset;
  213686. if (bytesEmpty < 0)
  213687. bytesEmpty += totalBytesPerBuffer;
  213688. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213689. {
  213690. writeOffset = writeCursor;
  213691. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213692. }
  213693. if (bytesEmpty >= bytesPerBuffer)
  213694. {
  213695. void* lpbuf1 = 0;
  213696. void* lpbuf2 = 0;
  213697. DWORD dwSize1 = 0;
  213698. DWORD dwSize2 = 0;
  213699. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213700. &lpbuf1, &dwSize1,
  213701. &lpbuf2, &dwSize2, 0);
  213702. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213703. {
  213704. pOutputBuffer->Restore();
  213705. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213706. &lpbuf1, &dwSize1,
  213707. &lpbuf2, &dwSize2, 0);
  213708. }
  213709. if (hr == S_OK)
  213710. {
  213711. if (bitDepth == 16)
  213712. {
  213713. int* dest = static_cast<int*> (lpbuf1);
  213714. const float* left = leftBuffer;
  213715. const float* right = rightBuffer;
  213716. int samples1 = dwSize1 >> 2;
  213717. int samples2 = dwSize2 >> 2;
  213718. if (left == 0)
  213719. {
  213720. while (--samples1 >= 0)
  213721. *dest++ = (convertInputValue (*right++) << 16);
  213722. dest = static_cast<int*> (lpbuf2);
  213723. while (--samples2 >= 0)
  213724. *dest++ = (convertInputValue (*right++) << 16);
  213725. }
  213726. else if (right == 0)
  213727. {
  213728. while (--samples1 >= 0)
  213729. *dest++ = (0xffff & convertInputValue (*left++));
  213730. dest = static_cast<int*> (lpbuf2);
  213731. while (--samples2 >= 0)
  213732. *dest++ = (0xffff & convertInputValue (*left++));
  213733. }
  213734. else
  213735. {
  213736. while (--samples1 >= 0)
  213737. {
  213738. const int l = convertInputValue (*left++);
  213739. const int r = convertInputValue (*right++);
  213740. *dest++ = (r << 16) | (0xffff & l);
  213741. }
  213742. dest = static_cast<int*> (lpbuf2);
  213743. while (--samples2 >= 0)
  213744. {
  213745. const int l = convertInputValue (*left++);
  213746. const int r = convertInputValue (*right++);
  213747. *dest++ = (r << 16) | (0xffff & l);
  213748. }
  213749. }
  213750. }
  213751. else
  213752. {
  213753. jassertfalse;
  213754. }
  213755. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213756. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213757. }
  213758. else
  213759. {
  213760. jassertfalse;
  213761. logError (hr);
  213762. }
  213763. bytesEmpty -= bytesPerBuffer;
  213764. return true;
  213765. }
  213766. else
  213767. {
  213768. return false;
  213769. }
  213770. }
  213771. int bitDepth;
  213772. bool doneFlag;
  213773. private:
  213774. String name;
  213775. LPGUID guid;
  213776. int sampleRate, bufferSizeSamples;
  213777. float* leftBuffer;
  213778. float* rightBuffer;
  213779. IDirectSound* pDirectSound;
  213780. IDirectSoundBuffer* pOutputBuffer;
  213781. DWORD writeOffset;
  213782. int totalBytesPerBuffer, bytesPerBuffer;
  213783. unsigned int lastPlayCursor;
  213784. static inline int convertInputValue (const float v) throw()
  213785. {
  213786. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  213787. }
  213788. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  213789. };
  213790. struct DSoundInternalInChannel
  213791. {
  213792. public:
  213793. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  213794. int bufferSize, float* left, float* right)
  213795. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213796. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213797. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  213798. {
  213799. }
  213800. ~DSoundInternalInChannel()
  213801. {
  213802. close();
  213803. }
  213804. void close()
  213805. {
  213806. HRESULT hr;
  213807. if (pInputBuffer != 0)
  213808. {
  213809. log ("closing dsound in: " + name);
  213810. hr = pInputBuffer->Stop();
  213811. logError (hr);
  213812. hr = pInputBuffer->Release();
  213813. pInputBuffer = 0;
  213814. logError (hr);
  213815. }
  213816. if (pDirectSoundCapture != 0)
  213817. {
  213818. hr = pDirectSoundCapture->Release();
  213819. pDirectSoundCapture = 0;
  213820. logError (hr);
  213821. }
  213822. if (pDirectSound != 0)
  213823. {
  213824. hr = pDirectSound->Release();
  213825. pDirectSound = 0;
  213826. logError (hr);
  213827. }
  213828. }
  213829. const String open()
  213830. {
  213831. log ("opening dsound in device: " + name
  213832. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213833. pDirectSound = 0;
  213834. pDirectSoundCapture = 0;
  213835. pInputBuffer = 0;
  213836. readOffset = 0;
  213837. totalBytesPerBuffer = 0;
  213838. String error;
  213839. HRESULT hr = E_NOINTERFACE;
  213840. if (dsDirectSoundCaptureCreate != 0)
  213841. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213842. logError (hr);
  213843. if (hr == S_OK)
  213844. {
  213845. const int numChannels = 2;
  213846. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213847. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213848. WAVEFORMATEX wfFormat;
  213849. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213850. wfFormat.nChannels = (unsigned short)numChannels;
  213851. wfFormat.nSamplesPerSec = sampleRate;
  213852. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213853. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213854. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213855. wfFormat.cbSize = 0;
  213856. DSCBUFFERDESC captureDesc;
  213857. zerostruct (captureDesc);
  213858. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213859. captureDesc.dwFlags = 0;
  213860. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213861. captureDesc.lpwfxFormat = &wfFormat;
  213862. log ("opening dsound in step 2");
  213863. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213864. logError (hr);
  213865. if (hr == S_OK)
  213866. {
  213867. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213868. logError (hr);
  213869. if (hr == S_OK)
  213870. return String::empty;
  213871. }
  213872. }
  213873. error = getDSErrorMessage (hr);
  213874. close();
  213875. return error;
  213876. }
  213877. void synchronisePosition()
  213878. {
  213879. if (pInputBuffer != 0)
  213880. {
  213881. DWORD capturePos;
  213882. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213883. }
  213884. }
  213885. bool service()
  213886. {
  213887. if (pInputBuffer == 0)
  213888. return true;
  213889. DWORD capturePos, readPos;
  213890. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213891. logError (hr);
  213892. if (hr != S_OK)
  213893. return true;
  213894. int bytesFilled = readPos - readOffset;
  213895. if (bytesFilled < 0)
  213896. bytesFilled += totalBytesPerBuffer;
  213897. if (bytesFilled >= bytesPerBuffer)
  213898. {
  213899. LPBYTE lpbuf1 = 0;
  213900. LPBYTE lpbuf2 = 0;
  213901. DWORD dwsize1 = 0;
  213902. DWORD dwsize2 = 0;
  213903. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  213904. (void**) &lpbuf1, &dwsize1,
  213905. (void**) &lpbuf2, &dwsize2, 0);
  213906. if (hr == S_OK)
  213907. {
  213908. if (bitDepth == 16)
  213909. {
  213910. const float g = 1.0f / 32768.0f;
  213911. float* destL = leftBuffer;
  213912. float* destR = rightBuffer;
  213913. int samples1 = dwsize1 >> 2;
  213914. int samples2 = dwsize2 >> 2;
  213915. const short* src = (const short*)lpbuf1;
  213916. if (destL == 0)
  213917. {
  213918. while (--samples1 >= 0)
  213919. {
  213920. ++src;
  213921. *destR++ = *src++ * g;
  213922. }
  213923. src = (const short*)lpbuf2;
  213924. while (--samples2 >= 0)
  213925. {
  213926. ++src;
  213927. *destR++ = *src++ * g;
  213928. }
  213929. }
  213930. else if (destR == 0)
  213931. {
  213932. while (--samples1 >= 0)
  213933. {
  213934. *destL++ = *src++ * g;
  213935. ++src;
  213936. }
  213937. src = (const short*)lpbuf2;
  213938. while (--samples2 >= 0)
  213939. {
  213940. *destL++ = *src++ * g;
  213941. ++src;
  213942. }
  213943. }
  213944. else
  213945. {
  213946. while (--samples1 >= 0)
  213947. {
  213948. *destL++ = *src++ * g;
  213949. *destR++ = *src++ * g;
  213950. }
  213951. src = (const short*)lpbuf2;
  213952. while (--samples2 >= 0)
  213953. {
  213954. *destL++ = *src++ * g;
  213955. *destR++ = *src++ * g;
  213956. }
  213957. }
  213958. }
  213959. else
  213960. {
  213961. jassertfalse;
  213962. }
  213963. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213964. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213965. }
  213966. else
  213967. {
  213968. logError (hr);
  213969. jassertfalse;
  213970. }
  213971. bytesFilled -= bytesPerBuffer;
  213972. return true;
  213973. }
  213974. else
  213975. {
  213976. return false;
  213977. }
  213978. }
  213979. unsigned int readOffset;
  213980. int bytesPerBuffer, totalBytesPerBuffer;
  213981. int bitDepth;
  213982. bool doneFlag;
  213983. private:
  213984. String name;
  213985. LPGUID guid;
  213986. int sampleRate, bufferSizeSamples;
  213987. float* leftBuffer;
  213988. float* rightBuffer;
  213989. IDirectSound* pDirectSound;
  213990. IDirectSoundCapture* pDirectSoundCapture;
  213991. IDirectSoundCaptureBuffer* pInputBuffer;
  213992. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  213993. };
  213994. class DSoundAudioIODevice : public AudioIODevice,
  213995. public Thread
  213996. {
  213997. public:
  213998. DSoundAudioIODevice (const String& deviceName,
  213999. const int outputDeviceIndex_,
  214000. const int inputDeviceIndex_)
  214001. : AudioIODevice (deviceName, "DirectSound"),
  214002. Thread ("Juce DSound"),
  214003. outputDeviceIndex (outputDeviceIndex_),
  214004. inputDeviceIndex (inputDeviceIndex_),
  214005. isOpen_ (false),
  214006. isStarted (false),
  214007. bufferSizeSamples (0),
  214008. totalSamplesOut (0),
  214009. sampleRate (0.0),
  214010. inputBuffers (1, 1),
  214011. outputBuffers (1, 1),
  214012. callback (0)
  214013. {
  214014. if (outputDeviceIndex_ >= 0)
  214015. {
  214016. outChannels.add (TRANS("Left"));
  214017. outChannels.add (TRANS("Right"));
  214018. }
  214019. if (inputDeviceIndex_ >= 0)
  214020. {
  214021. inChannels.add (TRANS("Left"));
  214022. inChannels.add (TRANS("Right"));
  214023. }
  214024. }
  214025. ~DSoundAudioIODevice()
  214026. {
  214027. close();
  214028. }
  214029. const String open (const BigInteger& inputChannels,
  214030. const BigInteger& outputChannels,
  214031. double sampleRate, int bufferSizeSamples)
  214032. {
  214033. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214034. isOpen_ = lastError.isEmpty();
  214035. return lastError;
  214036. }
  214037. void close()
  214038. {
  214039. stop();
  214040. if (isOpen_)
  214041. {
  214042. closeDevice();
  214043. isOpen_ = false;
  214044. }
  214045. }
  214046. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214047. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214048. double getCurrentSampleRate() { return sampleRate; }
  214049. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214050. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214051. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214052. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214053. const StringArray getOutputChannelNames() { return outChannels; }
  214054. const StringArray getInputChannelNames() { return inChannels; }
  214055. int getNumSampleRates() { return 4; }
  214056. int getDefaultBufferSize() { return 2560; }
  214057. int getNumBufferSizesAvailable() { return 50; }
  214058. double getSampleRate (int index)
  214059. {
  214060. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214061. return samps [jlimit (0, 3, index)];
  214062. }
  214063. int getBufferSizeSamples (int index)
  214064. {
  214065. int n = 64;
  214066. for (int i = 0; i < index; ++i)
  214067. n += (n < 512) ? 32
  214068. : ((n < 1024) ? 64
  214069. : ((n < 2048) ? 128 : 256));
  214070. return n;
  214071. }
  214072. int getCurrentBitDepth()
  214073. {
  214074. int i, bits = 256;
  214075. for (i = inChans.size(); --i >= 0;)
  214076. bits = jmin (bits, inChans[i]->bitDepth);
  214077. for (i = outChans.size(); --i >= 0;)
  214078. bits = jmin (bits, outChans[i]->bitDepth);
  214079. if (bits > 32)
  214080. bits = 16;
  214081. return bits;
  214082. }
  214083. void start (AudioIODeviceCallback* call)
  214084. {
  214085. if (isOpen_ && call != 0 && ! isStarted)
  214086. {
  214087. if (! isThreadRunning())
  214088. {
  214089. // something gone wrong and the thread's stopped..
  214090. isOpen_ = false;
  214091. return;
  214092. }
  214093. call->audioDeviceAboutToStart (this);
  214094. const ScopedLock sl (startStopLock);
  214095. callback = call;
  214096. isStarted = true;
  214097. }
  214098. }
  214099. void stop()
  214100. {
  214101. if (isStarted)
  214102. {
  214103. AudioIODeviceCallback* const callbackLocal = callback;
  214104. {
  214105. const ScopedLock sl (startStopLock);
  214106. isStarted = false;
  214107. }
  214108. if (callbackLocal != 0)
  214109. callbackLocal->audioDeviceStopped();
  214110. }
  214111. }
  214112. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214113. const String getLastError() { return lastError; }
  214114. StringArray inChannels, outChannels;
  214115. int outputDeviceIndex, inputDeviceIndex;
  214116. private:
  214117. bool isOpen_;
  214118. bool isStarted;
  214119. String lastError;
  214120. OwnedArray <DSoundInternalInChannel> inChans;
  214121. OwnedArray <DSoundInternalOutChannel> outChans;
  214122. WaitableEvent startEvent;
  214123. int bufferSizeSamples;
  214124. int volatile totalSamplesOut;
  214125. int64 volatile lastBlockTime;
  214126. double sampleRate;
  214127. BigInteger enabledInputs, enabledOutputs;
  214128. AudioSampleBuffer inputBuffers, outputBuffers;
  214129. AudioIODeviceCallback* callback;
  214130. CriticalSection startStopLock;
  214131. const String openDevice (const BigInteger& inputChannels,
  214132. const BigInteger& outputChannels,
  214133. double sampleRate_, int bufferSizeSamples_);
  214134. void closeDevice()
  214135. {
  214136. isStarted = false;
  214137. stopThread (5000);
  214138. inChans.clear();
  214139. outChans.clear();
  214140. inputBuffers.setSize (1, 1);
  214141. outputBuffers.setSize (1, 1);
  214142. }
  214143. void resync()
  214144. {
  214145. if (! threadShouldExit())
  214146. {
  214147. sleep (5);
  214148. int i;
  214149. for (i = 0; i < outChans.size(); ++i)
  214150. outChans.getUnchecked(i)->synchronisePosition();
  214151. for (i = 0; i < inChans.size(); ++i)
  214152. inChans.getUnchecked(i)->synchronisePosition();
  214153. }
  214154. }
  214155. public:
  214156. void run()
  214157. {
  214158. while (! threadShouldExit())
  214159. {
  214160. if (wait (100))
  214161. break;
  214162. }
  214163. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214164. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214165. while (! threadShouldExit())
  214166. {
  214167. int numToDo = 0;
  214168. uint32 startTime = Time::getMillisecondCounter();
  214169. int i;
  214170. for (i = inChans.size(); --i >= 0;)
  214171. {
  214172. inChans.getUnchecked(i)->doneFlag = false;
  214173. ++numToDo;
  214174. }
  214175. for (i = outChans.size(); --i >= 0;)
  214176. {
  214177. outChans.getUnchecked(i)->doneFlag = false;
  214178. ++numToDo;
  214179. }
  214180. if (numToDo > 0)
  214181. {
  214182. const int maxCount = 3;
  214183. int count = maxCount;
  214184. for (;;)
  214185. {
  214186. for (i = inChans.size(); --i >= 0;)
  214187. {
  214188. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214189. if ((! in->doneFlag) && in->service())
  214190. {
  214191. in->doneFlag = true;
  214192. --numToDo;
  214193. }
  214194. }
  214195. for (i = outChans.size(); --i >= 0;)
  214196. {
  214197. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214198. if ((! out->doneFlag) && out->service())
  214199. {
  214200. out->doneFlag = true;
  214201. --numToDo;
  214202. }
  214203. }
  214204. if (numToDo <= 0)
  214205. break;
  214206. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214207. {
  214208. resync();
  214209. break;
  214210. }
  214211. if (--count <= 0)
  214212. {
  214213. Sleep (1);
  214214. count = maxCount;
  214215. }
  214216. if (threadShouldExit())
  214217. return;
  214218. }
  214219. }
  214220. else
  214221. {
  214222. sleep (1);
  214223. }
  214224. const ScopedLock sl (startStopLock);
  214225. if (isStarted)
  214226. {
  214227. JUCE_TRY
  214228. {
  214229. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214230. inputBuffers.getNumChannels(),
  214231. outputBuffers.getArrayOfChannels(),
  214232. outputBuffers.getNumChannels(),
  214233. bufferSizeSamples);
  214234. }
  214235. JUCE_CATCH_EXCEPTION
  214236. totalSamplesOut += bufferSizeSamples;
  214237. }
  214238. else
  214239. {
  214240. outputBuffers.clear();
  214241. totalSamplesOut = 0;
  214242. sleep (1);
  214243. }
  214244. }
  214245. }
  214246. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214247. };
  214248. class DSoundAudioIODeviceType : public AudioIODeviceType
  214249. {
  214250. public:
  214251. DSoundAudioIODeviceType()
  214252. : AudioIODeviceType ("DirectSound"),
  214253. hasScanned (false)
  214254. {
  214255. initialiseDSoundFunctions();
  214256. }
  214257. void scanForDevices()
  214258. {
  214259. hasScanned = true;
  214260. outputDeviceNames.clear();
  214261. outputGuids.clear();
  214262. inputDeviceNames.clear();
  214263. inputGuids.clear();
  214264. if (dsDirectSoundEnumerateW != 0)
  214265. {
  214266. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214267. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214268. }
  214269. }
  214270. const StringArray getDeviceNames (bool wantInputNames) const
  214271. {
  214272. jassert (hasScanned); // need to call scanForDevices() before doing this
  214273. return wantInputNames ? inputDeviceNames
  214274. : outputDeviceNames;
  214275. }
  214276. int getDefaultDeviceIndex (bool /*forInput*/) const
  214277. {
  214278. jassert (hasScanned); // need to call scanForDevices() before doing this
  214279. return 0;
  214280. }
  214281. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214282. {
  214283. jassert (hasScanned); // need to call scanForDevices() before doing this
  214284. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214285. if (d == 0)
  214286. return -1;
  214287. return asInput ? d->inputDeviceIndex
  214288. : d->outputDeviceIndex;
  214289. }
  214290. bool hasSeparateInputsAndOutputs() const { return true; }
  214291. AudioIODevice* createDevice (const String& outputDeviceName,
  214292. const String& inputDeviceName)
  214293. {
  214294. jassert (hasScanned); // need to call scanForDevices() before doing this
  214295. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214296. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214297. if (outputIndex >= 0 || inputIndex >= 0)
  214298. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214299. : inputDeviceName,
  214300. outputIndex, inputIndex);
  214301. return 0;
  214302. }
  214303. StringArray outputDeviceNames, inputDeviceNames;
  214304. OwnedArray <GUID> outputGuids, inputGuids;
  214305. private:
  214306. bool hasScanned;
  214307. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214308. {
  214309. desc = desc.trim();
  214310. if (desc.isNotEmpty())
  214311. {
  214312. const String origDesc (desc);
  214313. int n = 2;
  214314. while (outputDeviceNames.contains (desc))
  214315. desc = origDesc + " (" + String (n++) + ")";
  214316. outputDeviceNames.add (desc);
  214317. if (lpGUID != 0)
  214318. outputGuids.add (new GUID (*lpGUID));
  214319. else
  214320. outputGuids.add (0);
  214321. }
  214322. return TRUE;
  214323. }
  214324. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214325. {
  214326. return ((DSoundAudioIODeviceType*) object)
  214327. ->outputEnumProc (lpGUID, String (description));
  214328. }
  214329. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214330. {
  214331. return ((DSoundAudioIODeviceType*) object)
  214332. ->outputEnumProc (lpGUID, String (description));
  214333. }
  214334. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214335. {
  214336. desc = desc.trim();
  214337. if (desc.isNotEmpty())
  214338. {
  214339. const String origDesc (desc);
  214340. int n = 2;
  214341. while (inputDeviceNames.contains (desc))
  214342. desc = origDesc + " (" + String (n++) + ")";
  214343. inputDeviceNames.add (desc);
  214344. if (lpGUID != 0)
  214345. inputGuids.add (new GUID (*lpGUID));
  214346. else
  214347. inputGuids.add (0);
  214348. }
  214349. return TRUE;
  214350. }
  214351. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214352. {
  214353. return ((DSoundAudioIODeviceType*) object)
  214354. ->inputEnumProc (lpGUID, String (description));
  214355. }
  214356. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214357. {
  214358. return ((DSoundAudioIODeviceType*) object)
  214359. ->inputEnumProc (lpGUID, String (description));
  214360. }
  214361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214362. };
  214363. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214364. const BigInteger& outputChannels,
  214365. double sampleRate_, int bufferSizeSamples_)
  214366. {
  214367. closeDevice();
  214368. totalSamplesOut = 0;
  214369. sampleRate = sampleRate_;
  214370. if (bufferSizeSamples_ <= 0)
  214371. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214372. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214373. DSoundAudioIODeviceType dlh;
  214374. dlh.scanForDevices();
  214375. enabledInputs = inputChannels;
  214376. enabledInputs.setRange (inChannels.size(),
  214377. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214378. false);
  214379. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214380. inputBuffers.clear();
  214381. int i, numIns = 0;
  214382. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214383. {
  214384. float* left = 0;
  214385. if (enabledInputs[i])
  214386. left = inputBuffers.getSampleData (numIns++);
  214387. float* right = 0;
  214388. if (enabledInputs[i + 1])
  214389. right = inputBuffers.getSampleData (numIns++);
  214390. if (left != 0 || right != 0)
  214391. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214392. dlh.inputGuids [inputDeviceIndex],
  214393. (int) sampleRate, bufferSizeSamples,
  214394. left, right));
  214395. }
  214396. enabledOutputs = outputChannels;
  214397. enabledOutputs.setRange (outChannels.size(),
  214398. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214399. false);
  214400. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214401. outputBuffers.clear();
  214402. int numOuts = 0;
  214403. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214404. {
  214405. float* left = 0;
  214406. if (enabledOutputs[i])
  214407. left = outputBuffers.getSampleData (numOuts++);
  214408. float* right = 0;
  214409. if (enabledOutputs[i + 1])
  214410. right = outputBuffers.getSampleData (numOuts++);
  214411. if (left != 0 || right != 0)
  214412. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214413. dlh.outputGuids [outputDeviceIndex],
  214414. (int) sampleRate, bufferSizeSamples,
  214415. left, right));
  214416. }
  214417. String error;
  214418. // boost our priority while opening the devices to try to get better sync between them
  214419. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214420. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214421. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214422. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214423. for (i = 0; i < outChans.size(); ++i)
  214424. {
  214425. error = outChans[i]->open();
  214426. if (error.isNotEmpty())
  214427. {
  214428. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214429. break;
  214430. }
  214431. }
  214432. if (error.isEmpty())
  214433. {
  214434. for (i = 0; i < inChans.size(); ++i)
  214435. {
  214436. error = inChans[i]->open();
  214437. if (error.isNotEmpty())
  214438. {
  214439. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214440. break;
  214441. }
  214442. }
  214443. }
  214444. if (error.isEmpty())
  214445. {
  214446. totalSamplesOut = 0;
  214447. for (i = 0; i < outChans.size(); ++i)
  214448. outChans.getUnchecked(i)->synchronisePosition();
  214449. for (i = 0; i < inChans.size(); ++i)
  214450. inChans.getUnchecked(i)->synchronisePosition();
  214451. startThread (9);
  214452. sleep (10);
  214453. notify();
  214454. }
  214455. else
  214456. {
  214457. log (error);
  214458. }
  214459. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214460. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214461. return error;
  214462. }
  214463. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214464. {
  214465. return new DSoundAudioIODeviceType();
  214466. }
  214467. #undef log
  214468. #endif
  214469. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214470. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214471. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214472. // compiled on its own).
  214473. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214474. #ifndef WASAPI_ENABLE_LOGGING
  214475. #define WASAPI_ENABLE_LOGGING 0
  214476. #endif
  214477. namespace WasapiClasses
  214478. {
  214479. void logFailure (HRESULT hr)
  214480. {
  214481. (void) hr;
  214482. #if WASAPI_ENABLE_LOGGING
  214483. if (FAILED (hr))
  214484. {
  214485. String e;
  214486. e << Time::getCurrentTime().toString (true, true, true, true)
  214487. << " -- WASAPI error: ";
  214488. switch (hr)
  214489. {
  214490. case E_POINTER: e << "E_POINTER"; break;
  214491. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214492. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214493. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214494. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214495. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214496. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214497. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214498. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214499. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214500. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214501. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214502. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214503. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214504. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214505. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214506. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214507. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214508. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214509. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214510. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214511. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214512. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214513. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214514. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214515. default: e << String::toHexString ((int) hr); break;
  214516. }
  214517. DBG (e);
  214518. jassertfalse;
  214519. }
  214520. #endif
  214521. }
  214522. #undef check
  214523. bool check (HRESULT hr)
  214524. {
  214525. logFailure (hr);
  214526. return SUCCEEDED (hr);
  214527. }
  214528. const String getDeviceID (IMMDevice* const device)
  214529. {
  214530. String s;
  214531. WCHAR* deviceId = 0;
  214532. if (check (device->GetId (&deviceId)))
  214533. {
  214534. s = String (deviceId);
  214535. CoTaskMemFree (deviceId);
  214536. }
  214537. return s;
  214538. }
  214539. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214540. {
  214541. EDataFlow flow = eRender;
  214542. ComSmartPtr <IMMEndpoint> endPoint;
  214543. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214544. (void) check (endPoint->GetDataFlow (&flow));
  214545. return flow;
  214546. }
  214547. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214548. {
  214549. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214550. }
  214551. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214552. {
  214553. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214554. : sizeof (WAVEFORMATEX));
  214555. }
  214556. class WASAPIDeviceBase
  214557. {
  214558. public:
  214559. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214560. : device (device_),
  214561. sampleRate (0),
  214562. defaultSampleRate (0),
  214563. numChannels (0),
  214564. actualNumChannels (0),
  214565. minBufferSize (0),
  214566. defaultBufferSize (0),
  214567. latencySamples (0),
  214568. useExclusiveMode (useExclusiveMode_)
  214569. {
  214570. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214571. ComSmartPtr <IAudioClient> tempClient (createClient());
  214572. if (tempClient == 0)
  214573. return;
  214574. REFERENCE_TIME defaultPeriod, minPeriod;
  214575. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214576. return;
  214577. WAVEFORMATEX* mixFormat = 0;
  214578. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214579. return;
  214580. WAVEFORMATEXTENSIBLE format;
  214581. copyWavFormat (format, mixFormat);
  214582. CoTaskMemFree (mixFormat);
  214583. actualNumChannels = numChannels = format.Format.nChannels;
  214584. defaultSampleRate = format.Format.nSamplesPerSec;
  214585. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214586. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214587. rates.addUsingDefaultSort (defaultSampleRate);
  214588. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214589. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214590. {
  214591. if (ratesToTest[i] == defaultSampleRate)
  214592. continue;
  214593. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214594. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214595. (WAVEFORMATEX*) &format, 0)))
  214596. if (! rates.contains (ratesToTest[i]))
  214597. rates.addUsingDefaultSort (ratesToTest[i]);
  214598. }
  214599. }
  214600. ~WASAPIDeviceBase()
  214601. {
  214602. device = 0;
  214603. CloseHandle (clientEvent);
  214604. }
  214605. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214606. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214607. {
  214608. sampleRate = newSampleRate;
  214609. channels = newChannels;
  214610. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214611. numChannels = channels.getHighestBit() + 1;
  214612. if (numChannels == 0)
  214613. return true;
  214614. client = createClient();
  214615. if (client != 0
  214616. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214617. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214618. {
  214619. channelMaps.clear();
  214620. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214621. if (channels[i])
  214622. channelMaps.add (i);
  214623. REFERENCE_TIME latency;
  214624. if (check (client->GetStreamLatency (&latency)))
  214625. latencySamples = refTimeToSamples (latency, sampleRate);
  214626. (void) check (client->GetBufferSize (&actualBufferSize));
  214627. return check (client->SetEventHandle (clientEvent));
  214628. }
  214629. return false;
  214630. }
  214631. void closeClient()
  214632. {
  214633. if (client != 0)
  214634. client->Stop();
  214635. client = 0;
  214636. ResetEvent (clientEvent);
  214637. }
  214638. ComSmartPtr <IMMDevice> device;
  214639. ComSmartPtr <IAudioClient> client;
  214640. double sampleRate, defaultSampleRate;
  214641. int numChannels, actualNumChannels;
  214642. int minBufferSize, defaultBufferSize, latencySamples;
  214643. const bool useExclusiveMode;
  214644. Array <double> rates;
  214645. HANDLE clientEvent;
  214646. BigInteger channels;
  214647. Array <int> channelMaps;
  214648. UINT32 actualBufferSize;
  214649. int bytesPerSample;
  214650. virtual void updateFormat (bool isFloat) = 0;
  214651. private:
  214652. const ComSmartPtr <IAudioClient> createClient()
  214653. {
  214654. ComSmartPtr <IAudioClient> client;
  214655. if (device != 0)
  214656. {
  214657. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214658. logFailure (hr);
  214659. }
  214660. return client;
  214661. }
  214662. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214663. {
  214664. WAVEFORMATEXTENSIBLE format;
  214665. zerostruct (format);
  214666. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214667. {
  214668. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214669. }
  214670. else
  214671. {
  214672. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214673. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214674. }
  214675. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214676. format.Format.nChannels = (WORD) numChannels;
  214677. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214678. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214679. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214680. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214681. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214682. switch (numChannels)
  214683. {
  214684. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214685. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214686. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214687. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214688. 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;
  214689. default: break;
  214690. }
  214691. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214692. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214693. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214694. logFailure (hr);
  214695. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214696. {
  214697. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214698. hr = S_OK;
  214699. }
  214700. CoTaskMemFree (nearestFormat);
  214701. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214702. if (useExclusiveMode)
  214703. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214704. GUID session;
  214705. if (hr == S_OK
  214706. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214707. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214708. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214709. {
  214710. actualNumChannels = format.Format.nChannels;
  214711. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214712. bytesPerSample = format.Format.wBitsPerSample / 8;
  214713. updateFormat (isFloat);
  214714. return true;
  214715. }
  214716. return false;
  214717. }
  214718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  214719. };
  214720. class WASAPIInputDevice : public WASAPIDeviceBase
  214721. {
  214722. public:
  214723. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214724. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214725. reservoir (1, 1)
  214726. {
  214727. }
  214728. ~WASAPIInputDevice()
  214729. {
  214730. close();
  214731. }
  214732. bool open (const double newSampleRate, const BigInteger& newChannels)
  214733. {
  214734. reservoirSize = 0;
  214735. reservoirCapacity = 16384;
  214736. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214737. return openClient (newSampleRate, newChannels)
  214738. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  214739. (void**) captureClient.resetAndGetPointerAddress())));
  214740. }
  214741. void close()
  214742. {
  214743. closeClient();
  214744. captureClient = 0;
  214745. reservoir.setSize (0);
  214746. }
  214747. template <class SourceType>
  214748. void updateFormatWithType (SourceType*)
  214749. {
  214750. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  214751. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  214752. }
  214753. void updateFormat (bool isFloat)
  214754. {
  214755. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214756. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214757. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214758. else updateFormatWithType ((AudioData::Int16*) 0);
  214759. }
  214760. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214761. {
  214762. if (numChannels <= 0)
  214763. return;
  214764. int offset = 0;
  214765. while (bufferSize > 0)
  214766. {
  214767. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214768. {
  214769. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214770. for (int i = 0; i < numDestBuffers; ++i)
  214771. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  214772. bufferSize -= samplesToDo;
  214773. offset += samplesToDo;
  214774. reservoirSize = 0;
  214775. }
  214776. else
  214777. {
  214778. UINT32 packetLength = 0;
  214779. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  214780. break;
  214781. if (packetLength == 0)
  214782. {
  214783. if (thread.threadShouldExit()
  214784. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214785. break;
  214786. continue;
  214787. }
  214788. uint8* inputData;
  214789. UINT32 numSamplesAvailable;
  214790. DWORD flags;
  214791. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214792. {
  214793. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214794. for (int i = 0; i < numDestBuffers; ++i)
  214795. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  214796. bufferSize -= samplesToDo;
  214797. offset += samplesToDo;
  214798. if (samplesToDo < (int) numSamplesAvailable)
  214799. {
  214800. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214801. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214802. bytesPerSample * actualNumChannels * reservoirSize);
  214803. }
  214804. captureClient->ReleaseBuffer (numSamplesAvailable);
  214805. }
  214806. }
  214807. }
  214808. }
  214809. ComSmartPtr <IAudioCaptureClient> captureClient;
  214810. MemoryBlock reservoir;
  214811. int reservoirSize, reservoirCapacity;
  214812. ScopedPointer <AudioData::Converter> converter;
  214813. private:
  214814. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  214815. };
  214816. class WASAPIOutputDevice : public WASAPIDeviceBase
  214817. {
  214818. public:
  214819. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214820. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214821. {
  214822. }
  214823. ~WASAPIOutputDevice()
  214824. {
  214825. close();
  214826. }
  214827. bool open (const double newSampleRate, const BigInteger& newChannels)
  214828. {
  214829. return openClient (newSampleRate, newChannels)
  214830. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  214831. }
  214832. void close()
  214833. {
  214834. closeClient();
  214835. renderClient = 0;
  214836. }
  214837. template <class DestType>
  214838. void updateFormatWithType (DestType*)
  214839. {
  214840. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  214841. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  214842. }
  214843. void updateFormat (bool isFloat)
  214844. {
  214845. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214846. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214847. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214848. else updateFormatWithType ((AudioData::Int16*) 0);
  214849. }
  214850. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214851. {
  214852. if (numChannels <= 0)
  214853. return;
  214854. int offset = 0;
  214855. while (bufferSize > 0)
  214856. {
  214857. UINT32 padding = 0;
  214858. if (! check (client->GetCurrentPadding (&padding)))
  214859. return;
  214860. int samplesToDo = useExclusiveMode ? bufferSize
  214861. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214862. if (samplesToDo <= 0)
  214863. {
  214864. if (thread.threadShouldExit()
  214865. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214866. break;
  214867. continue;
  214868. }
  214869. uint8* outputData = 0;
  214870. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  214871. {
  214872. for (int i = 0; i < numSrcBuffers; ++i)
  214873. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  214874. renderClient->ReleaseBuffer (samplesToDo, 0);
  214875. offset += samplesToDo;
  214876. bufferSize -= samplesToDo;
  214877. }
  214878. }
  214879. }
  214880. ComSmartPtr <IAudioRenderClient> renderClient;
  214881. ScopedPointer <AudioData::Converter> converter;
  214882. private:
  214883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  214884. };
  214885. class WASAPIAudioIODevice : public AudioIODevice,
  214886. public Thread
  214887. {
  214888. public:
  214889. WASAPIAudioIODevice (const String& deviceName,
  214890. const String& outputDeviceId_,
  214891. const String& inputDeviceId_,
  214892. const bool useExclusiveMode_)
  214893. : AudioIODevice (deviceName, "Windows Audio"),
  214894. Thread ("Juce WASAPI"),
  214895. outputDeviceId (outputDeviceId_),
  214896. inputDeviceId (inputDeviceId_),
  214897. useExclusiveMode (useExclusiveMode_),
  214898. isOpen_ (false),
  214899. isStarted (false),
  214900. currentBufferSizeSamples (0),
  214901. currentSampleRate (0),
  214902. callback (0)
  214903. {
  214904. }
  214905. ~WASAPIAudioIODevice()
  214906. {
  214907. close();
  214908. }
  214909. bool initialise()
  214910. {
  214911. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214912. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214913. latencyIn = latencyOut = 0;
  214914. Array <double> ratesIn, ratesOut;
  214915. if (createDevices())
  214916. {
  214917. jassert (inputDevice != 0 || outputDevice != 0);
  214918. if (inputDevice != 0 && outputDevice != 0)
  214919. {
  214920. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214921. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214922. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214923. sampleRates = inputDevice->rates;
  214924. sampleRates.removeValuesNotIn (outputDevice->rates);
  214925. }
  214926. else
  214927. {
  214928. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  214929. : static_cast<WASAPIDeviceBase*> (outputDevice);
  214930. defaultSampleRate = d->defaultSampleRate;
  214931. minBufferSize = d->minBufferSize;
  214932. defaultBufferSize = d->defaultBufferSize;
  214933. sampleRates = d->rates;
  214934. }
  214935. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214936. if (minBufferSize != defaultBufferSize)
  214937. bufferSizes.addUsingDefaultSort (minBufferSize);
  214938. int n = 64;
  214939. for (int i = 0; i < 40; ++i)
  214940. {
  214941. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214942. bufferSizes.addUsingDefaultSort (n);
  214943. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214944. }
  214945. return true;
  214946. }
  214947. return false;
  214948. }
  214949. const StringArray getOutputChannelNames()
  214950. {
  214951. StringArray outChannels;
  214952. if (outputDevice != 0)
  214953. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214954. outChannels.add ("Output channel " + String (i));
  214955. return outChannels;
  214956. }
  214957. const StringArray getInputChannelNames()
  214958. {
  214959. StringArray inChannels;
  214960. if (inputDevice != 0)
  214961. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214962. inChannels.add ("Input channel " + String (i));
  214963. return inChannels;
  214964. }
  214965. int getNumSampleRates() { return sampleRates.size(); }
  214966. double getSampleRate (int index) { return sampleRates [index]; }
  214967. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214968. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214969. int getDefaultBufferSize() { return defaultBufferSize; }
  214970. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214971. double getCurrentSampleRate() { return currentSampleRate; }
  214972. int getCurrentBitDepth() { return 32; }
  214973. int getOutputLatencyInSamples() { return latencyOut; }
  214974. int getInputLatencyInSamples() { return latencyIn; }
  214975. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214976. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214977. const String getLastError() { return lastError; }
  214978. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214979. double sampleRate, int bufferSizeSamples)
  214980. {
  214981. close();
  214982. lastError = String::empty;
  214983. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214984. {
  214985. lastError = "The input and output devices don't share a common sample rate!";
  214986. return lastError;
  214987. }
  214988. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214989. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214990. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214991. {
  214992. lastError = "Couldn't open the input device!";
  214993. return lastError;
  214994. }
  214995. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214996. {
  214997. close();
  214998. lastError = "Couldn't open the output device!";
  214999. return lastError;
  215000. }
  215001. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215002. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215003. startThread (8);
  215004. Thread::sleep (5);
  215005. if (inputDevice != 0 && inputDevice->client != 0)
  215006. {
  215007. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215008. HRESULT hr = inputDevice->client->Start();
  215009. logFailure (hr); //xxx handle this
  215010. }
  215011. if (outputDevice != 0 && outputDevice->client != 0)
  215012. {
  215013. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215014. HRESULT hr = outputDevice->client->Start();
  215015. logFailure (hr); //xxx handle this
  215016. }
  215017. isOpen_ = true;
  215018. return lastError;
  215019. }
  215020. void close()
  215021. {
  215022. stop();
  215023. signalThreadShouldExit();
  215024. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215025. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215026. stopThread (5000);
  215027. if (inputDevice != 0) inputDevice->close();
  215028. if (outputDevice != 0) outputDevice->close();
  215029. isOpen_ = false;
  215030. }
  215031. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215032. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215033. void start (AudioIODeviceCallback* call)
  215034. {
  215035. if (isOpen_ && call != 0 && ! isStarted)
  215036. {
  215037. if (! isThreadRunning())
  215038. {
  215039. // something's gone wrong and the thread's stopped..
  215040. isOpen_ = false;
  215041. return;
  215042. }
  215043. call->audioDeviceAboutToStart (this);
  215044. const ScopedLock sl (startStopLock);
  215045. callback = call;
  215046. isStarted = true;
  215047. }
  215048. }
  215049. void stop()
  215050. {
  215051. if (isStarted)
  215052. {
  215053. AudioIODeviceCallback* const callbackLocal = callback;
  215054. {
  215055. const ScopedLock sl (startStopLock);
  215056. isStarted = false;
  215057. }
  215058. if (callbackLocal != 0)
  215059. callbackLocal->audioDeviceStopped();
  215060. }
  215061. }
  215062. void setMMThreadPriority()
  215063. {
  215064. DynamicLibraryLoader dll ("avrt.dll");
  215065. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215066. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215067. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215068. {
  215069. DWORD dummy = 0;
  215070. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215071. if (h != 0)
  215072. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215073. }
  215074. }
  215075. void run()
  215076. {
  215077. setMMThreadPriority();
  215078. const int bufferSize = currentBufferSizeSamples;
  215079. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215080. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215081. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215082. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215083. float** const inputBuffers = ins.getArrayOfChannels();
  215084. float** const outputBuffers = outs.getArrayOfChannels();
  215085. ins.clear();
  215086. while (! threadShouldExit())
  215087. {
  215088. if (inputDevice != 0)
  215089. {
  215090. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215091. if (threadShouldExit())
  215092. break;
  215093. }
  215094. JUCE_TRY
  215095. {
  215096. const ScopedLock sl (startStopLock);
  215097. if (isStarted)
  215098. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215099. outputBuffers, numOutputBuffers, bufferSize);
  215100. else
  215101. outs.clear();
  215102. }
  215103. JUCE_CATCH_EXCEPTION
  215104. if (outputDevice != 0)
  215105. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215106. }
  215107. }
  215108. String outputDeviceId, inputDeviceId;
  215109. String lastError;
  215110. private:
  215111. // Device stats...
  215112. ScopedPointer<WASAPIInputDevice> inputDevice;
  215113. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215114. const bool useExclusiveMode;
  215115. double defaultSampleRate;
  215116. int minBufferSize, defaultBufferSize;
  215117. int latencyIn, latencyOut;
  215118. Array <double> sampleRates;
  215119. Array <int> bufferSizes;
  215120. // Active state...
  215121. bool isOpen_, isStarted;
  215122. int currentBufferSizeSamples;
  215123. double currentSampleRate;
  215124. AudioIODeviceCallback* callback;
  215125. CriticalSection startStopLock;
  215126. bool createDevices()
  215127. {
  215128. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215129. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215130. return false;
  215131. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215132. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215133. return false;
  215134. UINT32 numDevices = 0;
  215135. if (! check (deviceCollection->GetCount (&numDevices)))
  215136. return false;
  215137. for (UINT32 i = 0; i < numDevices; ++i)
  215138. {
  215139. ComSmartPtr <IMMDevice> device;
  215140. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215141. continue;
  215142. const String deviceId (getDeviceID (device));
  215143. if (deviceId.isEmpty())
  215144. continue;
  215145. const EDataFlow flow = getDataFlow (device);
  215146. if (deviceId == inputDeviceId && flow == eCapture)
  215147. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215148. else if (deviceId == outputDeviceId && flow == eRender)
  215149. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215150. }
  215151. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215152. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215153. }
  215154. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215155. };
  215156. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215157. {
  215158. public:
  215159. WASAPIAudioIODeviceType()
  215160. : AudioIODeviceType ("Windows Audio"),
  215161. hasScanned (false)
  215162. {
  215163. }
  215164. ~WASAPIAudioIODeviceType()
  215165. {
  215166. }
  215167. void scanForDevices()
  215168. {
  215169. hasScanned = true;
  215170. outputDeviceNames.clear();
  215171. inputDeviceNames.clear();
  215172. outputDeviceIds.clear();
  215173. inputDeviceIds.clear();
  215174. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215175. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215176. return;
  215177. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215178. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215179. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215180. UINT32 numDevices = 0;
  215181. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215182. && check (deviceCollection->GetCount (&numDevices))))
  215183. return;
  215184. for (UINT32 i = 0; i < numDevices; ++i)
  215185. {
  215186. ComSmartPtr <IMMDevice> device;
  215187. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215188. continue;
  215189. const String deviceId (getDeviceID (device));
  215190. DWORD state = 0;
  215191. if (! check (device->GetState (&state)))
  215192. continue;
  215193. if (state != DEVICE_STATE_ACTIVE)
  215194. continue;
  215195. String name;
  215196. {
  215197. ComSmartPtr <IPropertyStore> properties;
  215198. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215199. continue;
  215200. PROPVARIANT value;
  215201. PropVariantInit (&value);
  215202. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215203. name = value.pwszVal;
  215204. PropVariantClear (&value);
  215205. }
  215206. const EDataFlow flow = getDataFlow (device);
  215207. if (flow == eRender)
  215208. {
  215209. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215210. outputDeviceIds.insert (index, deviceId);
  215211. outputDeviceNames.insert (index, name);
  215212. }
  215213. else if (flow == eCapture)
  215214. {
  215215. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215216. inputDeviceIds.insert (index, deviceId);
  215217. inputDeviceNames.insert (index, name);
  215218. }
  215219. }
  215220. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215221. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215222. }
  215223. const StringArray getDeviceNames (bool wantInputNames) const
  215224. {
  215225. jassert (hasScanned); // need to call scanForDevices() before doing this
  215226. return wantInputNames ? inputDeviceNames
  215227. : outputDeviceNames;
  215228. }
  215229. int getDefaultDeviceIndex (bool /*forInput*/) const
  215230. {
  215231. jassert (hasScanned); // need to call scanForDevices() before doing this
  215232. return 0;
  215233. }
  215234. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215235. {
  215236. jassert (hasScanned); // need to call scanForDevices() before doing this
  215237. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215238. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215239. : outputDeviceIds.indexOf (d->outputDeviceId));
  215240. }
  215241. bool hasSeparateInputsAndOutputs() const { return true; }
  215242. AudioIODevice* createDevice (const String& outputDeviceName,
  215243. const String& inputDeviceName)
  215244. {
  215245. jassert (hasScanned); // need to call scanForDevices() before doing this
  215246. const bool useExclusiveMode = false;
  215247. ScopedPointer<WASAPIAudioIODevice> device;
  215248. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215249. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215250. if (outputIndex >= 0 || inputIndex >= 0)
  215251. {
  215252. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215253. : inputDeviceName,
  215254. outputDeviceIds [outputIndex],
  215255. inputDeviceIds [inputIndex],
  215256. useExclusiveMode);
  215257. if (! device->initialise())
  215258. device = 0;
  215259. }
  215260. return device.release();
  215261. }
  215262. StringArray outputDeviceNames, outputDeviceIds;
  215263. StringArray inputDeviceNames, inputDeviceIds;
  215264. private:
  215265. bool hasScanned;
  215266. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215267. {
  215268. String s;
  215269. IMMDevice* dev = 0;
  215270. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215271. eMultimedia, &dev)))
  215272. {
  215273. WCHAR* deviceId = 0;
  215274. if (check (dev->GetId (&deviceId)))
  215275. {
  215276. s = String (deviceId);
  215277. CoTaskMemFree (deviceId);
  215278. }
  215279. dev->Release();
  215280. }
  215281. return s;
  215282. }
  215283. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215284. };
  215285. }
  215286. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215287. {
  215288. return new WasapiClasses::WASAPIAudioIODeviceType();
  215289. }
  215290. #endif
  215291. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215292. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215293. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215294. // compiled on its own).
  215295. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215296. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215297. {
  215298. public:
  215299. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215300. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215301. const ComSmartPtr <IBaseFilter>& filter_,
  215302. int minWidth, int minHeight,
  215303. int maxWidth, int maxHeight)
  215304. : owner (owner_),
  215305. captureGraphBuilder (captureGraphBuilder_),
  215306. filter (filter_),
  215307. ok (false),
  215308. imageNeedsFlipping (false),
  215309. width (0),
  215310. height (0),
  215311. activeUsers (0),
  215312. recordNextFrameTime (false),
  215313. previewMaxFPS (60)
  215314. {
  215315. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215316. if (FAILED (hr))
  215317. return;
  215318. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215319. if (FAILED (hr))
  215320. return;
  215321. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215322. if (FAILED (hr))
  215323. return;
  215324. {
  215325. ComSmartPtr <IAMStreamConfig> streamConfig;
  215326. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215327. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215328. if (streamConfig != 0)
  215329. {
  215330. getVideoSizes (streamConfig);
  215331. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215332. return;
  215333. }
  215334. }
  215335. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215336. if (FAILED (hr))
  215337. return;
  215338. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215339. if (FAILED (hr))
  215340. return;
  215341. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215342. if (FAILED (hr))
  215343. return;
  215344. if (! connectFilters (filter, smartTee))
  215345. return;
  215346. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215347. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215348. if (FAILED (hr))
  215349. return;
  215350. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215351. if (FAILED (hr))
  215352. return;
  215353. AM_MEDIA_TYPE mt;
  215354. zerostruct (mt);
  215355. mt.majortype = MEDIATYPE_Video;
  215356. mt.subtype = MEDIASUBTYPE_RGB24;
  215357. mt.formattype = FORMAT_VideoInfo;
  215358. sampleGrabber->SetMediaType (&mt);
  215359. callback = new GrabberCallback (*this);
  215360. hr = sampleGrabber->SetCallback (callback, 1);
  215361. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215362. if (FAILED (hr))
  215363. return;
  215364. ComSmartPtr <IPin> grabberInputPin;
  215365. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215366. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215367. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215368. return;
  215369. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215370. if (FAILED (hr))
  215371. return;
  215372. zerostruct (mt);
  215373. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215374. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215375. width = pVih->bmiHeader.biWidth;
  215376. height = pVih->bmiHeader.biHeight;
  215377. ComSmartPtr <IBaseFilter> nullFilter;
  215378. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215379. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215380. if (connectFilters (sampleGrabberBase, nullFilter)
  215381. && addGraphToRot())
  215382. {
  215383. activeImage = Image (Image::RGB, width, height, true);
  215384. loadingImage = Image (Image::RGB, width, height, true);
  215385. ok = true;
  215386. }
  215387. }
  215388. ~DShowCameraDeviceInteral()
  215389. {
  215390. if (mediaControl != 0)
  215391. mediaControl->Stop();
  215392. removeGraphFromRot();
  215393. for (int i = viewerComps.size(); --i >= 0;)
  215394. viewerComps.getUnchecked(i)->ownerDeleted();
  215395. callback = 0;
  215396. graphBuilder = 0;
  215397. sampleGrabber = 0;
  215398. mediaControl = 0;
  215399. filter = 0;
  215400. captureGraphBuilder = 0;
  215401. smartTee = 0;
  215402. smartTeePreviewOutputPin = 0;
  215403. smartTeeCaptureOutputPin = 0;
  215404. asfWriter = 0;
  215405. }
  215406. void addUser()
  215407. {
  215408. if (ok && activeUsers++ == 0)
  215409. mediaControl->Run();
  215410. }
  215411. void removeUser()
  215412. {
  215413. if (ok && --activeUsers == 0)
  215414. mediaControl->Stop();
  215415. }
  215416. int getPreviewMaxFPS() const
  215417. {
  215418. return previewMaxFPS;
  215419. }
  215420. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215421. {
  215422. if (recordNextFrameTime)
  215423. {
  215424. const double defaultCameraLatency = 0.1;
  215425. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215426. recordNextFrameTime = false;
  215427. ComSmartPtr <IPin> pin;
  215428. if (getPin (filter, PINDIR_OUTPUT, pin))
  215429. {
  215430. ComSmartPtr <IAMPushSource> pushSource;
  215431. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215432. if (pushSource != 0)
  215433. {
  215434. REFERENCE_TIME latency = 0;
  215435. hr = pushSource->GetLatency (&latency);
  215436. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215437. }
  215438. }
  215439. }
  215440. {
  215441. const int lineStride = width * 3;
  215442. const ScopedLock sl (imageSwapLock);
  215443. {
  215444. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215445. for (int i = 0; i < height; ++i)
  215446. memcpy (destData.getLinePointer ((height - 1) - i),
  215447. buffer + lineStride * i,
  215448. lineStride);
  215449. }
  215450. imageNeedsFlipping = true;
  215451. }
  215452. if (listeners.size() > 0)
  215453. callListeners (loadingImage);
  215454. sendChangeMessage();
  215455. }
  215456. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215457. {
  215458. if (imageNeedsFlipping)
  215459. {
  215460. const ScopedLock sl (imageSwapLock);
  215461. swapVariables (loadingImage, activeImage);
  215462. imageNeedsFlipping = false;
  215463. }
  215464. RectanglePlacement rp (RectanglePlacement::centred);
  215465. double dx = 0, dy = 0, dw = width, dh = height;
  215466. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215467. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215468. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215469. {
  215470. Graphics::ScopedSaveState ss (g);
  215471. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215472. g.fillAll (Colours::black);
  215473. }
  215474. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215475. }
  215476. bool createFileCaptureFilter (const File& file, int quality)
  215477. {
  215478. removeFileCaptureFilter();
  215479. file.deleteFile();
  215480. mediaControl->Stop();
  215481. firstRecordedTime = Time();
  215482. recordNextFrameTime = true;
  215483. previewMaxFPS = 60;
  215484. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215485. if (SUCCEEDED (hr))
  215486. {
  215487. ComSmartPtr <IFileSinkFilter> fileSink;
  215488. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215489. if (SUCCEEDED (hr))
  215490. {
  215491. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215492. if (SUCCEEDED (hr))
  215493. {
  215494. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215495. if (SUCCEEDED (hr))
  215496. {
  215497. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215498. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215499. asfConfig->SetIndexMode (true);
  215500. ComSmartPtr <IWMProfileManager> profileManager;
  215501. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215502. // This gibberish is the DirectShow profile for a video-only wmv file.
  215503. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215504. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215505. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215506. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215507. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215508. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215509. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215510. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215511. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215512. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215513. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215514. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215515. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215516. "</videoinfoheader>"
  215517. "</wmmediatype>"
  215518. "</streamconfig>"
  215519. "</profile>");
  215520. const int fps[] = { 10, 15, 30 };
  215521. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215522. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215523. maxFramesPerSecond = (quality >> 24) & 0xff;
  215524. prof = prof.replace ("$WIDTH", String (width))
  215525. .replace ("$HEIGHT", String (height))
  215526. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215527. ComSmartPtr <IWMProfile> currentProfile;
  215528. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  215529. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215530. if (SUCCEEDED (hr))
  215531. {
  215532. ComSmartPtr <IPin> asfWriterInputPin;
  215533. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215534. {
  215535. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215536. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215537. && SUCCEEDED (mediaControl->Run()))
  215538. {
  215539. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215540. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215541. previewMaxFPS = (quality >> 16) & 0xff;
  215542. return true;
  215543. }
  215544. }
  215545. }
  215546. }
  215547. }
  215548. }
  215549. }
  215550. removeFileCaptureFilter();
  215551. if (ok && activeUsers > 0)
  215552. mediaControl->Run();
  215553. return false;
  215554. }
  215555. void removeFileCaptureFilter()
  215556. {
  215557. mediaControl->Stop();
  215558. if (asfWriter != 0)
  215559. {
  215560. graphBuilder->RemoveFilter (asfWriter);
  215561. asfWriter = 0;
  215562. }
  215563. if (ok && activeUsers > 0)
  215564. mediaControl->Run();
  215565. previewMaxFPS = 60;
  215566. }
  215567. void addListener (CameraDevice::Listener* listenerToAdd)
  215568. {
  215569. const ScopedLock sl (listenerLock);
  215570. if (listeners.size() == 0)
  215571. addUser();
  215572. listeners.addIfNotAlreadyThere (listenerToAdd);
  215573. }
  215574. void removeListener (CameraDevice::Listener* listenerToRemove)
  215575. {
  215576. const ScopedLock sl (listenerLock);
  215577. listeners.removeValue (listenerToRemove);
  215578. if (listeners.size() == 0)
  215579. removeUser();
  215580. }
  215581. void callListeners (const Image& image)
  215582. {
  215583. const ScopedLock sl (listenerLock);
  215584. for (int i = listeners.size(); --i >= 0;)
  215585. {
  215586. CameraDevice::Listener* const l = listeners[i];
  215587. if (l != 0)
  215588. l->imageReceived (image);
  215589. }
  215590. }
  215591. class DShowCaptureViewerComp : public Component,
  215592. public ChangeListener
  215593. {
  215594. public:
  215595. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215596. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215597. {
  215598. setOpaque (true);
  215599. owner->addChangeListener (this);
  215600. owner->addUser();
  215601. owner->viewerComps.add (this);
  215602. setSize (owner->width, owner->height);
  215603. }
  215604. ~DShowCaptureViewerComp()
  215605. {
  215606. if (owner != 0)
  215607. {
  215608. owner->viewerComps.removeValue (this);
  215609. owner->removeUser();
  215610. owner->removeChangeListener (this);
  215611. }
  215612. }
  215613. void ownerDeleted()
  215614. {
  215615. owner = 0;
  215616. }
  215617. void paint (Graphics& g)
  215618. {
  215619. g.setColour (Colours::black);
  215620. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215621. if (owner != 0)
  215622. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215623. else
  215624. g.fillAll (Colours::black);
  215625. }
  215626. void changeListenerCallback (ChangeBroadcaster*)
  215627. {
  215628. const int64 now = Time::currentTimeMillis();
  215629. if (now >= lastRepaintTime + (1000 / maxFPS))
  215630. {
  215631. lastRepaintTime = now;
  215632. repaint();
  215633. if (owner != 0)
  215634. maxFPS = owner->getPreviewMaxFPS();
  215635. }
  215636. }
  215637. private:
  215638. DShowCameraDeviceInteral* owner;
  215639. int maxFPS;
  215640. int64 lastRepaintTime;
  215641. };
  215642. bool ok;
  215643. int width, height;
  215644. Time firstRecordedTime;
  215645. Array <DShowCaptureViewerComp*> viewerComps;
  215646. private:
  215647. CameraDevice* const owner;
  215648. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215649. ComSmartPtr <IBaseFilter> filter;
  215650. ComSmartPtr <IBaseFilter> smartTee;
  215651. ComSmartPtr <IGraphBuilder> graphBuilder;
  215652. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215653. ComSmartPtr <IMediaControl> mediaControl;
  215654. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215655. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215656. ComSmartPtr <IBaseFilter> asfWriter;
  215657. int activeUsers;
  215658. Array <int> widths, heights;
  215659. DWORD graphRegistrationID;
  215660. CriticalSection imageSwapLock;
  215661. bool imageNeedsFlipping;
  215662. Image loadingImage;
  215663. Image activeImage;
  215664. bool recordNextFrameTime;
  215665. int previewMaxFPS;
  215666. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215667. {
  215668. widths.clear();
  215669. heights.clear();
  215670. int count = 0, size = 0;
  215671. streamConfig->GetNumberOfCapabilities (&count, &size);
  215672. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215673. {
  215674. for (int i = 0; i < count; ++i)
  215675. {
  215676. VIDEO_STREAM_CONFIG_CAPS scc;
  215677. AM_MEDIA_TYPE* config;
  215678. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215679. if (SUCCEEDED (hr))
  215680. {
  215681. const int w = scc.InputSize.cx;
  215682. const int h = scc.InputSize.cy;
  215683. bool duplicate = false;
  215684. for (int j = widths.size(); --j >= 0;)
  215685. {
  215686. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215687. {
  215688. duplicate = true;
  215689. break;
  215690. }
  215691. }
  215692. if (! duplicate)
  215693. {
  215694. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215695. widths.add (w);
  215696. heights.add (h);
  215697. }
  215698. deleteMediaType (config);
  215699. }
  215700. }
  215701. }
  215702. }
  215703. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215704. const int minWidth, const int minHeight,
  215705. const int maxWidth, const int maxHeight)
  215706. {
  215707. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215708. streamConfig->GetNumberOfCapabilities (&count, &size);
  215709. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215710. {
  215711. AM_MEDIA_TYPE* config;
  215712. VIDEO_STREAM_CONFIG_CAPS scc;
  215713. for (int i = 0; i < count; ++i)
  215714. {
  215715. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215716. if (SUCCEEDED (hr))
  215717. {
  215718. if (scc.InputSize.cx >= minWidth
  215719. && scc.InputSize.cy >= minHeight
  215720. && scc.InputSize.cx <= maxWidth
  215721. && scc.InputSize.cy <= maxHeight)
  215722. {
  215723. int area = scc.InputSize.cx * scc.InputSize.cy;
  215724. if (area > bestArea)
  215725. {
  215726. bestIndex = i;
  215727. bestArea = area;
  215728. }
  215729. }
  215730. deleteMediaType (config);
  215731. }
  215732. }
  215733. if (bestIndex >= 0)
  215734. {
  215735. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215736. hr = streamConfig->SetFormat (config);
  215737. deleteMediaType (config);
  215738. return SUCCEEDED (hr);
  215739. }
  215740. }
  215741. return false;
  215742. }
  215743. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  215744. {
  215745. ComSmartPtr <IEnumPins> enumerator;
  215746. ComSmartPtr <IPin> pin;
  215747. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  215748. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  215749. {
  215750. PIN_DIRECTION dir;
  215751. pin->QueryDirection (&dir);
  215752. if (wantedDirection == dir)
  215753. {
  215754. PIN_INFO info;
  215755. zerostruct (info);
  215756. pin->QueryPinInfo (&info);
  215757. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215758. {
  215759. result = pin;
  215760. return true;
  215761. }
  215762. }
  215763. }
  215764. return false;
  215765. }
  215766. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215767. {
  215768. ComSmartPtr <IPin> in, out;
  215769. return getPin (first, PINDIR_OUTPUT, out)
  215770. && getPin (second, PINDIR_INPUT, in)
  215771. && SUCCEEDED (graphBuilder->Connect (out, in));
  215772. }
  215773. bool addGraphToRot()
  215774. {
  215775. ComSmartPtr <IRunningObjectTable> rot;
  215776. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215777. return false;
  215778. ComSmartPtr <IMoniker> moniker;
  215779. WCHAR buffer[128];
  215780. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  215781. if (FAILED (hr))
  215782. return false;
  215783. graphRegistrationID = 0;
  215784. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215785. }
  215786. void removeGraphFromRot()
  215787. {
  215788. ComSmartPtr <IRunningObjectTable> rot;
  215789. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215790. rot->Revoke (graphRegistrationID);
  215791. }
  215792. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215793. {
  215794. if (pmt->cbFormat != 0)
  215795. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215796. if (pmt->pUnk != 0)
  215797. pmt->pUnk->Release();
  215798. CoTaskMemFree (pmt);
  215799. }
  215800. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215801. {
  215802. public:
  215803. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215804. : owner (owner_)
  215805. {
  215806. }
  215807. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215808. {
  215809. return E_FAIL;
  215810. }
  215811. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215812. {
  215813. owner.handleFrame (time, buffer, bufferSize);
  215814. return S_OK;
  215815. }
  215816. private:
  215817. DShowCameraDeviceInteral& owner;
  215818. GrabberCallback (const GrabberCallback&);
  215819. GrabberCallback& operator= (const GrabberCallback&);
  215820. };
  215821. ComSmartPtr <GrabberCallback> callback;
  215822. Array <CameraDevice::Listener*> listeners;
  215823. CriticalSection listenerLock;
  215824. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  215825. };
  215826. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215827. : name (name_)
  215828. {
  215829. isRecording = false;
  215830. }
  215831. CameraDevice::~CameraDevice()
  215832. {
  215833. stopRecording();
  215834. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215835. internal = 0;
  215836. }
  215837. Component* CameraDevice::createViewerComponent()
  215838. {
  215839. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215840. }
  215841. const String CameraDevice::getFileExtension()
  215842. {
  215843. return ".wmv";
  215844. }
  215845. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215846. {
  215847. stopRecording();
  215848. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215849. d->addUser();
  215850. isRecording = d->createFileCaptureFilter (file, quality);
  215851. }
  215852. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215853. {
  215854. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215855. return d->firstRecordedTime;
  215856. }
  215857. void CameraDevice::stopRecording()
  215858. {
  215859. if (isRecording)
  215860. {
  215861. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215862. d->removeFileCaptureFilter();
  215863. d->removeUser();
  215864. isRecording = false;
  215865. }
  215866. }
  215867. void CameraDevice::addListener (Listener* listenerToAdd)
  215868. {
  215869. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215870. if (listenerToAdd != 0)
  215871. d->addListener (listenerToAdd);
  215872. }
  215873. void CameraDevice::removeListener (Listener* listenerToRemove)
  215874. {
  215875. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215876. if (listenerToRemove != 0)
  215877. d->removeListener (listenerToRemove);
  215878. }
  215879. namespace
  215880. {
  215881. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215882. const int deviceIndexToOpen,
  215883. String& name)
  215884. {
  215885. int index = 0;
  215886. ComSmartPtr <IBaseFilter> result;
  215887. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215888. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215889. if (SUCCEEDED (hr))
  215890. {
  215891. ComSmartPtr <IEnumMoniker> enumerator;
  215892. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  215893. if (SUCCEEDED (hr) && enumerator != 0)
  215894. {
  215895. ComSmartPtr <IMoniker> moniker;
  215896. ULONG fetched;
  215897. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  215898. {
  215899. ComSmartPtr <IBaseFilter> captureFilter;
  215900. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  215901. if (SUCCEEDED (hr))
  215902. {
  215903. ComSmartPtr <IPropertyBag> propertyBag;
  215904. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  215905. if (SUCCEEDED (hr))
  215906. {
  215907. VARIANT var;
  215908. var.vt = VT_BSTR;
  215909. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215910. propertyBag = 0;
  215911. if (SUCCEEDED (hr))
  215912. {
  215913. if (names != 0)
  215914. names->add (var.bstrVal);
  215915. if (index == deviceIndexToOpen)
  215916. {
  215917. name = var.bstrVal;
  215918. result = captureFilter;
  215919. break;
  215920. }
  215921. ++index;
  215922. }
  215923. }
  215924. }
  215925. }
  215926. }
  215927. }
  215928. return result;
  215929. }
  215930. }
  215931. const StringArray CameraDevice::getAvailableDevices()
  215932. {
  215933. StringArray devs;
  215934. String dummy;
  215935. enumerateCameras (&devs, -1, dummy);
  215936. return devs;
  215937. }
  215938. CameraDevice* CameraDevice::openDevice (int index,
  215939. int minWidth, int minHeight,
  215940. int maxWidth, int maxHeight)
  215941. {
  215942. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215943. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215944. if (SUCCEEDED (hr))
  215945. {
  215946. String name;
  215947. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215948. if (filter != 0)
  215949. {
  215950. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215951. DShowCameraDeviceInteral* const intern
  215952. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215953. minWidth, minHeight, maxWidth, maxHeight);
  215954. cam->internal = intern;
  215955. if (intern->ok)
  215956. return cam.release();
  215957. }
  215958. }
  215959. return 0;
  215960. }
  215961. #endif
  215962. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215963. #endif
  215964. // Auto-link the other win32 libs that are needed by library calls..
  215965. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215966. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215967. // Auto-links to various win32 libs that are needed by library calls..
  215968. #pragma comment(lib, "kernel32.lib")
  215969. #pragma comment(lib, "user32.lib")
  215970. #pragma comment(lib, "shell32.lib")
  215971. #pragma comment(lib, "gdi32.lib")
  215972. #pragma comment(lib, "vfw32.lib")
  215973. #pragma comment(lib, "comdlg32.lib")
  215974. #pragma comment(lib, "winmm.lib")
  215975. #pragma comment(lib, "wininet.lib")
  215976. #pragma comment(lib, "ole32.lib")
  215977. #pragma comment(lib, "oleaut32.lib")
  215978. #pragma comment(lib, "advapi32.lib")
  215979. #pragma comment(lib, "ws2_32.lib")
  215980. #pragma comment(lib, "version.lib")
  215981. #pragma comment(lib, "shlwapi.lib")
  215982. #ifdef _NATIVE_WCHAR_T_DEFINED
  215983. #ifdef _DEBUG
  215984. #pragma comment(lib, "comsuppwd.lib")
  215985. #else
  215986. #pragma comment(lib, "comsuppw.lib")
  215987. #endif
  215988. #else
  215989. #ifdef _DEBUG
  215990. #pragma comment(lib, "comsuppd.lib")
  215991. #else
  215992. #pragma comment(lib, "comsupp.lib")
  215993. #endif
  215994. #endif
  215995. #if JUCE_OPENGL
  215996. #pragma comment(lib, "OpenGL32.Lib")
  215997. #pragma comment(lib, "GlU32.Lib")
  215998. #endif
  215999. #if JUCE_QUICKTIME
  216000. #pragma comment (lib, "QTMLClient.lib")
  216001. #endif
  216002. #if JUCE_USE_CAMERA
  216003. #pragma comment (lib, "Strmiids.lib")
  216004. #pragma comment (lib, "wmvcore.lib")
  216005. #endif
  216006. #if JUCE_DIRECT2D
  216007. #pragma comment (lib, "Dwrite.lib")
  216008. #pragma comment (lib, "D2d1.lib")
  216009. #endif
  216010. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216011. #endif
  216012. END_JUCE_NAMESPACE
  216013. #endif
  216014. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216015. #elif JUCE_LINUX
  216016. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216017. /*
  216018. This file wraps together all the mac-specific code, so that
  216019. we can include all the native headers just once, and compile all our
  216020. platform-specific stuff in one big lump, keeping it out of the way of
  216021. the rest of the codebase.
  216022. */
  216023. #if JUCE_LINUX
  216024. #undef JUCE_BUILD_NATIVE
  216025. #define JUCE_BUILD_NATIVE 1
  216026. BEGIN_JUCE_NAMESPACE
  216027. #define JUCE_INCLUDED_FILE 1
  216028. // Now include the actual code files..
  216029. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216030. /*
  216031. This file contains posix routines that are common to both the Linux and Mac builds.
  216032. It gets included directly in the cpp files for these platforms.
  216033. */
  216034. CriticalSection::CriticalSection() throw()
  216035. {
  216036. pthread_mutexattr_t atts;
  216037. pthread_mutexattr_init (&atts);
  216038. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216039. #if ! JUCE_ANDROID
  216040. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216041. #endif
  216042. pthread_mutex_init (&internal, &atts);
  216043. }
  216044. CriticalSection::~CriticalSection() throw()
  216045. {
  216046. pthread_mutex_destroy (&internal);
  216047. }
  216048. void CriticalSection::enter() const throw()
  216049. {
  216050. pthread_mutex_lock (&internal);
  216051. }
  216052. bool CriticalSection::tryEnter() const throw()
  216053. {
  216054. return pthread_mutex_trylock (&internal) == 0;
  216055. }
  216056. void CriticalSection::exit() const throw()
  216057. {
  216058. pthread_mutex_unlock (&internal);
  216059. }
  216060. class WaitableEventImpl
  216061. {
  216062. public:
  216063. WaitableEventImpl (const bool manualReset_)
  216064. : triggered (false),
  216065. manualReset (manualReset_)
  216066. {
  216067. pthread_cond_init (&condition, 0);
  216068. pthread_mutexattr_t atts;
  216069. pthread_mutexattr_init (&atts);
  216070. #if ! JUCE_ANDROID
  216071. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216072. #endif
  216073. pthread_mutex_init (&mutex, &atts);
  216074. }
  216075. ~WaitableEventImpl()
  216076. {
  216077. pthread_cond_destroy (&condition);
  216078. pthread_mutex_destroy (&mutex);
  216079. }
  216080. bool wait (const int timeOutMillisecs) throw()
  216081. {
  216082. pthread_mutex_lock (&mutex);
  216083. if (! triggered)
  216084. {
  216085. if (timeOutMillisecs < 0)
  216086. {
  216087. do
  216088. {
  216089. pthread_cond_wait (&condition, &mutex);
  216090. }
  216091. while (! triggered);
  216092. }
  216093. else
  216094. {
  216095. struct timeval now;
  216096. gettimeofday (&now, 0);
  216097. struct timespec time;
  216098. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216099. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216100. if (time.tv_nsec >= 1000000000)
  216101. {
  216102. time.tv_nsec -= 1000000000;
  216103. time.tv_sec++;
  216104. }
  216105. do
  216106. {
  216107. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216108. {
  216109. pthread_mutex_unlock (&mutex);
  216110. return false;
  216111. }
  216112. }
  216113. while (! triggered);
  216114. }
  216115. }
  216116. if (! manualReset)
  216117. triggered = false;
  216118. pthread_mutex_unlock (&mutex);
  216119. return true;
  216120. }
  216121. void signal() throw()
  216122. {
  216123. pthread_mutex_lock (&mutex);
  216124. triggered = true;
  216125. pthread_cond_broadcast (&condition);
  216126. pthread_mutex_unlock (&mutex);
  216127. }
  216128. void reset() throw()
  216129. {
  216130. pthread_mutex_lock (&mutex);
  216131. triggered = false;
  216132. pthread_mutex_unlock (&mutex);
  216133. }
  216134. private:
  216135. pthread_cond_t condition;
  216136. pthread_mutex_t mutex;
  216137. bool triggered;
  216138. const bool manualReset;
  216139. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216140. };
  216141. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216142. : internal (new WaitableEventImpl (manualReset))
  216143. {
  216144. }
  216145. WaitableEvent::~WaitableEvent() throw()
  216146. {
  216147. delete static_cast <WaitableEventImpl*> (internal);
  216148. }
  216149. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216150. {
  216151. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216152. }
  216153. void WaitableEvent::signal() const throw()
  216154. {
  216155. static_cast <WaitableEventImpl*> (internal)->signal();
  216156. }
  216157. void WaitableEvent::reset() const throw()
  216158. {
  216159. static_cast <WaitableEventImpl*> (internal)->reset();
  216160. }
  216161. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216162. {
  216163. struct timespec time;
  216164. time.tv_sec = millisecs / 1000;
  216165. time.tv_nsec = (millisecs % 1000) * 1000000;
  216166. nanosleep (&time, 0);
  216167. }
  216168. const juce_wchar File::separator = '/';
  216169. const String File::separatorString ("/");
  216170. const File File::getCurrentWorkingDirectory()
  216171. {
  216172. HeapBlock<char> heapBuffer;
  216173. char localBuffer [1024];
  216174. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216175. int bufferSize = 4096;
  216176. while (cwd == 0 && errno == ERANGE)
  216177. {
  216178. heapBuffer.malloc (bufferSize);
  216179. cwd = getcwd (heapBuffer, bufferSize - 1);
  216180. bufferSize += 1024;
  216181. }
  216182. return File (String::fromUTF8 (cwd));
  216183. }
  216184. bool File::setAsCurrentWorkingDirectory() const
  216185. {
  216186. return chdir (getFullPathName().toUTF8()) == 0;
  216187. }
  216188. namespace
  216189. {
  216190. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216191. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216192. #else
  216193. typedef struct stat juce_statStruct;
  216194. #endif
  216195. bool juce_stat (const String& fileName, juce_statStruct& info)
  216196. {
  216197. return fileName.isNotEmpty()
  216198. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216199. && (stat64 (fileName.toUTF8(), &info) == 0);
  216200. #else
  216201. && (stat (fileName.toUTF8(), &info) == 0);
  216202. #endif
  216203. }
  216204. // if this file doesn't exist, find a parent of it that does..
  216205. bool juce_doStatFS (File f, struct statfs& result)
  216206. {
  216207. for (int i = 5; --i >= 0;)
  216208. {
  216209. if (f.exists())
  216210. break;
  216211. f = f.getParentDirectory();
  216212. }
  216213. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216214. }
  216215. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216216. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216217. {
  216218. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216219. {
  216220. juce_statStruct info;
  216221. const bool statOk = juce_stat (path, info);
  216222. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216223. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216224. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216225. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216226. }
  216227. if (isReadOnly != 0)
  216228. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216229. }
  216230. }
  216231. bool File::isDirectory() const
  216232. {
  216233. juce_statStruct info;
  216234. return fullPath.isEmpty()
  216235. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216236. }
  216237. bool File::exists() const
  216238. {
  216239. juce_statStruct info;
  216240. return fullPath.isNotEmpty()
  216241. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216242. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216243. #else
  216244. && (lstat (fullPath.toUTF8(), &info) == 0);
  216245. #endif
  216246. }
  216247. bool File::existsAsFile() const
  216248. {
  216249. return exists() && ! isDirectory();
  216250. }
  216251. int64 File::getSize() const
  216252. {
  216253. juce_statStruct info;
  216254. return juce_stat (fullPath, info) ? info.st_size : 0;
  216255. }
  216256. bool File::hasWriteAccess() const
  216257. {
  216258. if (exists())
  216259. return access (fullPath.toUTF8(), W_OK) == 0;
  216260. if ((! isDirectory()) && fullPath.containsChar (separator))
  216261. return getParentDirectory().hasWriteAccess();
  216262. return false;
  216263. }
  216264. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216265. {
  216266. juce_statStruct info;
  216267. if (! juce_stat (fullPath, info))
  216268. return false;
  216269. info.st_mode &= 0777; // Just permissions
  216270. if (shouldBeReadOnly)
  216271. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216272. else
  216273. // Give everybody write permission?
  216274. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216275. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216276. }
  216277. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216278. {
  216279. modificationTime = 0;
  216280. accessTime = 0;
  216281. creationTime = 0;
  216282. juce_statStruct info;
  216283. if (juce_stat (fullPath, info))
  216284. {
  216285. modificationTime = (int64) info.st_mtime * 1000;
  216286. accessTime = (int64) info.st_atime * 1000;
  216287. creationTime = (int64) info.st_ctime * 1000;
  216288. }
  216289. }
  216290. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216291. {
  216292. juce_statStruct info;
  216293. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216294. {
  216295. struct utimbuf times;
  216296. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216297. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216298. return utime (fullPath.toUTF8(), &times) == 0;
  216299. }
  216300. return false;
  216301. }
  216302. bool File::deleteFile() const
  216303. {
  216304. if (! exists())
  216305. return true;
  216306. if (isDirectory())
  216307. return rmdir (fullPath.toUTF8()) == 0;
  216308. return remove (fullPath.toUTF8()) == 0;
  216309. }
  216310. bool File::moveInternal (const File& dest) const
  216311. {
  216312. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216313. return true;
  216314. if (hasWriteAccess() && copyInternal (dest))
  216315. {
  216316. if (deleteFile())
  216317. return true;
  216318. dest.deleteFile();
  216319. }
  216320. return false;
  216321. }
  216322. void File::createDirectoryInternal (const String& fileName) const
  216323. {
  216324. mkdir (fileName.toUTF8(), 0777);
  216325. }
  216326. int64 juce_fileSetPosition (void* handle, int64 pos)
  216327. {
  216328. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216329. return pos;
  216330. return -1;
  216331. }
  216332. void FileInputStream::openHandle()
  216333. {
  216334. totalSize = file.getSize();
  216335. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216336. if (f != -1)
  216337. fileHandle = (void*) f;
  216338. }
  216339. void FileInputStream::closeHandle()
  216340. {
  216341. if (fileHandle != 0)
  216342. {
  216343. close ((int) (pointer_sized_int) fileHandle);
  216344. fileHandle = 0;
  216345. }
  216346. }
  216347. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216348. {
  216349. if (fileHandle != 0)
  216350. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216351. return 0;
  216352. }
  216353. void FileOutputStream::openHandle()
  216354. {
  216355. if (file.exists())
  216356. {
  216357. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216358. if (f != -1)
  216359. {
  216360. currentPosition = lseek (f, 0, SEEK_END);
  216361. if (currentPosition >= 0)
  216362. fileHandle = (void*) f;
  216363. else
  216364. close (f);
  216365. }
  216366. }
  216367. else
  216368. {
  216369. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216370. if (f != -1)
  216371. fileHandle = (void*) f;
  216372. }
  216373. }
  216374. void FileOutputStream::closeHandle()
  216375. {
  216376. if (fileHandle != 0)
  216377. {
  216378. close ((int) (pointer_sized_int) fileHandle);
  216379. fileHandle = 0;
  216380. }
  216381. }
  216382. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216383. {
  216384. if (fileHandle != 0)
  216385. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216386. return 0;
  216387. }
  216388. void FileOutputStream::flushInternal()
  216389. {
  216390. if (fileHandle != 0)
  216391. fsync ((int) (pointer_sized_int) fileHandle);
  216392. }
  216393. const File juce_getExecutableFile()
  216394. {
  216395. #if JUCE_ANDROID
  216396. // TODO
  216397. return File::nonexistent;
  216398. #else
  216399. Dl_info exeInfo;
  216400. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216401. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216402. #endif
  216403. }
  216404. int64 File::getBytesFreeOnVolume() const
  216405. {
  216406. struct statfs buf;
  216407. if (juce_doStatFS (*this, buf))
  216408. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216409. return 0;
  216410. }
  216411. int64 File::getVolumeTotalSize() const
  216412. {
  216413. struct statfs buf;
  216414. if (juce_doStatFS (*this, buf))
  216415. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216416. return 0;
  216417. }
  216418. const String File::getVolumeLabel() const
  216419. {
  216420. #if JUCE_MAC
  216421. struct VolAttrBuf
  216422. {
  216423. u_int32_t length;
  216424. attrreference_t mountPointRef;
  216425. char mountPointSpace [MAXPATHLEN];
  216426. } attrBuf;
  216427. struct attrlist attrList;
  216428. zerostruct (attrList);
  216429. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216430. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216431. File f (*this);
  216432. for (;;)
  216433. {
  216434. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216435. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216436. (int) attrBuf.mountPointRef.attr_length);
  216437. const File parent (f.getParentDirectory());
  216438. if (f == parent)
  216439. break;
  216440. f = parent;
  216441. }
  216442. #endif
  216443. return String::empty;
  216444. }
  216445. int File::getVolumeSerialNumber() const
  216446. {
  216447. int result = 0;
  216448. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  216449. char info [512];
  216450. #ifndef HDIO_GET_IDENTITY
  216451. #define HDIO_GET_IDENTITY 0x030d
  216452. #endif
  216453. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  216454. {
  216455. DBG (String (info + 20, 20));
  216456. result = String (info + 20, 20).trim().getIntValue();
  216457. }
  216458. close (fd);*/
  216459. return result;
  216460. }
  216461. void juce_runSystemCommand (const String& command)
  216462. {
  216463. int result = system (command.toUTF8());
  216464. (void) result;
  216465. }
  216466. const String juce_getOutputFromCommand (const String& command)
  216467. {
  216468. // slight bodge here, as we just pipe the output into a temp file and read it...
  216469. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216470. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216471. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216472. String result (tempFile.loadFileAsString());
  216473. tempFile.deleteFile();
  216474. return result;
  216475. }
  216476. class InterProcessLock::Pimpl
  216477. {
  216478. public:
  216479. Pimpl (const String& name, const int timeOutMillisecs)
  216480. : handle (0), refCount (1)
  216481. {
  216482. #if JUCE_MAC
  216483. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216484. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216485. #else
  216486. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216487. #endif
  216488. temp.create();
  216489. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216490. if (handle != 0)
  216491. {
  216492. struct flock fl;
  216493. zerostruct (fl);
  216494. fl.l_whence = SEEK_SET;
  216495. fl.l_type = F_WRLCK;
  216496. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216497. for (;;)
  216498. {
  216499. const int result = fcntl (handle, F_SETLK, &fl);
  216500. if (result >= 0)
  216501. return;
  216502. if (errno != EINTR)
  216503. {
  216504. if (timeOutMillisecs == 0
  216505. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216506. break;
  216507. Thread::sleep (10);
  216508. }
  216509. }
  216510. }
  216511. closeFile();
  216512. }
  216513. ~Pimpl()
  216514. {
  216515. closeFile();
  216516. }
  216517. void closeFile()
  216518. {
  216519. if (handle != 0)
  216520. {
  216521. struct flock fl;
  216522. zerostruct (fl);
  216523. fl.l_whence = SEEK_SET;
  216524. fl.l_type = F_UNLCK;
  216525. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216526. {}
  216527. close (handle);
  216528. handle = 0;
  216529. }
  216530. }
  216531. int handle, refCount;
  216532. };
  216533. InterProcessLock::InterProcessLock (const String& name_)
  216534. : name (name_)
  216535. {
  216536. }
  216537. InterProcessLock::~InterProcessLock()
  216538. {
  216539. }
  216540. bool InterProcessLock::enter (const int timeOutMillisecs)
  216541. {
  216542. const ScopedLock sl (lock);
  216543. if (pimpl == 0)
  216544. {
  216545. pimpl = new Pimpl (name, timeOutMillisecs);
  216546. if (pimpl->handle == 0)
  216547. pimpl = 0;
  216548. }
  216549. else
  216550. {
  216551. pimpl->refCount++;
  216552. }
  216553. return pimpl != 0;
  216554. }
  216555. void InterProcessLock::exit()
  216556. {
  216557. const ScopedLock sl (lock);
  216558. // Trying to release the lock too many times!
  216559. jassert (pimpl != 0);
  216560. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216561. pimpl = 0;
  216562. }
  216563. void JUCE_API juce_threadEntryPoint (void*);
  216564. void* threadEntryProc (void* userData)
  216565. {
  216566. JUCE_AUTORELEASEPOOL
  216567. juce_threadEntryPoint (userData);
  216568. return 0;
  216569. }
  216570. void Thread::launchThread()
  216571. {
  216572. threadHandle_ = 0;
  216573. pthread_t handle = 0;
  216574. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216575. {
  216576. pthread_detach (handle);
  216577. threadHandle_ = (void*) handle;
  216578. threadId_ = (ThreadID) threadHandle_;
  216579. }
  216580. }
  216581. void Thread::closeThreadHandle()
  216582. {
  216583. threadId_ = 0;
  216584. threadHandle_ = 0;
  216585. }
  216586. void Thread::killThread()
  216587. {
  216588. if (threadHandle_ != 0)
  216589. {
  216590. #if JUCE_ANDROID
  216591. jassertfalse; // pthread_cancel not available!
  216592. #else
  216593. pthread_cancel ((pthread_t) threadHandle_);
  216594. #endif
  216595. }
  216596. }
  216597. void Thread::setCurrentThreadName (const String& /*name*/)
  216598. {
  216599. }
  216600. bool Thread::setThreadPriority (void* handle, int priority)
  216601. {
  216602. struct sched_param param;
  216603. int policy;
  216604. priority = jlimit (0, 10, priority);
  216605. if (handle == 0)
  216606. handle = (void*) pthread_self();
  216607. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216608. return false;
  216609. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216610. const int minPriority = sched_get_priority_min (policy);
  216611. const int maxPriority = sched_get_priority_max (policy);
  216612. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216613. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216614. }
  216615. Thread::ThreadID Thread::getCurrentThreadId()
  216616. {
  216617. return (ThreadID) pthread_self();
  216618. }
  216619. void Thread::yield()
  216620. {
  216621. sched_yield();
  216622. }
  216623. /* Remove this macro if you're having problems compiling the cpu affinity
  216624. calls (the API for these has changed about quite a bit in various Linux
  216625. versions, and a lot of distros seem to ship with obsolete versions)
  216626. */
  216627. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216628. #define SUPPORT_AFFINITIES 1
  216629. #endif
  216630. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216631. {
  216632. #if SUPPORT_AFFINITIES
  216633. cpu_set_t affinity;
  216634. CPU_ZERO (&affinity);
  216635. for (int i = 0; i < 32; ++i)
  216636. if ((affinityMask & (1 << i)) != 0)
  216637. CPU_SET (i, &affinity);
  216638. /*
  216639. N.B. If this line causes a compile error, then you've probably not got the latest
  216640. version of glibc installed.
  216641. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216642. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216643. */
  216644. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216645. sched_yield();
  216646. #else
  216647. /* affinities aren't supported because either the appropriate header files weren't found,
  216648. or the SUPPORT_AFFINITIES macro was turned off
  216649. */
  216650. jassertfalse;
  216651. (void) affinityMask;
  216652. #endif
  216653. }
  216654. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216655. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216656. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216657. // compiled on its own).
  216658. #if JUCE_INCLUDED_FILE
  216659. enum
  216660. {
  216661. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216662. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216663. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216664. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216665. };
  216666. bool File::copyInternal (const File& dest) const
  216667. {
  216668. FileInputStream in (*this);
  216669. if (dest.deleteFile())
  216670. {
  216671. {
  216672. FileOutputStream out (dest);
  216673. if (out.failedToOpen())
  216674. return false;
  216675. if (out.writeFromInputStream (in, -1) == getSize())
  216676. return true;
  216677. }
  216678. dest.deleteFile();
  216679. }
  216680. return false;
  216681. }
  216682. void File::findFileSystemRoots (Array<File>& destArray)
  216683. {
  216684. destArray.add (File ("/"));
  216685. }
  216686. bool File::isOnCDRomDrive() const
  216687. {
  216688. struct statfs buf;
  216689. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216690. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216691. }
  216692. bool File::isOnHardDisk() const
  216693. {
  216694. struct statfs buf;
  216695. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216696. {
  216697. switch (buf.f_type)
  216698. {
  216699. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216700. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216701. case U_NFS_SUPER_MAGIC: // Network NFS
  216702. case U_SMB_SUPER_MAGIC: // Network Samba
  216703. return false;
  216704. default:
  216705. // Assume anything else is a hard-disk (but note it could
  216706. // be a RAM disk. There isn't a good way of determining
  216707. // this for sure)
  216708. return true;
  216709. }
  216710. }
  216711. // Assume so if this fails for some reason
  216712. return true;
  216713. }
  216714. bool File::isOnRemovableDrive() const
  216715. {
  216716. jassertfalse; // xxx not implemented for linux!
  216717. return false;
  216718. }
  216719. bool File::isHidden() const
  216720. {
  216721. return getFileName().startsWithChar ('.');
  216722. }
  216723. namespace
  216724. {
  216725. const File juce_readlink (const String& file, const File& defaultFile)
  216726. {
  216727. const int size = 8192;
  216728. HeapBlock<char> buffer;
  216729. buffer.malloc (size + 4);
  216730. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  216731. if (numBytes > 0 && numBytes <= size)
  216732. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  216733. return defaultFile;
  216734. }
  216735. }
  216736. const File File::getLinkedTarget() const
  216737. {
  216738. return juce_readlink (getFullPathName().toUTF8(), *this);
  216739. }
  216740. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216741. const File File::getSpecialLocation (const SpecialLocationType type)
  216742. {
  216743. switch (type)
  216744. {
  216745. case userHomeDirectory:
  216746. {
  216747. const char* homeDir = getenv ("HOME");
  216748. if (homeDir == 0)
  216749. {
  216750. struct passwd* const pw = getpwuid (getuid());
  216751. if (pw != 0)
  216752. homeDir = pw->pw_dir;
  216753. }
  216754. return File (String::fromUTF8 (homeDir));
  216755. }
  216756. case userDocumentsDirectory:
  216757. case userMusicDirectory:
  216758. case userMoviesDirectory:
  216759. case userApplicationDataDirectory:
  216760. return File ("~");
  216761. case userDesktopDirectory:
  216762. return File ("~/Desktop");
  216763. case commonApplicationDataDirectory:
  216764. return File ("/var");
  216765. case globalApplicationsDirectory:
  216766. return File ("/usr");
  216767. case tempDirectory:
  216768. {
  216769. File tmp ("/var/tmp");
  216770. if (! tmp.isDirectory())
  216771. {
  216772. tmp = "/tmp";
  216773. if (! tmp.isDirectory())
  216774. tmp = File::getCurrentWorkingDirectory();
  216775. }
  216776. return tmp;
  216777. }
  216778. case invokedExecutableFile:
  216779. if (juce_Argv0 != 0)
  216780. return File (String::fromUTF8 (juce_Argv0));
  216781. // deliberate fall-through...
  216782. case currentExecutableFile:
  216783. case currentApplicationFile:
  216784. return juce_getExecutableFile();
  216785. case hostApplicationPath:
  216786. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  216787. default:
  216788. jassertfalse; // unknown type?
  216789. break;
  216790. }
  216791. return File::nonexistent;
  216792. }
  216793. const String File::getVersion() const
  216794. {
  216795. return String::empty; // xxx not yet implemented
  216796. }
  216797. bool File::moveToTrash() const
  216798. {
  216799. if (! exists())
  216800. return true;
  216801. File trashCan ("~/.Trash");
  216802. if (! trashCan.isDirectory())
  216803. trashCan = "~/.local/share/Trash/files";
  216804. if (! trashCan.isDirectory())
  216805. return false;
  216806. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216807. getFileExtension()));
  216808. }
  216809. class DirectoryIterator::NativeIterator::Pimpl
  216810. {
  216811. public:
  216812. Pimpl (const File& directory, const String& wildCard_)
  216813. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216814. wildCard (wildCard_),
  216815. dir (opendir (directory.getFullPathName().toUTF8()))
  216816. {
  216817. wildcardUTF8 = wildCard.toUTF8();
  216818. }
  216819. ~Pimpl()
  216820. {
  216821. if (dir != 0)
  216822. closedir (dir);
  216823. }
  216824. bool next (String& filenameFound,
  216825. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216826. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216827. {
  216828. if (dir != 0)
  216829. {
  216830. for (;;)
  216831. {
  216832. struct dirent* const de = readdir (dir);
  216833. if (de == 0)
  216834. break;
  216835. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216836. {
  216837. filenameFound = String::fromUTF8 (de->d_name);
  216838. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  216839. if (isHidden != 0)
  216840. *isHidden = filenameFound.startsWithChar ('.');
  216841. return true;
  216842. }
  216843. }
  216844. }
  216845. return false;
  216846. }
  216847. private:
  216848. String parentDir, wildCard;
  216849. const char* wildcardUTF8;
  216850. DIR* dir;
  216851. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  216852. };
  216853. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216854. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216855. {
  216856. }
  216857. DirectoryIterator::NativeIterator::~NativeIterator()
  216858. {
  216859. }
  216860. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216861. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216862. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216863. {
  216864. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216865. }
  216866. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216867. {
  216868. String cmdString (fileName.replace (" ", "\\ ",false));
  216869. cmdString << " " << parameters;
  216870. if (URL::isProbablyAWebsiteURL (fileName)
  216871. || cmdString.startsWithIgnoreCase ("file:")
  216872. || URL::isProbablyAnEmailAddress (fileName))
  216873. {
  216874. // create a command that tries to launch a bunch of likely browsers
  216875. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216876. StringArray cmdLines;
  216877. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216878. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216879. cmdString = cmdLines.joinIntoString (" || ");
  216880. }
  216881. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216882. const int cpid = fork();
  216883. if (cpid == 0)
  216884. {
  216885. setsid();
  216886. // Child process
  216887. execve (argv[0], (char**) argv, environ);
  216888. exit (0);
  216889. }
  216890. return cpid >= 0;
  216891. }
  216892. void File::revealToUser() const
  216893. {
  216894. if (isDirectory())
  216895. startAsProcess();
  216896. else if (getParentDirectory().exists())
  216897. getParentDirectory().startAsProcess();
  216898. }
  216899. #endif
  216900. /*** End of inlined file: juce_linux_Files.cpp ***/
  216901. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216902. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216903. // compiled on its own).
  216904. #if JUCE_INCLUDED_FILE
  216905. struct NamedPipeInternal
  216906. {
  216907. String pipeInName, pipeOutName;
  216908. int pipeIn, pipeOut;
  216909. bool volatile createdPipe, blocked, stopReadOperation;
  216910. static void signalHandler (int) {}
  216911. };
  216912. void NamedPipe::cancelPendingReads()
  216913. {
  216914. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  216915. {
  216916. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216917. intern->stopReadOperation = true;
  216918. char buffer [1] = { 0 };
  216919. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216920. (void) bytesWritten;
  216921. int timeout = 2000;
  216922. while (intern->blocked && --timeout >= 0)
  216923. Thread::sleep (2);
  216924. intern->stopReadOperation = false;
  216925. }
  216926. }
  216927. void NamedPipe::close()
  216928. {
  216929. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216930. if (intern != 0)
  216931. {
  216932. internal = 0;
  216933. if (intern->pipeIn != -1)
  216934. ::close (intern->pipeIn);
  216935. if (intern->pipeOut != -1)
  216936. ::close (intern->pipeOut);
  216937. if (intern->createdPipe)
  216938. {
  216939. unlink (intern->pipeInName.toUTF8());
  216940. unlink (intern->pipeOutName.toUTF8());
  216941. }
  216942. delete intern;
  216943. }
  216944. }
  216945. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216946. {
  216947. close();
  216948. NamedPipeInternal* const intern = new NamedPipeInternal();
  216949. internal = intern;
  216950. intern->createdPipe = createPipe;
  216951. intern->blocked = false;
  216952. intern->stopReadOperation = false;
  216953. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216954. siginterrupt (SIGPIPE, 1);
  216955. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216956. intern->pipeInName = pipePath + "_in";
  216957. intern->pipeOutName = pipePath + "_out";
  216958. intern->pipeIn = -1;
  216959. intern->pipeOut = -1;
  216960. if (createPipe)
  216961. {
  216962. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216963. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216964. {
  216965. delete intern;
  216966. internal = 0;
  216967. return false;
  216968. }
  216969. }
  216970. return true;
  216971. }
  216972. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216973. {
  216974. int bytesRead = -1;
  216975. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216976. if (intern != 0)
  216977. {
  216978. intern->blocked = true;
  216979. if (intern->pipeIn == -1)
  216980. {
  216981. if (intern->createdPipe)
  216982. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216983. else
  216984. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216985. if (intern->pipeIn == -1)
  216986. {
  216987. intern->blocked = false;
  216988. return -1;
  216989. }
  216990. }
  216991. bytesRead = 0;
  216992. char* p = static_cast<char*> (destBuffer);
  216993. while (bytesRead < maxBytesToRead)
  216994. {
  216995. const int bytesThisTime = maxBytesToRead - bytesRead;
  216996. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216997. if (numRead <= 0 || intern->stopReadOperation)
  216998. {
  216999. bytesRead = -1;
  217000. break;
  217001. }
  217002. bytesRead += numRead;
  217003. p += bytesRead;
  217004. }
  217005. intern->blocked = false;
  217006. }
  217007. return bytesRead;
  217008. }
  217009. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217010. {
  217011. int bytesWritten = -1;
  217012. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217013. if (intern != 0)
  217014. {
  217015. if (intern->pipeOut == -1)
  217016. {
  217017. if (intern->createdPipe)
  217018. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217019. else
  217020. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217021. if (intern->pipeOut == -1)
  217022. {
  217023. return -1;
  217024. }
  217025. }
  217026. const char* p = static_cast<const char*> (sourceBuffer);
  217027. bytesWritten = 0;
  217028. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217029. while (bytesWritten < numBytesToWrite
  217030. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217031. {
  217032. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217033. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217034. if (numWritten <= 0)
  217035. {
  217036. bytesWritten = -1;
  217037. break;
  217038. }
  217039. bytesWritten += numWritten;
  217040. p += bytesWritten;
  217041. }
  217042. }
  217043. return bytesWritten;
  217044. }
  217045. #endif
  217046. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217047. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217048. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217049. // compiled on its own).
  217050. #if JUCE_INCLUDED_FILE
  217051. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217052. {
  217053. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217054. if (s != -1)
  217055. {
  217056. char buf [1024];
  217057. struct ifconf ifc;
  217058. ifc.ifc_len = sizeof (buf);
  217059. ifc.ifc_buf = buf;
  217060. ioctl (s, SIOCGIFCONF, &ifc);
  217061. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217062. {
  217063. struct ifreq ifr;
  217064. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217065. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217066. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217067. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217068. {
  217069. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217070. }
  217071. }
  217072. close (s);
  217073. }
  217074. }
  217075. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217076. const String& emailSubject,
  217077. const String& bodyText,
  217078. const StringArray& filesToAttach)
  217079. {
  217080. jassertfalse; // xxx todo
  217081. return false;
  217082. }
  217083. class WebInputStream : public InputStream
  217084. {
  217085. public:
  217086. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217087. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217088. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217089. : socketHandle (-1), levelsOfRedirection (0),
  217090. address (address_), headers (headers_), postData (postData_), position (0),
  217091. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217092. {
  217093. createConnection (progressCallback, progressCallbackContext);
  217094. if (responseHeaders != 0 && ! isError())
  217095. {
  217096. for (int i = 0; i < headerLines.size(); ++i)
  217097. {
  217098. const String& headersEntry = headerLines[i];
  217099. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217100. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217101. const String previousValue ((*responseHeaders) [key]);
  217102. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217103. }
  217104. }
  217105. }
  217106. ~WebInputStream()
  217107. {
  217108. closeSocket();
  217109. }
  217110. bool isError() const { return socketHandle < 0; }
  217111. bool isExhausted() { return finished; }
  217112. int64 getPosition() { return position; }
  217113. int64 getTotalLength()
  217114. {
  217115. jassertfalse; //xxx to do
  217116. return -1;
  217117. }
  217118. int read (void* buffer, int bytesToRead)
  217119. {
  217120. if (finished || isError())
  217121. return 0;
  217122. fd_set readbits;
  217123. FD_ZERO (&readbits);
  217124. FD_SET (socketHandle, &readbits);
  217125. struct timeval tv;
  217126. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217127. tv.tv_usec = 0;
  217128. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217129. return 0; // (timeout)
  217130. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217131. if (bytesRead == 0)
  217132. finished = true;
  217133. position += bytesRead;
  217134. return bytesRead;
  217135. }
  217136. bool setPosition (int64 wantedPos)
  217137. {
  217138. if (isError())
  217139. return false;
  217140. if (wantedPos != position)
  217141. {
  217142. finished = false;
  217143. if (wantedPos < position)
  217144. {
  217145. closeSocket();
  217146. position = 0;
  217147. createConnection (0, 0);
  217148. }
  217149. skipNextBytes (wantedPos - position);
  217150. }
  217151. return true;
  217152. }
  217153. private:
  217154. int socketHandle, levelsOfRedirection;
  217155. StringArray headerLines;
  217156. String address, headers;
  217157. MemoryBlock postData;
  217158. int64 position;
  217159. bool finished;
  217160. const bool isPost;
  217161. const int timeOutMs;
  217162. void closeSocket()
  217163. {
  217164. if (socketHandle >= 0)
  217165. close (socketHandle);
  217166. socketHandle = -1;
  217167. levelsOfRedirection = 0;
  217168. }
  217169. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217170. {
  217171. closeSocket();
  217172. uint32 timeOutTime = Time::getMillisecondCounter();
  217173. if (timeOutMs == 0)
  217174. timeOutTime += 60000;
  217175. else if (timeOutMs < 0)
  217176. timeOutTime = 0xffffffff;
  217177. else
  217178. timeOutTime += timeOutMs;
  217179. String hostName, hostPath;
  217180. int hostPort;
  217181. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217182. return;
  217183. const struct hostent* host = 0;
  217184. int port = 0;
  217185. String proxyName, proxyPath;
  217186. int proxyPort = 0;
  217187. String proxyURL (getenv ("http_proxy"));
  217188. if (proxyURL.startsWithIgnoreCase ("http://"))
  217189. {
  217190. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217191. return;
  217192. host = gethostbyname (proxyName.toUTF8());
  217193. port = proxyPort;
  217194. }
  217195. else
  217196. {
  217197. host = gethostbyname (hostName.toUTF8());
  217198. port = hostPort;
  217199. }
  217200. if (host == 0)
  217201. return;
  217202. {
  217203. struct sockaddr_in socketAddress;
  217204. zerostruct (socketAddress);
  217205. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217206. socketAddress.sin_family = host->h_addrtype;
  217207. socketAddress.sin_port = htons (port);
  217208. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217209. if (socketHandle == -1)
  217210. return;
  217211. int receiveBufferSize = 16384;
  217212. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217213. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217214. #if JUCE_MAC
  217215. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217216. #endif
  217217. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217218. {
  217219. closeSocket();
  217220. return;
  217221. }
  217222. }
  217223. {
  217224. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217225. hostPath, address, headers, postData, isPost));
  217226. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217227. {
  217228. closeSocket();
  217229. return;
  217230. }
  217231. }
  217232. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217233. if (responseHeader.isNotEmpty())
  217234. {
  217235. headerLines.clear();
  217236. headerLines.addLines (responseHeader);
  217237. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217238. .substring (0, 3).getIntValue();
  217239. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217240. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217241. String location (findHeaderItem (headerLines, "Location:"));
  217242. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217243. {
  217244. if (! location.startsWithIgnoreCase ("http://"))
  217245. location = "http://" + location;
  217246. if (++levelsOfRedirection <= 3)
  217247. {
  217248. address = location;
  217249. createConnection (progressCallback, progressCallbackContext);
  217250. return;
  217251. }
  217252. }
  217253. else
  217254. {
  217255. levelsOfRedirection = 0;
  217256. return;
  217257. }
  217258. }
  217259. closeSocket();
  217260. }
  217261. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217262. {
  217263. int bytesRead = 0, numConsecutiveLFs = 0;
  217264. MemoryBlock buffer (1024, true);
  217265. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217266. && Time::getMillisecondCounter() <= timeOutTime)
  217267. {
  217268. fd_set readbits;
  217269. FD_ZERO (&readbits);
  217270. FD_SET (socketHandle, &readbits);
  217271. struct timeval tv;
  217272. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217273. tv.tv_usec = 0;
  217274. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217275. return String::empty; // (timeout)
  217276. buffer.ensureSize (bytesRead + 8, true);
  217277. char* const dest = (char*) buffer.getData() + bytesRead;
  217278. if (recv (socketHandle, dest, 1, 0) == -1)
  217279. return String::empty;
  217280. const char lastByte = *dest;
  217281. ++bytesRead;
  217282. if (lastByte == '\n')
  217283. ++numConsecutiveLFs;
  217284. else if (lastByte != '\r')
  217285. numConsecutiveLFs = 0;
  217286. }
  217287. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217288. if (header.startsWithIgnoreCase ("HTTP/"))
  217289. return header.trimEnd();
  217290. return String::empty;
  217291. }
  217292. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217293. const String& proxyName, const int proxyPort,
  217294. const String& hostPath, const String& originalURL,
  217295. const String& headers, const MemoryBlock& postData,
  217296. const bool isPost)
  217297. {
  217298. String header (isPost ? "POST " : "GET ");
  217299. if (proxyName.isEmpty())
  217300. {
  217301. header << hostPath << " HTTP/1.0\r\nHost: "
  217302. << hostName << ':' << hostPort;
  217303. }
  217304. else
  217305. {
  217306. header << originalURL << " HTTP/1.0\r\nHost: "
  217307. << proxyName << ':' << proxyPort;
  217308. }
  217309. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217310. << "\r\nConnection: Close\r\nContent-Length: "
  217311. << (int) postData.getSize() << "\r\n"
  217312. << headers << "\r\n";
  217313. MemoryBlock mb;
  217314. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217315. mb.append (postData.getData(), postData.getSize());
  217316. return mb;
  217317. }
  217318. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217319. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217320. {
  217321. size_t totalHeaderSent = 0;
  217322. while (totalHeaderSent < requestHeader.getSize())
  217323. {
  217324. if (Time::getMillisecondCounter() > timeOutTime)
  217325. return false;
  217326. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217327. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217328. return false;
  217329. totalHeaderSent += numToSend;
  217330. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217331. return false;
  217332. }
  217333. return true;
  217334. }
  217335. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217336. {
  217337. if (! url.startsWithIgnoreCase ("http://"))
  217338. return false;
  217339. const int nextSlash = url.indexOfChar (7, '/');
  217340. int nextColon = url.indexOfChar (7, ':');
  217341. if (nextColon > nextSlash && nextSlash > 0)
  217342. nextColon = -1;
  217343. if (nextColon >= 0)
  217344. {
  217345. host = url.substring (7, nextColon);
  217346. if (nextSlash >= 0)
  217347. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217348. else
  217349. port = url.substring (nextColon + 1).getIntValue();
  217350. }
  217351. else
  217352. {
  217353. port = 80;
  217354. if (nextSlash >= 0)
  217355. host = url.substring (7, nextSlash);
  217356. else
  217357. host = url.substring (7);
  217358. }
  217359. if (nextSlash >= 0)
  217360. path = url.substring (nextSlash);
  217361. else
  217362. path = "/";
  217363. return true;
  217364. }
  217365. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217366. {
  217367. for (int i = 0; i < lines.size(); ++i)
  217368. if (lines[i].startsWithIgnoreCase (itemName))
  217369. return lines[i].substring (itemName.length()).trim();
  217370. return String::empty;
  217371. }
  217372. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217373. };
  217374. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217375. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217376. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217377. {
  217378. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217379. progressCallback, progressCallbackContext,
  217380. headers, timeOutMs, responseHeaders));
  217381. return wi->isError() ? 0 : wi.release();
  217382. }
  217383. #endif
  217384. /*** End of inlined file: juce_linux_Network.cpp ***/
  217385. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217386. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217387. // compiled on its own).
  217388. #if JUCE_INCLUDED_FILE
  217389. void Logger::outputDebugString (const String& text)
  217390. {
  217391. std::cerr << text << std::endl;
  217392. }
  217393. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217394. {
  217395. return Linux;
  217396. }
  217397. const String SystemStats::getOperatingSystemName()
  217398. {
  217399. return "Linux";
  217400. }
  217401. bool SystemStats::isOperatingSystem64Bit()
  217402. {
  217403. #if JUCE_64BIT
  217404. return true;
  217405. #else
  217406. //xxx not sure how to find this out?..
  217407. return false;
  217408. #endif
  217409. }
  217410. namespace LinuxStatsHelpers
  217411. {
  217412. const String getCpuInfo (const char* const key)
  217413. {
  217414. StringArray lines;
  217415. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217416. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217417. if (lines[i].startsWithIgnoreCase (key))
  217418. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217419. return String::empty;
  217420. }
  217421. }
  217422. const String SystemStats::getCpuVendor()
  217423. {
  217424. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217425. }
  217426. int SystemStats::getCpuSpeedInMegaherz()
  217427. {
  217428. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217429. }
  217430. int SystemStats::getMemorySizeInMegabytes()
  217431. {
  217432. struct sysinfo sysi;
  217433. if (sysinfo (&sysi) == 0)
  217434. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217435. return 0;
  217436. }
  217437. int SystemStats::getPageSize()
  217438. {
  217439. return sysconf (_SC_PAGESIZE);
  217440. }
  217441. const String SystemStats::getLogonName()
  217442. {
  217443. const char* user = getenv ("USER");
  217444. if (user == 0)
  217445. {
  217446. struct passwd* const pw = getpwuid (getuid());
  217447. if (pw != 0)
  217448. user = pw->pw_name;
  217449. }
  217450. return String::fromUTF8 (user);
  217451. }
  217452. const String SystemStats::getFullUserName()
  217453. {
  217454. return getLogonName();
  217455. }
  217456. void SystemStats::initialiseStats()
  217457. {
  217458. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217459. cpuFlags.hasMMX = flags.contains ("mmx");
  217460. cpuFlags.hasSSE = flags.contains ("sse");
  217461. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217462. cpuFlags.has3DNow = flags.contains ("3dnow");
  217463. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217464. }
  217465. void PlatformUtilities::fpuReset()
  217466. {
  217467. }
  217468. uint32 juce_millisecondsSinceStartup() throw()
  217469. {
  217470. timespec t;
  217471. clock_gettime (CLOCK_MONOTONIC, &t);
  217472. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217473. }
  217474. int64 Time::getHighResolutionTicks() throw()
  217475. {
  217476. timespec t;
  217477. clock_gettime (CLOCK_MONOTONIC, &t);
  217478. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217479. }
  217480. int64 Time::getHighResolutionTicksPerSecond() throw()
  217481. {
  217482. return 1000000; // (microseconds)
  217483. }
  217484. double Time::getMillisecondCounterHiRes() throw()
  217485. {
  217486. return getHighResolutionTicks() * 0.001;
  217487. }
  217488. bool Time::setSystemTimeToThisTime() const
  217489. {
  217490. timeval t;
  217491. t.tv_sec = millisSinceEpoch / 1000;
  217492. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217493. return settimeofday (&t, 0) == 0;
  217494. }
  217495. #endif
  217496. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217497. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217498. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217499. // compiled on its own).
  217500. #if JUCE_INCLUDED_FILE
  217501. /*
  217502. Note that a lot of methods that you'd expect to find in this file actually
  217503. live in juce_posix_SharedCode.h!
  217504. */
  217505. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217506. void Process::setPriority (ProcessPriority prior)
  217507. {
  217508. struct sched_param param;
  217509. int policy, maxp, minp;
  217510. const int p = (int) prior;
  217511. if (p <= 1)
  217512. policy = SCHED_OTHER;
  217513. else
  217514. policy = SCHED_RR;
  217515. minp = sched_get_priority_min (policy);
  217516. maxp = sched_get_priority_max (policy);
  217517. if (p < 2)
  217518. param.sched_priority = 0;
  217519. else if (p == 2 )
  217520. // Set to middle of lower realtime priority range
  217521. param.sched_priority = minp + (maxp - minp) / 4;
  217522. else
  217523. // Set to middle of higher realtime priority range
  217524. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217525. pthread_setschedparam (pthread_self(), policy, &param);
  217526. }
  217527. void Process::terminate()
  217528. {
  217529. exit (0);
  217530. }
  217531. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217532. {
  217533. static char testResult = 0;
  217534. if (testResult == 0)
  217535. {
  217536. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217537. if (testResult >= 0)
  217538. {
  217539. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217540. testResult = 1;
  217541. }
  217542. }
  217543. return testResult < 0;
  217544. }
  217545. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217546. {
  217547. return juce_isRunningUnderDebugger();
  217548. }
  217549. void Process::raisePrivilege()
  217550. {
  217551. // If running suid root, change effective user
  217552. // to root
  217553. if (geteuid() != 0 && getuid() == 0)
  217554. {
  217555. setreuid (geteuid(), getuid());
  217556. setregid (getegid(), getgid());
  217557. }
  217558. }
  217559. void Process::lowerPrivilege()
  217560. {
  217561. // If runing suid root, change effective user
  217562. // back to real user
  217563. if (geteuid() == 0 && getuid() != 0)
  217564. {
  217565. setreuid (geteuid(), getuid());
  217566. setregid (getegid(), getgid());
  217567. }
  217568. }
  217569. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217570. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217571. {
  217572. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217573. }
  217574. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217575. {
  217576. dlclose(handle);
  217577. }
  217578. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217579. {
  217580. return dlsym (libraryHandle, procedureName.toCString());
  217581. }
  217582. #endif
  217583. #endif
  217584. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217585. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217586. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217587. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217588. // compiled on its own).
  217589. #if JUCE_INCLUDED_FILE
  217590. extern Display* display;
  217591. extern Window juce_messageWindowHandle;
  217592. namespace ClipboardHelpers
  217593. {
  217594. static String localClipboardContent;
  217595. static Atom atom_UTF8_STRING;
  217596. static Atom atom_CLIPBOARD;
  217597. static Atom atom_TARGETS;
  217598. static void initSelectionAtoms()
  217599. {
  217600. static bool isInitialised = false;
  217601. if (! isInitialised)
  217602. {
  217603. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217604. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217605. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217606. }
  217607. }
  217608. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217609. // works only for strings shorter than 1000000 bytes
  217610. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217611. {
  217612. String returnData;
  217613. char* clipData;
  217614. Atom actualType;
  217615. int actualFormat;
  217616. unsigned long numItems, bytesLeft;
  217617. if (XGetWindowProperty (display, window, prop,
  217618. 0L /* offset */, 1000000 /* length (max) */, False,
  217619. AnyPropertyType /* format */,
  217620. &actualType, &actualFormat, &numItems, &bytesLeft,
  217621. (unsigned char**) &clipData) == Success)
  217622. {
  217623. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217624. returnData = String::fromUTF8 (clipData, numItems);
  217625. else if (actualType == XA_STRING && actualFormat == 8)
  217626. returnData = String (clipData, numItems);
  217627. if (clipData != 0)
  217628. XFree (clipData);
  217629. jassert (bytesLeft == 0 || numItems == 1000000);
  217630. }
  217631. XDeleteProperty (display, window, prop);
  217632. return returnData;
  217633. }
  217634. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217635. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217636. {
  217637. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217638. // The selection owner will be asked to set the JUCE_SEL property on the
  217639. // juce_messageWindowHandle with the selection content
  217640. XConvertSelection (display, selection, requestedFormat, property_name,
  217641. juce_messageWindowHandle, CurrentTime);
  217642. int count = 50; // will wait at most for 200 ms
  217643. while (--count >= 0)
  217644. {
  217645. XEvent event;
  217646. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217647. {
  217648. if (event.xselection.property == property_name)
  217649. {
  217650. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217651. selectionContent = readWindowProperty (event.xselection.requestor,
  217652. event.xselection.property,
  217653. requestedFormat);
  217654. return true;
  217655. }
  217656. else
  217657. {
  217658. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217659. }
  217660. }
  217661. // not very elegant.. we could do a select() or something like that...
  217662. // however clipboard content requesting is inherently slow on x11, it
  217663. // often takes 50ms or more so...
  217664. Thread::sleep (4);
  217665. }
  217666. return false;
  217667. }
  217668. }
  217669. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217670. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217671. {
  217672. ClipboardHelpers::initSelectionAtoms();
  217673. // the selection content is sent to the target window as a window property
  217674. XSelectionEvent reply;
  217675. reply.type = SelectionNotify;
  217676. reply.display = evt.display;
  217677. reply.requestor = evt.requestor;
  217678. reply.selection = evt.selection;
  217679. reply.target = evt.target;
  217680. reply.property = None; // == "fail"
  217681. reply.time = evt.time;
  217682. HeapBlock <char> data;
  217683. int propertyFormat = 0, numDataItems = 0;
  217684. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217685. {
  217686. if (evt.target == XA_STRING)
  217687. {
  217688. // format data according to system locale
  217689. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217690. data.calloc (numDataItems + 1);
  217691. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217692. propertyFormat = 8; // bits/item
  217693. }
  217694. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217695. {
  217696. // translate to utf8
  217697. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217698. data.calloc (numDataItems + 1);
  217699. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217700. propertyFormat = 8; // bits/item
  217701. }
  217702. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217703. {
  217704. // another application wants to know what we are able to send
  217705. numDataItems = 2;
  217706. propertyFormat = 32; // atoms are 32-bit
  217707. data.calloc (numDataItems * 4);
  217708. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217709. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217710. atoms[1] = XA_STRING;
  217711. }
  217712. }
  217713. else
  217714. {
  217715. DBG ("requested unsupported clipboard");
  217716. }
  217717. if (data != 0)
  217718. {
  217719. const int maxReasonableSelectionSize = 1000000;
  217720. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217721. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217722. {
  217723. XChangeProperty (evt.display, evt.requestor,
  217724. evt.property, evt.target,
  217725. propertyFormat /* 8 or 32 */, PropModeReplace,
  217726. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217727. reply.property = evt.property; // " == success"
  217728. }
  217729. }
  217730. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217731. }
  217732. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217733. {
  217734. ClipboardHelpers::initSelectionAtoms();
  217735. ClipboardHelpers::localClipboardContent = clipText;
  217736. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217737. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217738. }
  217739. const String SystemClipboard::getTextFromClipboard()
  217740. {
  217741. ClipboardHelpers::initSelectionAtoms();
  217742. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217743. level" clipboard that is supposed to be filled by ctrl-C
  217744. etc). When a clipboard manager is running, the content of this
  217745. selection is preserved even when the original selection owner
  217746. exits.
  217747. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217748. filled by good old x11 apps such as xterm)
  217749. */
  217750. String content;
  217751. Atom selection = XA_PRIMARY;
  217752. Window selectionOwner = None;
  217753. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217754. {
  217755. selection = ClipboardHelpers::atom_CLIPBOARD;
  217756. selectionOwner = XGetSelectionOwner (display, selection);
  217757. }
  217758. if (selectionOwner != None)
  217759. {
  217760. if (selectionOwner == juce_messageWindowHandle)
  217761. {
  217762. content = ClipboardHelpers::localClipboardContent;
  217763. }
  217764. else
  217765. {
  217766. // first try: we want an utf8 string
  217767. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217768. if (! ok)
  217769. {
  217770. // second chance, ask for a good old locale-dependent string ..
  217771. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217772. }
  217773. }
  217774. }
  217775. return content;
  217776. }
  217777. #endif
  217778. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217779. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217780. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217781. // compiled on its own).
  217782. #if JUCE_INCLUDED_FILE
  217783. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217784. #define JUCE_DEBUG_XERRORS 1
  217785. #endif
  217786. Display* display = 0;
  217787. Window juce_messageWindowHandle = None;
  217788. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217789. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217790. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217791. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217792. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217793. class InternalMessageQueue
  217794. {
  217795. public:
  217796. InternalMessageQueue()
  217797. : bytesInSocket (0),
  217798. totalEventCount (0)
  217799. {
  217800. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217801. (void) ret; jassert (ret == 0);
  217802. //setNonBlocking (fd[0]);
  217803. //setNonBlocking (fd[1]);
  217804. }
  217805. ~InternalMessageQueue()
  217806. {
  217807. close (fd[0]);
  217808. close (fd[1]);
  217809. clearSingletonInstance();
  217810. }
  217811. void postMessage (Message* msg)
  217812. {
  217813. const int maxBytesInSocketQueue = 128;
  217814. ScopedLock sl (lock);
  217815. queue.add (msg);
  217816. if (bytesInSocket < maxBytesInSocketQueue)
  217817. {
  217818. ++bytesInSocket;
  217819. ScopedUnlock ul (lock);
  217820. const unsigned char x = 0xff;
  217821. size_t bytesWritten = write (fd[0], &x, 1);
  217822. (void) bytesWritten;
  217823. }
  217824. }
  217825. bool isEmpty() const
  217826. {
  217827. ScopedLock sl (lock);
  217828. return queue.size() == 0;
  217829. }
  217830. bool dispatchNextEvent()
  217831. {
  217832. // This alternates between giving priority to XEvents or internal messages,
  217833. // to keep everything running smoothly..
  217834. if ((++totalEventCount & 1) != 0)
  217835. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217836. else
  217837. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217838. }
  217839. // Wait for an event (either XEvent, or an internal Message)
  217840. bool sleepUntilEvent (const int timeoutMs)
  217841. {
  217842. if (! isEmpty())
  217843. return true;
  217844. if (display != 0)
  217845. {
  217846. ScopedXLock xlock;
  217847. if (XPending (display))
  217848. return true;
  217849. }
  217850. struct timeval tv;
  217851. tv.tv_sec = 0;
  217852. tv.tv_usec = timeoutMs * 1000;
  217853. int fd0 = getWaitHandle();
  217854. int fdmax = fd0;
  217855. fd_set readset;
  217856. FD_ZERO (&readset);
  217857. FD_SET (fd0, &readset);
  217858. if (display != 0)
  217859. {
  217860. ScopedXLock xlock;
  217861. int fd1 = XConnectionNumber (display);
  217862. FD_SET (fd1, &readset);
  217863. fdmax = jmax (fd0, fd1);
  217864. }
  217865. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217866. return (ret > 0); // ret <= 0 if error or timeout
  217867. }
  217868. struct MessageThreadFuncCall
  217869. {
  217870. enum { uniqueID = 0x73774623 };
  217871. MessageCallbackFunction* func;
  217872. void* parameter;
  217873. void* result;
  217874. CriticalSection lock;
  217875. WaitableEvent event;
  217876. };
  217877. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217878. private:
  217879. CriticalSection lock;
  217880. ReferenceCountedArray <Message> queue;
  217881. int fd[2];
  217882. int bytesInSocket;
  217883. int totalEventCount;
  217884. int getWaitHandle() const throw() { return fd[1]; }
  217885. static bool setNonBlocking (int handle)
  217886. {
  217887. int socketFlags = fcntl (handle, F_GETFL, 0);
  217888. if (socketFlags == -1)
  217889. return false;
  217890. socketFlags |= O_NONBLOCK;
  217891. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217892. }
  217893. static bool dispatchNextXEvent()
  217894. {
  217895. if (display == 0)
  217896. return false;
  217897. XEvent evt;
  217898. {
  217899. ScopedXLock xlock;
  217900. if (! XPending (display))
  217901. return false;
  217902. XNextEvent (display, &evt);
  217903. }
  217904. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217905. juce_handleSelectionRequest (evt.xselectionrequest);
  217906. else if (evt.xany.window != juce_messageWindowHandle)
  217907. juce_windowMessageReceive (&evt);
  217908. return true;
  217909. }
  217910. const Message::Ptr popNextMessage()
  217911. {
  217912. const ScopedLock sl (lock);
  217913. if (bytesInSocket > 0)
  217914. {
  217915. --bytesInSocket;
  217916. const ScopedUnlock ul (lock);
  217917. unsigned char x;
  217918. size_t numBytes = read (fd[1], &x, 1);
  217919. (void) numBytes;
  217920. }
  217921. return queue.removeAndReturn (0);
  217922. }
  217923. bool dispatchNextInternalMessage()
  217924. {
  217925. const Message::Ptr msg (popNextMessage());
  217926. if (msg == 0)
  217927. return false;
  217928. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217929. {
  217930. // Handle callback message
  217931. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217932. call->result = (*(call->func)) (call->parameter);
  217933. call->event.signal();
  217934. }
  217935. else
  217936. {
  217937. // Handle "normal" messages
  217938. MessageManager::getInstance()->deliverMessage (msg);
  217939. }
  217940. return true;
  217941. }
  217942. };
  217943. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217944. namespace LinuxErrorHandling
  217945. {
  217946. static bool errorOccurred = false;
  217947. static bool keyboardBreakOccurred = false;
  217948. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217949. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217950. // Usually happens when client-server connection is broken
  217951. static int ioErrorHandler (Display* display)
  217952. {
  217953. DBG ("ERROR: connection to X server broken.. terminating.");
  217954. if (JUCEApplication::isStandaloneApp())
  217955. MessageManager::getInstance()->stopDispatchLoop();
  217956. errorOccurred = true;
  217957. return 0;
  217958. }
  217959. // A protocol error has occurred
  217960. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217961. {
  217962. #if JUCE_DEBUG_XERRORS
  217963. char errorStr[64] = { 0 };
  217964. char requestStr[64] = { 0 };
  217965. XGetErrorText (display, event->error_code, errorStr, 64);
  217966. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217967. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217968. #endif
  217969. return 0;
  217970. }
  217971. static void installXErrorHandlers()
  217972. {
  217973. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217974. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217975. }
  217976. static void removeXErrorHandlers()
  217977. {
  217978. if (JUCEApplication::isStandaloneApp())
  217979. {
  217980. XSetIOErrorHandler (oldIOErrorHandler);
  217981. oldIOErrorHandler = 0;
  217982. XSetErrorHandler (oldErrorHandler);
  217983. oldErrorHandler = 0;
  217984. }
  217985. }
  217986. static void keyboardBreakSignalHandler (int sig)
  217987. {
  217988. if (sig == SIGINT)
  217989. keyboardBreakOccurred = true;
  217990. }
  217991. static void installKeyboardBreakHandler()
  217992. {
  217993. struct sigaction saction;
  217994. sigset_t maskSet;
  217995. sigemptyset (&maskSet);
  217996. saction.sa_handler = keyboardBreakSignalHandler;
  217997. saction.sa_mask = maskSet;
  217998. saction.sa_flags = 0;
  217999. sigaction (SIGINT, &saction, 0);
  218000. }
  218001. }
  218002. void MessageManager::doPlatformSpecificInitialisation()
  218003. {
  218004. if (JUCEApplication::isStandaloneApp())
  218005. {
  218006. // Initialise xlib for multiple thread support
  218007. static bool initThreadCalled = false;
  218008. if (! initThreadCalled)
  218009. {
  218010. if (! XInitThreads())
  218011. {
  218012. // This is fatal! Print error and closedown
  218013. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218014. Process::terminate();
  218015. return;
  218016. }
  218017. initThreadCalled = true;
  218018. }
  218019. LinuxErrorHandling::installXErrorHandlers();
  218020. LinuxErrorHandling::installKeyboardBreakHandler();
  218021. }
  218022. // Create the internal message queue
  218023. InternalMessageQueue::getInstance();
  218024. // Try to connect to a display
  218025. String displayName (getenv ("DISPLAY"));
  218026. if (displayName.isEmpty())
  218027. displayName = ":0.0";
  218028. display = XOpenDisplay (displayName.toCString());
  218029. if (display != 0) // This is not fatal! we can run headless.
  218030. {
  218031. // Create a context to store user data associated with Windows we create in WindowDriver
  218032. windowHandleXContext = XUniqueContext();
  218033. // We're only interested in client messages for this window, which are always sent
  218034. XSetWindowAttributes swa;
  218035. swa.event_mask = NoEventMask;
  218036. // Create our message window (this will never be mapped)
  218037. const int screen = DefaultScreen (display);
  218038. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218039. 0, 0, 1, 1, 0, 0, InputOnly,
  218040. DefaultVisual (display, screen),
  218041. CWEventMask, &swa);
  218042. }
  218043. }
  218044. void MessageManager::doPlatformSpecificShutdown()
  218045. {
  218046. InternalMessageQueue::deleteInstance();
  218047. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218048. {
  218049. XDestroyWindow (display, juce_messageWindowHandle);
  218050. XCloseDisplay (display);
  218051. juce_messageWindowHandle = 0;
  218052. display = 0;
  218053. LinuxErrorHandling::removeXErrorHandlers();
  218054. }
  218055. }
  218056. bool juce_postMessageToSystemQueue (Message* message)
  218057. {
  218058. if (LinuxErrorHandling::errorOccurred)
  218059. return false;
  218060. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218061. return true;
  218062. }
  218063. void MessageManager::broadcastMessage (const String& value)
  218064. {
  218065. /* TODO */
  218066. }
  218067. class AsyncFunctionCaller : public AsyncUpdater
  218068. {
  218069. public:
  218070. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218071. {
  218072. if (MessageManager::getInstance()->isThisTheMessageThread())
  218073. return func_ (parameter_);
  218074. AsyncFunctionCaller caller (func_, parameter_);
  218075. caller.triggerAsyncUpdate();
  218076. caller.finished.wait();
  218077. return caller.result;
  218078. }
  218079. void handleAsyncUpdate()
  218080. {
  218081. result = (*func) (parameter);
  218082. finished.signal();
  218083. }
  218084. private:
  218085. WaitableEvent finished;
  218086. MessageCallbackFunction* func;
  218087. void* parameter;
  218088. void* volatile result;
  218089. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218090. : result (0), func (func_), parameter (parameter_)
  218091. {}
  218092. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218093. };
  218094. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218095. {
  218096. if (LinuxErrorHandling::errorOccurred)
  218097. return 0;
  218098. return AsyncFunctionCaller::call (func, parameter);
  218099. }
  218100. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218101. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218102. {
  218103. while (! LinuxErrorHandling::errorOccurred)
  218104. {
  218105. if (LinuxErrorHandling::keyboardBreakOccurred)
  218106. {
  218107. LinuxErrorHandling::errorOccurred = true;
  218108. if (JUCEApplication::isStandaloneApp())
  218109. Process::terminate();
  218110. break;
  218111. }
  218112. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218113. return true;
  218114. if (returnIfNoPendingMessages)
  218115. break;
  218116. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218117. }
  218118. return false;
  218119. }
  218120. #endif
  218121. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218122. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218123. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218124. // compiled on its own).
  218125. #if JUCE_INCLUDED_FILE
  218126. class FreeTypeFontFace
  218127. {
  218128. public:
  218129. enum FontStyle
  218130. {
  218131. Plain = 0,
  218132. Bold = 1,
  218133. Italic = 2
  218134. };
  218135. FreeTypeFontFace (const String& familyName)
  218136. : hasSerif (false),
  218137. monospaced (false)
  218138. {
  218139. family = familyName;
  218140. }
  218141. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218142. {
  218143. if (names [(int) style].fileName.isEmpty())
  218144. {
  218145. names [(int) style].fileName = name;
  218146. names [(int) style].faceIndex = faceIndex;
  218147. }
  218148. }
  218149. const String& getFamilyName() const throw() { return family; }
  218150. const String& getFileName (const int style, int& faceIndex) const throw()
  218151. {
  218152. faceIndex = names[style].faceIndex;
  218153. return names[style].fileName;
  218154. }
  218155. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218156. bool getMonospaced() const throw() { return monospaced; }
  218157. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218158. bool getSerif() const throw() { return hasSerif; }
  218159. private:
  218160. String family;
  218161. struct FontNameIndex
  218162. {
  218163. String fileName;
  218164. int faceIndex;
  218165. };
  218166. FontNameIndex names[4];
  218167. bool hasSerif, monospaced;
  218168. };
  218169. class FreeTypeInterface : public DeletedAtShutdown
  218170. {
  218171. public:
  218172. FreeTypeInterface()
  218173. : ftLib (0),
  218174. lastFace (0),
  218175. lastBold (false),
  218176. lastItalic (false)
  218177. {
  218178. if (FT_Init_FreeType (&ftLib) != 0)
  218179. {
  218180. ftLib = 0;
  218181. DBG ("Failed to initialize FreeType");
  218182. }
  218183. StringArray fontDirs;
  218184. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218185. fontDirs.removeEmptyStrings (true);
  218186. if (fontDirs.size() == 0)
  218187. {
  218188. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218189. if (fontsInfo != 0)
  218190. {
  218191. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218192. {
  218193. fontDirs.add (e->getAllSubText().trim());
  218194. }
  218195. }
  218196. }
  218197. if (fontDirs.size() == 0)
  218198. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218199. for (int i = 0; i < fontDirs.size(); ++i)
  218200. enumerateFaces (fontDirs[i]);
  218201. }
  218202. ~FreeTypeInterface()
  218203. {
  218204. if (lastFace != 0)
  218205. FT_Done_Face (lastFace);
  218206. if (ftLib != 0)
  218207. FT_Done_FreeType (ftLib);
  218208. clearSingletonInstance();
  218209. }
  218210. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218211. {
  218212. for (int i = 0; i < faces.size(); i++)
  218213. if (faces[i]->getFamilyName() == familyName)
  218214. return faces[i];
  218215. if (! create)
  218216. return 0;
  218217. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218218. faces.add (newFace);
  218219. return newFace;
  218220. }
  218221. // Enumerate all font faces available in a given directory
  218222. void enumerateFaces (const String& path)
  218223. {
  218224. File dirPath (path);
  218225. if (path.isEmpty() || ! dirPath.isDirectory())
  218226. return;
  218227. DirectoryIterator di (dirPath, true);
  218228. while (di.next())
  218229. {
  218230. File possible (di.getFile());
  218231. if (possible.hasFileExtension ("ttf")
  218232. || possible.hasFileExtension ("pfb")
  218233. || possible.hasFileExtension ("pcf"))
  218234. {
  218235. FT_Face face;
  218236. int faceIndex = 0;
  218237. int numFaces = 0;
  218238. do
  218239. {
  218240. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218241. faceIndex, &face) == 0)
  218242. {
  218243. if (faceIndex == 0)
  218244. numFaces = face->num_faces;
  218245. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218246. {
  218247. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218248. int style = (int) FreeTypeFontFace::Plain;
  218249. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218250. style |= (int) FreeTypeFontFace::Bold;
  218251. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218252. style |= (int) FreeTypeFontFace::Italic;
  218253. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218254. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218255. // Surely there must be a better way to do this?
  218256. const String name (face->family_name);
  218257. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218258. || name.containsIgnoreCase ("Verdana")
  218259. || name.containsIgnoreCase ("Arial")));
  218260. }
  218261. FT_Done_Face (face);
  218262. }
  218263. ++faceIndex;
  218264. }
  218265. while (faceIndex < numFaces);
  218266. }
  218267. }
  218268. }
  218269. // Create a FreeType face object for a given font
  218270. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218271. {
  218272. FT_Face face = 0;
  218273. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218274. {
  218275. face = lastFace;
  218276. }
  218277. else
  218278. {
  218279. if (lastFace != 0)
  218280. {
  218281. FT_Done_Face (lastFace);
  218282. lastFace = 0;
  218283. }
  218284. lastFontName = fontName;
  218285. lastBold = bold;
  218286. lastItalic = italic;
  218287. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218288. if (ftFace != 0)
  218289. {
  218290. int style = (int) FreeTypeFontFace::Plain;
  218291. if (bold)
  218292. style |= (int) FreeTypeFontFace::Bold;
  218293. if (italic)
  218294. style |= (int) FreeTypeFontFace::Italic;
  218295. int faceIndex;
  218296. String fileName (ftFace->getFileName (style, faceIndex));
  218297. if (fileName.isEmpty())
  218298. {
  218299. style ^= (int) FreeTypeFontFace::Bold;
  218300. fileName = ftFace->getFileName (style, faceIndex);
  218301. if (fileName.isEmpty())
  218302. {
  218303. style ^= (int) FreeTypeFontFace::Bold;
  218304. style ^= (int) FreeTypeFontFace::Italic;
  218305. fileName = ftFace->getFileName (style, faceIndex);
  218306. if (! fileName.length())
  218307. {
  218308. style ^= (int) FreeTypeFontFace::Bold;
  218309. fileName = ftFace->getFileName (style, faceIndex);
  218310. }
  218311. }
  218312. }
  218313. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218314. {
  218315. face = lastFace;
  218316. // If there isn't a unicode charmap then select the first one.
  218317. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218318. FT_Set_Charmap (face, face->charmaps[0]);
  218319. }
  218320. }
  218321. }
  218322. return face;
  218323. }
  218324. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218325. {
  218326. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218327. const float height = (float) (face->ascender - face->descender);
  218328. const float scaleX = 1.0f / height;
  218329. const float scaleY = -1.0f / height;
  218330. Path destShape;
  218331. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218332. || face->glyph->format != ft_glyph_format_outline)
  218333. {
  218334. return false;
  218335. }
  218336. const FT_Outline* const outline = &face->glyph->outline;
  218337. const short* const contours = outline->contours;
  218338. const char* const tags = outline->tags;
  218339. FT_Vector* const points = outline->points;
  218340. for (int c = 0; c < outline->n_contours; c++)
  218341. {
  218342. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218343. const int endPoint = contours[c];
  218344. for (int p = startPoint; p <= endPoint; p++)
  218345. {
  218346. const float x = scaleX * points[p].x;
  218347. const float y = scaleY * points[p].y;
  218348. if (p == startPoint)
  218349. {
  218350. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218351. {
  218352. float x2 = scaleX * points [endPoint].x;
  218353. float y2 = scaleY * points [endPoint].y;
  218354. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218355. {
  218356. x2 = (x + x2) * 0.5f;
  218357. y2 = (y + y2) * 0.5f;
  218358. }
  218359. destShape.startNewSubPath (x2, y2);
  218360. }
  218361. else
  218362. {
  218363. destShape.startNewSubPath (x, y);
  218364. }
  218365. }
  218366. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218367. {
  218368. if (p != startPoint)
  218369. destShape.lineTo (x, y);
  218370. }
  218371. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218372. {
  218373. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218374. float x2 = scaleX * points [nextIndex].x;
  218375. float y2 = scaleY * points [nextIndex].y;
  218376. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218377. {
  218378. x2 = (x + x2) * 0.5f;
  218379. y2 = (y + y2) * 0.5f;
  218380. }
  218381. else
  218382. {
  218383. ++p;
  218384. }
  218385. destShape.quadraticTo (x, y, x2, y2);
  218386. }
  218387. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218388. {
  218389. if (p >= endPoint)
  218390. return false;
  218391. const int next1 = p + 1;
  218392. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218393. const float x2 = scaleX * points [next1].x;
  218394. const float y2 = scaleY * points [next1].y;
  218395. const float x3 = scaleX * points [next2].x;
  218396. const float y3 = scaleY * points [next2].y;
  218397. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218398. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218399. return false;
  218400. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218401. p += 2;
  218402. }
  218403. }
  218404. destShape.closeSubPath();
  218405. }
  218406. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218407. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218408. addKerning (face, dest, character, glyphIndex);
  218409. return true;
  218410. }
  218411. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218412. {
  218413. const float height = (float) (face->ascender - face->descender);
  218414. uint32 rightGlyphIndex;
  218415. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218416. while (rightGlyphIndex != 0)
  218417. {
  218418. FT_Vector kerning;
  218419. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218420. {
  218421. if (kerning.x != 0)
  218422. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218423. }
  218424. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218425. }
  218426. }
  218427. // Add a glyph to a font
  218428. bool addGlyphToFont (const uint32 character, const String& fontName,
  218429. bool bold, bool italic, CustomTypeface& dest)
  218430. {
  218431. FT_Face face = createFT_Face (fontName, bold, italic);
  218432. return face != 0 && addGlyph (face, dest, character);
  218433. }
  218434. void getFamilyNames (StringArray& familyNames) const
  218435. {
  218436. for (int i = 0; i < faces.size(); i++)
  218437. familyNames.add (faces[i]->getFamilyName());
  218438. }
  218439. void getMonospacedNames (StringArray& monoSpaced) const
  218440. {
  218441. for (int i = 0; i < faces.size(); i++)
  218442. if (faces[i]->getMonospaced())
  218443. monoSpaced.add (faces[i]->getFamilyName());
  218444. }
  218445. void getSerifNames (StringArray& serif) const
  218446. {
  218447. for (int i = 0; i < faces.size(); i++)
  218448. if (faces[i]->getSerif())
  218449. serif.add (faces[i]->getFamilyName());
  218450. }
  218451. void getSansSerifNames (StringArray& sansSerif) const
  218452. {
  218453. for (int i = 0; i < faces.size(); i++)
  218454. if (! faces[i]->getSerif())
  218455. sansSerif.add (faces[i]->getFamilyName());
  218456. }
  218457. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218458. private:
  218459. FT_Library ftLib;
  218460. FT_Face lastFace;
  218461. String lastFontName;
  218462. bool lastBold, lastItalic;
  218463. OwnedArray<FreeTypeFontFace> faces;
  218464. };
  218465. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218466. class FreetypeTypeface : public CustomTypeface
  218467. {
  218468. public:
  218469. FreetypeTypeface (const Font& font)
  218470. {
  218471. FT_Face face = FreeTypeInterface::getInstance()
  218472. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218473. if (face == 0)
  218474. {
  218475. #if JUCE_DEBUG
  218476. String msg ("Failed to create typeface: ");
  218477. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218478. DBG (msg);
  218479. #endif
  218480. }
  218481. else
  218482. {
  218483. setCharacteristics (font.getTypefaceName(),
  218484. face->ascender / (float) (face->ascender - face->descender),
  218485. font.isBold(), font.isItalic(),
  218486. L' ');
  218487. }
  218488. }
  218489. bool loadGlyphIfPossible (juce_wchar character)
  218490. {
  218491. return FreeTypeInterface::getInstance()
  218492. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218493. }
  218494. };
  218495. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218496. {
  218497. return new FreetypeTypeface (font);
  218498. }
  218499. const StringArray Font::findAllTypefaceNames()
  218500. {
  218501. StringArray s;
  218502. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218503. s.sort (true);
  218504. return s;
  218505. }
  218506. namespace
  218507. {
  218508. const String pickBestFont (const StringArray& names,
  218509. const char* const choicesString)
  218510. {
  218511. StringArray choices;
  218512. choices.addTokens (String (choicesString), ",", String::empty);
  218513. choices.trim();
  218514. choices.removeEmptyStrings();
  218515. int i, j;
  218516. for (j = 0; j < choices.size(); ++j)
  218517. if (names.contains (choices[j], true))
  218518. return choices[j];
  218519. for (j = 0; j < choices.size(); ++j)
  218520. for (i = 0; i < names.size(); i++)
  218521. if (names[i].startsWithIgnoreCase (choices[j]))
  218522. return names[i];
  218523. for (j = 0; j < choices.size(); ++j)
  218524. for (i = 0; i < names.size(); i++)
  218525. if (names[i].containsIgnoreCase (choices[j]))
  218526. return names[i];
  218527. return names[0];
  218528. }
  218529. const String linux_getDefaultSansSerifFontName()
  218530. {
  218531. StringArray allFonts;
  218532. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218533. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218534. }
  218535. const String linux_getDefaultSerifFontName()
  218536. {
  218537. StringArray allFonts;
  218538. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218539. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218540. }
  218541. const String linux_getDefaultMonospacedFontName()
  218542. {
  218543. StringArray allFonts;
  218544. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218545. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218546. }
  218547. }
  218548. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218549. {
  218550. defaultSans = linux_getDefaultSansSerifFontName();
  218551. defaultSerif = linux_getDefaultSerifFontName();
  218552. defaultFixed = linux_getDefaultMonospacedFontName();
  218553. }
  218554. #endif
  218555. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218556. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218557. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218558. // compiled on its own).
  218559. #if JUCE_INCLUDED_FILE
  218560. // These are defined in juce_linux_Messaging.cpp
  218561. extern Display* display;
  218562. extern XContext windowHandleXContext;
  218563. namespace Atoms
  218564. {
  218565. enum ProtocolItems
  218566. {
  218567. TAKE_FOCUS = 0,
  218568. DELETE_WINDOW = 1,
  218569. PING = 2
  218570. };
  218571. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218572. ActiveWin, Pid, WindowType, WindowState,
  218573. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218574. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218575. XdndActionDescription, XdndActionCopy,
  218576. allowedActions[5],
  218577. allowedMimeTypes[2];
  218578. const unsigned long DndVersion = 3;
  218579. static void initialiseAtoms()
  218580. {
  218581. static bool atomsInitialised = false;
  218582. if (! atomsInitialised)
  218583. {
  218584. atomsInitialised = true;
  218585. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218586. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218587. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218588. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218589. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218590. State = XInternAtom (display, "WM_STATE", True);
  218591. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218592. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218593. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218594. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218595. XdndAware = XInternAtom (display, "XdndAware", False);
  218596. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218597. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218598. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218599. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218600. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218601. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218602. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218603. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218604. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218605. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218606. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218607. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218608. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218609. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218610. allowedActions[1] = XdndActionCopy;
  218611. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218612. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218613. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218614. }
  218615. }
  218616. }
  218617. namespace Keys
  218618. {
  218619. enum MouseButtons
  218620. {
  218621. NoButton = 0,
  218622. LeftButton = 1,
  218623. MiddleButton = 2,
  218624. RightButton = 3,
  218625. WheelUp = 4,
  218626. WheelDown = 5
  218627. };
  218628. static int AltMask = 0;
  218629. static int NumLockMask = 0;
  218630. static bool numLock = false;
  218631. static bool capsLock = false;
  218632. static char keyStates [32];
  218633. static const int extendedKeyModifier = 0x10000000;
  218634. }
  218635. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218636. {
  218637. int keysym;
  218638. if (keyCode & Keys::extendedKeyModifier)
  218639. {
  218640. keysym = 0xff00 | (keyCode & 0xff);
  218641. }
  218642. else
  218643. {
  218644. keysym = keyCode;
  218645. if (keysym == (XK_Tab & 0xff)
  218646. || keysym == (XK_Return & 0xff)
  218647. || keysym == (XK_Escape & 0xff)
  218648. || keysym == (XK_BackSpace & 0xff))
  218649. {
  218650. keysym |= 0xff00;
  218651. }
  218652. }
  218653. ScopedXLock xlock;
  218654. const int keycode = XKeysymToKeycode (display, keysym);
  218655. const int keybyte = keycode >> 3;
  218656. const int keybit = (1 << (keycode & 7));
  218657. return (Keys::keyStates [keybyte] & keybit) != 0;
  218658. }
  218659. #if JUCE_USE_XSHM
  218660. namespace XSHMHelpers
  218661. {
  218662. static int trappedErrorCode = 0;
  218663. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218664. {
  218665. trappedErrorCode = err->error_code;
  218666. return 0;
  218667. }
  218668. static bool isShmAvailable() throw()
  218669. {
  218670. static bool isChecked = false;
  218671. static bool isAvailable = false;
  218672. if (! isChecked)
  218673. {
  218674. isChecked = true;
  218675. int major, minor;
  218676. Bool pixmaps;
  218677. ScopedXLock xlock;
  218678. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218679. {
  218680. trappedErrorCode = 0;
  218681. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218682. XShmSegmentInfo segmentInfo;
  218683. zerostruct (segmentInfo);
  218684. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218685. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218686. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218687. xImage->bytes_per_line * xImage->height,
  218688. IPC_CREAT | 0777)) >= 0)
  218689. {
  218690. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218691. if (segmentInfo.shmaddr != (void*) -1)
  218692. {
  218693. segmentInfo.readOnly = False;
  218694. xImage->data = segmentInfo.shmaddr;
  218695. XSync (display, False);
  218696. if (XShmAttach (display, &segmentInfo) != 0)
  218697. {
  218698. XSync (display, False);
  218699. XShmDetach (display, &segmentInfo);
  218700. isAvailable = true;
  218701. }
  218702. }
  218703. XFlush (display);
  218704. XDestroyImage (xImage);
  218705. shmdt (segmentInfo.shmaddr);
  218706. }
  218707. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218708. XSetErrorHandler (oldHandler);
  218709. if (trappedErrorCode != 0)
  218710. isAvailable = false;
  218711. }
  218712. }
  218713. return isAvailable;
  218714. }
  218715. }
  218716. #endif
  218717. #if JUCE_USE_XRENDER
  218718. namespace XRender
  218719. {
  218720. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218721. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218722. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218723. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218724. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218725. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218726. static tXRenderFindFormat xRenderFindFormat = 0;
  218727. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218728. static bool isAvailable()
  218729. {
  218730. static bool hasLoaded = false;
  218731. if (! hasLoaded)
  218732. {
  218733. ScopedXLock xlock;
  218734. hasLoaded = true;
  218735. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218736. if (h != 0)
  218737. {
  218738. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218739. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218740. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218741. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218742. }
  218743. if (xRenderQueryVersion != 0
  218744. && xRenderFindStandardFormat != 0
  218745. && xRenderFindFormat != 0
  218746. && xRenderFindVisualFormat != 0)
  218747. {
  218748. int major, minor;
  218749. if (xRenderQueryVersion (display, &major, &minor))
  218750. return true;
  218751. }
  218752. xRenderQueryVersion = 0;
  218753. }
  218754. return xRenderQueryVersion != 0;
  218755. }
  218756. static XRenderPictFormat* findPictureFormat()
  218757. {
  218758. ScopedXLock xlock;
  218759. XRenderPictFormat* pictFormat = 0;
  218760. if (isAvailable())
  218761. {
  218762. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218763. if (pictFormat == 0)
  218764. {
  218765. XRenderPictFormat desiredFormat;
  218766. desiredFormat.type = PictTypeDirect;
  218767. desiredFormat.depth = 32;
  218768. desiredFormat.direct.alphaMask = 0xff;
  218769. desiredFormat.direct.redMask = 0xff;
  218770. desiredFormat.direct.greenMask = 0xff;
  218771. desiredFormat.direct.blueMask = 0xff;
  218772. desiredFormat.direct.alpha = 24;
  218773. desiredFormat.direct.red = 16;
  218774. desiredFormat.direct.green = 8;
  218775. desiredFormat.direct.blue = 0;
  218776. pictFormat = xRenderFindFormat (display,
  218777. PictFormatType | PictFormatDepth
  218778. | PictFormatRedMask | PictFormatRed
  218779. | PictFormatGreenMask | PictFormatGreen
  218780. | PictFormatBlueMask | PictFormatBlue
  218781. | PictFormatAlphaMask | PictFormatAlpha,
  218782. &desiredFormat,
  218783. 0);
  218784. }
  218785. }
  218786. return pictFormat;
  218787. }
  218788. }
  218789. #endif
  218790. namespace Visuals
  218791. {
  218792. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218793. {
  218794. ScopedXLock xlock;
  218795. Visual* visual = 0;
  218796. int numVisuals = 0;
  218797. long desiredMask = VisualNoMask;
  218798. XVisualInfo desiredVisual;
  218799. desiredVisual.screen = DefaultScreen (display);
  218800. desiredVisual.depth = desiredDepth;
  218801. desiredMask = VisualScreenMask | VisualDepthMask;
  218802. if (desiredDepth == 32)
  218803. {
  218804. desiredVisual.c_class = TrueColor;
  218805. desiredVisual.red_mask = 0x00FF0000;
  218806. desiredVisual.green_mask = 0x0000FF00;
  218807. desiredVisual.blue_mask = 0x000000FF;
  218808. desiredVisual.bits_per_rgb = 8;
  218809. desiredMask |= VisualClassMask;
  218810. desiredMask |= VisualRedMaskMask;
  218811. desiredMask |= VisualGreenMaskMask;
  218812. desiredMask |= VisualBlueMaskMask;
  218813. desiredMask |= VisualBitsPerRGBMask;
  218814. }
  218815. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218816. desiredMask,
  218817. &desiredVisual,
  218818. &numVisuals);
  218819. if (xvinfos != 0)
  218820. {
  218821. for (int i = 0; i < numVisuals; i++)
  218822. {
  218823. if (xvinfos[i].depth == desiredDepth)
  218824. {
  218825. visual = xvinfos[i].visual;
  218826. break;
  218827. }
  218828. }
  218829. XFree (xvinfos);
  218830. }
  218831. return visual;
  218832. }
  218833. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218834. {
  218835. Visual* visual = 0;
  218836. if (desiredDepth == 32)
  218837. {
  218838. #if JUCE_USE_XSHM
  218839. if (XSHMHelpers::isShmAvailable())
  218840. {
  218841. #if JUCE_USE_XRENDER
  218842. if (XRender::isAvailable())
  218843. {
  218844. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218845. if (pictFormat != 0)
  218846. {
  218847. int numVisuals = 0;
  218848. XVisualInfo desiredVisual;
  218849. desiredVisual.screen = DefaultScreen (display);
  218850. desiredVisual.depth = 32;
  218851. desiredVisual.bits_per_rgb = 8;
  218852. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218853. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218854. &desiredVisual, &numVisuals);
  218855. if (xvinfos != 0)
  218856. {
  218857. for (int i = 0; i < numVisuals; ++i)
  218858. {
  218859. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218860. if (pictVisualFormat != 0
  218861. && pictVisualFormat->type == PictTypeDirect
  218862. && pictVisualFormat->direct.alphaMask)
  218863. {
  218864. visual = xvinfos[i].visual;
  218865. matchedDepth = 32;
  218866. break;
  218867. }
  218868. }
  218869. XFree (xvinfos);
  218870. }
  218871. }
  218872. }
  218873. #endif
  218874. if (visual == 0)
  218875. {
  218876. visual = findVisualWithDepth (32);
  218877. if (visual != 0)
  218878. matchedDepth = 32;
  218879. }
  218880. }
  218881. #endif
  218882. }
  218883. if (visual == 0 && desiredDepth >= 24)
  218884. {
  218885. visual = findVisualWithDepth (24);
  218886. if (visual != 0)
  218887. matchedDepth = 24;
  218888. }
  218889. if (visual == 0 && desiredDepth >= 16)
  218890. {
  218891. visual = findVisualWithDepth (16);
  218892. if (visual != 0)
  218893. matchedDepth = 16;
  218894. }
  218895. return visual;
  218896. }
  218897. }
  218898. class XBitmapImage : public Image::SharedImage
  218899. {
  218900. public:
  218901. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218902. const bool clearImage, const int imageDepth_, Visual* visual)
  218903. : Image::SharedImage (format_, w, h),
  218904. imageDepth (imageDepth_),
  218905. gc (None)
  218906. {
  218907. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218908. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218909. lineStride = ((w * pixelStride + 3) & ~3);
  218910. ScopedXLock xlock;
  218911. #if JUCE_USE_XSHM
  218912. usingXShm = false;
  218913. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218914. {
  218915. zerostruct (segmentInfo);
  218916. segmentInfo.shmid = -1;
  218917. segmentInfo.shmaddr = (char *) -1;
  218918. segmentInfo.readOnly = False;
  218919. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218920. if (xImage != 0)
  218921. {
  218922. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218923. xImage->bytes_per_line * xImage->height,
  218924. IPC_CREAT | 0777)) >= 0)
  218925. {
  218926. if (segmentInfo.shmid != -1)
  218927. {
  218928. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218929. if (segmentInfo.shmaddr != (void*) -1)
  218930. {
  218931. segmentInfo.readOnly = False;
  218932. xImage->data = segmentInfo.shmaddr;
  218933. imageData = (uint8*) segmentInfo.shmaddr;
  218934. if (XShmAttach (display, &segmentInfo) != 0)
  218935. usingXShm = true;
  218936. else
  218937. jassertfalse;
  218938. }
  218939. else
  218940. {
  218941. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218942. }
  218943. }
  218944. }
  218945. }
  218946. }
  218947. if (! usingXShm)
  218948. #endif
  218949. {
  218950. imageDataAllocated.malloc (lineStride * h);
  218951. imageData = imageDataAllocated;
  218952. if (format_ == Image::ARGB && clearImage)
  218953. zeromem (imageData, h * lineStride);
  218954. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218955. xImage->width = w;
  218956. xImage->height = h;
  218957. xImage->xoffset = 0;
  218958. xImage->format = ZPixmap;
  218959. xImage->data = (char*) imageData;
  218960. xImage->byte_order = ImageByteOrder (display);
  218961. xImage->bitmap_unit = BitmapUnit (display);
  218962. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218963. xImage->bitmap_pad = 32;
  218964. xImage->depth = pixelStride * 8;
  218965. xImage->bytes_per_line = lineStride;
  218966. xImage->bits_per_pixel = pixelStride * 8;
  218967. xImage->red_mask = 0x00FF0000;
  218968. xImage->green_mask = 0x0000FF00;
  218969. xImage->blue_mask = 0x000000FF;
  218970. if (imageDepth == 16)
  218971. {
  218972. const int pixelStride = 2;
  218973. const int lineStride = ((w * pixelStride + 3) & ~3);
  218974. imageData16Bit.malloc (lineStride * h);
  218975. xImage->data = imageData16Bit;
  218976. xImage->bitmap_pad = 16;
  218977. xImage->depth = pixelStride * 8;
  218978. xImage->bytes_per_line = lineStride;
  218979. xImage->bits_per_pixel = pixelStride * 8;
  218980. xImage->red_mask = visual->red_mask;
  218981. xImage->green_mask = visual->green_mask;
  218982. xImage->blue_mask = visual->blue_mask;
  218983. }
  218984. if (! XInitImage (xImage))
  218985. jassertfalse;
  218986. }
  218987. }
  218988. ~XBitmapImage()
  218989. {
  218990. ScopedXLock xlock;
  218991. if (gc != None)
  218992. XFreeGC (display, gc);
  218993. #if JUCE_USE_XSHM
  218994. if (usingXShm)
  218995. {
  218996. XShmDetach (display, &segmentInfo);
  218997. XFlush (display);
  218998. XDestroyImage (xImage);
  218999. shmdt (segmentInfo.shmaddr);
  219000. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219001. }
  219002. else
  219003. #endif
  219004. {
  219005. xImage->data = 0;
  219006. XDestroyImage (xImage);
  219007. }
  219008. }
  219009. Image::ImageType getType() const { return Image::NativeImage; }
  219010. LowLevelGraphicsContext* createLowLevelContext()
  219011. {
  219012. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219013. }
  219014. SharedImage* clone()
  219015. {
  219016. jassertfalse;
  219017. return 0;
  219018. }
  219019. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219020. {
  219021. ScopedXLock xlock;
  219022. if (gc == None)
  219023. {
  219024. XGCValues gcvalues;
  219025. gcvalues.foreground = None;
  219026. gcvalues.background = None;
  219027. gcvalues.function = GXcopy;
  219028. gcvalues.plane_mask = AllPlanes;
  219029. gcvalues.clip_mask = None;
  219030. gcvalues.graphics_exposures = False;
  219031. gc = XCreateGC (display, window,
  219032. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219033. &gcvalues);
  219034. }
  219035. if (imageDepth == 16)
  219036. {
  219037. const uint32 rMask = xImage->red_mask;
  219038. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219039. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219040. const uint32 gMask = xImage->green_mask;
  219041. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219042. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219043. const uint32 bMask = xImage->blue_mask;
  219044. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219045. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219046. const Image::BitmapData srcData (Image (this), false);
  219047. for (int y = sy; y < sy + dh; ++y)
  219048. {
  219049. const uint8* p = srcData.getPixelPointer (sx, y);
  219050. for (int x = sx; x < sx + dw; ++x)
  219051. {
  219052. const PixelRGB* const pixel = (const PixelRGB*) p;
  219053. p += srcData.pixelStride;
  219054. XPutPixel (xImage, x, y,
  219055. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219056. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219057. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219058. }
  219059. }
  219060. }
  219061. // blit results to screen.
  219062. #if JUCE_USE_XSHM
  219063. if (usingXShm)
  219064. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219065. else
  219066. #endif
  219067. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219068. }
  219069. private:
  219070. XImage* xImage;
  219071. const int imageDepth;
  219072. HeapBlock <uint8> imageDataAllocated;
  219073. HeapBlock <char> imageData16Bit;
  219074. GC gc;
  219075. #if JUCE_USE_XSHM
  219076. XShmSegmentInfo segmentInfo;
  219077. bool usingXShm;
  219078. #endif
  219079. static int getShiftNeeded (const uint32 mask) throw()
  219080. {
  219081. for (int i = 32; --i >= 0;)
  219082. if (((mask >> i) & 1) != 0)
  219083. return i - 7;
  219084. jassertfalse;
  219085. return 0;
  219086. }
  219087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219088. };
  219089. namespace PixmapHelpers
  219090. {
  219091. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219092. {
  219093. ScopedXLock xlock;
  219094. const int width = image.getWidth();
  219095. const int height = image.getHeight();
  219096. HeapBlock <uint32> colour (width * height);
  219097. int index = 0;
  219098. for (int y = 0; y < height; ++y)
  219099. for (int x = 0; x < width; ++x)
  219100. colour[index++] = image.getPixelAt (x, y).getARGB();
  219101. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219102. 0, reinterpret_cast<char*> (colour.getData()),
  219103. width, height, 32, 0);
  219104. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219105. width, height, 24);
  219106. GC gc = XCreateGC (display, pixmap, 0, 0);
  219107. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219108. XFreeGC (display, gc);
  219109. return pixmap;
  219110. }
  219111. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219112. {
  219113. ScopedXLock xlock;
  219114. const int width = image.getWidth();
  219115. const int height = image.getHeight();
  219116. const int stride = (width + 7) >> 3;
  219117. HeapBlock <char> mask;
  219118. mask.calloc (stride * height);
  219119. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219120. for (int y = 0; y < height; ++y)
  219121. {
  219122. for (int x = 0; x < width; ++x)
  219123. {
  219124. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219125. const int offset = y * stride + (x >> 3);
  219126. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219127. mask[offset] |= bit;
  219128. }
  219129. }
  219130. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219131. mask.getData(), width, height, 1, 0, 1);
  219132. }
  219133. }
  219134. class LinuxComponentPeer : public ComponentPeer
  219135. {
  219136. public:
  219137. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219138. : ComponentPeer (component, windowStyleFlags),
  219139. windowH (0),
  219140. parentWindow (0),
  219141. wx (0),
  219142. wy (0),
  219143. ww (0),
  219144. wh (0),
  219145. fullScreen (false),
  219146. mapped (false),
  219147. visual (0),
  219148. depth (0)
  219149. {
  219150. // it's dangerous to create a window on a thread other than the message thread..
  219151. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219152. repainter = new LinuxRepaintManager (this);
  219153. createWindow();
  219154. setTitle (component->getName());
  219155. }
  219156. ~LinuxComponentPeer()
  219157. {
  219158. // it's dangerous to delete a window on a thread other than the message thread..
  219159. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219160. deleteIconPixmaps();
  219161. destroyWindow();
  219162. windowH = 0;
  219163. }
  219164. void* getNativeHandle() const
  219165. {
  219166. return (void*) windowH;
  219167. }
  219168. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219169. {
  219170. XPointer peer = 0;
  219171. ScopedXLock xlock;
  219172. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219173. {
  219174. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219175. peer = 0;
  219176. }
  219177. return (LinuxComponentPeer*) peer;
  219178. }
  219179. void setVisible (bool shouldBeVisible)
  219180. {
  219181. ScopedXLock xlock;
  219182. if (shouldBeVisible)
  219183. XMapWindow (display, windowH);
  219184. else
  219185. XUnmapWindow (display, windowH);
  219186. }
  219187. void setTitle (const String& title)
  219188. {
  219189. XTextProperty nameProperty;
  219190. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219191. ScopedXLock xlock;
  219192. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219193. {
  219194. XSetWMName (display, windowH, &nameProperty);
  219195. XSetWMIconName (display, windowH, &nameProperty);
  219196. XFree (nameProperty.value);
  219197. }
  219198. }
  219199. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219200. {
  219201. fullScreen = isNowFullScreen;
  219202. if (windowH != 0)
  219203. {
  219204. WeakReference<Component> deletionChecker (component);
  219205. wx = x;
  219206. wy = y;
  219207. ww = jmax (1, w);
  219208. wh = jmax (1, h);
  219209. ScopedXLock xlock;
  219210. // Make sure the Window manager does what we want
  219211. XSizeHints* hints = XAllocSizeHints();
  219212. hints->flags = USSize | USPosition;
  219213. hints->width = ww;
  219214. hints->height = wh;
  219215. hints->x = wx;
  219216. hints->y = wy;
  219217. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219218. {
  219219. hints->min_width = hints->max_width = hints->width;
  219220. hints->min_height = hints->max_height = hints->height;
  219221. hints->flags |= PMinSize | PMaxSize;
  219222. }
  219223. XSetWMNormalHints (display, windowH, hints);
  219224. XFree (hints);
  219225. XMoveResizeWindow (display, windowH,
  219226. wx - windowBorder.getLeft(),
  219227. wy - windowBorder.getTop(), ww, wh);
  219228. if (deletionChecker != 0)
  219229. {
  219230. updateBorderSize();
  219231. handleMovedOrResized();
  219232. }
  219233. }
  219234. }
  219235. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219236. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219237. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219238. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219239. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219240. {
  219241. return relativePosition + getScreenPosition();
  219242. }
  219243. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219244. {
  219245. return screenPosition - getScreenPosition();
  219246. }
  219247. void setAlpha (float newAlpha)
  219248. {
  219249. //xxx todo!
  219250. }
  219251. void setMinimised (bool shouldBeMinimised)
  219252. {
  219253. if (shouldBeMinimised)
  219254. {
  219255. Window root = RootWindow (display, DefaultScreen (display));
  219256. XClientMessageEvent clientMsg;
  219257. clientMsg.display = display;
  219258. clientMsg.window = windowH;
  219259. clientMsg.type = ClientMessage;
  219260. clientMsg.format = 32;
  219261. clientMsg.message_type = Atoms::ChangeState;
  219262. clientMsg.data.l[0] = IconicState;
  219263. ScopedXLock xlock;
  219264. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219265. }
  219266. else
  219267. {
  219268. setVisible (true);
  219269. }
  219270. }
  219271. bool isMinimised() const
  219272. {
  219273. bool minimised = false;
  219274. unsigned char* stateProp;
  219275. unsigned long nitems, bytesLeft;
  219276. Atom actualType;
  219277. int actualFormat;
  219278. ScopedXLock xlock;
  219279. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219280. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219281. &stateProp) == Success
  219282. && actualType == Atoms::State
  219283. && actualFormat == 32
  219284. && nitems > 0)
  219285. {
  219286. if (((unsigned long*) stateProp)[0] == IconicState)
  219287. minimised = true;
  219288. XFree (stateProp);
  219289. }
  219290. return minimised;
  219291. }
  219292. void setFullScreen (const bool shouldBeFullScreen)
  219293. {
  219294. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219295. setMinimised (false);
  219296. if (fullScreen != shouldBeFullScreen)
  219297. {
  219298. if (shouldBeFullScreen)
  219299. r = Desktop::getInstance().getMainMonitorArea();
  219300. if (! r.isEmpty())
  219301. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219302. getComponent()->repaint();
  219303. }
  219304. }
  219305. bool isFullScreen() const
  219306. {
  219307. return fullScreen;
  219308. }
  219309. bool isChildWindowOf (Window possibleParent) const
  219310. {
  219311. Window* windowList = 0;
  219312. uint32 windowListSize = 0;
  219313. Window parent, root;
  219314. ScopedXLock xlock;
  219315. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219316. {
  219317. if (windowList != 0)
  219318. XFree (windowList);
  219319. return parent == possibleParent;
  219320. }
  219321. return false;
  219322. }
  219323. bool isFrontWindow() const
  219324. {
  219325. Window* windowList = 0;
  219326. uint32 windowListSize = 0;
  219327. bool result = false;
  219328. ScopedXLock xlock;
  219329. Window parent, root = RootWindow (display, DefaultScreen (display));
  219330. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219331. {
  219332. for (int i = windowListSize; --i >= 0;)
  219333. {
  219334. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219335. if (peer != 0)
  219336. {
  219337. result = (peer == this);
  219338. break;
  219339. }
  219340. }
  219341. }
  219342. if (windowList != 0)
  219343. XFree (windowList);
  219344. return result;
  219345. }
  219346. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219347. {
  219348. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219349. return false;
  219350. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219351. {
  219352. Component* const c = Desktop::getInstance().getComponent (i);
  219353. if (c == getComponent())
  219354. break;
  219355. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219356. return false;
  219357. }
  219358. if (trueIfInAChildWindow)
  219359. return true;
  219360. ::Window root, child;
  219361. unsigned int bw, depth;
  219362. int wx, wy, w, h;
  219363. ScopedXLock xlock;
  219364. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219365. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219366. &bw, &depth))
  219367. {
  219368. return false;
  219369. }
  219370. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219371. return false;
  219372. return child == None;
  219373. }
  219374. const BorderSize<int> getFrameSize() const
  219375. {
  219376. return BorderSize<int>();
  219377. }
  219378. bool setAlwaysOnTop (bool alwaysOnTop)
  219379. {
  219380. return false;
  219381. }
  219382. void toFront (bool makeActive)
  219383. {
  219384. if (makeActive)
  219385. {
  219386. setVisible (true);
  219387. grabFocus();
  219388. }
  219389. XEvent ev;
  219390. ev.xclient.type = ClientMessage;
  219391. ev.xclient.serial = 0;
  219392. ev.xclient.send_event = True;
  219393. ev.xclient.message_type = Atoms::ActiveWin;
  219394. ev.xclient.window = windowH;
  219395. ev.xclient.format = 32;
  219396. ev.xclient.data.l[0] = 2;
  219397. ev.xclient.data.l[1] = CurrentTime;
  219398. ev.xclient.data.l[2] = 0;
  219399. ev.xclient.data.l[3] = 0;
  219400. ev.xclient.data.l[4] = 0;
  219401. {
  219402. ScopedXLock xlock;
  219403. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219404. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219405. XWindowAttributes attr;
  219406. XGetWindowAttributes (display, windowH, &attr);
  219407. if (component->isAlwaysOnTop())
  219408. XRaiseWindow (display, windowH);
  219409. XSync (display, False);
  219410. }
  219411. handleBroughtToFront();
  219412. }
  219413. void toBehind (ComponentPeer* other)
  219414. {
  219415. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219416. jassert (otherPeer != 0); // wrong type of window?
  219417. if (otherPeer != 0)
  219418. {
  219419. setMinimised (false);
  219420. Window newStack[] = { otherPeer->windowH, windowH };
  219421. ScopedXLock xlock;
  219422. XRestackWindows (display, newStack, 2);
  219423. }
  219424. }
  219425. bool isFocused() const
  219426. {
  219427. int revert = 0;
  219428. Window focusedWindow = 0;
  219429. ScopedXLock xlock;
  219430. XGetInputFocus (display, &focusedWindow, &revert);
  219431. return focusedWindow == windowH;
  219432. }
  219433. void grabFocus()
  219434. {
  219435. XWindowAttributes atts;
  219436. ScopedXLock xlock;
  219437. if (windowH != 0
  219438. && XGetWindowAttributes (display, windowH, &atts)
  219439. && atts.map_state == IsViewable
  219440. && ! isFocused())
  219441. {
  219442. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219443. isActiveApplication = true;
  219444. }
  219445. }
  219446. void textInputRequired (const Point<int>&)
  219447. {
  219448. }
  219449. void repaint (const Rectangle<int>& area)
  219450. {
  219451. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219452. }
  219453. void performAnyPendingRepaintsNow()
  219454. {
  219455. repainter->performAnyPendingRepaintsNow();
  219456. }
  219457. void setIcon (const Image& newIcon)
  219458. {
  219459. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219460. HeapBlock <unsigned long> data (dataSize);
  219461. int index = 0;
  219462. data[index++] = newIcon.getWidth();
  219463. data[index++] = newIcon.getHeight();
  219464. for (int y = 0; y < newIcon.getHeight(); ++y)
  219465. for (int x = 0; x < newIcon.getWidth(); ++x)
  219466. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219467. ScopedXLock xlock;
  219468. XChangeProperty (display, windowH,
  219469. XInternAtom (display, "_NET_WM_ICON", False),
  219470. XA_CARDINAL, 32, PropModeReplace,
  219471. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219472. deleteIconPixmaps();
  219473. XWMHints* wmHints = XGetWMHints (display, windowH);
  219474. if (wmHints == 0)
  219475. wmHints = XAllocWMHints();
  219476. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219477. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219478. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219479. XSetWMHints (display, windowH, wmHints);
  219480. XFree (wmHints);
  219481. XSync (display, False);
  219482. }
  219483. void deleteIconPixmaps()
  219484. {
  219485. ScopedXLock xlock;
  219486. XWMHints* wmHints = XGetWMHints (display, windowH);
  219487. if (wmHints != 0)
  219488. {
  219489. if ((wmHints->flags & IconPixmapHint) != 0)
  219490. {
  219491. wmHints->flags &= ~IconPixmapHint;
  219492. XFreePixmap (display, wmHints->icon_pixmap);
  219493. }
  219494. if ((wmHints->flags & IconMaskHint) != 0)
  219495. {
  219496. wmHints->flags &= ~IconMaskHint;
  219497. XFreePixmap (display, wmHints->icon_mask);
  219498. }
  219499. XSetWMHints (display, windowH, wmHints);
  219500. XFree (wmHints);
  219501. }
  219502. }
  219503. void handleWindowMessage (XEvent* event)
  219504. {
  219505. switch (event->xany.type)
  219506. {
  219507. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219508. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219509. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219510. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219511. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219512. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219513. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219514. case FocusIn: handleFocusInEvent(); break;
  219515. case FocusOut: handleFocusOutEvent(); break;
  219516. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219517. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219518. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219519. case SelectionNotify: handleDragAndDropSelection (event); break;
  219520. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219521. case ReparentNotify: handleReparentNotifyEvent(); break;
  219522. case GravityNotify: handleGravityNotify(); break;
  219523. case CirculateNotify:
  219524. case CreateNotify:
  219525. case DestroyNotify:
  219526. // Think we can ignore these
  219527. break;
  219528. case MapNotify:
  219529. mapped = true;
  219530. handleBroughtToFront();
  219531. break;
  219532. case UnmapNotify:
  219533. mapped = false;
  219534. break;
  219535. case SelectionClear:
  219536. case SelectionRequest:
  219537. break;
  219538. default:
  219539. #if JUCE_USE_XSHM
  219540. {
  219541. ScopedXLock xlock;
  219542. if (event->xany.type == XShmGetEventBase (display))
  219543. repainter->notifyPaintCompleted();
  219544. }
  219545. #endif
  219546. break;
  219547. }
  219548. }
  219549. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219550. {
  219551. char utf8 [64] = { 0 };
  219552. juce_wchar unicodeChar = 0;
  219553. int keyCode = 0;
  219554. bool keyDownChange = false;
  219555. KeySym sym;
  219556. {
  219557. ScopedXLock xlock;
  219558. updateKeyStates (keyEvent->keycode, true);
  219559. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219560. ::setlocale (LC_ALL, "");
  219561. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219562. ::setlocale (LC_ALL, oldLocale);
  219563. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219564. keyCode = (int) unicodeChar;
  219565. if (keyCode < 0x20)
  219566. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219567. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219568. }
  219569. const ModifierKeys oldMods (currentModifiers);
  219570. bool keyPressed = false;
  219571. if ((sym & 0xff00) == 0xff00)
  219572. {
  219573. switch (sym) // Translate keypad
  219574. {
  219575. case XK_KP_Divide: keyCode = XK_slash; break;
  219576. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219577. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219578. case XK_KP_Add: keyCode = XK_plus; break;
  219579. case XK_KP_Enter: keyCode = XK_Return; break;
  219580. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219581. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219582. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219583. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219584. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219585. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219586. case XK_KP_5: keyCode = XK_5; break;
  219587. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219588. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219589. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219590. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219591. default: break;
  219592. }
  219593. switch (sym)
  219594. {
  219595. case XK_Left:
  219596. case XK_Right:
  219597. case XK_Up:
  219598. case XK_Down:
  219599. case XK_Page_Up:
  219600. case XK_Page_Down:
  219601. case XK_End:
  219602. case XK_Home:
  219603. case XK_Delete:
  219604. case XK_Insert:
  219605. keyPressed = true;
  219606. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219607. break;
  219608. case XK_Tab:
  219609. case XK_Return:
  219610. case XK_Escape:
  219611. case XK_BackSpace:
  219612. keyPressed = true;
  219613. keyCode &= 0xff;
  219614. break;
  219615. default:
  219616. if (sym >= XK_F1 && sym <= XK_F16)
  219617. {
  219618. keyPressed = true;
  219619. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219620. }
  219621. break;
  219622. }
  219623. }
  219624. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219625. keyPressed = true;
  219626. if (oldMods != currentModifiers)
  219627. handleModifierKeysChange();
  219628. if (keyDownChange)
  219629. handleKeyUpOrDown (true);
  219630. if (keyPressed)
  219631. handleKeyPress (keyCode, unicodeChar);
  219632. }
  219633. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219634. {
  219635. updateKeyStates (keyEvent->keycode, false);
  219636. KeySym sym;
  219637. {
  219638. ScopedXLock xlock;
  219639. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219640. }
  219641. const ModifierKeys oldMods (currentModifiers);
  219642. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219643. if (oldMods != currentModifiers)
  219644. handleModifierKeysChange();
  219645. if (keyDownChange)
  219646. handleKeyUpOrDown (false);
  219647. }
  219648. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219649. {
  219650. updateKeyModifiers (buttonPressEvent->state);
  219651. bool buttonMsg = false;
  219652. const int map = pointerMap [buttonPressEvent->button - Button1];
  219653. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219654. {
  219655. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219656. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219657. }
  219658. if (map == Keys::LeftButton)
  219659. {
  219660. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219661. buttonMsg = true;
  219662. }
  219663. else if (map == Keys::RightButton)
  219664. {
  219665. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219666. buttonMsg = true;
  219667. }
  219668. else if (map == Keys::MiddleButton)
  219669. {
  219670. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219671. buttonMsg = true;
  219672. }
  219673. if (buttonMsg)
  219674. {
  219675. toFront (true);
  219676. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219677. getEventTime (buttonPressEvent->time));
  219678. }
  219679. clearLastMousePos();
  219680. }
  219681. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219682. {
  219683. updateKeyModifiers (buttonRelEvent->state);
  219684. const int map = pointerMap [buttonRelEvent->button - Button1];
  219685. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219686. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219687. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219688. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219689. getEventTime (buttonRelEvent->time));
  219690. clearLastMousePos();
  219691. }
  219692. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219693. {
  219694. updateKeyModifiers (movedEvent->state);
  219695. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219696. if (lastMousePos != mousePos)
  219697. {
  219698. lastMousePos = mousePos;
  219699. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219700. {
  219701. Window wRoot = 0, wParent = 0;
  219702. {
  219703. ScopedXLock xlock;
  219704. unsigned int numChildren;
  219705. Window* wChild = 0;
  219706. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219707. }
  219708. if (wParent != 0
  219709. && wParent != windowH
  219710. && wParent != wRoot)
  219711. {
  219712. parentWindow = wParent;
  219713. updateBounds();
  219714. }
  219715. else
  219716. {
  219717. parentWindow = 0;
  219718. }
  219719. }
  219720. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219721. }
  219722. }
  219723. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219724. {
  219725. clearLastMousePos();
  219726. if (! currentModifiers.isAnyMouseButtonDown())
  219727. {
  219728. updateKeyModifiers (enterEvent->state);
  219729. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219730. }
  219731. }
  219732. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219733. {
  219734. // Suppress the normal leave if we've got a pointer grab, or if
  219735. // it's a bogus one caused by clicking a mouse button when running
  219736. // in a Window manager
  219737. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219738. || leaveEvent->mode == NotifyUngrab)
  219739. {
  219740. updateKeyModifiers (leaveEvent->state);
  219741. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219742. }
  219743. }
  219744. void handleFocusInEvent()
  219745. {
  219746. isActiveApplication = true;
  219747. if (isFocused())
  219748. handleFocusGain();
  219749. }
  219750. void handleFocusOutEvent()
  219751. {
  219752. isActiveApplication = false;
  219753. if (! isFocused())
  219754. handleFocusLoss();
  219755. }
  219756. void handleExposeEvent (XExposeEvent* exposeEvent)
  219757. {
  219758. // Batch together all pending expose events
  219759. XEvent nextEvent;
  219760. ScopedXLock xlock;
  219761. if (exposeEvent->window != windowH)
  219762. {
  219763. Window child;
  219764. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219765. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219766. &child);
  219767. }
  219768. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219769. exposeEvent->width, exposeEvent->height));
  219770. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219771. {
  219772. XPeekEvent (display, (XEvent*) &nextEvent);
  219773. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  219774. break;
  219775. XNextEvent (display, (XEvent*) &nextEvent);
  219776. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219777. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219778. nextExposeEvent->width, nextExposeEvent->height));
  219779. }
  219780. }
  219781. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  219782. {
  219783. updateBounds();
  219784. updateBorderSize();
  219785. handleMovedOrResized();
  219786. // if the native title bar is dragged, need to tell any active menus, etc.
  219787. if ((styleFlags & windowHasTitleBar) != 0
  219788. && component->isCurrentlyBlockedByAnotherModalComponent())
  219789. {
  219790. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219791. if (currentModalComp != 0)
  219792. currentModalComp->inputAttemptWhenModal();
  219793. }
  219794. if (confEvent->window == windowH
  219795. && confEvent->above != 0
  219796. && isFrontWindow())
  219797. {
  219798. handleBroughtToFront();
  219799. }
  219800. }
  219801. void handleReparentNotifyEvent()
  219802. {
  219803. parentWindow = 0;
  219804. Window wRoot = 0;
  219805. Window* wChild = 0;
  219806. unsigned int numChildren;
  219807. {
  219808. ScopedXLock xlock;
  219809. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219810. }
  219811. if (parentWindow == windowH || parentWindow == wRoot)
  219812. parentWindow = 0;
  219813. handleGravityNotify();
  219814. }
  219815. void handleGravityNotify()
  219816. {
  219817. updateBounds();
  219818. updateBorderSize();
  219819. handleMovedOrResized();
  219820. }
  219821. void handleMappingNotify (XMappingEvent* const mappingEvent)
  219822. {
  219823. if (mappingEvent->request != MappingPointer)
  219824. {
  219825. // Deal with modifier/keyboard mapping
  219826. ScopedXLock xlock;
  219827. XRefreshKeyboardMapping (mappingEvent);
  219828. updateModifierMappings();
  219829. }
  219830. }
  219831. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  219832. {
  219833. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219834. {
  219835. const Atom atom = (Atom) clientMsg->data.l[0];
  219836. if (atom == Atoms::ProtocolList [Atoms::PING])
  219837. {
  219838. Window root = RootWindow (display, DefaultScreen (display));
  219839. clientMsg->window = root;
  219840. XSendEvent (display, root, False, NoEventMask, event);
  219841. XFlush (display);
  219842. }
  219843. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219844. {
  219845. XWindowAttributes atts;
  219846. ScopedXLock xlock;
  219847. if (clientMsg->window != 0
  219848. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219849. {
  219850. if (atts.map_state == IsViewable)
  219851. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219852. }
  219853. }
  219854. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219855. {
  219856. handleUserClosingWindow();
  219857. }
  219858. }
  219859. else if (clientMsg->message_type == Atoms::XdndEnter)
  219860. {
  219861. handleDragAndDropEnter (clientMsg);
  219862. }
  219863. else if (clientMsg->message_type == Atoms::XdndLeave)
  219864. {
  219865. resetDragAndDrop();
  219866. }
  219867. else if (clientMsg->message_type == Atoms::XdndPosition)
  219868. {
  219869. handleDragAndDropPosition (clientMsg);
  219870. }
  219871. else if (clientMsg->message_type == Atoms::XdndDrop)
  219872. {
  219873. handleDragAndDropDrop (clientMsg);
  219874. }
  219875. else if (clientMsg->message_type == Atoms::XdndStatus)
  219876. {
  219877. handleDragAndDropStatus (clientMsg);
  219878. }
  219879. else if (clientMsg->message_type == Atoms::XdndFinished)
  219880. {
  219881. resetDragAndDrop();
  219882. }
  219883. }
  219884. void showMouseCursor (Cursor cursor) throw()
  219885. {
  219886. ScopedXLock xlock;
  219887. XDefineCursor (display, windowH, cursor);
  219888. }
  219889. void setTaskBarIcon (const Image& image)
  219890. {
  219891. ScopedXLock xlock;
  219892. taskbarImage = image;
  219893. Screen* const screen = XDefaultScreenOfDisplay (display);
  219894. const int screenNumber = XScreenNumberOfScreen (screen);
  219895. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219896. screenAtom << screenNumber;
  219897. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219898. XGrabServer (display);
  219899. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219900. if (managerWin != None)
  219901. XSelectInput (display, managerWin, StructureNotifyMask);
  219902. XUngrabServer (display);
  219903. XFlush (display);
  219904. if (managerWin != None)
  219905. {
  219906. XEvent ev;
  219907. zerostruct (ev);
  219908. ev.xclient.type = ClientMessage;
  219909. ev.xclient.window = managerWin;
  219910. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219911. ev.xclient.format = 32;
  219912. ev.xclient.data.l[0] = CurrentTime;
  219913. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219914. ev.xclient.data.l[2] = windowH;
  219915. ev.xclient.data.l[3] = 0;
  219916. ev.xclient.data.l[4] = 0;
  219917. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219918. XSync (display, False);
  219919. }
  219920. // For older KDE's ...
  219921. long atomData = 1;
  219922. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219923. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219924. // For more recent KDE's...
  219925. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219926. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219927. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219928. XSizeHints* hints = XAllocSizeHints();
  219929. hints->flags = PMinSize;
  219930. hints->min_width = 22;
  219931. hints->min_height = 22;
  219932. XSetWMNormalHints (display, windowH, hints);
  219933. XFree (hints);
  219934. }
  219935. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219936. bool dontRepaint;
  219937. static ModifierKeys currentModifiers;
  219938. static bool isActiveApplication;
  219939. private:
  219940. class LinuxRepaintManager : public Timer
  219941. {
  219942. public:
  219943. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219944. : peer (peer_),
  219945. lastTimeImageUsed (0)
  219946. {
  219947. #if JUCE_USE_XSHM
  219948. shmCompletedDrawing = true;
  219949. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219950. if (useARGBImagesForRendering)
  219951. {
  219952. ScopedXLock xlock;
  219953. XShmSegmentInfo segmentinfo;
  219954. XImage* const testImage
  219955. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219956. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219957. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219958. XDestroyImage (testImage);
  219959. }
  219960. #endif
  219961. }
  219962. void timerCallback()
  219963. {
  219964. #if JUCE_USE_XSHM
  219965. if (! shmCompletedDrawing)
  219966. return;
  219967. #endif
  219968. if (! regionsNeedingRepaint.isEmpty())
  219969. {
  219970. stopTimer();
  219971. performAnyPendingRepaintsNow();
  219972. }
  219973. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219974. {
  219975. stopTimer();
  219976. image = Image::null;
  219977. }
  219978. }
  219979. void repaint (const Rectangle<int>& area)
  219980. {
  219981. if (! isTimerRunning())
  219982. startTimer (repaintTimerPeriod);
  219983. regionsNeedingRepaint.add (area);
  219984. }
  219985. void performAnyPendingRepaintsNow()
  219986. {
  219987. #if JUCE_USE_XSHM
  219988. if (! shmCompletedDrawing)
  219989. {
  219990. startTimer (repaintTimerPeriod);
  219991. return;
  219992. }
  219993. #endif
  219994. peer->clearMaskedRegion();
  219995. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219996. regionsNeedingRepaint.clear();
  219997. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219998. if (! totalArea.isEmpty())
  219999. {
  220000. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220001. || image.getHeight() < totalArea.getHeight())
  220002. {
  220003. #if JUCE_USE_XSHM
  220004. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220005. : Image::RGB,
  220006. #else
  220007. image = Image (new XBitmapImage (Image::RGB,
  220008. #endif
  220009. (totalArea.getWidth() + 31) & ~31,
  220010. (totalArea.getHeight() + 31) & ~31,
  220011. false, peer->depth, peer->visual));
  220012. }
  220013. startTimer (repaintTimerPeriod);
  220014. RectangleList adjustedList (originalRepaintRegion);
  220015. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220016. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220017. if (peer->depth == 32)
  220018. {
  220019. RectangleList::Iterator i (originalRepaintRegion);
  220020. while (i.next())
  220021. image.clear (*i.getRectangle() - totalArea.getPosition());
  220022. }
  220023. peer->handlePaint (context);
  220024. if (! peer->maskedRegion.isEmpty())
  220025. originalRepaintRegion.subtract (peer->maskedRegion);
  220026. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220027. {
  220028. #if JUCE_USE_XSHM
  220029. shmCompletedDrawing = false;
  220030. #endif
  220031. const Rectangle<int>& r = *i.getRectangle();
  220032. static_cast<XBitmapImage*> (image.getSharedImage())
  220033. ->blitToWindow (peer->windowH,
  220034. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220035. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220036. }
  220037. }
  220038. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220039. startTimer (repaintTimerPeriod);
  220040. }
  220041. #if JUCE_USE_XSHM
  220042. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220043. #endif
  220044. private:
  220045. enum { repaintTimerPeriod = 1000 / 100 };
  220046. LinuxComponentPeer* const peer;
  220047. Image image;
  220048. uint32 lastTimeImageUsed;
  220049. RectangleList regionsNeedingRepaint;
  220050. #if JUCE_USE_XSHM
  220051. bool useARGBImagesForRendering, shmCompletedDrawing;
  220052. #endif
  220053. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220054. };
  220055. ScopedPointer <LinuxRepaintManager> repainter;
  220056. friend class LinuxRepaintManager;
  220057. Window windowH, parentWindow;
  220058. int wx, wy, ww, wh;
  220059. Image taskbarImage;
  220060. bool fullScreen, mapped;
  220061. Visual* visual;
  220062. int depth;
  220063. BorderSize<int> windowBorder;
  220064. struct MotifWmHints
  220065. {
  220066. unsigned long flags;
  220067. unsigned long functions;
  220068. unsigned long decorations;
  220069. long input_mode;
  220070. unsigned long status;
  220071. };
  220072. static void updateKeyStates (const int keycode, const bool press) throw()
  220073. {
  220074. const int keybyte = keycode >> 3;
  220075. const int keybit = (1 << (keycode & 7));
  220076. if (press)
  220077. Keys::keyStates [keybyte] |= keybit;
  220078. else
  220079. Keys::keyStates [keybyte] &= ~keybit;
  220080. }
  220081. static void updateKeyModifiers (const int status) throw()
  220082. {
  220083. int keyMods = 0;
  220084. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220085. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220086. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220087. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220088. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220089. Keys::capsLock = ((status & LockMask) != 0);
  220090. }
  220091. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220092. {
  220093. int modifier = 0;
  220094. bool isModifier = true;
  220095. switch (sym)
  220096. {
  220097. case XK_Shift_L:
  220098. case XK_Shift_R:
  220099. modifier = ModifierKeys::shiftModifier;
  220100. break;
  220101. case XK_Control_L:
  220102. case XK_Control_R:
  220103. modifier = ModifierKeys::ctrlModifier;
  220104. break;
  220105. case XK_Alt_L:
  220106. case XK_Alt_R:
  220107. modifier = ModifierKeys::altModifier;
  220108. break;
  220109. case XK_Num_Lock:
  220110. if (press)
  220111. Keys::numLock = ! Keys::numLock;
  220112. break;
  220113. case XK_Caps_Lock:
  220114. if (press)
  220115. Keys::capsLock = ! Keys::capsLock;
  220116. break;
  220117. case XK_Scroll_Lock:
  220118. break;
  220119. default:
  220120. isModifier = false;
  220121. break;
  220122. }
  220123. if (modifier != 0)
  220124. {
  220125. if (press)
  220126. currentModifiers = currentModifiers.withFlags (modifier);
  220127. else
  220128. currentModifiers = currentModifiers.withoutFlags (modifier);
  220129. }
  220130. return isModifier;
  220131. }
  220132. // Alt and Num lock are not defined by standard X
  220133. // modifier constants: check what they're mapped to
  220134. static void updateModifierMappings() throw()
  220135. {
  220136. ScopedXLock xlock;
  220137. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220138. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220139. Keys::AltMask = 0;
  220140. Keys::NumLockMask = 0;
  220141. XModifierKeymap* mapping = XGetModifierMapping (display);
  220142. if (mapping)
  220143. {
  220144. for (int i = 0; i < 8; i++)
  220145. {
  220146. if (mapping->modifiermap [i << 1] == altLeftCode)
  220147. Keys::AltMask = 1 << i;
  220148. else if (mapping->modifiermap [i << 1] == numLockCode)
  220149. Keys::NumLockMask = 1 << i;
  220150. }
  220151. XFreeModifiermap (mapping);
  220152. }
  220153. }
  220154. void removeWindowDecorations (Window wndH)
  220155. {
  220156. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220157. if (hints != None)
  220158. {
  220159. MotifWmHints motifHints;
  220160. zerostruct (motifHints);
  220161. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220162. motifHints.decorations = 0;
  220163. ScopedXLock xlock;
  220164. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220165. (unsigned char*) &motifHints, 4);
  220166. }
  220167. hints = XInternAtom (display, "_WIN_HINTS", True);
  220168. if (hints != None)
  220169. {
  220170. long gnomeHints = 0;
  220171. ScopedXLock xlock;
  220172. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220173. (unsigned char*) &gnomeHints, 1);
  220174. }
  220175. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220176. if (hints != None)
  220177. {
  220178. long kwmHints = 2; /*KDE_tinyDecoration*/
  220179. ScopedXLock xlock;
  220180. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220181. (unsigned char*) &kwmHints, 1);
  220182. }
  220183. }
  220184. void addWindowButtons (Window wndH)
  220185. {
  220186. ScopedXLock xlock;
  220187. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220188. if (hints != None)
  220189. {
  220190. MotifWmHints motifHints;
  220191. zerostruct (motifHints);
  220192. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220193. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220194. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220195. if ((styleFlags & windowHasCloseButton) != 0)
  220196. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220197. if ((styleFlags & windowHasMinimiseButton) != 0)
  220198. {
  220199. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220200. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220201. }
  220202. if ((styleFlags & windowHasMaximiseButton) != 0)
  220203. {
  220204. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220205. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220206. }
  220207. if ((styleFlags & windowIsResizable) != 0)
  220208. {
  220209. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220210. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220211. }
  220212. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220213. }
  220214. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220215. if (hints != None)
  220216. {
  220217. int netHints [6];
  220218. int num = 0;
  220219. if ((styleFlags & windowIsResizable) != 0)
  220220. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220221. if ((styleFlags & windowHasMaximiseButton) != 0)
  220222. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220223. if ((styleFlags & windowHasMinimiseButton) != 0)
  220224. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220225. if ((styleFlags & windowHasCloseButton) != 0)
  220226. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220227. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220228. }
  220229. }
  220230. void setWindowType()
  220231. {
  220232. int netHints [2];
  220233. int numHints = 0;
  220234. if ((styleFlags & windowIsTemporary) != 0
  220235. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220236. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220237. else
  220238. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220239. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220240. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220241. (unsigned char*) &netHints, numHints);
  220242. numHints = 0;
  220243. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220244. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220245. if (component->isAlwaysOnTop())
  220246. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220247. if (numHints > 0)
  220248. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220249. (unsigned char*) &netHints, numHints);
  220250. }
  220251. void createWindow()
  220252. {
  220253. ScopedXLock xlock;
  220254. Atoms::initialiseAtoms();
  220255. resetDragAndDrop();
  220256. // Get defaults for various properties
  220257. const int screen = DefaultScreen (display);
  220258. Window root = RootWindow (display, screen);
  220259. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220260. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220261. if (visual == 0)
  220262. {
  220263. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220264. Process::terminate();
  220265. }
  220266. // Create and install a colormap suitable fr our visual
  220267. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220268. XInstallColormap (display, colormap);
  220269. // Set up the window attributes
  220270. XSetWindowAttributes swa;
  220271. swa.border_pixel = 0;
  220272. swa.background_pixmap = None;
  220273. swa.colormap = colormap;
  220274. swa.event_mask = getAllEventsMask();
  220275. windowH = XCreateWindow (display, root,
  220276. 0, 0, 1, 1,
  220277. 0, depth, InputOutput, visual,
  220278. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220279. &swa);
  220280. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220281. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220282. GrabModeAsync, GrabModeAsync, None, None);
  220283. // Set the window context to identify the window handle object
  220284. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220285. {
  220286. // Failed
  220287. jassertfalse;
  220288. Logger::outputDebugString ("Failed to create context information for window.\n");
  220289. XDestroyWindow (display, windowH);
  220290. windowH = 0;
  220291. return;
  220292. }
  220293. // Set window manager hints
  220294. XWMHints* wmHints = XAllocWMHints();
  220295. wmHints->flags = InputHint | StateHint;
  220296. wmHints->input = True; // Locally active input model
  220297. wmHints->initial_state = NormalState;
  220298. XSetWMHints (display, windowH, wmHints);
  220299. XFree (wmHints);
  220300. // Set the window type
  220301. setWindowType();
  220302. // Define decoration
  220303. if ((styleFlags & windowHasTitleBar) == 0)
  220304. removeWindowDecorations (windowH);
  220305. else
  220306. addWindowButtons (windowH);
  220307. setTitle (getComponent()->getName());
  220308. // Associate the PID, allowing to be shut down when something goes wrong
  220309. unsigned long pid = getpid();
  220310. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220311. (unsigned char*) &pid, 1);
  220312. // Set window manager protocols
  220313. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220314. (unsigned char*) Atoms::ProtocolList, 2);
  220315. // Set drag and drop flags
  220316. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220317. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220318. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220319. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220320. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220321. (const unsigned char*) "", 0);
  220322. unsigned long dndVersion = Atoms::DndVersion;
  220323. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220324. (const unsigned char*) &dndVersion, 1);
  220325. // Initialise the pointer and keyboard mapping
  220326. // This is not the same as the logical pointer mapping the X server uses:
  220327. // we don't mess with this.
  220328. static bool mappingInitialised = false;
  220329. if (! mappingInitialised)
  220330. {
  220331. mappingInitialised = true;
  220332. const int numButtons = XGetPointerMapping (display, 0, 0);
  220333. if (numButtons == 2)
  220334. {
  220335. pointerMap[0] = Keys::LeftButton;
  220336. pointerMap[1] = Keys::RightButton;
  220337. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220338. }
  220339. else if (numButtons >= 3)
  220340. {
  220341. pointerMap[0] = Keys::LeftButton;
  220342. pointerMap[1] = Keys::MiddleButton;
  220343. pointerMap[2] = Keys::RightButton;
  220344. if (numButtons >= 5)
  220345. {
  220346. pointerMap[3] = Keys::WheelUp;
  220347. pointerMap[4] = Keys::WheelDown;
  220348. }
  220349. }
  220350. updateModifierMappings();
  220351. }
  220352. }
  220353. void destroyWindow()
  220354. {
  220355. ScopedXLock xlock;
  220356. XPointer handlePointer;
  220357. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220358. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220359. XDestroyWindow (display, windowH);
  220360. // Wait for it to complete and then remove any events for this
  220361. // window from the event queue.
  220362. XSync (display, false);
  220363. XEvent event;
  220364. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220365. {}
  220366. }
  220367. static int getAllEventsMask() throw()
  220368. {
  220369. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220370. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220371. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220372. }
  220373. static int64 getEventTime (::Time t)
  220374. {
  220375. static int64 eventTimeOffset = 0x12345678;
  220376. const int64 thisMessageTime = t;
  220377. if (eventTimeOffset == 0x12345678)
  220378. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220379. return eventTimeOffset + thisMessageTime;
  220380. }
  220381. void updateBorderSize()
  220382. {
  220383. if ((styleFlags & windowHasTitleBar) == 0)
  220384. {
  220385. windowBorder = BorderSize<int> (0);
  220386. }
  220387. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220388. {
  220389. ScopedXLock xlock;
  220390. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220391. if (hints != None)
  220392. {
  220393. unsigned char* data = 0;
  220394. unsigned long nitems, bytesLeft;
  220395. Atom actualType;
  220396. int actualFormat;
  220397. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220398. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220399. &data) == Success)
  220400. {
  220401. const unsigned long* const sizes = (const unsigned long*) data;
  220402. if (actualFormat == 32)
  220403. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220404. (int) sizes[3], (int) sizes[1]);
  220405. XFree (data);
  220406. }
  220407. }
  220408. }
  220409. }
  220410. void updateBounds()
  220411. {
  220412. jassert (windowH != 0);
  220413. if (windowH != 0)
  220414. {
  220415. Window root, child;
  220416. unsigned int bw, depth;
  220417. ScopedXLock xlock;
  220418. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220419. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220420. &bw, &depth))
  220421. {
  220422. wx = wy = ww = wh = 0;
  220423. }
  220424. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220425. {
  220426. wx = wy = 0;
  220427. }
  220428. }
  220429. }
  220430. void resetDragAndDrop()
  220431. {
  220432. dragAndDropFiles.clear();
  220433. lastDropPos = Point<int> (-1, -1);
  220434. dragAndDropCurrentMimeType = 0;
  220435. dragAndDropSourceWindow = 0;
  220436. srcMimeTypeAtomList.clear();
  220437. }
  220438. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220439. {
  220440. msg.type = ClientMessage;
  220441. msg.display = display;
  220442. msg.window = dragAndDropSourceWindow;
  220443. msg.format = 32;
  220444. msg.data.l[0] = windowH;
  220445. ScopedXLock xlock;
  220446. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220447. }
  220448. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220449. {
  220450. XClientMessageEvent msg;
  220451. zerostruct (msg);
  220452. msg.message_type = Atoms::XdndStatus;
  220453. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220454. msg.data.l[4] = dropAction;
  220455. sendDragAndDropMessage (msg);
  220456. }
  220457. void sendDragAndDropLeave()
  220458. {
  220459. XClientMessageEvent msg;
  220460. zerostruct (msg);
  220461. msg.message_type = Atoms::XdndLeave;
  220462. sendDragAndDropMessage (msg);
  220463. }
  220464. void sendDragAndDropFinish()
  220465. {
  220466. XClientMessageEvent msg;
  220467. zerostruct (msg);
  220468. msg.message_type = Atoms::XdndFinished;
  220469. sendDragAndDropMessage (msg);
  220470. }
  220471. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220472. {
  220473. if ((clientMsg->data.l[1] & 1) == 0)
  220474. {
  220475. sendDragAndDropLeave();
  220476. if (dragAndDropFiles.size() > 0)
  220477. handleFileDragExit (dragAndDropFiles);
  220478. dragAndDropFiles.clear();
  220479. }
  220480. }
  220481. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220482. {
  220483. if (dragAndDropSourceWindow == 0)
  220484. return;
  220485. dragAndDropSourceWindow = clientMsg->data.l[0];
  220486. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220487. (int) clientMsg->data.l[2] & 0xffff);
  220488. dropPos -= getScreenPosition();
  220489. if (lastDropPos != dropPos)
  220490. {
  220491. lastDropPos = dropPos;
  220492. dragAndDropTimestamp = clientMsg->data.l[3];
  220493. Atom targetAction = Atoms::XdndActionCopy;
  220494. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220495. {
  220496. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220497. {
  220498. targetAction = Atoms::allowedActions[i];
  220499. break;
  220500. }
  220501. }
  220502. sendDragAndDropStatus (true, targetAction);
  220503. if (dragAndDropFiles.size() == 0)
  220504. updateDraggedFileList (clientMsg);
  220505. if (dragAndDropFiles.size() > 0)
  220506. handleFileDragMove (dragAndDropFiles, dropPos);
  220507. }
  220508. }
  220509. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220510. {
  220511. if (dragAndDropFiles.size() == 0)
  220512. updateDraggedFileList (clientMsg);
  220513. const StringArray files (dragAndDropFiles);
  220514. const Point<int> lastPos (lastDropPos);
  220515. sendDragAndDropFinish();
  220516. resetDragAndDrop();
  220517. if (files.size() > 0)
  220518. handleFileDragDrop (files, lastPos);
  220519. }
  220520. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220521. {
  220522. dragAndDropFiles.clear();
  220523. srcMimeTypeAtomList.clear();
  220524. dragAndDropCurrentMimeType = 0;
  220525. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220526. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220527. {
  220528. dragAndDropSourceWindow = 0;
  220529. return;
  220530. }
  220531. dragAndDropSourceWindow = clientMsg->data.l[0];
  220532. if ((clientMsg->data.l[1] & 1) != 0)
  220533. {
  220534. Atom actual;
  220535. int format;
  220536. unsigned long count = 0, remaining = 0;
  220537. unsigned char* data = 0;
  220538. ScopedXLock xlock;
  220539. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220540. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220541. &count, &remaining, &data);
  220542. if (data != 0)
  220543. {
  220544. if (actual == XA_ATOM && format == 32 && count != 0)
  220545. {
  220546. const unsigned long* const types = (const unsigned long*) data;
  220547. for (unsigned int i = 0; i < count; ++i)
  220548. if (types[i] != None)
  220549. srcMimeTypeAtomList.add (types[i]);
  220550. }
  220551. XFree (data);
  220552. }
  220553. }
  220554. if (srcMimeTypeAtomList.size() == 0)
  220555. {
  220556. for (int i = 2; i < 5; ++i)
  220557. if (clientMsg->data.l[i] != None)
  220558. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220559. if (srcMimeTypeAtomList.size() == 0)
  220560. {
  220561. dragAndDropSourceWindow = 0;
  220562. return;
  220563. }
  220564. }
  220565. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220566. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220567. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220568. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220569. handleDragAndDropPosition (clientMsg);
  220570. }
  220571. void handleDragAndDropSelection (const XEvent* const evt)
  220572. {
  220573. dragAndDropFiles.clear();
  220574. if (evt->xselection.property != 0)
  220575. {
  220576. StringArray lines;
  220577. {
  220578. MemoryBlock dropData;
  220579. for (;;)
  220580. {
  220581. Atom actual;
  220582. uint8* data = 0;
  220583. unsigned long count = 0, remaining = 0;
  220584. int format = 0;
  220585. ScopedXLock xlock;
  220586. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220587. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220588. &format, &count, &remaining, &data) == Success)
  220589. {
  220590. dropData.append (data, count * format / 8);
  220591. XFree (data);
  220592. if (remaining == 0)
  220593. break;
  220594. }
  220595. else
  220596. {
  220597. XFree (data);
  220598. break;
  220599. }
  220600. }
  220601. lines.addLines (dropData.toString());
  220602. }
  220603. for (int i = 0; i < lines.size(); ++i)
  220604. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220605. dragAndDropFiles.trim();
  220606. dragAndDropFiles.removeEmptyStrings();
  220607. }
  220608. }
  220609. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220610. {
  220611. dragAndDropFiles.clear();
  220612. if (dragAndDropSourceWindow != None
  220613. && dragAndDropCurrentMimeType != 0)
  220614. {
  220615. dragAndDropTimestamp = clientMsg->data.l[2];
  220616. ScopedXLock xlock;
  220617. XConvertSelection (display,
  220618. Atoms::XdndSelection,
  220619. dragAndDropCurrentMimeType,
  220620. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220621. windowH,
  220622. dragAndDropTimestamp);
  220623. }
  220624. }
  220625. StringArray dragAndDropFiles;
  220626. int dragAndDropTimestamp;
  220627. Point<int> lastDropPos;
  220628. Atom dragAndDropCurrentMimeType;
  220629. Window dragAndDropSourceWindow;
  220630. Array <Atom> srcMimeTypeAtomList;
  220631. static int pointerMap[5];
  220632. static Point<int> lastMousePos;
  220633. static void clearLastMousePos() throw()
  220634. {
  220635. lastMousePos = Point<int> (0x100000, 0x100000);
  220636. }
  220637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220638. };
  220639. ModifierKeys LinuxComponentPeer::currentModifiers;
  220640. bool LinuxComponentPeer::isActiveApplication = false;
  220641. int LinuxComponentPeer::pointerMap[5];
  220642. Point<int> LinuxComponentPeer::lastMousePos;
  220643. bool Process::isForegroundProcess()
  220644. {
  220645. return LinuxComponentPeer::isActiveApplication;
  220646. }
  220647. void ModifierKeys::updateCurrentModifiers() throw()
  220648. {
  220649. currentModifiers = LinuxComponentPeer::currentModifiers;
  220650. }
  220651. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220652. {
  220653. Window root, child;
  220654. int x, y, winx, winy;
  220655. unsigned int mask;
  220656. int mouseMods = 0;
  220657. ScopedXLock xlock;
  220658. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220659. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220660. {
  220661. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220662. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220663. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220664. }
  220665. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220666. return LinuxComponentPeer::currentModifiers;
  220667. }
  220668. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220669. {
  220670. if (enableOrDisable)
  220671. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220672. }
  220673. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220674. {
  220675. return new LinuxComponentPeer (this, styleFlags);
  220676. }
  220677. // (this callback is hooked up in the messaging code)
  220678. void juce_windowMessageReceive (XEvent* event)
  220679. {
  220680. if (event->xany.window != None)
  220681. {
  220682. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220683. if (ComponentPeer::isValidPeer (peer))
  220684. peer->handleWindowMessage (event);
  220685. }
  220686. else
  220687. {
  220688. switch (event->xany.type)
  220689. {
  220690. case KeymapNotify:
  220691. {
  220692. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220693. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220694. break;
  220695. }
  220696. default:
  220697. break;
  220698. }
  220699. }
  220700. }
  220701. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220702. {
  220703. if (display == 0)
  220704. return;
  220705. #if JUCE_USE_XINERAMA
  220706. int major_opcode, first_event, first_error;
  220707. ScopedXLock xlock;
  220708. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220709. {
  220710. typedef Bool (*tXineramaIsActive) (Display*);
  220711. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220712. static tXineramaIsActive xXineramaIsActive = 0;
  220713. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220714. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220715. {
  220716. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220717. if (h == 0)
  220718. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220719. if (h != 0)
  220720. {
  220721. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220722. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220723. }
  220724. }
  220725. if (xXineramaIsActive != 0
  220726. && xXineramaQueryScreens != 0
  220727. && xXineramaIsActive (display))
  220728. {
  220729. int numMonitors = 0;
  220730. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220731. if (screens != 0)
  220732. {
  220733. for (int i = numMonitors; --i >= 0;)
  220734. {
  220735. int index = screens[i].screen_number;
  220736. if (index >= 0)
  220737. {
  220738. while (monitorCoords.size() < index)
  220739. monitorCoords.add (Rectangle<int>());
  220740. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220741. screens[i].y_org,
  220742. screens[i].width,
  220743. screens[i].height));
  220744. }
  220745. }
  220746. XFree (screens);
  220747. }
  220748. }
  220749. }
  220750. if (monitorCoords.size() == 0)
  220751. #endif
  220752. {
  220753. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220754. if (hints != None)
  220755. {
  220756. const int numMonitors = ScreenCount (display);
  220757. for (int i = 0; i < numMonitors; ++i)
  220758. {
  220759. Window root = RootWindow (display, i);
  220760. unsigned long nitems, bytesLeft;
  220761. Atom actualType;
  220762. int actualFormat;
  220763. unsigned char* data = 0;
  220764. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220765. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220766. &data) == Success)
  220767. {
  220768. const long* const position = (const long*) data;
  220769. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220770. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220771. position[2], position[3]));
  220772. XFree (data);
  220773. }
  220774. }
  220775. }
  220776. if (monitorCoords.size() == 0)
  220777. {
  220778. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220779. DisplayHeight (display, DefaultScreen (display))));
  220780. }
  220781. }
  220782. }
  220783. void Desktop::createMouseInputSources()
  220784. {
  220785. mouseSources.add (new MouseInputSource (0, true));
  220786. }
  220787. bool Desktop::canUseSemiTransparentWindows() throw()
  220788. {
  220789. int matchedDepth = 0;
  220790. const int desiredDepth = 32;
  220791. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220792. && (matchedDepth == desiredDepth);
  220793. }
  220794. const Point<int> MouseInputSource::getCurrentMousePosition()
  220795. {
  220796. Window root, child;
  220797. int x, y, winx, winy;
  220798. unsigned int mask;
  220799. ScopedXLock xlock;
  220800. if (XQueryPointer (display,
  220801. RootWindow (display, DefaultScreen (display)),
  220802. &root, &child,
  220803. &x, &y, &winx, &winy, &mask) == False)
  220804. {
  220805. // Pointer not on the default screen
  220806. x = y = -1;
  220807. }
  220808. return Point<int> (x, y);
  220809. }
  220810. void Desktop::setMousePosition (const Point<int>& newPosition)
  220811. {
  220812. ScopedXLock xlock;
  220813. Window root = RootWindow (display, DefaultScreen (display));
  220814. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220815. }
  220816. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  220817. {
  220818. return upright;
  220819. }
  220820. static bool screenSaverAllowed = true;
  220821. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220822. {
  220823. if (screenSaverAllowed != isEnabled)
  220824. {
  220825. screenSaverAllowed = isEnabled;
  220826. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220827. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220828. if (xScreenSaverSuspend == 0)
  220829. {
  220830. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220831. if (h != 0)
  220832. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220833. }
  220834. ScopedXLock xlock;
  220835. if (xScreenSaverSuspend != 0)
  220836. xScreenSaverSuspend (display, ! isEnabled);
  220837. }
  220838. }
  220839. bool Desktop::isScreenSaverEnabled()
  220840. {
  220841. return screenSaverAllowed;
  220842. }
  220843. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220844. {
  220845. ScopedXLock xlock;
  220846. const unsigned int imageW = image.getWidth();
  220847. const unsigned int imageH = image.getHeight();
  220848. #if JUCE_USE_XCURSOR
  220849. {
  220850. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220851. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220852. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220853. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220854. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220855. static tXcursorImageCreate xXcursorImageCreate = 0;
  220856. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220857. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220858. static bool hasBeenLoaded = false;
  220859. if (! hasBeenLoaded)
  220860. {
  220861. hasBeenLoaded = true;
  220862. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220863. if (h != 0)
  220864. {
  220865. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220866. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220867. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220868. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220869. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220870. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220871. || ! xXcursorSupportsARGB (display))
  220872. xXcursorSupportsARGB = 0;
  220873. }
  220874. }
  220875. if (xXcursorSupportsARGB != 0)
  220876. {
  220877. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220878. if (xcImage != 0)
  220879. {
  220880. xcImage->xhot = hotspotX;
  220881. xcImage->yhot = hotspotY;
  220882. XcursorPixel* dest = xcImage->pixels;
  220883. for (int y = 0; y < (int) imageH; ++y)
  220884. for (int x = 0; x < (int) imageW; ++x)
  220885. *dest++ = image.getPixelAt (x, y).getARGB();
  220886. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220887. xXcursorImageDestroy (xcImage);
  220888. if (result != 0)
  220889. return result;
  220890. }
  220891. }
  220892. }
  220893. #endif
  220894. Window root = RootWindow (display, DefaultScreen (display));
  220895. unsigned int cursorW, cursorH;
  220896. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220897. return 0;
  220898. Image im (Image::ARGB, cursorW, cursorH, true);
  220899. {
  220900. Graphics g (im);
  220901. if (imageW > cursorW || imageH > cursorH)
  220902. {
  220903. hotspotX = (hotspotX * cursorW) / imageW;
  220904. hotspotY = (hotspotY * cursorH) / imageH;
  220905. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220906. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220907. false);
  220908. }
  220909. else
  220910. {
  220911. g.drawImageAt (image, 0, 0);
  220912. }
  220913. }
  220914. const int stride = (cursorW + 7) >> 3;
  220915. HeapBlock <char> maskPlane, sourcePlane;
  220916. maskPlane.calloc (stride * cursorH);
  220917. sourcePlane.calloc (stride * cursorH);
  220918. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220919. for (int y = cursorH; --y >= 0;)
  220920. {
  220921. for (int x = cursorW; --x >= 0;)
  220922. {
  220923. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220924. const int offset = y * stride + (x >> 3);
  220925. const Colour c (im.getPixelAt (x, y));
  220926. if (c.getAlpha() >= 128)
  220927. maskPlane[offset] |= mask;
  220928. if (c.getBrightness() >= 0.5f)
  220929. sourcePlane[offset] |= mask;
  220930. }
  220931. }
  220932. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220933. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220934. XColor white, black;
  220935. black.red = black.green = black.blue = 0;
  220936. white.red = white.green = white.blue = 0xffff;
  220937. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220938. XFreePixmap (display, sourcePixmap);
  220939. XFreePixmap (display, maskPixmap);
  220940. return result;
  220941. }
  220942. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220943. {
  220944. ScopedXLock xlock;
  220945. if (cursorHandle != 0)
  220946. XFreeCursor (display, (Cursor) cursorHandle);
  220947. }
  220948. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220949. {
  220950. unsigned int shape;
  220951. switch (type)
  220952. {
  220953. case NormalCursor: return None; // Use parent cursor
  220954. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220955. case WaitCursor: shape = XC_watch; break;
  220956. case IBeamCursor: shape = XC_xterm; break;
  220957. case PointingHandCursor: shape = XC_hand2; break;
  220958. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220959. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220960. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220961. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220962. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220963. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220964. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220965. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220966. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220967. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220968. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220969. case CrosshairCursor: shape = XC_crosshair; break;
  220970. case DraggingHandCursor:
  220971. {
  220972. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220973. 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,
  220974. 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 };
  220975. const int dragHandDataSize = 99;
  220976. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220977. }
  220978. case CopyingCursor:
  220979. {
  220980. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220981. 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,
  220982. 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,
  220983. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220984. const int copyCursorSize = 119;
  220985. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220986. }
  220987. default:
  220988. jassertfalse;
  220989. return None;
  220990. }
  220991. ScopedXLock xlock;
  220992. return (void*) XCreateFontCursor (display, shape);
  220993. }
  220994. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220995. {
  220996. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220997. if (lp != 0)
  220998. lp->showMouseCursor ((Cursor) getHandle());
  220999. }
  221000. void MouseCursor::showInAllWindows() const
  221001. {
  221002. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221003. showInWindow (ComponentPeer::getPeer (i));
  221004. }
  221005. const Image juce_createIconForFile (const File& file)
  221006. {
  221007. return Image::null;
  221008. }
  221009. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221010. {
  221011. return createSoftwareImage (format, width, height, clearImage);
  221012. }
  221013. #if JUCE_OPENGL
  221014. class WindowedGLContext : public OpenGLContext
  221015. {
  221016. public:
  221017. WindowedGLContext (Component* const component,
  221018. const OpenGLPixelFormat& pixelFormat_,
  221019. GLXContext sharedContext)
  221020. : renderContext (0),
  221021. embeddedWindow (0),
  221022. pixelFormat (pixelFormat_),
  221023. swapInterval (0)
  221024. {
  221025. jassert (component != 0);
  221026. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221027. if (peer == 0)
  221028. return;
  221029. ScopedXLock xlock;
  221030. XSync (display, False);
  221031. GLint attribs [64];
  221032. int n = 0;
  221033. attribs[n++] = GLX_RGBA;
  221034. attribs[n++] = GLX_DOUBLEBUFFER;
  221035. attribs[n++] = GLX_RED_SIZE;
  221036. attribs[n++] = pixelFormat.redBits;
  221037. attribs[n++] = GLX_GREEN_SIZE;
  221038. attribs[n++] = pixelFormat.greenBits;
  221039. attribs[n++] = GLX_BLUE_SIZE;
  221040. attribs[n++] = pixelFormat.blueBits;
  221041. attribs[n++] = GLX_ALPHA_SIZE;
  221042. attribs[n++] = pixelFormat.alphaBits;
  221043. attribs[n++] = GLX_DEPTH_SIZE;
  221044. attribs[n++] = pixelFormat.depthBufferBits;
  221045. attribs[n++] = GLX_STENCIL_SIZE;
  221046. attribs[n++] = pixelFormat.stencilBufferBits;
  221047. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221048. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221049. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221050. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221051. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221052. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221053. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221054. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221055. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221056. attribs[n++] = None;
  221057. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221058. if (bestVisual == 0)
  221059. return;
  221060. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221061. Window windowH = (Window) peer->getNativeHandle();
  221062. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221063. XSetWindowAttributes swa;
  221064. swa.colormap = colourMap;
  221065. swa.border_pixel = 0;
  221066. swa.event_mask = ExposureMask | StructureNotifyMask;
  221067. embeddedWindow = XCreateWindow (display, windowH,
  221068. 0, 0, 1, 1, 0,
  221069. bestVisual->depth,
  221070. InputOutput,
  221071. bestVisual->visual,
  221072. CWBorderPixel | CWColormap | CWEventMask,
  221073. &swa);
  221074. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221075. XMapWindow (display, embeddedWindow);
  221076. XFreeColormap (display, colourMap);
  221077. XFree (bestVisual);
  221078. XSync (display, False);
  221079. }
  221080. ~WindowedGLContext()
  221081. {
  221082. ScopedXLock xlock;
  221083. deleteContext();
  221084. XUnmapWindow (display, embeddedWindow);
  221085. XDestroyWindow (display, embeddedWindow);
  221086. }
  221087. void deleteContext()
  221088. {
  221089. makeInactive();
  221090. if (renderContext != 0)
  221091. {
  221092. ScopedXLock xlock;
  221093. glXDestroyContext (display, renderContext);
  221094. renderContext = 0;
  221095. }
  221096. }
  221097. bool makeActive() const throw()
  221098. {
  221099. jassert (renderContext != 0);
  221100. ScopedXLock xlock;
  221101. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221102. && XSync (display, False);
  221103. }
  221104. bool makeInactive() const throw()
  221105. {
  221106. ScopedXLock xlock;
  221107. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221108. }
  221109. bool isActive() const throw()
  221110. {
  221111. ScopedXLock xlock;
  221112. return glXGetCurrentContext() == renderContext;
  221113. }
  221114. const OpenGLPixelFormat getPixelFormat() const
  221115. {
  221116. return pixelFormat;
  221117. }
  221118. void* getRawContext() const throw()
  221119. {
  221120. return renderContext;
  221121. }
  221122. void updateWindowPosition (int x, int y, int w, int h, int)
  221123. {
  221124. ScopedXLock xlock;
  221125. XMoveResizeWindow (display, embeddedWindow,
  221126. x, y, jmax (1, w), jmax (1, h));
  221127. }
  221128. void swapBuffers()
  221129. {
  221130. ScopedXLock xlock;
  221131. glXSwapBuffers (display, embeddedWindow);
  221132. }
  221133. bool setSwapInterval (const int numFramesPerSwap)
  221134. {
  221135. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221136. if (GLXSwapIntervalSGI != 0)
  221137. {
  221138. swapInterval = numFramesPerSwap;
  221139. GLXSwapIntervalSGI (numFramesPerSwap);
  221140. return true;
  221141. }
  221142. return false;
  221143. }
  221144. int getSwapInterval() const
  221145. {
  221146. return swapInterval;
  221147. }
  221148. void repaint()
  221149. {
  221150. }
  221151. GLXContext renderContext;
  221152. private:
  221153. Window embeddedWindow;
  221154. OpenGLPixelFormat pixelFormat;
  221155. int swapInterval;
  221156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221157. };
  221158. OpenGLContext* OpenGLComponent::createContext()
  221159. {
  221160. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221161. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221162. return (c->renderContext != 0) ? c.release() : 0;
  221163. }
  221164. void juce_glViewport (const int w, const int h)
  221165. {
  221166. glViewport (0, 0, w, h);
  221167. }
  221168. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221169. OwnedArray <OpenGLPixelFormat>& results)
  221170. {
  221171. results.add (new OpenGLPixelFormat()); // xxx
  221172. }
  221173. #endif
  221174. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221175. {
  221176. jassertfalse; // not implemented!
  221177. return false;
  221178. }
  221179. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221180. {
  221181. jassertfalse; // not implemented!
  221182. return false;
  221183. }
  221184. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221185. {
  221186. if (! isOnDesktop ())
  221187. addToDesktop (0);
  221188. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221189. if (wp != 0)
  221190. {
  221191. wp->setTaskBarIcon (newImage);
  221192. setVisible (true);
  221193. toFront (false);
  221194. repaint();
  221195. }
  221196. }
  221197. void SystemTrayIconComponent::paint (Graphics& g)
  221198. {
  221199. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221200. if (wp != 0)
  221201. {
  221202. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221203. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221204. false);
  221205. }
  221206. }
  221207. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221208. {
  221209. // xxx not yet implemented!
  221210. }
  221211. void PlatformUtilities::beep()
  221212. {
  221213. std::cout << "\a" << std::flush;
  221214. }
  221215. bool AlertWindow::showNativeDialogBox (const String& title,
  221216. const String& bodyText,
  221217. bool isOkCancel)
  221218. {
  221219. // use a non-native one for the time being..
  221220. if (isOkCancel)
  221221. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221222. else
  221223. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221224. return true;
  221225. }
  221226. const int KeyPress::spaceKey = XK_space & 0xff;
  221227. const int KeyPress::returnKey = XK_Return & 0xff;
  221228. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221229. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221230. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221231. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221232. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221233. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221234. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221235. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221236. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221237. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221238. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221239. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221240. const int KeyPress::tabKey = XK_Tab & 0xff;
  221241. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221242. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221243. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221244. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221245. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221246. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221247. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221248. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221249. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221250. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221251. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221252. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221253. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221254. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221255. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221256. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221257. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221258. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221259. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221260. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221261. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221262. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221263. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221264. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221265. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221266. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221267. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221268. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221269. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221270. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221271. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221272. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221273. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221274. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221275. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221276. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221277. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221278. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221279. #endif
  221280. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221281. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221282. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221283. // compiled on its own).
  221284. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221285. namespace
  221286. {
  221287. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221288. {
  221289. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221290. snd_pcm_hw_params_t* hwParams;
  221291. snd_pcm_hw_params_alloca (&hwParams);
  221292. for (int i = 0; ratesToTry[i] != 0; ++i)
  221293. {
  221294. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221295. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221296. {
  221297. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221298. }
  221299. }
  221300. }
  221301. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221302. {
  221303. snd_pcm_hw_params_t *params;
  221304. snd_pcm_hw_params_alloca (&params);
  221305. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221306. {
  221307. snd_pcm_hw_params_get_channels_min (params, minChans);
  221308. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221309. }
  221310. }
  221311. void getDeviceProperties (const String& deviceID,
  221312. unsigned int& minChansOut,
  221313. unsigned int& maxChansOut,
  221314. unsigned int& minChansIn,
  221315. unsigned int& maxChansIn,
  221316. Array <int>& rates)
  221317. {
  221318. if (deviceID.isEmpty())
  221319. return;
  221320. snd_ctl_t* handle;
  221321. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221322. {
  221323. snd_pcm_info_t* info;
  221324. snd_pcm_info_alloca (&info);
  221325. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221326. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221327. snd_pcm_info_set_subdevice (info, 0);
  221328. if (snd_ctl_pcm_info (handle, info) >= 0)
  221329. {
  221330. snd_pcm_t* pcmHandle;
  221331. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221332. {
  221333. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221334. getDeviceSampleRates (pcmHandle, rates);
  221335. snd_pcm_close (pcmHandle);
  221336. }
  221337. }
  221338. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221339. if (snd_ctl_pcm_info (handle, info) >= 0)
  221340. {
  221341. snd_pcm_t* pcmHandle;
  221342. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221343. {
  221344. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221345. if (rates.size() == 0)
  221346. getDeviceSampleRates (pcmHandle, rates);
  221347. snd_pcm_close (pcmHandle);
  221348. }
  221349. }
  221350. snd_ctl_close (handle);
  221351. }
  221352. }
  221353. }
  221354. class ALSADevice
  221355. {
  221356. public:
  221357. ALSADevice (const String& deviceID, bool forInput)
  221358. : handle (0),
  221359. bitDepth (16),
  221360. numChannelsRunning (0),
  221361. latency (0),
  221362. isInput (forInput),
  221363. isInterleaved (true)
  221364. {
  221365. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221366. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221367. SND_PCM_ASYNC));
  221368. }
  221369. ~ALSADevice()
  221370. {
  221371. if (handle != 0)
  221372. snd_pcm_close (handle);
  221373. }
  221374. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221375. {
  221376. if (handle == 0)
  221377. return false;
  221378. snd_pcm_hw_params_t* hwParams;
  221379. snd_pcm_hw_params_alloca (&hwParams);
  221380. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221381. return false;
  221382. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221383. isInterleaved = false;
  221384. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221385. isInterleaved = true;
  221386. else
  221387. {
  221388. jassertfalse;
  221389. return false;
  221390. }
  221391. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221392. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221393. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221394. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221395. SND_PCM_FORMAT_S32_BE, 32,
  221396. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221397. SND_PCM_FORMAT_S24_3BE, 24,
  221398. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221399. SND_PCM_FORMAT_S16_BE, 16 };
  221400. bitDepth = 0;
  221401. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221402. {
  221403. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221404. {
  221405. bitDepth = formatsToTry [i + 1] & 255;
  221406. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221407. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221408. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221409. break;
  221410. }
  221411. }
  221412. if (bitDepth == 0)
  221413. {
  221414. error = "device doesn't support a compatible PCM format";
  221415. DBG ("ALSA error: " + error + "\n");
  221416. return false;
  221417. }
  221418. int dir = 0;
  221419. unsigned int periods = 4;
  221420. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221421. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221422. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221423. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221424. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221425. || failed (snd_pcm_hw_params (handle, hwParams)))
  221426. {
  221427. return false;
  221428. }
  221429. snd_pcm_uframes_t frames = 0;
  221430. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221431. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221432. latency = 0;
  221433. else
  221434. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221435. snd_pcm_sw_params_t* swParams;
  221436. snd_pcm_sw_params_alloca (&swParams);
  221437. snd_pcm_uframes_t boundary;
  221438. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221439. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221440. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221441. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221442. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221443. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221444. || failed (snd_pcm_sw_params (handle, swParams)))
  221445. {
  221446. return false;
  221447. }
  221448. #if 0
  221449. // enable this to dump the config of the devices that get opened
  221450. snd_output_t* out;
  221451. snd_output_stdio_attach (&out, stderr, 0);
  221452. snd_pcm_hw_params_dump (hwParams, out);
  221453. snd_pcm_sw_params_dump (swParams, out);
  221454. #endif
  221455. numChannelsRunning = numChannels;
  221456. return true;
  221457. }
  221458. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221459. {
  221460. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221461. float** const data = outputChannelBuffer.getArrayOfChannels();
  221462. snd_pcm_sframes_t numDone = 0;
  221463. if (isInterleaved)
  221464. {
  221465. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221466. for (int i = 0; i < numChannelsRunning; ++i)
  221467. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221468. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221469. }
  221470. else
  221471. {
  221472. for (int i = 0; i < numChannelsRunning; ++i)
  221473. converter->convertSamples (data[i], data[i], numSamples);
  221474. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221475. }
  221476. if (failed (numDone))
  221477. {
  221478. if (numDone == -EPIPE)
  221479. {
  221480. if (failed (snd_pcm_prepare (handle)))
  221481. return false;
  221482. }
  221483. else if (numDone != -ESTRPIPE)
  221484. return false;
  221485. }
  221486. return true;
  221487. }
  221488. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221489. {
  221490. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221491. float** const data = inputChannelBuffer.getArrayOfChannels();
  221492. if (isInterleaved)
  221493. {
  221494. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221495. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221496. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221497. if (failed (num))
  221498. {
  221499. if (num == -EPIPE)
  221500. {
  221501. if (failed (snd_pcm_prepare (handle)))
  221502. return false;
  221503. }
  221504. else if (num != -ESTRPIPE)
  221505. return false;
  221506. }
  221507. for (int i = 0; i < numChannelsRunning; ++i)
  221508. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221509. }
  221510. else
  221511. {
  221512. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221513. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221514. return false;
  221515. for (int i = 0; i < numChannelsRunning; ++i)
  221516. converter->convertSamples (data[i], data[i], numSamples);
  221517. }
  221518. return true;
  221519. }
  221520. snd_pcm_t* handle;
  221521. String error;
  221522. int bitDepth, numChannelsRunning, latency;
  221523. private:
  221524. const bool isInput;
  221525. bool isInterleaved;
  221526. MemoryBlock scratch;
  221527. ScopedPointer<AudioData::Converter> converter;
  221528. template <class SampleType>
  221529. struct ConverterHelper
  221530. {
  221531. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221532. {
  221533. if (forInput)
  221534. {
  221535. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221536. if (isLittleEndian)
  221537. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221538. else
  221539. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221540. }
  221541. else
  221542. {
  221543. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221544. if (isLittleEndian)
  221545. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221546. else
  221547. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221548. }
  221549. }
  221550. };
  221551. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221552. {
  221553. switch (bitDepth)
  221554. {
  221555. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221556. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221557. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221558. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221559. default: jassertfalse; break; // unsupported format!
  221560. }
  221561. return 0;
  221562. }
  221563. bool failed (const int errorNum)
  221564. {
  221565. if (errorNum >= 0)
  221566. return false;
  221567. error = snd_strerror (errorNum);
  221568. DBG ("ALSA error: " + error + "\n");
  221569. return true;
  221570. }
  221571. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221572. };
  221573. class ALSAThread : public Thread
  221574. {
  221575. public:
  221576. ALSAThread (const String& inputId_,
  221577. const String& outputId_)
  221578. : Thread ("Juce ALSA"),
  221579. sampleRate (0),
  221580. bufferSize (0),
  221581. outputLatency (0),
  221582. inputLatency (0),
  221583. callback (0),
  221584. inputId (inputId_),
  221585. outputId (outputId_),
  221586. numCallbacks (0),
  221587. inputChannelBuffer (1, 1),
  221588. outputChannelBuffer (1, 1)
  221589. {
  221590. initialiseRatesAndChannels();
  221591. }
  221592. ~ALSAThread()
  221593. {
  221594. close();
  221595. }
  221596. void open (BigInteger inputChannels,
  221597. BigInteger outputChannels,
  221598. const double sampleRate_,
  221599. const int bufferSize_)
  221600. {
  221601. close();
  221602. error = String::empty;
  221603. sampleRate = sampleRate_;
  221604. bufferSize = bufferSize_;
  221605. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221606. inputChannelBuffer.clear();
  221607. inputChannelDataForCallback.clear();
  221608. currentInputChans.clear();
  221609. if (inputChannels.getHighestBit() >= 0)
  221610. {
  221611. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221612. {
  221613. if (inputChannels[i])
  221614. {
  221615. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221616. currentInputChans.setBit (i);
  221617. }
  221618. }
  221619. }
  221620. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221621. outputChannelBuffer.clear();
  221622. outputChannelDataForCallback.clear();
  221623. currentOutputChans.clear();
  221624. if (outputChannels.getHighestBit() >= 0)
  221625. {
  221626. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221627. {
  221628. if (outputChannels[i])
  221629. {
  221630. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221631. currentOutputChans.setBit (i);
  221632. }
  221633. }
  221634. }
  221635. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221636. {
  221637. outputDevice = new ALSADevice (outputId, false);
  221638. if (outputDevice->error.isNotEmpty())
  221639. {
  221640. error = outputDevice->error;
  221641. outputDevice = 0;
  221642. return;
  221643. }
  221644. currentOutputChans.setRange (0, minChansOut, true);
  221645. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221646. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221647. bufferSize))
  221648. {
  221649. error = outputDevice->error;
  221650. outputDevice = 0;
  221651. return;
  221652. }
  221653. outputLatency = outputDevice->latency;
  221654. }
  221655. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221656. {
  221657. inputDevice = new ALSADevice (inputId, true);
  221658. if (inputDevice->error.isNotEmpty())
  221659. {
  221660. error = inputDevice->error;
  221661. inputDevice = 0;
  221662. return;
  221663. }
  221664. currentInputChans.setRange (0, minChansIn, true);
  221665. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221666. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221667. bufferSize))
  221668. {
  221669. error = inputDevice->error;
  221670. inputDevice = 0;
  221671. return;
  221672. }
  221673. inputLatency = inputDevice->latency;
  221674. }
  221675. if (outputDevice == 0 && inputDevice == 0)
  221676. {
  221677. error = "no channels";
  221678. return;
  221679. }
  221680. if (outputDevice != 0 && inputDevice != 0)
  221681. {
  221682. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221683. }
  221684. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221685. return;
  221686. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221687. return;
  221688. startThread (9);
  221689. int count = 1000;
  221690. while (numCallbacks == 0)
  221691. {
  221692. sleep (5);
  221693. if (--count < 0 || ! isThreadRunning())
  221694. {
  221695. error = "device didn't start";
  221696. break;
  221697. }
  221698. }
  221699. }
  221700. void close()
  221701. {
  221702. stopThread (6000);
  221703. inputDevice = 0;
  221704. outputDevice = 0;
  221705. inputChannelBuffer.setSize (1, 1);
  221706. outputChannelBuffer.setSize (1, 1);
  221707. numCallbacks = 0;
  221708. }
  221709. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221710. {
  221711. const ScopedLock sl (callbackLock);
  221712. callback = newCallback;
  221713. }
  221714. void run()
  221715. {
  221716. while (! threadShouldExit())
  221717. {
  221718. if (inputDevice != 0)
  221719. {
  221720. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221721. {
  221722. DBG ("ALSA: read failure");
  221723. break;
  221724. }
  221725. }
  221726. if (threadShouldExit())
  221727. break;
  221728. {
  221729. const ScopedLock sl (callbackLock);
  221730. ++numCallbacks;
  221731. if (callback != 0)
  221732. {
  221733. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221734. inputChannelDataForCallback.size(),
  221735. outputChannelDataForCallback.getRawDataPointer(),
  221736. outputChannelDataForCallback.size(),
  221737. bufferSize);
  221738. }
  221739. else
  221740. {
  221741. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221742. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221743. }
  221744. }
  221745. if (outputDevice != 0)
  221746. {
  221747. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221748. if (threadShouldExit())
  221749. break;
  221750. failed (snd_pcm_avail_update (outputDevice->handle));
  221751. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  221752. {
  221753. DBG ("ALSA: write failure");
  221754. break;
  221755. }
  221756. }
  221757. }
  221758. }
  221759. int getBitDepth() const throw()
  221760. {
  221761. if (outputDevice != 0)
  221762. return outputDevice->bitDepth;
  221763. if (inputDevice != 0)
  221764. return inputDevice->bitDepth;
  221765. return 16;
  221766. }
  221767. String error;
  221768. double sampleRate;
  221769. int bufferSize, outputLatency, inputLatency;
  221770. BigInteger currentInputChans, currentOutputChans;
  221771. Array <int> sampleRates;
  221772. StringArray channelNamesOut, channelNamesIn;
  221773. AudioIODeviceCallback* callback;
  221774. private:
  221775. const String inputId, outputId;
  221776. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221777. int numCallbacks;
  221778. CriticalSection callbackLock;
  221779. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221780. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221781. unsigned int minChansOut, maxChansOut;
  221782. unsigned int minChansIn, maxChansIn;
  221783. bool failed (const int errorNum)
  221784. {
  221785. if (errorNum >= 0)
  221786. return false;
  221787. error = snd_strerror (errorNum);
  221788. DBG ("ALSA error: " + error + "\n");
  221789. return true;
  221790. }
  221791. void initialiseRatesAndChannels()
  221792. {
  221793. sampleRates.clear();
  221794. channelNamesOut.clear();
  221795. channelNamesIn.clear();
  221796. minChansOut = 0;
  221797. maxChansOut = 0;
  221798. minChansIn = 0;
  221799. maxChansIn = 0;
  221800. unsigned int dummy = 0;
  221801. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221802. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221803. unsigned int i;
  221804. for (i = 0; i < maxChansOut; ++i)
  221805. channelNamesOut.add ("channel " + String ((int) i + 1));
  221806. for (i = 0; i < maxChansIn; ++i)
  221807. channelNamesIn.add ("channel " + String ((int) i + 1));
  221808. }
  221809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  221810. };
  221811. class ALSAAudioIODevice : public AudioIODevice
  221812. {
  221813. public:
  221814. ALSAAudioIODevice (const String& deviceName,
  221815. const String& inputId_,
  221816. const String& outputId_)
  221817. : AudioIODevice (deviceName, "ALSA"),
  221818. inputId (inputId_),
  221819. outputId (outputId_),
  221820. isOpen_ (false),
  221821. isStarted (false),
  221822. internal (inputId_, outputId_)
  221823. {
  221824. }
  221825. ~ALSAAudioIODevice()
  221826. {
  221827. }
  221828. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  221829. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  221830. int getNumSampleRates() { return internal.sampleRates.size(); }
  221831. double getSampleRate (int index) { return internal.sampleRates [index]; }
  221832. int getDefaultBufferSize() { return 512; }
  221833. int getNumBufferSizesAvailable() { return 50; }
  221834. int getBufferSizeSamples (int index)
  221835. {
  221836. int n = 16;
  221837. for (int i = 0; i < index; ++i)
  221838. n += n < 64 ? 16
  221839. : (n < 512 ? 32
  221840. : (n < 1024 ? 64
  221841. : (n < 2048 ? 128 : 256)));
  221842. return n;
  221843. }
  221844. const String open (const BigInteger& inputChannels,
  221845. const BigInteger& outputChannels,
  221846. double sampleRate,
  221847. int bufferSizeSamples)
  221848. {
  221849. close();
  221850. if (bufferSizeSamples <= 0)
  221851. bufferSizeSamples = getDefaultBufferSize();
  221852. if (sampleRate <= 0)
  221853. {
  221854. for (int i = 0; i < getNumSampleRates(); ++i)
  221855. {
  221856. if (getSampleRate (i) >= 44100)
  221857. {
  221858. sampleRate = getSampleRate (i);
  221859. break;
  221860. }
  221861. }
  221862. }
  221863. internal.open (inputChannels, outputChannels,
  221864. sampleRate, bufferSizeSamples);
  221865. isOpen_ = internal.error.isEmpty();
  221866. return internal.error;
  221867. }
  221868. void close()
  221869. {
  221870. stop();
  221871. internal.close();
  221872. isOpen_ = false;
  221873. }
  221874. bool isOpen() { return isOpen_; }
  221875. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  221876. const String getLastError() { return internal.error; }
  221877. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  221878. double getCurrentSampleRate() { return internal.sampleRate; }
  221879. int getCurrentBitDepth() { return internal.getBitDepth(); }
  221880. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  221881. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  221882. int getOutputLatencyInSamples() { return internal.outputLatency; }
  221883. int getInputLatencyInSamples() { return internal.inputLatency; }
  221884. void start (AudioIODeviceCallback* callback)
  221885. {
  221886. if (! isOpen_)
  221887. callback = 0;
  221888. if (callback != 0)
  221889. callback->audioDeviceAboutToStart (this);
  221890. internal.setCallback (callback);
  221891. isStarted = (callback != 0);
  221892. }
  221893. void stop()
  221894. {
  221895. AudioIODeviceCallback* const oldCallback = internal.callback;
  221896. start (0);
  221897. if (oldCallback != 0)
  221898. oldCallback->audioDeviceStopped();
  221899. }
  221900. String inputId, outputId;
  221901. private:
  221902. bool isOpen_, isStarted;
  221903. ALSAThread internal;
  221904. };
  221905. class ALSAAudioIODeviceType : public AudioIODeviceType
  221906. {
  221907. public:
  221908. ALSAAudioIODeviceType()
  221909. : AudioIODeviceType ("ALSA"),
  221910. hasScanned (false)
  221911. {
  221912. }
  221913. ~ALSAAudioIODeviceType()
  221914. {
  221915. }
  221916. void scanForDevices()
  221917. {
  221918. if (hasScanned)
  221919. return;
  221920. hasScanned = true;
  221921. inputNames.clear();
  221922. inputIds.clear();
  221923. outputNames.clear();
  221924. outputIds.clear();
  221925. /* void** hints = 0;
  221926. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  221927. {
  221928. for (void** hint = hints; *hint != 0; ++hint)
  221929. {
  221930. const String name (getHint (*hint, "NAME"));
  221931. if (name.isNotEmpty())
  221932. {
  221933. const String ioid (getHint (*hint, "IOID"));
  221934. String desc (getHint (*hint, "DESC"));
  221935. if (desc.isEmpty())
  221936. desc = name;
  221937. desc = desc.replaceCharacters ("\n\r", " ");
  221938. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  221939. if (ioid.isEmpty() || ioid == "Input")
  221940. {
  221941. inputNames.add (desc);
  221942. inputIds.add (name);
  221943. }
  221944. if (ioid.isEmpty() || ioid == "Output")
  221945. {
  221946. outputNames.add (desc);
  221947. outputIds.add (name);
  221948. }
  221949. }
  221950. }
  221951. snd_device_name_free_hint (hints);
  221952. }
  221953. */
  221954. snd_ctl_t* handle = 0;
  221955. snd_ctl_card_info_t* info = 0;
  221956. snd_ctl_card_info_alloca (&info);
  221957. int cardNum = -1;
  221958. while (outputIds.size() + inputIds.size() <= 32)
  221959. {
  221960. snd_card_next (&cardNum);
  221961. if (cardNum < 0)
  221962. break;
  221963. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221964. {
  221965. if (snd_ctl_card_info (handle, info) >= 0)
  221966. {
  221967. String cardId (snd_ctl_card_info_get_id (info));
  221968. if (cardId.removeCharacters ("0123456789").isEmpty())
  221969. cardId = String (cardNum);
  221970. int device = -1;
  221971. for (;;)
  221972. {
  221973. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221974. break;
  221975. String id, name;
  221976. id << "hw:" << cardId << ',' << device;
  221977. bool isInput, isOutput;
  221978. if (testDevice (id, isInput, isOutput))
  221979. {
  221980. name << snd_ctl_card_info_get_name (info);
  221981. if (name.isEmpty())
  221982. name = id;
  221983. if (isInput)
  221984. {
  221985. inputNames.add (name);
  221986. inputIds.add (id);
  221987. }
  221988. if (isOutput)
  221989. {
  221990. outputNames.add (name);
  221991. outputIds.add (id);
  221992. }
  221993. }
  221994. }
  221995. }
  221996. snd_ctl_close (handle);
  221997. }
  221998. }
  221999. inputNames.appendNumbersToDuplicates (false, true);
  222000. outputNames.appendNumbersToDuplicates (false, true);
  222001. }
  222002. const StringArray getDeviceNames (bool wantInputNames) const
  222003. {
  222004. jassert (hasScanned); // need to call scanForDevices() before doing this
  222005. return wantInputNames ? inputNames : outputNames;
  222006. }
  222007. int getDefaultDeviceIndex (bool forInput) const
  222008. {
  222009. jassert (hasScanned); // need to call scanForDevices() before doing this
  222010. return 0;
  222011. }
  222012. bool hasSeparateInputsAndOutputs() const { return true; }
  222013. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222014. {
  222015. jassert (hasScanned); // need to call scanForDevices() before doing this
  222016. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222017. if (d == 0)
  222018. return -1;
  222019. return asInput ? inputIds.indexOf (d->inputId)
  222020. : outputIds.indexOf (d->outputId);
  222021. }
  222022. AudioIODevice* createDevice (const String& outputDeviceName,
  222023. const String& inputDeviceName)
  222024. {
  222025. jassert (hasScanned); // need to call scanForDevices() before doing this
  222026. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222027. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222028. String deviceName (outputIndex >= 0 ? outputDeviceName
  222029. : inputDeviceName);
  222030. if (inputIndex >= 0 || outputIndex >= 0)
  222031. return new ALSAAudioIODevice (deviceName,
  222032. inputIds [inputIndex],
  222033. outputIds [outputIndex]);
  222034. return 0;
  222035. }
  222036. private:
  222037. StringArray inputNames, outputNames, inputIds, outputIds;
  222038. bool hasScanned;
  222039. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222040. {
  222041. unsigned int minChansOut = 0, maxChansOut = 0;
  222042. unsigned int minChansIn = 0, maxChansIn = 0;
  222043. Array <int> rates;
  222044. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222045. DBG ("ALSA device: " + id
  222046. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222047. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222048. + " rates=" + String (rates.size()));
  222049. isInput = maxChansIn > 0;
  222050. isOutput = maxChansOut > 0;
  222051. return (isInput || isOutput) && rates.size() > 0;
  222052. }
  222053. /*static const String getHint (void* hint, const char* type)
  222054. {
  222055. char* const n = snd_device_name_get_hint (hint, type);
  222056. const String s ((const char*) n);
  222057. free (n);
  222058. return s;
  222059. }*/
  222060. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222061. };
  222062. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222063. {
  222064. return new ALSAAudioIODeviceType();
  222065. }
  222066. #endif
  222067. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222068. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222069. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222070. // compiled on its own).
  222071. #ifdef JUCE_INCLUDED_FILE
  222072. #if JUCE_JACK
  222073. static void* juce_libjack_handle = 0;
  222074. void* juce_load_jack_function (const char* const name)
  222075. {
  222076. if (juce_libjack_handle == 0)
  222077. return 0;
  222078. return dlsym (juce_libjack_handle, name);
  222079. }
  222080. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222081. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222082. return_type fn_name argument_types { \
  222083. static fn_name##_ptr_t fn = 0; \
  222084. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222085. if (fn) return (*fn)arguments; \
  222086. else return 0; \
  222087. }
  222088. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222089. typedef void (*fn_name##_ptr_t)argument_types; \
  222090. void fn_name argument_types { \
  222091. static fn_name##_ptr_t fn = 0; \
  222092. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222093. if (fn) (*fn)arguments; \
  222094. }
  222095. 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));
  222096. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222097. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222098. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222099. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222100. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222101. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222102. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222103. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222104. 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));
  222105. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222106. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222107. 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));
  222108. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222109. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222110. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222111. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222112. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222113. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222114. #if JUCE_DEBUG
  222115. #define JACK_LOGGING_ENABLED 1
  222116. #endif
  222117. #if JACK_LOGGING_ENABLED
  222118. namespace
  222119. {
  222120. void jack_Log (const String& s)
  222121. {
  222122. std::cerr << s << std::endl;
  222123. }
  222124. void dumpJackErrorMessage (const jack_status_t status)
  222125. {
  222126. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222127. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222128. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222129. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222130. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222131. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222132. }
  222133. }
  222134. #else
  222135. #define dumpJackErrorMessage(a) {}
  222136. #define jack_Log(...) {}
  222137. #endif
  222138. #ifndef JUCE_JACK_CLIENT_NAME
  222139. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222140. #endif
  222141. class JackAudioIODevice : public AudioIODevice
  222142. {
  222143. public:
  222144. JackAudioIODevice (const String& deviceName,
  222145. const String& inputId_,
  222146. const String& outputId_)
  222147. : AudioIODevice (deviceName, "JACK"),
  222148. inputId (inputId_),
  222149. outputId (outputId_),
  222150. isOpen_ (false),
  222151. callback (0),
  222152. totalNumberOfInputChannels (0),
  222153. totalNumberOfOutputChannels (0)
  222154. {
  222155. jassert (deviceName.isNotEmpty());
  222156. jack_status_t status;
  222157. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222158. if (client == 0)
  222159. {
  222160. dumpJackErrorMessage (status);
  222161. }
  222162. else
  222163. {
  222164. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222165. // open input ports
  222166. const StringArray inputChannels (getInputChannelNames());
  222167. for (int i = 0; i < inputChannels.size(); i++)
  222168. {
  222169. String inputName;
  222170. inputName << "in_" << ++totalNumberOfInputChannels;
  222171. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222172. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222173. }
  222174. // open output ports
  222175. const StringArray outputChannels (getOutputChannelNames());
  222176. for (int i = 0; i < outputChannels.size (); i++)
  222177. {
  222178. String outputName;
  222179. outputName << "out_" << ++totalNumberOfOutputChannels;
  222180. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222181. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222182. }
  222183. inChans.calloc (totalNumberOfInputChannels + 2);
  222184. outChans.calloc (totalNumberOfOutputChannels + 2);
  222185. }
  222186. }
  222187. ~JackAudioIODevice()
  222188. {
  222189. close();
  222190. if (client != 0)
  222191. {
  222192. JUCE_NAMESPACE::jack_client_close (client);
  222193. client = 0;
  222194. }
  222195. }
  222196. const StringArray getChannelNames (bool forInput) const
  222197. {
  222198. StringArray names;
  222199. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222200. forInput ? JackPortIsInput : JackPortIsOutput);
  222201. if (ports != 0)
  222202. {
  222203. int j = 0;
  222204. while (ports[j] != 0)
  222205. {
  222206. const String portName (ports [j++]);
  222207. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222208. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222209. }
  222210. free (ports);
  222211. }
  222212. return names;
  222213. }
  222214. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222215. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222216. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222217. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222218. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222219. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222220. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222221. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222222. double sampleRate, int bufferSizeSamples)
  222223. {
  222224. if (client == 0)
  222225. {
  222226. lastError = "No JACK client running";
  222227. return lastError;
  222228. }
  222229. lastError = String::empty;
  222230. close();
  222231. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222232. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222233. JUCE_NAMESPACE::jack_activate (client);
  222234. isOpen_ = true;
  222235. if (! inputChannels.isZero())
  222236. {
  222237. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222238. if (ports != 0)
  222239. {
  222240. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222241. for (int i = 0; i < numInputChannels; ++i)
  222242. {
  222243. const String portName (ports[i]);
  222244. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222245. {
  222246. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222247. if (error != 0)
  222248. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222249. }
  222250. }
  222251. free (ports);
  222252. }
  222253. }
  222254. if (! outputChannels.isZero())
  222255. {
  222256. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222257. if (ports != 0)
  222258. {
  222259. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222260. for (int i = 0; i < numOutputChannels; ++i)
  222261. {
  222262. const String portName (ports[i]);
  222263. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222264. {
  222265. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222266. if (error != 0)
  222267. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222268. }
  222269. }
  222270. free (ports);
  222271. }
  222272. }
  222273. return lastError;
  222274. }
  222275. void close()
  222276. {
  222277. stop();
  222278. if (client != 0)
  222279. {
  222280. JUCE_NAMESPACE::jack_deactivate (client);
  222281. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222282. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222283. }
  222284. isOpen_ = false;
  222285. }
  222286. void start (AudioIODeviceCallback* newCallback)
  222287. {
  222288. if (isOpen_ && newCallback != callback)
  222289. {
  222290. if (newCallback != 0)
  222291. newCallback->audioDeviceAboutToStart (this);
  222292. AudioIODeviceCallback* const oldCallback = callback;
  222293. {
  222294. const ScopedLock sl (callbackLock);
  222295. callback = newCallback;
  222296. }
  222297. if (oldCallback != 0)
  222298. oldCallback->audioDeviceStopped();
  222299. }
  222300. }
  222301. void stop()
  222302. {
  222303. start (0);
  222304. }
  222305. bool isOpen() { return isOpen_; }
  222306. bool isPlaying() { return callback != 0; }
  222307. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222308. double getCurrentSampleRate() { return getSampleRate (0); }
  222309. int getCurrentBitDepth() { return 32; }
  222310. const String getLastError() { return lastError; }
  222311. const BigInteger getActiveOutputChannels() const
  222312. {
  222313. BigInteger outputBits;
  222314. for (int i = 0; i < outputPorts.size(); i++)
  222315. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222316. outputBits.setBit (i);
  222317. return outputBits;
  222318. }
  222319. const BigInteger getActiveInputChannels() const
  222320. {
  222321. BigInteger inputBits;
  222322. for (int i = 0; i < inputPorts.size(); i++)
  222323. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222324. inputBits.setBit (i);
  222325. return inputBits;
  222326. }
  222327. int getOutputLatencyInSamples()
  222328. {
  222329. int latency = 0;
  222330. for (int i = 0; i < outputPorts.size(); i++)
  222331. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222332. return latency;
  222333. }
  222334. int getInputLatencyInSamples()
  222335. {
  222336. int latency = 0;
  222337. for (int i = 0; i < inputPorts.size(); i++)
  222338. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222339. return latency;
  222340. }
  222341. String inputId, outputId;
  222342. private:
  222343. void process (const int numSamples)
  222344. {
  222345. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222346. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222347. {
  222348. jack_default_audio_sample_t* in
  222349. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222350. if (in != 0)
  222351. inChans [numActiveInChans++] = (float*) in;
  222352. }
  222353. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222354. {
  222355. jack_default_audio_sample_t* out
  222356. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222357. if (out != 0)
  222358. outChans [numActiveOutChans++] = (float*) out;
  222359. }
  222360. const ScopedLock sl (callbackLock);
  222361. if (callback != 0)
  222362. {
  222363. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222364. outChans, numActiveOutChans, numSamples);
  222365. }
  222366. else
  222367. {
  222368. for (i = 0; i < numActiveOutChans; ++i)
  222369. zeromem (outChans[i], sizeof (float) * numSamples);
  222370. }
  222371. }
  222372. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222373. {
  222374. if (callbackArgument != 0)
  222375. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222376. return 0;
  222377. }
  222378. static void threadInitCallback (void* callbackArgument)
  222379. {
  222380. jack_Log ("JackAudioIODevice::initialise");
  222381. }
  222382. static void shutdownCallback (void* callbackArgument)
  222383. {
  222384. jack_Log ("JackAudioIODevice::shutdown");
  222385. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222386. if (device != 0)
  222387. {
  222388. device->client = 0;
  222389. device->close();
  222390. }
  222391. }
  222392. static void errorCallback (const char* msg)
  222393. {
  222394. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222395. }
  222396. bool isOpen_;
  222397. jack_client_t* client;
  222398. String lastError;
  222399. AudioIODeviceCallback* callback;
  222400. CriticalSection callbackLock;
  222401. HeapBlock <float*> inChans, outChans;
  222402. int totalNumberOfInputChannels;
  222403. int totalNumberOfOutputChannels;
  222404. Array<void*> inputPorts, outputPorts;
  222405. };
  222406. class JackAudioIODeviceType : public AudioIODeviceType
  222407. {
  222408. public:
  222409. JackAudioIODeviceType()
  222410. : AudioIODeviceType ("JACK"),
  222411. hasScanned (false)
  222412. {
  222413. }
  222414. ~JackAudioIODeviceType()
  222415. {
  222416. }
  222417. void scanForDevices()
  222418. {
  222419. hasScanned = true;
  222420. inputNames.clear();
  222421. inputIds.clear();
  222422. outputNames.clear();
  222423. outputIds.clear();
  222424. if (juce_libjack_handle == 0)
  222425. {
  222426. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222427. if (juce_libjack_handle == 0)
  222428. return;
  222429. }
  222430. // open a dummy client
  222431. jack_status_t status;
  222432. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222433. if (client == 0)
  222434. {
  222435. dumpJackErrorMessage (status);
  222436. }
  222437. else
  222438. {
  222439. // scan for output devices
  222440. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222441. if (ports != 0)
  222442. {
  222443. int j = 0;
  222444. while (ports[j] != 0)
  222445. {
  222446. String clientName (ports[j]);
  222447. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222448. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222449. && ! inputNames.contains (clientName))
  222450. {
  222451. inputNames.add (clientName);
  222452. inputIds.add (ports [j]);
  222453. }
  222454. ++j;
  222455. }
  222456. free (ports);
  222457. }
  222458. // scan for input devices
  222459. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222460. if (ports != 0)
  222461. {
  222462. int j = 0;
  222463. while (ports[j] != 0)
  222464. {
  222465. String clientName (ports[j]);
  222466. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222467. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222468. && ! outputNames.contains (clientName))
  222469. {
  222470. outputNames.add (clientName);
  222471. outputIds.add (ports [j]);
  222472. }
  222473. ++j;
  222474. }
  222475. free (ports);
  222476. }
  222477. JUCE_NAMESPACE::jack_client_close (client);
  222478. }
  222479. }
  222480. const StringArray getDeviceNames (bool wantInputNames) const
  222481. {
  222482. jassert (hasScanned); // need to call scanForDevices() before doing this
  222483. return wantInputNames ? inputNames : outputNames;
  222484. }
  222485. int getDefaultDeviceIndex (bool forInput) const
  222486. {
  222487. jassert (hasScanned); // need to call scanForDevices() before doing this
  222488. return 0;
  222489. }
  222490. bool hasSeparateInputsAndOutputs() const { return true; }
  222491. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222492. {
  222493. jassert (hasScanned); // need to call scanForDevices() before doing this
  222494. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222495. if (d == 0)
  222496. return -1;
  222497. return asInput ? inputIds.indexOf (d->inputId)
  222498. : outputIds.indexOf (d->outputId);
  222499. }
  222500. AudioIODevice* createDevice (const String& outputDeviceName,
  222501. const String& inputDeviceName)
  222502. {
  222503. jassert (hasScanned); // need to call scanForDevices() before doing this
  222504. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222505. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222506. if (inputIndex >= 0 || outputIndex >= 0)
  222507. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222508. : inputDeviceName,
  222509. inputIds [inputIndex],
  222510. outputIds [outputIndex]);
  222511. return 0;
  222512. }
  222513. private:
  222514. StringArray inputNames, outputNames, inputIds, outputIds;
  222515. bool hasScanned;
  222516. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222517. };
  222518. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222519. {
  222520. return new JackAudioIODeviceType();
  222521. }
  222522. #else // if JACK is turned off..
  222523. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222524. #endif
  222525. #endif
  222526. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222527. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222528. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222529. // compiled on its own).
  222530. #if JUCE_INCLUDED_FILE
  222531. #if JUCE_ALSA
  222532. namespace
  222533. {
  222534. snd_seq_t* iterateMidiDevices (const bool forInput,
  222535. StringArray& deviceNamesFound,
  222536. const int deviceIndexToOpen)
  222537. {
  222538. snd_seq_t* returnedHandle = 0;
  222539. snd_seq_t* seqHandle;
  222540. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222541. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222542. {
  222543. snd_seq_system_info_t* systemInfo;
  222544. snd_seq_client_info_t* clientInfo;
  222545. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222546. {
  222547. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222548. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222549. {
  222550. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222551. while (--numClients >= 0 && returnedHandle == 0)
  222552. {
  222553. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222554. {
  222555. snd_seq_port_info_t* portInfo;
  222556. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222557. {
  222558. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222559. const int client = snd_seq_client_info_get_client (clientInfo);
  222560. snd_seq_port_info_set_client (portInfo, client);
  222561. snd_seq_port_info_set_port (portInfo, -1);
  222562. while (--numPorts >= 0)
  222563. {
  222564. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222565. && (snd_seq_port_info_get_capability (portInfo)
  222566. & (forInput ? SND_SEQ_PORT_CAP_READ
  222567. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222568. {
  222569. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222570. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222571. {
  222572. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222573. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222574. if (sourcePort != -1)
  222575. {
  222576. snd_seq_set_client_name (seqHandle,
  222577. forInput ? "Juce Midi Input"
  222578. : "Juce Midi Output");
  222579. const int portId
  222580. = snd_seq_create_simple_port (seqHandle,
  222581. forInput ? "Juce Midi In Port"
  222582. : "Juce Midi Out Port",
  222583. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222584. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222585. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222586. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222587. returnedHandle = seqHandle;
  222588. }
  222589. }
  222590. }
  222591. }
  222592. snd_seq_port_info_free (portInfo);
  222593. }
  222594. }
  222595. }
  222596. snd_seq_client_info_free (clientInfo);
  222597. }
  222598. snd_seq_system_info_free (systemInfo);
  222599. }
  222600. if (returnedHandle == 0)
  222601. snd_seq_close (seqHandle);
  222602. }
  222603. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222604. return returnedHandle;
  222605. }
  222606. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222607. {
  222608. snd_seq_t* seqHandle = 0;
  222609. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222610. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222611. {
  222612. snd_seq_set_client_name (seqHandle,
  222613. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222614. const int portId
  222615. = snd_seq_create_simple_port (seqHandle,
  222616. forInput ? "in"
  222617. : "out",
  222618. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222619. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222620. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222621. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222622. if (portId < 0)
  222623. {
  222624. snd_seq_close (seqHandle);
  222625. seqHandle = 0;
  222626. }
  222627. }
  222628. return seqHandle;
  222629. }
  222630. }
  222631. class MidiOutputDevice
  222632. {
  222633. public:
  222634. MidiOutputDevice (MidiOutput* const midiOutput_,
  222635. snd_seq_t* const seqHandle_)
  222636. :
  222637. midiOutput (midiOutput_),
  222638. seqHandle (seqHandle_),
  222639. maxEventSize (16 * 1024)
  222640. {
  222641. jassert (seqHandle != 0 && midiOutput != 0);
  222642. snd_midi_event_new (maxEventSize, &midiParser);
  222643. }
  222644. ~MidiOutputDevice()
  222645. {
  222646. snd_midi_event_free (midiParser);
  222647. snd_seq_close (seqHandle);
  222648. }
  222649. void sendMessageNow (const MidiMessage& message)
  222650. {
  222651. if (message.getRawDataSize() > maxEventSize)
  222652. {
  222653. maxEventSize = message.getRawDataSize();
  222654. snd_midi_event_free (midiParser);
  222655. snd_midi_event_new (maxEventSize, &midiParser);
  222656. }
  222657. snd_seq_event_t event;
  222658. snd_seq_ev_clear (&event);
  222659. snd_midi_event_encode (midiParser,
  222660. message.getRawData(),
  222661. message.getRawDataSize(),
  222662. &event);
  222663. snd_midi_event_reset_encode (midiParser);
  222664. snd_seq_ev_set_source (&event, 0);
  222665. snd_seq_ev_set_subs (&event);
  222666. snd_seq_ev_set_direct (&event);
  222667. snd_seq_event_output (seqHandle, &event);
  222668. snd_seq_drain_output (seqHandle);
  222669. }
  222670. private:
  222671. MidiOutput* const midiOutput;
  222672. snd_seq_t* const seqHandle;
  222673. snd_midi_event_t* midiParser;
  222674. int maxEventSize;
  222675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222676. };
  222677. const StringArray MidiOutput::getDevices()
  222678. {
  222679. StringArray devices;
  222680. iterateMidiDevices (false, devices, -1);
  222681. return devices;
  222682. }
  222683. int MidiOutput::getDefaultDeviceIndex()
  222684. {
  222685. return 0;
  222686. }
  222687. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222688. {
  222689. MidiOutput* newDevice = 0;
  222690. StringArray devices;
  222691. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222692. if (handle != 0)
  222693. {
  222694. newDevice = new MidiOutput();
  222695. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222696. }
  222697. return newDevice;
  222698. }
  222699. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222700. {
  222701. MidiOutput* newDevice = 0;
  222702. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222703. if (handle != 0)
  222704. {
  222705. newDevice = new MidiOutput();
  222706. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222707. }
  222708. return newDevice;
  222709. }
  222710. MidiOutput::~MidiOutput()
  222711. {
  222712. delete static_cast <MidiOutputDevice*> (internal);
  222713. }
  222714. void MidiOutput::reset()
  222715. {
  222716. }
  222717. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222718. {
  222719. return false;
  222720. }
  222721. void MidiOutput::setVolume (float leftVol, float rightVol)
  222722. {
  222723. }
  222724. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222725. {
  222726. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222727. }
  222728. class MidiInputThread : public Thread
  222729. {
  222730. public:
  222731. MidiInputThread (MidiInput* const midiInput_,
  222732. snd_seq_t* const seqHandle_,
  222733. MidiInputCallback* const callback_)
  222734. : Thread ("Juce MIDI Input"),
  222735. midiInput (midiInput_),
  222736. seqHandle (seqHandle_),
  222737. callback (callback_)
  222738. {
  222739. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222740. }
  222741. ~MidiInputThread()
  222742. {
  222743. snd_seq_close (seqHandle);
  222744. }
  222745. void run()
  222746. {
  222747. const int maxEventSize = 16 * 1024;
  222748. snd_midi_event_t* midiParser;
  222749. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222750. {
  222751. HeapBlock <uint8> buffer (maxEventSize);
  222752. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222753. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222754. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222755. while (! threadShouldExit())
  222756. {
  222757. if (poll (pfd, numPfds, 500) > 0)
  222758. {
  222759. snd_seq_event_t* inputEvent = 0;
  222760. snd_seq_nonblock (seqHandle, 1);
  222761. do
  222762. {
  222763. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222764. {
  222765. // xxx what about SYSEXes that are too big for the buffer?
  222766. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222767. snd_midi_event_reset_decode (midiParser);
  222768. if (numBytes > 0)
  222769. {
  222770. const MidiMessage message ((const uint8*) buffer,
  222771. numBytes,
  222772. Time::getMillisecondCounter() * 0.001);
  222773. callback->handleIncomingMidiMessage (midiInput, message);
  222774. }
  222775. snd_seq_free_event (inputEvent);
  222776. }
  222777. }
  222778. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222779. snd_seq_free_event (inputEvent);
  222780. }
  222781. }
  222782. snd_midi_event_free (midiParser);
  222783. }
  222784. };
  222785. private:
  222786. MidiInput* const midiInput;
  222787. snd_seq_t* const seqHandle;
  222788. MidiInputCallback* const callback;
  222789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  222790. };
  222791. MidiInput::MidiInput (const String& name_)
  222792. : name (name_),
  222793. internal (0)
  222794. {
  222795. }
  222796. MidiInput::~MidiInput()
  222797. {
  222798. stop();
  222799. delete static_cast <MidiInputThread*> (internal);
  222800. }
  222801. void MidiInput::start()
  222802. {
  222803. static_cast <MidiInputThread*> (internal)->startThread();
  222804. }
  222805. void MidiInput::stop()
  222806. {
  222807. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  222808. }
  222809. int MidiInput::getDefaultDeviceIndex()
  222810. {
  222811. return 0;
  222812. }
  222813. const StringArray MidiInput::getDevices()
  222814. {
  222815. StringArray devices;
  222816. iterateMidiDevices (true, devices, -1);
  222817. return devices;
  222818. }
  222819. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222820. {
  222821. MidiInput* newDevice = 0;
  222822. StringArray devices;
  222823. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  222824. if (handle != 0)
  222825. {
  222826. newDevice = new MidiInput (devices [deviceIndex]);
  222827. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222828. }
  222829. return newDevice;
  222830. }
  222831. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222832. {
  222833. MidiInput* newDevice = 0;
  222834. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  222835. if (handle != 0)
  222836. {
  222837. newDevice = new MidiInput (deviceName);
  222838. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222839. }
  222840. return newDevice;
  222841. }
  222842. #else
  222843. // (These are just stub functions if ALSA is unavailable...)
  222844. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222845. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222846. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222847. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222848. MidiOutput::~MidiOutput() {}
  222849. void MidiOutput::reset() {}
  222850. bool MidiOutput::getVolume (float&, float&) { return false; }
  222851. void MidiOutput::setVolume (float, float) {}
  222852. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222853. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222854. MidiInput::~MidiInput() {}
  222855. void MidiInput::start() {}
  222856. void MidiInput::stop() {}
  222857. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222858. const StringArray MidiInput::getDevices() { return StringArray(); }
  222859. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222860. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222861. #endif
  222862. #endif
  222863. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222864. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222865. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222866. // compiled on its own).
  222867. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222868. AudioCDReader::AudioCDReader()
  222869. : AudioFormatReader (0, "CD Audio")
  222870. {
  222871. }
  222872. const StringArray AudioCDReader::getAvailableCDNames()
  222873. {
  222874. StringArray names;
  222875. return names;
  222876. }
  222877. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222878. {
  222879. return 0;
  222880. }
  222881. AudioCDReader::~AudioCDReader()
  222882. {
  222883. }
  222884. void AudioCDReader::refreshTrackLengths()
  222885. {
  222886. }
  222887. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222888. int64 startSampleInFile, int numSamples)
  222889. {
  222890. return false;
  222891. }
  222892. bool AudioCDReader::isCDStillPresent() const
  222893. {
  222894. return false;
  222895. }
  222896. bool AudioCDReader::isTrackAudio (int trackNum) const
  222897. {
  222898. return false;
  222899. }
  222900. void AudioCDReader::enableIndexScanning (bool b)
  222901. {
  222902. }
  222903. int AudioCDReader::getLastIndex() const
  222904. {
  222905. return 0;
  222906. }
  222907. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222908. {
  222909. return Array<int>();
  222910. }
  222911. #endif
  222912. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222913. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222914. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222915. // compiled on its own).
  222916. #if JUCE_INCLUDED_FILE
  222917. void FileChooser::showPlatformDialog (Array<File>& results,
  222918. const String& title,
  222919. const File& file,
  222920. const String& filters,
  222921. bool isDirectory,
  222922. bool selectsFiles,
  222923. bool isSave,
  222924. bool warnAboutOverwritingExistingFiles,
  222925. bool selectMultipleFiles,
  222926. FilePreviewComponent* previewComponent)
  222927. {
  222928. const String separator (":");
  222929. String command ("zenity --file-selection");
  222930. if (title.isNotEmpty())
  222931. command << " --title=\"" << title << "\"";
  222932. if (file != File::nonexistent)
  222933. command << " --filename=\"" << file.getFullPathName () << "\"";
  222934. if (isDirectory)
  222935. command << " --directory";
  222936. if (isSave)
  222937. command << " --save";
  222938. if (selectMultipleFiles)
  222939. command << " --multiple --separator=\"" << separator << "\"";
  222940. command << " 2>&1";
  222941. MemoryOutputStream result;
  222942. int status = -1;
  222943. FILE* stream = popen (command.toUTF8(), "r");
  222944. if (stream != 0)
  222945. {
  222946. for (;;)
  222947. {
  222948. char buffer [1024];
  222949. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222950. if (bytesRead <= 0)
  222951. break;
  222952. result.write (buffer, bytesRead);
  222953. }
  222954. status = pclose (stream);
  222955. }
  222956. if (status == 0)
  222957. {
  222958. StringArray tokens;
  222959. if (selectMultipleFiles)
  222960. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222961. else
  222962. tokens.add (result.toUTF8());
  222963. for (int i = 0; i < tokens.size(); i++)
  222964. results.add (File (tokens[i]));
  222965. return;
  222966. }
  222967. //xxx ain't got one!
  222968. jassertfalse;
  222969. }
  222970. #endif
  222971. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222972. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222973. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222974. // compiled on its own).
  222975. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222976. /*
  222977. Sorry.. This class isn't implemented on Linux!
  222978. */
  222979. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222980. : browser (0),
  222981. blankPageShown (false),
  222982. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222983. {
  222984. setOpaque (true);
  222985. }
  222986. WebBrowserComponent::~WebBrowserComponent()
  222987. {
  222988. }
  222989. void WebBrowserComponent::goToURL (const String& url,
  222990. const StringArray* headers,
  222991. const MemoryBlock* postData)
  222992. {
  222993. lastURL = url;
  222994. lastHeaders.clear();
  222995. if (headers != 0)
  222996. lastHeaders = *headers;
  222997. lastPostData.setSize (0);
  222998. if (postData != 0)
  222999. lastPostData = *postData;
  223000. blankPageShown = false;
  223001. }
  223002. void WebBrowserComponent::stop()
  223003. {
  223004. }
  223005. void WebBrowserComponent::goBack()
  223006. {
  223007. lastURL = String::empty;
  223008. blankPageShown = false;
  223009. }
  223010. void WebBrowserComponent::goForward()
  223011. {
  223012. lastURL = String::empty;
  223013. }
  223014. void WebBrowserComponent::refresh()
  223015. {
  223016. }
  223017. void WebBrowserComponent::paint (Graphics& g)
  223018. {
  223019. g.fillAll (Colours::white);
  223020. }
  223021. void WebBrowserComponent::checkWindowAssociation()
  223022. {
  223023. }
  223024. void WebBrowserComponent::reloadLastURL()
  223025. {
  223026. if (lastURL.isNotEmpty())
  223027. {
  223028. goToURL (lastURL, &lastHeaders, &lastPostData);
  223029. lastURL = String::empty;
  223030. }
  223031. }
  223032. void WebBrowserComponent::parentHierarchyChanged()
  223033. {
  223034. checkWindowAssociation();
  223035. }
  223036. void WebBrowserComponent::resized()
  223037. {
  223038. }
  223039. void WebBrowserComponent::visibilityChanged()
  223040. {
  223041. checkWindowAssociation();
  223042. }
  223043. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223044. {
  223045. return true;
  223046. }
  223047. #endif
  223048. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223049. #endif
  223050. END_JUCE_NAMESPACE
  223051. #endif
  223052. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223053. #elif JUCE_MAC || JUCE_IOS
  223054. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223055. /*
  223056. This file wraps together all the mac-specific code, so that
  223057. we can include all the native headers just once, and compile all our
  223058. platform-specific stuff in one big lump, keeping it out of the way of
  223059. the rest of the codebase.
  223060. */
  223061. #if JUCE_MAC || JUCE_IOS
  223062. #undef JUCE_BUILD_NATIVE
  223063. #define JUCE_BUILD_NATIVE 1
  223064. BEGIN_JUCE_NAMESPACE
  223065. #undef Point
  223066. namespace
  223067. {
  223068. template <class RectType>
  223069. const Rectangle<int> convertToRectInt (const RectType& r)
  223070. {
  223071. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223072. }
  223073. template <class RectType>
  223074. const Rectangle<float> convertToRectFloat (const RectType& r)
  223075. {
  223076. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223077. }
  223078. template <class RectType>
  223079. CGRect convertToCGRect (const RectType& r)
  223080. {
  223081. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223082. }
  223083. }
  223084. class MessageQueue
  223085. {
  223086. public:
  223087. MessageQueue()
  223088. {
  223089. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223090. runLoop = CFRunLoopGetMain();
  223091. #else
  223092. runLoop = CFRunLoopGetCurrent();
  223093. #endif
  223094. CFRunLoopSourceContext sourceContext;
  223095. zerostruct (sourceContext);
  223096. sourceContext.info = this;
  223097. sourceContext.perform = runLoopSourceCallback;
  223098. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223099. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223100. }
  223101. ~MessageQueue()
  223102. {
  223103. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223104. CFRunLoopSourceInvalidate (runLoopSource);
  223105. CFRelease (runLoopSource);
  223106. }
  223107. void post (Message* const message)
  223108. {
  223109. messages.add (message);
  223110. CFRunLoopSourceSignal (runLoopSource);
  223111. CFRunLoopWakeUp (runLoop);
  223112. }
  223113. private:
  223114. ReferenceCountedArray <Message, CriticalSection> messages;
  223115. CriticalSection lock;
  223116. CFRunLoopRef runLoop;
  223117. CFRunLoopSourceRef runLoopSource;
  223118. bool deliverNextMessage()
  223119. {
  223120. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223121. if (nextMessage == 0)
  223122. return false;
  223123. const ScopedAutoReleasePool pool;
  223124. MessageManager::getInstance()->deliverMessage (nextMessage);
  223125. return true;
  223126. }
  223127. void runLoopCallback()
  223128. {
  223129. for (int i = 4; --i >= 0;)
  223130. if (! deliverNextMessage())
  223131. return;
  223132. CFRunLoopSourceSignal (runLoopSource);
  223133. CFRunLoopWakeUp (runLoop);
  223134. }
  223135. static void runLoopSourceCallback (void* info)
  223136. {
  223137. static_cast <MessageQueue*> (info)->runLoopCallback();
  223138. }
  223139. };
  223140. #define JUCE_INCLUDED_FILE 1
  223141. // Now include the actual code files..
  223142. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223143. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223144. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223145. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223146. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223147. actually calling into a similarly named class in the other module's address space.
  223148. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223149. have unique names, and should avoid this problem.
  223150. If you're using the amalgamated version, you can just set this macro to something unique before
  223151. you include juce_amalgamated.cpp.
  223152. */
  223153. #ifndef JUCE_ObjCExtraSuffix
  223154. #define JUCE_ObjCExtraSuffix 3
  223155. #endif
  223156. #ifndef DOXYGEN
  223157. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223158. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223159. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223160. #endif
  223161. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223162. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223163. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223164. // compiled on its own).
  223165. #if JUCE_INCLUDED_FILE
  223166. namespace
  223167. {
  223168. const String nsStringToJuce (NSString* s)
  223169. {
  223170. return String::fromUTF8 ([s UTF8String]);
  223171. }
  223172. NSString* juceStringToNS (const String& s)
  223173. {
  223174. return [NSString stringWithUTF8String: s.toUTF8()];
  223175. }
  223176. const String convertUTF16ToString (const UniChar* utf16)
  223177. {
  223178. String s;
  223179. while (*utf16 != 0)
  223180. s += (juce_wchar) *utf16++;
  223181. return s;
  223182. }
  223183. }
  223184. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223185. {
  223186. String result;
  223187. if (cfString != 0)
  223188. {
  223189. CFRange range = { 0, CFStringGetLength (cfString) };
  223190. HeapBlock <UniChar> u (range.length + 1);
  223191. CFStringGetCharacters (cfString, range, u);
  223192. u[range.length] = 0;
  223193. result = convertUTF16ToString (u);
  223194. }
  223195. return result;
  223196. }
  223197. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223198. {
  223199. const int len = s.length();
  223200. HeapBlock <UniChar> temp (len + 2);
  223201. for (int i = 0; i <= len; ++i)
  223202. temp[i] = s[i];
  223203. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223204. }
  223205. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223206. {
  223207. #if JUCE_IOS
  223208. const ScopedAutoReleasePool pool;
  223209. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223210. #else
  223211. UnicodeMapping map;
  223212. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223213. kUnicodeNoSubset,
  223214. kTextEncodingDefaultFormat);
  223215. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223216. kUnicodeCanonicalCompVariant,
  223217. kTextEncodingDefaultFormat);
  223218. map.mappingVersion = kUnicodeUseLatestMapping;
  223219. UnicodeToTextInfo conversionInfo = 0;
  223220. String result;
  223221. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223222. {
  223223. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223224. HeapBlock <char> tempOut;
  223225. tempOut.calloc (bytesNeeded + 4);
  223226. ByteCount bytesRead = 0;
  223227. ByteCount outputBufferSize = 0;
  223228. if (ConvertFromUnicodeToText (conversionInfo,
  223229. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223230. kUnicodeDefaultDirectionMask,
  223231. 0, 0, 0, 0,
  223232. bytesNeeded, &bytesRead,
  223233. &outputBufferSize, tempOut) == noErr)
  223234. {
  223235. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223236. CharPointer_UTF32 dest (static_cast <juce_wchar*> (result));
  223237. dest.writeAll (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223238. }
  223239. DisposeUnicodeToTextInfo (&conversionInfo);
  223240. }
  223241. return result;
  223242. #endif
  223243. }
  223244. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223245. void SystemClipboard::copyTextToClipboard (const String& text)
  223246. {
  223247. #if JUCE_IOS
  223248. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223249. forPasteboardType: @"public.text"];
  223250. #else
  223251. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223252. owner: nil];
  223253. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223254. forType: NSStringPboardType];
  223255. #endif
  223256. }
  223257. const String SystemClipboard::getTextFromClipboard()
  223258. {
  223259. #if JUCE_IOS
  223260. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223261. #else
  223262. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223263. #endif
  223264. return text == 0 ? String::empty
  223265. : nsStringToJuce (text);
  223266. }
  223267. #endif
  223268. #endif
  223269. /*** End of inlined file: juce_mac_Strings.mm ***/
  223270. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223271. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223272. // compiled on its own).
  223273. #if JUCE_INCLUDED_FILE
  223274. namespace SystemStatsHelpers
  223275. {
  223276. static int64 highResTimerFrequency = 0;
  223277. static double highResTimerToMillisecRatio = 0;
  223278. #if JUCE_INTEL
  223279. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223280. {
  223281. uint32 la = a, lb = b, lc = c, ld = d;
  223282. asm ("mov %%ebx, %%esi \n\t"
  223283. "cpuid \n\t"
  223284. "xchg %%esi, %%ebx"
  223285. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223286. #if JUCE_64BIT
  223287. , "b" (lb), "c" (lc), "d" (ld)
  223288. #endif
  223289. );
  223290. a = la; b = lb; c = lc; d = ld;
  223291. }
  223292. #endif
  223293. }
  223294. void SystemStats::initialiseStats()
  223295. {
  223296. using namespace SystemStatsHelpers;
  223297. static bool initialised = false;
  223298. if (! initialised)
  223299. {
  223300. initialised = true;
  223301. #if JUCE_MAC
  223302. [NSApplication sharedApplication];
  223303. #endif
  223304. #if JUCE_INTEL
  223305. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223306. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223307. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223308. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223309. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223310. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223311. #else
  223312. cpuFlags.hasMMX = false;
  223313. cpuFlags.hasSSE = false;
  223314. cpuFlags.hasSSE2 = false;
  223315. cpuFlags.has3DNow = false;
  223316. #endif
  223317. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223318. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223319. #else
  223320. cpuFlags.numCpus = (int) MPProcessors();
  223321. #endif
  223322. mach_timebase_info_data_t timebase;
  223323. (void) mach_timebase_info (&timebase);
  223324. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223325. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223326. String s (SystemStats::getJUCEVersion());
  223327. rlimit lim;
  223328. getrlimit (RLIMIT_NOFILE, &lim);
  223329. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223330. setrlimit (RLIMIT_NOFILE, &lim);
  223331. }
  223332. }
  223333. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223334. {
  223335. return MacOSX;
  223336. }
  223337. const String SystemStats::getOperatingSystemName()
  223338. {
  223339. return "Mac OS X";
  223340. }
  223341. #if ! JUCE_IOS
  223342. int PlatformUtilities::getOSXMinorVersionNumber()
  223343. {
  223344. SInt32 versionMinor = 0;
  223345. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223346. (void) err;
  223347. jassert (err == noErr);
  223348. return (int) versionMinor;
  223349. }
  223350. #endif
  223351. bool SystemStats::isOperatingSystem64Bit()
  223352. {
  223353. #if JUCE_IOS
  223354. return false;
  223355. #elif JUCE_64BIT
  223356. return true;
  223357. #else
  223358. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223359. #endif
  223360. }
  223361. int SystemStats::getMemorySizeInMegabytes()
  223362. {
  223363. uint64 mem = 0;
  223364. size_t memSize = sizeof (mem);
  223365. int mib[] = { CTL_HW, HW_MEMSIZE };
  223366. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223367. return (int) (mem / (1024 * 1024));
  223368. }
  223369. const String SystemStats::getCpuVendor()
  223370. {
  223371. #if JUCE_INTEL
  223372. uint32 dummy = 0;
  223373. uint32 vendor[4];
  223374. zerostruct (vendor);
  223375. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223376. return String (reinterpret_cast <const char*> (vendor), 12);
  223377. #else
  223378. return String::empty;
  223379. #endif
  223380. }
  223381. int SystemStats::getCpuSpeedInMegaherz()
  223382. {
  223383. uint64 speedHz = 0;
  223384. size_t speedSize = sizeof (speedHz);
  223385. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223386. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223387. #if JUCE_BIG_ENDIAN
  223388. if (speedSize == 4)
  223389. speedHz >>= 32;
  223390. #endif
  223391. return (int) (speedHz / 1000000);
  223392. }
  223393. const String SystemStats::getLogonName()
  223394. {
  223395. return nsStringToJuce (NSUserName());
  223396. }
  223397. const String SystemStats::getFullUserName()
  223398. {
  223399. return nsStringToJuce (NSFullUserName());
  223400. }
  223401. uint32 juce_millisecondsSinceStartup() throw()
  223402. {
  223403. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223404. }
  223405. double Time::getMillisecondCounterHiRes() throw()
  223406. {
  223407. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223408. }
  223409. int64 Time::getHighResolutionTicks() throw()
  223410. {
  223411. return (int64) mach_absolute_time();
  223412. }
  223413. int64 Time::getHighResolutionTicksPerSecond() throw()
  223414. {
  223415. return SystemStatsHelpers::highResTimerFrequency;
  223416. }
  223417. bool Time::setSystemTimeToThisTime() const
  223418. {
  223419. jassertfalse;
  223420. return false;
  223421. }
  223422. int SystemStats::getPageSize()
  223423. {
  223424. return (int) NSPageSize();
  223425. }
  223426. void PlatformUtilities::fpuReset()
  223427. {
  223428. }
  223429. #endif
  223430. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223431. /*** Start of inlined file: juce_mac_Network.mm ***/
  223432. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223433. // compiled on its own).
  223434. #if JUCE_INCLUDED_FILE
  223435. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223436. {
  223437. ifaddrs* addrs = 0;
  223438. if (getifaddrs (&addrs) == 0)
  223439. {
  223440. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223441. {
  223442. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223443. if (sto->ss_family == AF_LINK)
  223444. {
  223445. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223446. #ifndef IFT_ETHER
  223447. #define IFT_ETHER 6
  223448. #endif
  223449. if (sadd->sdl_type == IFT_ETHER)
  223450. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223451. }
  223452. }
  223453. freeifaddrs (addrs);
  223454. }
  223455. }
  223456. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223457. const String& emailSubject,
  223458. const String& bodyText,
  223459. const StringArray& filesToAttach)
  223460. {
  223461. #if JUCE_IOS
  223462. //xxx probably need to use MFMailComposeViewController
  223463. jassertfalse;
  223464. return false;
  223465. #else
  223466. const ScopedAutoReleasePool pool;
  223467. String script;
  223468. script << "tell application \"Mail\"\r\n"
  223469. "set newMessage to make new outgoing message with properties {subject:\""
  223470. << emailSubject.replace ("\"", "\\\"")
  223471. << "\", content:\""
  223472. << bodyText.replace ("\"", "\\\"")
  223473. << "\" & return & return}\r\n"
  223474. "tell newMessage\r\n"
  223475. "set visible to true\r\n"
  223476. "set sender to \"sdfsdfsdfewf\"\r\n"
  223477. "make new to recipient at end of to recipients with properties {address:\""
  223478. << targetEmailAddress
  223479. << "\"}\r\n";
  223480. for (int i = 0; i < filesToAttach.size(); ++i)
  223481. {
  223482. script << "tell content\r\n"
  223483. "make new attachment with properties {file name:\""
  223484. << filesToAttach[i].replace ("\"", "\\\"")
  223485. << "\"} at after the last paragraph\r\n"
  223486. "end tell\r\n";
  223487. }
  223488. script << "end tell\r\n"
  223489. "end tell\r\n";
  223490. NSAppleScript* s = [[NSAppleScript alloc]
  223491. initWithSource: juceStringToNS (script)];
  223492. NSDictionary* error = 0;
  223493. const bool ok = [s executeAndReturnError: &error] != nil;
  223494. [s release];
  223495. return ok;
  223496. #endif
  223497. }
  223498. END_JUCE_NAMESPACE
  223499. using namespace JUCE_NAMESPACE;
  223500. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223501. @interface JuceURLConnection : NSObject
  223502. {
  223503. @public
  223504. NSURLRequest* request;
  223505. NSURLConnection* connection;
  223506. NSMutableData* data;
  223507. Thread* runLoopThread;
  223508. bool initialised, hasFailed, hasFinished;
  223509. int position;
  223510. int64 contentLength;
  223511. NSDictionary* headers;
  223512. NSLock* dataLock;
  223513. }
  223514. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223515. - (void) dealloc;
  223516. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223517. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223518. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223519. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223520. - (BOOL) isOpen;
  223521. - (int) read: (char*) dest numBytes: (int) num;
  223522. - (int) readPosition;
  223523. - (void) stop;
  223524. - (void) createConnection;
  223525. @end
  223526. class JuceURLConnectionMessageThread : public Thread
  223527. {
  223528. public:
  223529. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223530. : Thread ("http connection"),
  223531. owner (owner_)
  223532. {
  223533. }
  223534. ~JuceURLConnectionMessageThread()
  223535. {
  223536. stopThread (10000);
  223537. }
  223538. void run()
  223539. {
  223540. [owner createConnection];
  223541. while (! threadShouldExit())
  223542. {
  223543. const ScopedAutoReleasePool pool;
  223544. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223545. }
  223546. }
  223547. private:
  223548. JuceURLConnection* owner;
  223549. };
  223550. @implementation JuceURLConnection
  223551. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223552. withCallback: (URL::OpenStreamProgressCallback*) callback
  223553. withContext: (void*) context;
  223554. {
  223555. [super init];
  223556. request = req;
  223557. [request retain];
  223558. data = [[NSMutableData data] retain];
  223559. dataLock = [[NSLock alloc] init];
  223560. connection = 0;
  223561. initialised = false;
  223562. hasFailed = false;
  223563. hasFinished = false;
  223564. contentLength = -1;
  223565. headers = 0;
  223566. runLoopThread = new JuceURLConnectionMessageThread (self);
  223567. runLoopThread->startThread();
  223568. while (runLoopThread->isThreadRunning() && ! initialised)
  223569. {
  223570. if (callback != 0)
  223571. callback (context, -1, (int) [[request HTTPBody] length]);
  223572. Thread::sleep (1);
  223573. }
  223574. return self;
  223575. }
  223576. - (void) dealloc
  223577. {
  223578. [self stop];
  223579. deleteAndZero (runLoopThread);
  223580. [connection release];
  223581. [data release];
  223582. [dataLock release];
  223583. [request release];
  223584. [headers release];
  223585. [super dealloc];
  223586. }
  223587. - (void) createConnection
  223588. {
  223589. NSUInteger oldRetainCount = [self retainCount];
  223590. connection = [[NSURLConnection alloc] initWithRequest: request
  223591. delegate: self];
  223592. if (oldRetainCount == [self retainCount])
  223593. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223594. if (connection == nil)
  223595. runLoopThread->signalThreadShouldExit();
  223596. }
  223597. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223598. {
  223599. (void) conn;
  223600. [dataLock lock];
  223601. [data setLength: 0];
  223602. [dataLock unlock];
  223603. initialised = true;
  223604. contentLength = [response expectedContentLength];
  223605. [headers release];
  223606. headers = 0;
  223607. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223608. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223609. }
  223610. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223611. {
  223612. (void) conn;
  223613. DBG (nsStringToJuce ([error description]));
  223614. hasFailed = true;
  223615. initialised = true;
  223616. if (runLoopThread != 0)
  223617. runLoopThread->signalThreadShouldExit();
  223618. }
  223619. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223620. {
  223621. (void) conn;
  223622. [dataLock lock];
  223623. [data appendData: newData];
  223624. [dataLock unlock];
  223625. initialised = true;
  223626. }
  223627. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223628. {
  223629. (void) conn;
  223630. hasFinished = true;
  223631. initialised = true;
  223632. if (runLoopThread != 0)
  223633. runLoopThread->signalThreadShouldExit();
  223634. }
  223635. - (BOOL) isOpen
  223636. {
  223637. return connection != 0 && ! hasFailed;
  223638. }
  223639. - (int) readPosition
  223640. {
  223641. return position;
  223642. }
  223643. - (int) read: (char*) dest numBytes: (int) numNeeded
  223644. {
  223645. int numDone = 0;
  223646. while (numNeeded > 0)
  223647. {
  223648. int available = jmin (numNeeded, (int) [data length]);
  223649. if (available > 0)
  223650. {
  223651. [dataLock lock];
  223652. [data getBytes: dest length: available];
  223653. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223654. [dataLock unlock];
  223655. numDone += available;
  223656. numNeeded -= available;
  223657. dest += available;
  223658. }
  223659. else
  223660. {
  223661. if (hasFailed || hasFinished)
  223662. break;
  223663. Thread::sleep (1);
  223664. }
  223665. }
  223666. position += numDone;
  223667. return numDone;
  223668. }
  223669. - (void) stop
  223670. {
  223671. [connection cancel];
  223672. if (runLoopThread != 0)
  223673. runLoopThread->stopThread (10000);
  223674. }
  223675. @end
  223676. BEGIN_JUCE_NAMESPACE
  223677. class WebInputStream : public InputStream
  223678. {
  223679. public:
  223680. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223681. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223682. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223683. : connection (nil),
  223684. address (address_), headers (headers_), postData (postData_), position (0),
  223685. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223686. {
  223687. JUCE_AUTORELEASEPOOL
  223688. connection = createConnection (progressCallback, progressCallbackContext);
  223689. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223690. {
  223691. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223692. NSString* key;
  223693. while ((key = [enumerator nextObject]) != nil)
  223694. responseHeaders->set (nsStringToJuce (key),
  223695. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223696. }
  223697. }
  223698. ~WebInputStream()
  223699. {
  223700. close();
  223701. }
  223702. bool isError() const { return connection == nil; }
  223703. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223704. bool isExhausted() { return finished; }
  223705. int64 getPosition() { return position; }
  223706. int read (void* buffer, int bytesToRead)
  223707. {
  223708. if (finished || isError())
  223709. {
  223710. return 0;
  223711. }
  223712. else
  223713. {
  223714. JUCE_AUTORELEASEPOOL
  223715. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223716. position += bytesRead;
  223717. if (bytesRead == 0)
  223718. finished = true;
  223719. return bytesRead;
  223720. }
  223721. }
  223722. bool setPosition (int64 wantedPos)
  223723. {
  223724. if (wantedPos != position)
  223725. {
  223726. finished = false;
  223727. if (wantedPos < position)
  223728. {
  223729. close();
  223730. position = 0;
  223731. connection = createConnection (0, 0);
  223732. }
  223733. skipNextBytes (wantedPos - position);
  223734. }
  223735. return true;
  223736. }
  223737. private:
  223738. JuceURLConnection* connection;
  223739. String address, headers;
  223740. MemoryBlock postData;
  223741. int64 position;
  223742. bool finished;
  223743. const bool isPost;
  223744. const int timeOutMs;
  223745. void close()
  223746. {
  223747. [connection stop];
  223748. [connection release];
  223749. connection = nil;
  223750. }
  223751. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  223752. void* progressCallbackContext)
  223753. {
  223754. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  223755. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223756. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223757. if (req == nil)
  223758. return 0;
  223759. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223760. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223761. StringArray headerLines;
  223762. headerLines.addLines (headers);
  223763. headerLines.removeEmptyStrings (true);
  223764. for (int i = 0; i < headerLines.size(); ++i)
  223765. {
  223766. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223767. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223768. if (key.isNotEmpty() && value.isNotEmpty())
  223769. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223770. }
  223771. if (isPost && postData.getSize() > 0)
  223772. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223773. length: postData.getSize()]];
  223774. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223775. withCallback: progressCallback
  223776. withContext: progressCallbackContext];
  223777. if ([s isOpen])
  223778. return s;
  223779. [s release];
  223780. return 0;
  223781. }
  223782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  223783. };
  223784. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  223785. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223786. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  223787. {
  223788. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  223789. progressCallback, progressCallbackContext,
  223790. headers, timeOutMs, responseHeaders));
  223791. return wi->isError() ? 0 : wi.release();
  223792. }
  223793. #endif
  223794. /*** End of inlined file: juce_mac_Network.mm ***/
  223795. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223796. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223797. // compiled on its own).
  223798. #if JUCE_INCLUDED_FILE
  223799. struct NamedPipeInternal
  223800. {
  223801. String pipeInName, pipeOutName;
  223802. int pipeIn, pipeOut;
  223803. bool volatile createdPipe, blocked, stopReadOperation;
  223804. static void signalHandler (int) {}
  223805. };
  223806. void NamedPipe::cancelPendingReads()
  223807. {
  223808. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  223809. {
  223810. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223811. intern->stopReadOperation = true;
  223812. char buffer [1] = { 0 };
  223813. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223814. (void) bytesWritten;
  223815. int timeout = 2000;
  223816. while (intern->blocked && --timeout >= 0)
  223817. Thread::sleep (2);
  223818. intern->stopReadOperation = false;
  223819. }
  223820. }
  223821. void NamedPipe::close()
  223822. {
  223823. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223824. if (intern != 0)
  223825. {
  223826. internal = 0;
  223827. if (intern->pipeIn != -1)
  223828. ::close (intern->pipeIn);
  223829. if (intern->pipeOut != -1)
  223830. ::close (intern->pipeOut);
  223831. if (intern->createdPipe)
  223832. {
  223833. unlink (intern->pipeInName.toUTF8());
  223834. unlink (intern->pipeOutName.toUTF8());
  223835. }
  223836. delete intern;
  223837. }
  223838. }
  223839. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223840. {
  223841. close();
  223842. NamedPipeInternal* const intern = new NamedPipeInternal();
  223843. internal = intern;
  223844. intern->createdPipe = createPipe;
  223845. intern->blocked = false;
  223846. intern->stopReadOperation = false;
  223847. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223848. siginterrupt (SIGPIPE, 1);
  223849. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223850. intern->pipeInName = pipePath + "_in";
  223851. intern->pipeOutName = pipePath + "_out";
  223852. intern->pipeIn = -1;
  223853. intern->pipeOut = -1;
  223854. if (createPipe)
  223855. {
  223856. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223857. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223858. {
  223859. delete intern;
  223860. internal = 0;
  223861. return false;
  223862. }
  223863. }
  223864. return true;
  223865. }
  223866. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223867. {
  223868. int bytesRead = -1;
  223869. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223870. if (intern != 0)
  223871. {
  223872. intern->blocked = true;
  223873. if (intern->pipeIn == -1)
  223874. {
  223875. if (intern->createdPipe)
  223876. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223877. else
  223878. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223879. if (intern->pipeIn == -1)
  223880. {
  223881. intern->blocked = false;
  223882. return -1;
  223883. }
  223884. }
  223885. bytesRead = 0;
  223886. char* p = static_cast<char*> (destBuffer);
  223887. while (bytesRead < maxBytesToRead)
  223888. {
  223889. const int bytesThisTime = maxBytesToRead - bytesRead;
  223890. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223891. if (numRead <= 0 || intern->stopReadOperation)
  223892. {
  223893. bytesRead = -1;
  223894. break;
  223895. }
  223896. bytesRead += numRead;
  223897. p += bytesRead;
  223898. }
  223899. intern->blocked = false;
  223900. }
  223901. return bytesRead;
  223902. }
  223903. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223904. {
  223905. int bytesWritten = -1;
  223906. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223907. if (intern != 0)
  223908. {
  223909. if (intern->pipeOut == -1)
  223910. {
  223911. if (intern->createdPipe)
  223912. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223913. else
  223914. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223915. if (intern->pipeOut == -1)
  223916. {
  223917. return -1;
  223918. }
  223919. }
  223920. const char* p = static_cast<const char*> (sourceBuffer);
  223921. bytesWritten = 0;
  223922. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223923. while (bytesWritten < numBytesToWrite
  223924. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223925. {
  223926. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223927. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223928. if (numWritten <= 0)
  223929. {
  223930. bytesWritten = -1;
  223931. break;
  223932. }
  223933. bytesWritten += numWritten;
  223934. p += bytesWritten;
  223935. }
  223936. }
  223937. return bytesWritten;
  223938. }
  223939. #endif
  223940. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223941. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223942. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223943. // compiled on its own).
  223944. #if JUCE_INCLUDED_FILE
  223945. /*
  223946. Note that a lot of methods that you'd expect to find in this file actually
  223947. live in juce_posix_SharedCode.h!
  223948. */
  223949. bool Process::isForegroundProcess()
  223950. {
  223951. #if JUCE_MAC
  223952. return [NSApp isActive];
  223953. #else
  223954. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223955. #endif
  223956. }
  223957. void Process::raisePrivilege()
  223958. {
  223959. jassertfalse;
  223960. }
  223961. void Process::lowerPrivilege()
  223962. {
  223963. jassertfalse;
  223964. }
  223965. void Process::terminate()
  223966. {
  223967. exit (0);
  223968. }
  223969. void Process::setPriority (ProcessPriority)
  223970. {
  223971. // xxx
  223972. }
  223973. #endif
  223974. /*** End of inlined file: juce_mac_Threads.mm ***/
  223975. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223976. /*
  223977. This file contains posix routines that are common to both the Linux and Mac builds.
  223978. It gets included directly in the cpp files for these platforms.
  223979. */
  223980. CriticalSection::CriticalSection() throw()
  223981. {
  223982. pthread_mutexattr_t atts;
  223983. pthread_mutexattr_init (&atts);
  223984. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223985. #if ! JUCE_ANDROID
  223986. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223987. #endif
  223988. pthread_mutex_init (&internal, &atts);
  223989. }
  223990. CriticalSection::~CriticalSection() throw()
  223991. {
  223992. pthread_mutex_destroy (&internal);
  223993. }
  223994. void CriticalSection::enter() const throw()
  223995. {
  223996. pthread_mutex_lock (&internal);
  223997. }
  223998. bool CriticalSection::tryEnter() const throw()
  223999. {
  224000. return pthread_mutex_trylock (&internal) == 0;
  224001. }
  224002. void CriticalSection::exit() const throw()
  224003. {
  224004. pthread_mutex_unlock (&internal);
  224005. }
  224006. class WaitableEventImpl
  224007. {
  224008. public:
  224009. WaitableEventImpl (const bool manualReset_)
  224010. : triggered (false),
  224011. manualReset (manualReset_)
  224012. {
  224013. pthread_cond_init (&condition, 0);
  224014. pthread_mutexattr_t atts;
  224015. pthread_mutexattr_init (&atts);
  224016. #if ! JUCE_ANDROID
  224017. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224018. #endif
  224019. pthread_mutex_init (&mutex, &atts);
  224020. }
  224021. ~WaitableEventImpl()
  224022. {
  224023. pthread_cond_destroy (&condition);
  224024. pthread_mutex_destroy (&mutex);
  224025. }
  224026. bool wait (const int timeOutMillisecs) throw()
  224027. {
  224028. pthread_mutex_lock (&mutex);
  224029. if (! triggered)
  224030. {
  224031. if (timeOutMillisecs < 0)
  224032. {
  224033. do
  224034. {
  224035. pthread_cond_wait (&condition, &mutex);
  224036. }
  224037. while (! triggered);
  224038. }
  224039. else
  224040. {
  224041. struct timeval now;
  224042. gettimeofday (&now, 0);
  224043. struct timespec time;
  224044. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224045. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224046. if (time.tv_nsec >= 1000000000)
  224047. {
  224048. time.tv_nsec -= 1000000000;
  224049. time.tv_sec++;
  224050. }
  224051. do
  224052. {
  224053. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224054. {
  224055. pthread_mutex_unlock (&mutex);
  224056. return false;
  224057. }
  224058. }
  224059. while (! triggered);
  224060. }
  224061. }
  224062. if (! manualReset)
  224063. triggered = false;
  224064. pthread_mutex_unlock (&mutex);
  224065. return true;
  224066. }
  224067. void signal() throw()
  224068. {
  224069. pthread_mutex_lock (&mutex);
  224070. triggered = true;
  224071. pthread_cond_broadcast (&condition);
  224072. pthread_mutex_unlock (&mutex);
  224073. }
  224074. void reset() throw()
  224075. {
  224076. pthread_mutex_lock (&mutex);
  224077. triggered = false;
  224078. pthread_mutex_unlock (&mutex);
  224079. }
  224080. private:
  224081. pthread_cond_t condition;
  224082. pthread_mutex_t mutex;
  224083. bool triggered;
  224084. const bool manualReset;
  224085. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224086. };
  224087. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224088. : internal (new WaitableEventImpl (manualReset))
  224089. {
  224090. }
  224091. WaitableEvent::~WaitableEvent() throw()
  224092. {
  224093. delete static_cast <WaitableEventImpl*> (internal);
  224094. }
  224095. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224096. {
  224097. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224098. }
  224099. void WaitableEvent::signal() const throw()
  224100. {
  224101. static_cast <WaitableEventImpl*> (internal)->signal();
  224102. }
  224103. void WaitableEvent::reset() const throw()
  224104. {
  224105. static_cast <WaitableEventImpl*> (internal)->reset();
  224106. }
  224107. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224108. {
  224109. struct timespec time;
  224110. time.tv_sec = millisecs / 1000;
  224111. time.tv_nsec = (millisecs % 1000) * 1000000;
  224112. nanosleep (&time, 0);
  224113. }
  224114. const juce_wchar File::separator = '/';
  224115. const String File::separatorString ("/");
  224116. const File File::getCurrentWorkingDirectory()
  224117. {
  224118. HeapBlock<char> heapBuffer;
  224119. char localBuffer [1024];
  224120. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224121. int bufferSize = 4096;
  224122. while (cwd == 0 && errno == ERANGE)
  224123. {
  224124. heapBuffer.malloc (bufferSize);
  224125. cwd = getcwd (heapBuffer, bufferSize - 1);
  224126. bufferSize += 1024;
  224127. }
  224128. return File (String::fromUTF8 (cwd));
  224129. }
  224130. bool File::setAsCurrentWorkingDirectory() const
  224131. {
  224132. return chdir (getFullPathName().toUTF8()) == 0;
  224133. }
  224134. namespace
  224135. {
  224136. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224137. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224138. #else
  224139. typedef struct stat juce_statStruct;
  224140. #endif
  224141. bool juce_stat (const String& fileName, juce_statStruct& info)
  224142. {
  224143. return fileName.isNotEmpty()
  224144. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224145. && (stat64 (fileName.toUTF8(), &info) == 0);
  224146. #else
  224147. && (stat (fileName.toUTF8(), &info) == 0);
  224148. #endif
  224149. }
  224150. // if this file doesn't exist, find a parent of it that does..
  224151. bool juce_doStatFS (File f, struct statfs& result)
  224152. {
  224153. for (int i = 5; --i >= 0;)
  224154. {
  224155. if (f.exists())
  224156. break;
  224157. f = f.getParentDirectory();
  224158. }
  224159. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224160. }
  224161. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224162. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224163. {
  224164. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224165. {
  224166. juce_statStruct info;
  224167. const bool statOk = juce_stat (path, info);
  224168. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224169. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224170. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224171. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224172. }
  224173. if (isReadOnly != 0)
  224174. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224175. }
  224176. }
  224177. bool File::isDirectory() const
  224178. {
  224179. juce_statStruct info;
  224180. return fullPath.isEmpty()
  224181. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224182. }
  224183. bool File::exists() const
  224184. {
  224185. juce_statStruct info;
  224186. return fullPath.isNotEmpty()
  224187. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224188. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224189. #else
  224190. && (lstat (fullPath.toUTF8(), &info) == 0);
  224191. #endif
  224192. }
  224193. bool File::existsAsFile() const
  224194. {
  224195. return exists() && ! isDirectory();
  224196. }
  224197. int64 File::getSize() const
  224198. {
  224199. juce_statStruct info;
  224200. return juce_stat (fullPath, info) ? info.st_size : 0;
  224201. }
  224202. bool File::hasWriteAccess() const
  224203. {
  224204. if (exists())
  224205. return access (fullPath.toUTF8(), W_OK) == 0;
  224206. if ((! isDirectory()) && fullPath.containsChar (separator))
  224207. return getParentDirectory().hasWriteAccess();
  224208. return false;
  224209. }
  224210. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224211. {
  224212. juce_statStruct info;
  224213. if (! juce_stat (fullPath, info))
  224214. return false;
  224215. info.st_mode &= 0777; // Just permissions
  224216. if (shouldBeReadOnly)
  224217. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224218. else
  224219. // Give everybody write permission?
  224220. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224221. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224222. }
  224223. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224224. {
  224225. modificationTime = 0;
  224226. accessTime = 0;
  224227. creationTime = 0;
  224228. juce_statStruct info;
  224229. if (juce_stat (fullPath, info))
  224230. {
  224231. modificationTime = (int64) info.st_mtime * 1000;
  224232. accessTime = (int64) info.st_atime * 1000;
  224233. creationTime = (int64) info.st_ctime * 1000;
  224234. }
  224235. }
  224236. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224237. {
  224238. juce_statStruct info;
  224239. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224240. {
  224241. struct utimbuf times;
  224242. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224243. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224244. return utime (fullPath.toUTF8(), &times) == 0;
  224245. }
  224246. return false;
  224247. }
  224248. bool File::deleteFile() const
  224249. {
  224250. if (! exists())
  224251. return true;
  224252. if (isDirectory())
  224253. return rmdir (fullPath.toUTF8()) == 0;
  224254. return remove (fullPath.toUTF8()) == 0;
  224255. }
  224256. bool File::moveInternal (const File& dest) const
  224257. {
  224258. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224259. return true;
  224260. if (hasWriteAccess() && copyInternal (dest))
  224261. {
  224262. if (deleteFile())
  224263. return true;
  224264. dest.deleteFile();
  224265. }
  224266. return false;
  224267. }
  224268. void File::createDirectoryInternal (const String& fileName) const
  224269. {
  224270. mkdir (fileName.toUTF8(), 0777);
  224271. }
  224272. int64 juce_fileSetPosition (void* handle, int64 pos)
  224273. {
  224274. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224275. return pos;
  224276. return -1;
  224277. }
  224278. void FileInputStream::openHandle()
  224279. {
  224280. totalSize = file.getSize();
  224281. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224282. if (f != -1)
  224283. fileHandle = (void*) f;
  224284. }
  224285. void FileInputStream::closeHandle()
  224286. {
  224287. if (fileHandle != 0)
  224288. {
  224289. close ((int) (pointer_sized_int) fileHandle);
  224290. fileHandle = 0;
  224291. }
  224292. }
  224293. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224294. {
  224295. if (fileHandle != 0)
  224296. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224297. return 0;
  224298. }
  224299. void FileOutputStream::openHandle()
  224300. {
  224301. if (file.exists())
  224302. {
  224303. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224304. if (f != -1)
  224305. {
  224306. currentPosition = lseek (f, 0, SEEK_END);
  224307. if (currentPosition >= 0)
  224308. fileHandle = (void*) f;
  224309. else
  224310. close (f);
  224311. }
  224312. }
  224313. else
  224314. {
  224315. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224316. if (f != -1)
  224317. fileHandle = (void*) f;
  224318. }
  224319. }
  224320. void FileOutputStream::closeHandle()
  224321. {
  224322. if (fileHandle != 0)
  224323. {
  224324. close ((int) (pointer_sized_int) fileHandle);
  224325. fileHandle = 0;
  224326. }
  224327. }
  224328. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224329. {
  224330. if (fileHandle != 0)
  224331. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224332. return 0;
  224333. }
  224334. void FileOutputStream::flushInternal()
  224335. {
  224336. if (fileHandle != 0)
  224337. fsync ((int) (pointer_sized_int) fileHandle);
  224338. }
  224339. const File juce_getExecutableFile()
  224340. {
  224341. #if JUCE_ANDROID
  224342. // TODO
  224343. return File::nonexistent;
  224344. #else
  224345. Dl_info exeInfo;
  224346. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224347. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224348. #endif
  224349. }
  224350. int64 File::getBytesFreeOnVolume() const
  224351. {
  224352. struct statfs buf;
  224353. if (juce_doStatFS (*this, buf))
  224354. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224355. return 0;
  224356. }
  224357. int64 File::getVolumeTotalSize() const
  224358. {
  224359. struct statfs buf;
  224360. if (juce_doStatFS (*this, buf))
  224361. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224362. return 0;
  224363. }
  224364. const String File::getVolumeLabel() const
  224365. {
  224366. #if JUCE_MAC
  224367. struct VolAttrBuf
  224368. {
  224369. u_int32_t length;
  224370. attrreference_t mountPointRef;
  224371. char mountPointSpace [MAXPATHLEN];
  224372. } attrBuf;
  224373. struct attrlist attrList;
  224374. zerostruct (attrList);
  224375. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224376. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224377. File f (*this);
  224378. for (;;)
  224379. {
  224380. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224381. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224382. (int) attrBuf.mountPointRef.attr_length);
  224383. const File parent (f.getParentDirectory());
  224384. if (f == parent)
  224385. break;
  224386. f = parent;
  224387. }
  224388. #endif
  224389. return String::empty;
  224390. }
  224391. int File::getVolumeSerialNumber() const
  224392. {
  224393. int result = 0;
  224394. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  224395. char info [512];
  224396. #ifndef HDIO_GET_IDENTITY
  224397. #define HDIO_GET_IDENTITY 0x030d
  224398. #endif
  224399. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  224400. {
  224401. DBG (String (info + 20, 20));
  224402. result = String (info + 20, 20).trim().getIntValue();
  224403. }
  224404. close (fd);*/
  224405. return result;
  224406. }
  224407. void juce_runSystemCommand (const String& command)
  224408. {
  224409. int result = system (command.toUTF8());
  224410. (void) result;
  224411. }
  224412. const String juce_getOutputFromCommand (const String& command)
  224413. {
  224414. // slight bodge here, as we just pipe the output into a temp file and read it...
  224415. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224416. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224417. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224418. String result (tempFile.loadFileAsString());
  224419. tempFile.deleteFile();
  224420. return result;
  224421. }
  224422. class InterProcessLock::Pimpl
  224423. {
  224424. public:
  224425. Pimpl (const String& name, const int timeOutMillisecs)
  224426. : handle (0), refCount (1)
  224427. {
  224428. #if JUCE_MAC
  224429. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224430. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224431. #else
  224432. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224433. #endif
  224434. temp.create();
  224435. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224436. if (handle != 0)
  224437. {
  224438. struct flock fl;
  224439. zerostruct (fl);
  224440. fl.l_whence = SEEK_SET;
  224441. fl.l_type = F_WRLCK;
  224442. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224443. for (;;)
  224444. {
  224445. const int result = fcntl (handle, F_SETLK, &fl);
  224446. if (result >= 0)
  224447. return;
  224448. if (errno != EINTR)
  224449. {
  224450. if (timeOutMillisecs == 0
  224451. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224452. break;
  224453. Thread::sleep (10);
  224454. }
  224455. }
  224456. }
  224457. closeFile();
  224458. }
  224459. ~Pimpl()
  224460. {
  224461. closeFile();
  224462. }
  224463. void closeFile()
  224464. {
  224465. if (handle != 0)
  224466. {
  224467. struct flock fl;
  224468. zerostruct (fl);
  224469. fl.l_whence = SEEK_SET;
  224470. fl.l_type = F_UNLCK;
  224471. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224472. {}
  224473. close (handle);
  224474. handle = 0;
  224475. }
  224476. }
  224477. int handle, refCount;
  224478. };
  224479. InterProcessLock::InterProcessLock (const String& name_)
  224480. : name (name_)
  224481. {
  224482. }
  224483. InterProcessLock::~InterProcessLock()
  224484. {
  224485. }
  224486. bool InterProcessLock::enter (const int timeOutMillisecs)
  224487. {
  224488. const ScopedLock sl (lock);
  224489. if (pimpl == 0)
  224490. {
  224491. pimpl = new Pimpl (name, timeOutMillisecs);
  224492. if (pimpl->handle == 0)
  224493. pimpl = 0;
  224494. }
  224495. else
  224496. {
  224497. pimpl->refCount++;
  224498. }
  224499. return pimpl != 0;
  224500. }
  224501. void InterProcessLock::exit()
  224502. {
  224503. const ScopedLock sl (lock);
  224504. // Trying to release the lock too many times!
  224505. jassert (pimpl != 0);
  224506. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224507. pimpl = 0;
  224508. }
  224509. void JUCE_API juce_threadEntryPoint (void*);
  224510. void* threadEntryProc (void* userData)
  224511. {
  224512. JUCE_AUTORELEASEPOOL
  224513. juce_threadEntryPoint (userData);
  224514. return 0;
  224515. }
  224516. void Thread::launchThread()
  224517. {
  224518. threadHandle_ = 0;
  224519. pthread_t handle = 0;
  224520. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224521. {
  224522. pthread_detach (handle);
  224523. threadHandle_ = (void*) handle;
  224524. threadId_ = (ThreadID) threadHandle_;
  224525. }
  224526. }
  224527. void Thread::closeThreadHandle()
  224528. {
  224529. threadId_ = 0;
  224530. threadHandle_ = 0;
  224531. }
  224532. void Thread::killThread()
  224533. {
  224534. if (threadHandle_ != 0)
  224535. {
  224536. #if JUCE_ANDROID
  224537. jassertfalse; // pthread_cancel not available!
  224538. #else
  224539. pthread_cancel ((pthread_t) threadHandle_);
  224540. #endif
  224541. }
  224542. }
  224543. void Thread::setCurrentThreadName (const String& /*name*/)
  224544. {
  224545. }
  224546. bool Thread::setThreadPriority (void* handle, int priority)
  224547. {
  224548. struct sched_param param;
  224549. int policy;
  224550. priority = jlimit (0, 10, priority);
  224551. if (handle == 0)
  224552. handle = (void*) pthread_self();
  224553. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224554. return false;
  224555. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224556. const int minPriority = sched_get_priority_min (policy);
  224557. const int maxPriority = sched_get_priority_max (policy);
  224558. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224559. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224560. }
  224561. Thread::ThreadID Thread::getCurrentThreadId()
  224562. {
  224563. return (ThreadID) pthread_self();
  224564. }
  224565. void Thread::yield()
  224566. {
  224567. sched_yield();
  224568. }
  224569. /* Remove this macro if you're having problems compiling the cpu affinity
  224570. calls (the API for these has changed about quite a bit in various Linux
  224571. versions, and a lot of distros seem to ship with obsolete versions)
  224572. */
  224573. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224574. #define SUPPORT_AFFINITIES 1
  224575. #endif
  224576. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224577. {
  224578. #if SUPPORT_AFFINITIES
  224579. cpu_set_t affinity;
  224580. CPU_ZERO (&affinity);
  224581. for (int i = 0; i < 32; ++i)
  224582. if ((affinityMask & (1 << i)) != 0)
  224583. CPU_SET (i, &affinity);
  224584. /*
  224585. N.B. If this line causes a compile error, then you've probably not got the latest
  224586. version of glibc installed.
  224587. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224588. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224589. */
  224590. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224591. sched_yield();
  224592. #else
  224593. /* affinities aren't supported because either the appropriate header files weren't found,
  224594. or the SUPPORT_AFFINITIES macro was turned off
  224595. */
  224596. jassertfalse;
  224597. (void) affinityMask;
  224598. #endif
  224599. }
  224600. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224601. /*** Start of inlined file: juce_mac_Files.mm ***/
  224602. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224603. // compiled on its own).
  224604. #if JUCE_INCLUDED_FILE
  224605. /*
  224606. Note that a lot of methods that you'd expect to find in this file actually
  224607. live in juce_posix_SharedCode.h!
  224608. */
  224609. bool File::copyInternal (const File& dest) const
  224610. {
  224611. const ScopedAutoReleasePool pool;
  224612. NSFileManager* fm = [NSFileManager defaultManager];
  224613. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224614. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224615. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224616. toPath: juceStringToNS (dest.getFullPathName())
  224617. error: nil];
  224618. #else
  224619. && [fm copyPath: juceStringToNS (fullPath)
  224620. toPath: juceStringToNS (dest.getFullPathName())
  224621. handler: nil];
  224622. #endif
  224623. }
  224624. void File::findFileSystemRoots (Array<File>& destArray)
  224625. {
  224626. destArray.add (File ("/"));
  224627. }
  224628. namespace FileHelpers
  224629. {
  224630. bool isFileOnDriveType (const File& f, const char* const* types)
  224631. {
  224632. struct statfs buf;
  224633. if (juce_doStatFS (f, buf))
  224634. {
  224635. const String type (buf.f_fstypename);
  224636. while (*types != 0)
  224637. if (type.equalsIgnoreCase (*types++))
  224638. return true;
  224639. }
  224640. return false;
  224641. }
  224642. bool isHiddenFile (const String& path)
  224643. {
  224644. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224645. const ScopedAutoReleasePool pool;
  224646. NSNumber* hidden = nil;
  224647. NSError* err = nil;
  224648. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224649. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224650. && [hidden boolValue];
  224651. #else
  224652. #if JUCE_IOS
  224653. return File (path).getFileName().startsWithChar ('.');
  224654. #else
  224655. FSRef ref;
  224656. LSItemInfoRecord info;
  224657. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224658. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224659. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224660. #endif
  224661. #endif
  224662. }
  224663. #if JUCE_IOS
  224664. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224665. {
  224666. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224667. objectAtIndex: 0]);
  224668. }
  224669. #endif
  224670. bool launchExecutable (const String& pathAndArguments)
  224671. {
  224672. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224673. const int cpid = fork();
  224674. if (cpid == 0)
  224675. {
  224676. // Child process
  224677. if (execve (argv[0], (char**) argv, 0) < 0)
  224678. exit (0);
  224679. }
  224680. else
  224681. {
  224682. if (cpid < 0)
  224683. return false;
  224684. }
  224685. return true;
  224686. }
  224687. }
  224688. bool File::isOnCDRomDrive() const
  224689. {
  224690. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224691. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224692. }
  224693. bool File::isOnHardDisk() const
  224694. {
  224695. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224696. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224697. }
  224698. bool File::isOnRemovableDrive() const
  224699. {
  224700. #if JUCE_IOS
  224701. return false; // xxx is this possible?
  224702. #else
  224703. const ScopedAutoReleasePool pool;
  224704. BOOL removable = false;
  224705. [[NSWorkspace sharedWorkspace]
  224706. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224707. isRemovable: &removable
  224708. isWritable: nil
  224709. isUnmountable: nil
  224710. description: nil
  224711. type: nil];
  224712. return removable;
  224713. #endif
  224714. }
  224715. bool File::isHidden() const
  224716. {
  224717. return FileHelpers::isHiddenFile (getFullPathName());
  224718. }
  224719. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224720. const File File::getSpecialLocation (const SpecialLocationType type)
  224721. {
  224722. const ScopedAutoReleasePool pool;
  224723. String resultPath;
  224724. switch (type)
  224725. {
  224726. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224727. #if JUCE_IOS
  224728. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224729. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224730. case tempDirectory:
  224731. {
  224732. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224733. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224734. tmp.createDirectory();
  224735. return tmp.getFullPathName();
  224736. }
  224737. #else
  224738. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224739. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224740. case tempDirectory:
  224741. {
  224742. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224743. tmp.createDirectory();
  224744. return tmp.getFullPathName();
  224745. }
  224746. #endif
  224747. case userMusicDirectory: resultPath = "~/Music"; break;
  224748. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224749. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224750. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224751. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224752. case invokedExecutableFile:
  224753. if (juce_Argv0 != 0)
  224754. return File (String::fromUTF8 (juce_Argv0));
  224755. // deliberate fall-through...
  224756. case currentExecutableFile:
  224757. return juce_getExecutableFile();
  224758. case currentApplicationFile:
  224759. {
  224760. const File exe (juce_getExecutableFile());
  224761. const File parent (exe.getParentDirectory());
  224762. #if JUCE_IOS
  224763. return parent;
  224764. #else
  224765. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224766. ? parent.getParentDirectory().getParentDirectory()
  224767. : exe;
  224768. #endif
  224769. }
  224770. case hostApplicationPath:
  224771. {
  224772. unsigned int size = 8192;
  224773. HeapBlock<char> buffer;
  224774. buffer.calloc (size + 8);
  224775. _NSGetExecutablePath (buffer.getData(), &size);
  224776. return String::fromUTF8 (buffer, size);
  224777. }
  224778. default:
  224779. jassertfalse; // unknown type?
  224780. break;
  224781. }
  224782. if (resultPath.isNotEmpty())
  224783. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224784. return File::nonexistent;
  224785. }
  224786. const String File::getVersion() const
  224787. {
  224788. const ScopedAutoReleasePool pool;
  224789. String result;
  224790. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224791. if (bundle != 0)
  224792. {
  224793. NSDictionary* info = [bundle infoDictionary];
  224794. if (info != 0)
  224795. {
  224796. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224797. if (name != nil)
  224798. result = nsStringToJuce (name);
  224799. }
  224800. }
  224801. return result;
  224802. }
  224803. const File File::getLinkedTarget() const
  224804. {
  224805. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224806. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224807. #else
  224808. // (the cast here avoids a deprecation warning)
  224809. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224810. #endif
  224811. if (dest != nil)
  224812. return File (nsStringToJuce (dest));
  224813. return *this;
  224814. }
  224815. bool File::moveToTrash() const
  224816. {
  224817. if (! exists())
  224818. return true;
  224819. #if JUCE_IOS
  224820. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224821. #else
  224822. const ScopedAutoReleasePool pool;
  224823. NSString* p = juceStringToNS (getFullPathName());
  224824. return [[NSWorkspace sharedWorkspace]
  224825. performFileOperation: NSWorkspaceRecycleOperation
  224826. source: [p stringByDeletingLastPathComponent]
  224827. destination: @""
  224828. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224829. tag: nil ];
  224830. #endif
  224831. }
  224832. class DirectoryIterator::NativeIterator::Pimpl
  224833. {
  224834. public:
  224835. Pimpl (const File& directory, const String& wildCard_)
  224836. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224837. wildCard (wildCard_),
  224838. enumerator (0)
  224839. {
  224840. const ScopedAutoReleasePool pool;
  224841. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224842. wildcardUTF8 = wildCard.toUTF8();
  224843. }
  224844. ~Pimpl()
  224845. {
  224846. [enumerator release];
  224847. }
  224848. bool next (String& filenameFound,
  224849. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224850. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224851. {
  224852. const ScopedAutoReleasePool pool;
  224853. for (;;)
  224854. {
  224855. NSString* file;
  224856. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224857. return false;
  224858. [enumerator skipDescendents];
  224859. filenameFound = nsStringToJuce (file);
  224860. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224861. continue;
  224862. const String path (parentDir + filenameFound);
  224863. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  224864. if (isHidden != 0)
  224865. *isHidden = FileHelpers::isHiddenFile (path);
  224866. return true;
  224867. }
  224868. }
  224869. private:
  224870. String parentDir, wildCard;
  224871. const char* wildcardUTF8;
  224872. NSDirectoryEnumerator* enumerator;
  224873. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  224874. };
  224875. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224876. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224877. {
  224878. }
  224879. DirectoryIterator::NativeIterator::~NativeIterator()
  224880. {
  224881. }
  224882. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224883. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224884. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224885. {
  224886. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224887. }
  224888. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224889. {
  224890. #if JUCE_IOS
  224891. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224892. #else
  224893. const ScopedAutoReleasePool pool;
  224894. if (parameters.isEmpty())
  224895. {
  224896. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224897. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224898. }
  224899. bool ok = false;
  224900. if (PlatformUtilities::isBundle (fileName))
  224901. {
  224902. NSMutableArray* urls = [NSMutableArray array];
  224903. StringArray docs;
  224904. docs.addTokens (parameters, true);
  224905. for (int i = 0; i < docs.size(); ++i)
  224906. [urls addObject: juceStringToNS (docs[i])];
  224907. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224908. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224909. options: 0
  224910. additionalEventParamDescriptor: nil
  224911. launchIdentifiers: nil];
  224912. }
  224913. else if (File (fileName).exists())
  224914. {
  224915. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  224916. }
  224917. return ok;
  224918. #endif
  224919. }
  224920. void File::revealToUser() const
  224921. {
  224922. #if ! JUCE_IOS
  224923. if (exists())
  224924. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224925. else if (getParentDirectory().exists())
  224926. getParentDirectory().revealToUser();
  224927. #endif
  224928. }
  224929. #if ! JUCE_IOS
  224930. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224931. {
  224932. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  224933. }
  224934. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224935. {
  224936. char path [2048];
  224937. zerostruct (path);
  224938. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224939. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224940. return String::empty;
  224941. }
  224942. #endif
  224943. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224944. {
  224945. const ScopedAutoReleasePool pool;
  224946. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224947. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224948. #else
  224949. // (the cast here avoids a deprecation warning)
  224950. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224951. #endif
  224952. return [fileDict fileHFSTypeCode];
  224953. }
  224954. bool PlatformUtilities::isBundle (const String& filename)
  224955. {
  224956. #if JUCE_IOS
  224957. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224958. #else
  224959. const ScopedAutoReleasePool pool;
  224960. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224961. #endif
  224962. }
  224963. #endif
  224964. /*** End of inlined file: juce_mac_Files.mm ***/
  224965. #if JUCE_IOS
  224966. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  224967. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224968. // compiled on its own).
  224969. #if JUCE_INCLUDED_FILE
  224970. END_JUCE_NAMESPACE
  224971. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224972. {
  224973. }
  224974. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224975. - (void) applicationWillTerminate: (UIApplication*) application;
  224976. @end
  224977. @implementation JuceAppStartupDelegate
  224978. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224979. {
  224980. initialiseJuce_GUI();
  224981. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  224982. exit (0);
  224983. }
  224984. - (void) applicationWillTerminate: (UIApplication*) application
  224985. {
  224986. JUCEApplication::appWillTerminateByForce();
  224987. }
  224988. @end
  224989. BEGIN_JUCE_NAMESPACE
  224990. int juce_iOSMain (int argc, const char* argv[])
  224991. {
  224992. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224993. }
  224994. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224995. {
  224996. pool = [[NSAutoreleasePool alloc] init];
  224997. }
  224998. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224999. {
  225000. [((NSAutoreleasePool*) pool) release];
  225001. }
  225002. void PlatformUtilities::beep()
  225003. {
  225004. //xxx
  225005. //AudioServicesPlaySystemSound ();
  225006. }
  225007. void PlatformUtilities::addItemToDock (const File& file)
  225008. {
  225009. }
  225010. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225011. END_JUCE_NAMESPACE
  225012. @interface JuceAlertBoxDelegate : NSObject
  225013. {
  225014. @public
  225015. bool clickedOk;
  225016. }
  225017. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225018. @end
  225019. @implementation JuceAlertBoxDelegate
  225020. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225021. {
  225022. clickedOk = (buttonIndex == 0);
  225023. alertView.hidden = true;
  225024. }
  225025. @end
  225026. BEGIN_JUCE_NAMESPACE
  225027. // (This function is used directly by other bits of code)
  225028. bool juce_iPhoneShowModalAlert (const String& title,
  225029. const String& bodyText,
  225030. NSString* okButtonText,
  225031. NSString* cancelButtonText)
  225032. {
  225033. const ScopedAutoReleasePool pool;
  225034. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225035. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225036. message: juceStringToNS (bodyText)
  225037. delegate: callback
  225038. cancelButtonTitle: okButtonText
  225039. otherButtonTitles: cancelButtonText, nil];
  225040. [alert retain];
  225041. [alert show];
  225042. while (! alert.hidden && alert.superview != nil)
  225043. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225044. const bool result = callback->clickedOk;
  225045. [alert release];
  225046. [callback release];
  225047. return result;
  225048. }
  225049. bool AlertWindow::showNativeDialogBox (const String& title,
  225050. const String& bodyText,
  225051. bool isOkCancel)
  225052. {
  225053. return juce_iPhoneShowModalAlert (title, bodyText,
  225054. @"OK",
  225055. isOkCancel ? @"Cancel" : nil);
  225056. }
  225057. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225058. {
  225059. jassertfalse; // no such thing on the iphone!
  225060. return false;
  225061. }
  225062. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225063. {
  225064. jassertfalse; // no such thing on the iphone!
  225065. return false;
  225066. }
  225067. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225068. {
  225069. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225070. }
  225071. bool Desktop::isScreenSaverEnabled()
  225072. {
  225073. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225074. }
  225075. #endif
  225076. #endif
  225077. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225078. #else
  225079. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225080. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225081. // compiled on its own).
  225082. #if JUCE_INCLUDED_FILE
  225083. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225084. {
  225085. pool = [[NSAutoreleasePool alloc] init];
  225086. }
  225087. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225088. {
  225089. [((NSAutoreleasePool*) pool) release];
  225090. }
  225091. void PlatformUtilities::beep()
  225092. {
  225093. NSBeep();
  225094. }
  225095. void PlatformUtilities::addItemToDock (const File& file)
  225096. {
  225097. // check that it's not already there...
  225098. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225099. .containsIgnoreCase (file.getFullPathName()))
  225100. {
  225101. 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>"
  225102. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225103. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225104. }
  225105. }
  225106. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225107. bool AlertWindow::showNativeDialogBox (const String& title,
  225108. const String& bodyText,
  225109. bool isOkCancel)
  225110. {
  225111. const ScopedAutoReleasePool pool;
  225112. return NSRunAlertPanel (juceStringToNS (title),
  225113. juceStringToNS (bodyText),
  225114. @"Ok",
  225115. isOkCancel ? @"Cancel" : nil,
  225116. nil) == NSAlertDefaultReturn;
  225117. }
  225118. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225119. {
  225120. if (files.size() == 0)
  225121. return false;
  225122. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225123. if (draggingSource == 0)
  225124. {
  225125. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225126. return false;
  225127. }
  225128. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225129. if (sourceComp == 0)
  225130. {
  225131. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225132. return false;
  225133. }
  225134. const ScopedAutoReleasePool pool;
  225135. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225136. if (view == 0)
  225137. return false;
  225138. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225139. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225140. owner: nil];
  225141. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225142. for (int i = 0; i < files.size(); ++i)
  225143. [filesArray addObject: juceStringToNS (files[i])];
  225144. [pboard setPropertyList: filesArray
  225145. forType: NSFilenamesPboardType];
  225146. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225147. fromView: nil];
  225148. dragPosition.x -= 16;
  225149. dragPosition.y -= 16;
  225150. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225151. at: dragPosition
  225152. offset: NSMakeSize (0, 0)
  225153. event: [[view window] currentEvent]
  225154. pasteboard: pboard
  225155. source: view
  225156. slideBack: YES];
  225157. return true;
  225158. }
  225159. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225160. {
  225161. jassertfalse; // not implemented!
  225162. return false;
  225163. }
  225164. bool Desktop::canUseSemiTransparentWindows() throw()
  225165. {
  225166. return true;
  225167. }
  225168. const Point<int> MouseInputSource::getCurrentMousePosition()
  225169. {
  225170. const ScopedAutoReleasePool pool;
  225171. const NSPoint p ([NSEvent mouseLocation]);
  225172. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225173. }
  225174. void Desktop::setMousePosition (const Point<int>& newPosition)
  225175. {
  225176. // this rubbish needs to be done around the warp call, to avoid causing a
  225177. // bizarre glitch..
  225178. CGAssociateMouseAndMouseCursorPosition (false);
  225179. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225180. CGAssociateMouseAndMouseCursorPosition (true);
  225181. }
  225182. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225183. {
  225184. return upright;
  225185. }
  225186. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225187. class ScreenSaverDefeater : public Timer,
  225188. public DeletedAtShutdown
  225189. {
  225190. public:
  225191. ScreenSaverDefeater()
  225192. {
  225193. startTimer (10000);
  225194. timerCallback();
  225195. }
  225196. ~ScreenSaverDefeater() {}
  225197. void timerCallback()
  225198. {
  225199. if (Process::isForegroundProcess())
  225200. UpdateSystemActivity (UsrActivity);
  225201. }
  225202. };
  225203. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225204. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225205. {
  225206. if (isEnabled)
  225207. deleteAndZero (screenSaverDefeater);
  225208. else if (screenSaverDefeater == 0)
  225209. screenSaverDefeater = new ScreenSaverDefeater();
  225210. }
  225211. bool Desktop::isScreenSaverEnabled()
  225212. {
  225213. return screenSaverDefeater == 0;
  225214. }
  225215. #else
  225216. static IOPMAssertionID screenSaverDisablerID = 0;
  225217. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225218. {
  225219. if (isEnabled)
  225220. {
  225221. if (screenSaverDisablerID != 0)
  225222. {
  225223. IOPMAssertionRelease (screenSaverDisablerID);
  225224. screenSaverDisablerID = 0;
  225225. }
  225226. }
  225227. else
  225228. {
  225229. if (screenSaverDisablerID == 0)
  225230. {
  225231. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225232. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225233. CFSTR ("Juce"), &screenSaverDisablerID);
  225234. #else
  225235. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225236. &screenSaverDisablerID);
  225237. #endif
  225238. }
  225239. }
  225240. }
  225241. bool Desktop::isScreenSaverEnabled()
  225242. {
  225243. return screenSaverDisablerID == 0;
  225244. }
  225245. #endif
  225246. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225247. {
  225248. const ScopedAutoReleasePool pool;
  225249. monitorCoords.clear();
  225250. NSArray* screens = [NSScreen screens];
  225251. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225252. for (unsigned int i = 0; i < [screens count]; ++i)
  225253. {
  225254. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225255. NSRect r = clipToWorkArea ? [s visibleFrame]
  225256. : [s frame];
  225257. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225258. monitorCoords.add (convertToRectInt (r));
  225259. }
  225260. jassert (monitorCoords.size() > 0);
  225261. }
  225262. #endif
  225263. #endif
  225264. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225265. #endif
  225266. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225267. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225268. // compiled on its own).
  225269. #if JUCE_INCLUDED_FILE
  225270. void Logger::outputDebugString (const String& text)
  225271. {
  225272. std::cerr << text << std::endl;
  225273. }
  225274. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225275. {
  225276. static char testResult = 0;
  225277. if (testResult == 0)
  225278. {
  225279. struct kinfo_proc info;
  225280. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225281. size_t sz = sizeof (info);
  225282. sysctl (m, 4, &info, &sz, 0, 0);
  225283. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225284. }
  225285. return testResult > 0;
  225286. }
  225287. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225288. {
  225289. return juce_isRunningUnderDebugger();
  225290. }
  225291. #endif
  225292. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225293. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225294. #if JUCE_IOS
  225295. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225296. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225297. // compiled on its own).
  225298. #if JUCE_INCLUDED_FILE
  225299. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225300. #define SUPPORT_10_4_FONTS 1
  225301. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225302. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225303. #define SUPPORT_ONLY_10_4_FONTS 1
  225304. #endif
  225305. END_JUCE_NAMESPACE
  225306. @interface NSFont (PrivateHack)
  225307. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225308. @end
  225309. BEGIN_JUCE_NAMESPACE
  225310. #endif
  225311. class MacTypeface : public Typeface
  225312. {
  225313. public:
  225314. MacTypeface (const Font& font)
  225315. : Typeface (font.getTypefaceName())
  225316. {
  225317. const ScopedAutoReleasePool pool;
  225318. renderingTransform = CGAffineTransformIdentity;
  225319. bool needsItalicTransform = false;
  225320. #if JUCE_IOS
  225321. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225322. if (font.isItalic() || font.isBold())
  225323. {
  225324. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225325. for (NSString* i in familyFonts)
  225326. {
  225327. const String fn (nsStringToJuce (i));
  225328. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225329. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225330. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225331. || afterDash.containsIgnoreCase ("italic")
  225332. || fn.endsWithIgnoreCase ("oblique")
  225333. || fn.endsWithIgnoreCase ("italic");
  225334. if (probablyBold == font.isBold()
  225335. && probablyItalic == font.isItalic())
  225336. {
  225337. fontName = i;
  225338. needsItalicTransform = false;
  225339. break;
  225340. }
  225341. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225342. {
  225343. fontName = i;
  225344. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225345. }
  225346. }
  225347. if (needsItalicTransform)
  225348. renderingTransform.c = 0.15f;
  225349. }
  225350. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225351. const int ascender = abs (CGFontGetAscent (fontRef));
  225352. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225353. ascent = ascender / totalHeight;
  225354. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225355. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225356. #else
  225357. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225358. if (font.isItalic())
  225359. {
  225360. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225361. toHaveTrait: NSItalicFontMask];
  225362. if (newFont == nsFont)
  225363. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225364. nsFont = newFont;
  225365. }
  225366. if (font.isBold())
  225367. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225368. [nsFont retain];
  225369. ascent = std::abs ((float) [nsFont ascender]);
  225370. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225371. ascent /= totalSize;
  225372. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225373. if (needsItalicTransform)
  225374. {
  225375. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225376. renderingTransform.c = 0.15f;
  225377. }
  225378. #if SUPPORT_ONLY_10_4_FONTS
  225379. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225380. if (atsFont == 0)
  225381. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225382. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225383. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225384. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225385. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225386. #else
  225387. #if SUPPORT_10_4_FONTS
  225388. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225389. {
  225390. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225391. if (atsFont == 0)
  225392. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225393. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225394. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225395. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225396. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225397. }
  225398. else
  225399. #endif
  225400. {
  225401. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225402. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225403. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225404. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225405. }
  225406. #endif
  225407. #endif
  225408. }
  225409. ~MacTypeface()
  225410. {
  225411. #if ! JUCE_IOS
  225412. [nsFont release];
  225413. #endif
  225414. if (fontRef != 0)
  225415. CGFontRelease (fontRef);
  225416. }
  225417. float getAscent() const
  225418. {
  225419. return ascent;
  225420. }
  225421. float getDescent() const
  225422. {
  225423. return 1.0f - ascent;
  225424. }
  225425. float getStringWidth (const String& text)
  225426. {
  225427. if (fontRef == 0 || text.isEmpty())
  225428. return 0;
  225429. const int length = text.length();
  225430. HeapBlock <CGGlyph> glyphs;
  225431. createGlyphsForString (text, length, glyphs);
  225432. float x = 0;
  225433. #if SUPPORT_ONLY_10_4_FONTS
  225434. HeapBlock <NSSize> advances (length);
  225435. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225436. for (int i = 0; i < length; ++i)
  225437. x += advances[i].width;
  225438. #else
  225439. #if SUPPORT_10_4_FONTS
  225440. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225441. {
  225442. HeapBlock <NSSize> advances (length);
  225443. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225444. for (int i = 0; i < length; ++i)
  225445. x += advances[i].width;
  225446. }
  225447. else
  225448. #endif
  225449. {
  225450. HeapBlock <int> advances (length);
  225451. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225452. for (int i = 0; i < length; ++i)
  225453. x += advances[i];
  225454. }
  225455. #endif
  225456. return x * unitsToHeightScaleFactor;
  225457. }
  225458. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225459. {
  225460. xOffsets.add (0);
  225461. if (fontRef == 0 || text.isEmpty())
  225462. return;
  225463. const int length = text.length();
  225464. HeapBlock <CGGlyph> glyphs;
  225465. createGlyphsForString (text, length, glyphs);
  225466. #if SUPPORT_ONLY_10_4_FONTS
  225467. HeapBlock <NSSize> advances (length);
  225468. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225469. int x = 0;
  225470. for (int i = 0; i < length; ++i)
  225471. {
  225472. x += advances[i].width;
  225473. xOffsets.add (x * unitsToHeightScaleFactor);
  225474. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225475. }
  225476. #else
  225477. #if SUPPORT_10_4_FONTS
  225478. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225479. {
  225480. HeapBlock <NSSize> advances (length);
  225481. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225482. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225483. float x = 0;
  225484. for (int i = 0; i < length; ++i)
  225485. {
  225486. x += advances[i].width;
  225487. xOffsets.add (x * unitsToHeightScaleFactor);
  225488. resultGlyphs.add (nsGlyphs[i]);
  225489. }
  225490. }
  225491. else
  225492. #endif
  225493. {
  225494. HeapBlock <int> advances (length);
  225495. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225496. {
  225497. int x = 0;
  225498. for (int i = 0; i < length; ++i)
  225499. {
  225500. x += advances [i];
  225501. xOffsets.add (x * unitsToHeightScaleFactor);
  225502. resultGlyphs.add (glyphs[i]);
  225503. }
  225504. }
  225505. }
  225506. #endif
  225507. }
  225508. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225509. {
  225510. #if JUCE_IOS
  225511. return false;
  225512. #else
  225513. if (nsFont == 0)
  225514. return false;
  225515. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225516. jassert (path.isEmpty());
  225517. const ScopedAutoReleasePool pool;
  225518. NSBezierPath* bez = [NSBezierPath bezierPath];
  225519. [bez moveToPoint: NSMakePoint (0, 0)];
  225520. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225521. inFont: nsFont];
  225522. for (int i = 0; i < [bez elementCount]; ++i)
  225523. {
  225524. NSPoint p[3];
  225525. switch ([bez elementAtIndex: i associatedPoints: p])
  225526. {
  225527. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225528. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225529. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225530. (float) p[1].x, (float) -p[1].y,
  225531. (float) p[2].x, (float) -p[2].y); break;
  225532. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225533. default: jassertfalse; break;
  225534. }
  225535. }
  225536. path.applyTransform (pathTransform);
  225537. return true;
  225538. #endif
  225539. }
  225540. CGFontRef fontRef;
  225541. float fontHeightToCGSizeFactor;
  225542. CGAffineTransform renderingTransform;
  225543. private:
  225544. float ascent, unitsToHeightScaleFactor;
  225545. #if JUCE_IOS
  225546. #else
  225547. NSFont* nsFont;
  225548. AffineTransform pathTransform;
  225549. #endif
  225550. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225551. {
  225552. #if SUPPORT_10_4_FONTS
  225553. #if ! SUPPORT_ONLY_10_4_FONTS
  225554. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225555. #endif
  225556. {
  225557. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225558. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225559. for (int i = 0; i < length; ++i)
  225560. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225561. return;
  225562. }
  225563. #endif
  225564. #if ! SUPPORT_ONLY_10_4_FONTS
  225565. if (charToGlyphMapper == 0)
  225566. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225567. glyphs.malloc (length);
  225568. for (int i = 0; i < length; ++i)
  225569. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225570. #endif
  225571. }
  225572. #if ! SUPPORT_ONLY_10_4_FONTS
  225573. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225574. class CharToGlyphMapper
  225575. {
  225576. public:
  225577. CharToGlyphMapper (CGFontRef fontRef)
  225578. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225579. idRangeOffset (0), glyphIndexes (0)
  225580. {
  225581. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225582. if (cmapTable != 0)
  225583. {
  225584. const int numSubtables = getValue16 (cmapTable, 2);
  225585. for (int i = 0; i < numSubtables; ++i)
  225586. {
  225587. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225588. {
  225589. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225590. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225591. {
  225592. const int length = getValue16 (cmapTable, offset + 2);
  225593. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225594. segCount = segCountX2 / 2;
  225595. const int endCodeOffset = offset + 14;
  225596. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225597. const int idDeltaOffset = startCodeOffset + segCountX2;
  225598. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225599. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225600. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225601. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225602. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225603. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225604. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225605. }
  225606. break;
  225607. }
  225608. }
  225609. CFRelease (cmapTable);
  225610. }
  225611. }
  225612. ~CharToGlyphMapper()
  225613. {
  225614. if (endCode != 0)
  225615. {
  225616. CFRelease (endCode);
  225617. CFRelease (startCode);
  225618. CFRelease (idDelta);
  225619. CFRelease (idRangeOffset);
  225620. CFRelease (glyphIndexes);
  225621. }
  225622. }
  225623. int getGlyphForCharacter (const juce_wchar c) const
  225624. {
  225625. for (int i = 0; i < segCount; ++i)
  225626. {
  225627. if (getValue16 (endCode, i * 2) >= c)
  225628. {
  225629. const int start = getValue16 (startCode, i * 2);
  225630. if (start > c)
  225631. break;
  225632. const int delta = getValue16 (idDelta, i * 2);
  225633. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225634. if (rangeOffset == 0)
  225635. return delta + c;
  225636. else
  225637. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225638. }
  225639. }
  225640. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225641. return jmax (-1, (int) c - 29);
  225642. }
  225643. private:
  225644. int segCount;
  225645. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225646. static uint16 getValue16 (CFDataRef data, const int index)
  225647. {
  225648. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225649. }
  225650. static uint32 getValue32 (CFDataRef data, const int index)
  225651. {
  225652. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225653. }
  225654. };
  225655. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225656. #endif
  225657. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225658. };
  225659. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225660. {
  225661. return new MacTypeface (font);
  225662. }
  225663. const StringArray Font::findAllTypefaceNames()
  225664. {
  225665. StringArray names;
  225666. const ScopedAutoReleasePool pool;
  225667. #if JUCE_IOS
  225668. NSArray* fonts = [UIFont familyNames];
  225669. #else
  225670. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225671. #endif
  225672. for (unsigned int i = 0; i < [fonts count]; ++i)
  225673. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225674. names.sort (true);
  225675. return names;
  225676. }
  225677. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225678. {
  225679. #if JUCE_IOS
  225680. defaultSans = "Helvetica";
  225681. defaultSerif = "Times New Roman";
  225682. defaultFixed = "Courier New";
  225683. #else
  225684. defaultSans = "Lucida Grande";
  225685. defaultSerif = "Times New Roman";
  225686. defaultFixed = "Monaco";
  225687. #endif
  225688. defaultFallback = "Arial Unicode MS";
  225689. }
  225690. #endif
  225691. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225692. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225693. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225694. // compiled on its own).
  225695. #if JUCE_INCLUDED_FILE
  225696. class CoreGraphicsImage : public Image::SharedImage
  225697. {
  225698. public:
  225699. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225700. : Image::SharedImage (format_, width_, height_)
  225701. {
  225702. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225703. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225704. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225705. imageData = imageDataAllocated;
  225706. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225707. : CGColorSpaceCreateDeviceRGB();
  225708. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225709. colourSpace, getCGImageFlags (format_));
  225710. CGColorSpaceRelease (colourSpace);
  225711. }
  225712. ~CoreGraphicsImage()
  225713. {
  225714. CGContextRelease (context);
  225715. }
  225716. Image::ImageType getType() const { return Image::NativeImage; }
  225717. LowLevelGraphicsContext* createLowLevelContext();
  225718. SharedImage* clone()
  225719. {
  225720. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225721. memcpy (im->imageData, imageData, lineStride * height);
  225722. return im;
  225723. }
  225724. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  225725. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  225726. {
  225727. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225728. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225729. {
  225730. return CGBitmapContextCreateImage (nativeImage->context);
  225731. }
  225732. else
  225733. {
  225734. const Image::BitmapData srcData (juceImage, false);
  225735. CGDataProviderRef provider;
  225736. if (mustOutliveSource)
  225737. {
  225738. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  225739. provider = CGDataProviderCreateWithCFData (data);
  225740. CFRelease (data);
  225741. }
  225742. else
  225743. {
  225744. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225745. }
  225746. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225747. 8, srcData.pixelStride * 8, srcData.lineStride,
  225748. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225749. 0, true, kCGRenderingIntentDefault);
  225750. CGDataProviderRelease (provider);
  225751. return imageRef;
  225752. }
  225753. }
  225754. #if JUCE_MAC
  225755. static NSImage* createNSImage (const Image& image)
  225756. {
  225757. const ScopedAutoReleasePool pool;
  225758. NSImage* im = [[NSImage alloc] init];
  225759. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225760. [im lockFocus];
  225761. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225762. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  225763. CGColorSpaceRelease (colourSpace);
  225764. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225765. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225766. CGImageRelease (imageRef);
  225767. [im unlockFocus];
  225768. return im;
  225769. }
  225770. #endif
  225771. CGContextRef context;
  225772. HeapBlock<uint8> imageDataAllocated;
  225773. private:
  225774. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225775. {
  225776. #if JUCE_BIG_ENDIAN
  225777. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225778. #else
  225779. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225780. #endif
  225781. }
  225782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225783. };
  225784. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225785. {
  225786. #if USE_COREGRAPHICS_RENDERING
  225787. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225788. #else
  225789. return createSoftwareImage (format, width, height, clearImage);
  225790. #endif
  225791. }
  225792. class CoreGraphicsContext : public LowLevelGraphicsContext
  225793. {
  225794. public:
  225795. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225796. : context (context_),
  225797. flipHeight (flipHeight_),
  225798. lastClipRectIsValid (false),
  225799. state (new SavedState()),
  225800. numGradientLookupEntries (0)
  225801. {
  225802. CGContextRetain (context);
  225803. CGContextSaveGState(context);
  225804. CGContextSetShouldSmoothFonts (context, true);
  225805. CGContextSetShouldAntialias (context, true);
  225806. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225807. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225808. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225809. gradientCallbacks.version = 0;
  225810. gradientCallbacks.evaluate = gradientCallback;
  225811. gradientCallbacks.releaseInfo = 0;
  225812. setFont (Font());
  225813. }
  225814. ~CoreGraphicsContext()
  225815. {
  225816. CGContextRestoreGState (context);
  225817. CGContextRelease (context);
  225818. CGColorSpaceRelease (rgbColourSpace);
  225819. CGColorSpaceRelease (greyColourSpace);
  225820. }
  225821. bool isVectorDevice() const { return false; }
  225822. void setOrigin (int x, int y)
  225823. {
  225824. CGContextTranslateCTM (context, x, -y);
  225825. if (lastClipRectIsValid)
  225826. lastClipRect.translate (-x, -y);
  225827. }
  225828. void addTransform (const AffineTransform& transform)
  225829. {
  225830. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  225831. .translated (0, flipHeight)
  225832. .followedBy (transform)
  225833. .translated (0, -flipHeight)
  225834. .scaled (1.0f, -1.0f));
  225835. lastClipRectIsValid = false;
  225836. }
  225837. float getScaleFactor()
  225838. {
  225839. CGAffineTransform t = CGContextGetCTM (context);
  225840. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  225841. }
  225842. bool clipToRectangle (const Rectangle<int>& r)
  225843. {
  225844. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225845. if (lastClipRectIsValid)
  225846. {
  225847. // This is actually incorrect, because the actual clip region may be complex, and
  225848. // clipping its bounds to a rect may not be right... But, removing this shortcut
  225849. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  225850. // when calculating the resultant clip bounds, and makes the same mistake!
  225851. lastClipRect = lastClipRect.getIntersection (r);
  225852. return ! lastClipRect.isEmpty();
  225853. }
  225854. return ! isClipEmpty();
  225855. }
  225856. bool clipToRectangleList (const RectangleList& clipRegion)
  225857. {
  225858. if (clipRegion.isEmpty())
  225859. {
  225860. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225861. lastClipRectIsValid = true;
  225862. lastClipRect = Rectangle<int>();
  225863. return false;
  225864. }
  225865. else
  225866. {
  225867. const int numRects = clipRegion.getNumRectangles();
  225868. HeapBlock <CGRect> rects (numRects);
  225869. for (int i = 0; i < numRects; ++i)
  225870. {
  225871. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225872. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225873. }
  225874. CGContextClipToRects (context, rects, numRects);
  225875. lastClipRectIsValid = false;
  225876. return ! isClipEmpty();
  225877. }
  225878. }
  225879. void excludeClipRectangle (const Rectangle<int>& r)
  225880. {
  225881. RectangleList remaining (getClipBounds());
  225882. remaining.subtract (r);
  225883. clipToRectangleList (remaining);
  225884. lastClipRectIsValid = false;
  225885. }
  225886. void clipToPath (const Path& path, const AffineTransform& transform)
  225887. {
  225888. createPath (path, transform);
  225889. CGContextClip (context);
  225890. lastClipRectIsValid = false;
  225891. }
  225892. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225893. {
  225894. if (! transform.isSingularity())
  225895. {
  225896. Image singleChannelImage (sourceImage);
  225897. if (sourceImage.getFormat() != Image::SingleChannel)
  225898. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225899. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  225900. flip();
  225901. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225902. applyTransform (t);
  225903. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225904. CGContextClipToMask (context, r, image);
  225905. applyTransform (t.inverted());
  225906. flip();
  225907. CGImageRelease (image);
  225908. lastClipRectIsValid = false;
  225909. }
  225910. }
  225911. bool clipRegionIntersects (const Rectangle<int>& r)
  225912. {
  225913. return getClipBounds().intersects (r);
  225914. }
  225915. const Rectangle<int> getClipBounds() const
  225916. {
  225917. if (! lastClipRectIsValid)
  225918. {
  225919. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225920. lastClipRectIsValid = true;
  225921. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225922. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225923. roundToInt (bounds.size.width),
  225924. roundToInt (bounds.size.height));
  225925. }
  225926. return lastClipRect;
  225927. }
  225928. bool isClipEmpty() const
  225929. {
  225930. return getClipBounds().isEmpty();
  225931. }
  225932. void saveState()
  225933. {
  225934. CGContextSaveGState (context);
  225935. stateStack.add (new SavedState (*state));
  225936. }
  225937. void restoreState()
  225938. {
  225939. CGContextRestoreGState (context);
  225940. SavedState* const top = stateStack.getLast();
  225941. if (top != 0)
  225942. {
  225943. state = top;
  225944. stateStack.removeLast (1, false);
  225945. lastClipRectIsValid = false;
  225946. }
  225947. else
  225948. {
  225949. jassertfalse; // trying to pop with an empty stack!
  225950. }
  225951. }
  225952. void beginTransparencyLayer (float opacity)
  225953. {
  225954. saveState();
  225955. CGContextSetAlpha (context, opacity);
  225956. CGContextBeginTransparencyLayer (context, 0);
  225957. }
  225958. void endTransparencyLayer()
  225959. {
  225960. CGContextEndTransparencyLayer (context);
  225961. restoreState();
  225962. }
  225963. void setFill (const FillType& fillType)
  225964. {
  225965. state->fillType = fillType;
  225966. if (fillType.isColour())
  225967. {
  225968. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225969. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225970. CGContextSetAlpha (context, 1.0f);
  225971. }
  225972. }
  225973. void setOpacity (float newOpacity)
  225974. {
  225975. state->fillType.setOpacity (newOpacity);
  225976. setFill (state->fillType);
  225977. }
  225978. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225979. {
  225980. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225981. ? kCGInterpolationLow
  225982. : kCGInterpolationHigh);
  225983. }
  225984. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225985. {
  225986. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  225987. }
  225988. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  225989. {
  225990. if (replaceExistingContents)
  225991. {
  225992. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225993. CGContextClearRect (context, cgRect);
  225994. #else
  225995. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225996. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225997. CGContextClearRect (context, cgRect);
  225998. else
  225999. #endif
  226000. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226001. #endif
  226002. fillCGRect (cgRect, false);
  226003. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226004. }
  226005. else
  226006. {
  226007. if (state->fillType.isColour())
  226008. {
  226009. CGContextFillRect (context, cgRect);
  226010. }
  226011. else if (state->fillType.isGradient())
  226012. {
  226013. CGContextSaveGState (context);
  226014. CGContextClipToRect (context, cgRect);
  226015. drawGradient();
  226016. CGContextRestoreGState (context);
  226017. }
  226018. else
  226019. {
  226020. CGContextSaveGState (context);
  226021. CGContextClipToRect (context, cgRect);
  226022. drawImage (state->fillType.image, state->fillType.transform, true);
  226023. CGContextRestoreGState (context);
  226024. }
  226025. }
  226026. }
  226027. void fillPath (const Path& path, const AffineTransform& transform)
  226028. {
  226029. CGContextSaveGState (context);
  226030. if (state->fillType.isColour())
  226031. {
  226032. flip();
  226033. applyTransform (transform);
  226034. createPath (path);
  226035. if (path.isUsingNonZeroWinding())
  226036. CGContextFillPath (context);
  226037. else
  226038. CGContextEOFillPath (context);
  226039. }
  226040. else
  226041. {
  226042. createPath (path, transform);
  226043. if (path.isUsingNonZeroWinding())
  226044. CGContextClip (context);
  226045. else
  226046. CGContextEOClip (context);
  226047. if (state->fillType.isGradient())
  226048. drawGradient();
  226049. else
  226050. drawImage (state->fillType.image, state->fillType.transform, true);
  226051. }
  226052. CGContextRestoreGState (context);
  226053. }
  226054. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226055. {
  226056. const int iw = sourceImage.getWidth();
  226057. const int ih = sourceImage.getHeight();
  226058. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226059. CGContextSaveGState (context);
  226060. CGContextSetAlpha (context, state->fillType.getOpacity());
  226061. flip();
  226062. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226063. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226064. if (fillEntireClipAsTiles)
  226065. {
  226066. #if JUCE_IOS
  226067. CGContextDrawTiledImage (context, imageRect, image);
  226068. #else
  226069. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226070. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226071. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226072. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226073. CGContextDrawTiledImage (context, imageRect, image);
  226074. else
  226075. #endif
  226076. {
  226077. // Fallback to manually doing a tiled fill on 10.4
  226078. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226079. int x = 0, y = 0;
  226080. while (x > clip.origin.x) x -= iw;
  226081. while (y > clip.origin.y) y -= ih;
  226082. const int right = (int) (clip.origin.x + clip.size.width);
  226083. const int bottom = (int) (clip.origin.y + clip.size.height);
  226084. while (y < bottom)
  226085. {
  226086. for (int x2 = x; x2 < right; x2 += iw)
  226087. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226088. y += ih;
  226089. }
  226090. }
  226091. #endif
  226092. }
  226093. else
  226094. {
  226095. CGContextDrawImage (context, imageRect, image);
  226096. }
  226097. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226098. CGContextRestoreGState (context);
  226099. }
  226100. void drawLine (const Line<float>& line)
  226101. {
  226102. if (state->fillType.isColour())
  226103. {
  226104. CGContextSetLineCap (context, kCGLineCapSquare);
  226105. CGContextSetLineWidth (context, 1.0f);
  226106. CGContextSetRGBStrokeColor (context,
  226107. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226108. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226109. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226110. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226111. CGContextStrokeLineSegments (context, cgLine, 1);
  226112. }
  226113. else
  226114. {
  226115. Path p;
  226116. p.addLineSegment (line, 1.0f);
  226117. fillPath (p, AffineTransform::identity);
  226118. }
  226119. }
  226120. void drawVerticalLine (const int x, float top, float bottom)
  226121. {
  226122. if (state->fillType.isColour())
  226123. {
  226124. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226125. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226126. #else
  226127. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226128. // the x co-ord slightly to trick it..
  226129. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226130. #endif
  226131. }
  226132. else
  226133. {
  226134. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226135. }
  226136. }
  226137. void drawHorizontalLine (const int y, float left, float right)
  226138. {
  226139. if (state->fillType.isColour())
  226140. {
  226141. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226142. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226143. #else
  226144. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226145. // the x co-ord slightly to trick it..
  226146. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226147. #endif
  226148. }
  226149. else
  226150. {
  226151. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226152. }
  226153. }
  226154. void setFont (const Font& newFont)
  226155. {
  226156. if (state->font != newFont)
  226157. {
  226158. state->fontRef = 0;
  226159. state->font = newFont;
  226160. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226161. if (mf != 0)
  226162. {
  226163. state->fontRef = mf->fontRef;
  226164. CGContextSetFont (context, state->fontRef);
  226165. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226166. state->fontTransform = mf->renderingTransform;
  226167. state->fontTransform.a *= state->font.getHorizontalScale();
  226168. CGContextSetTextMatrix (context, state->fontTransform);
  226169. }
  226170. }
  226171. }
  226172. const Font getFont()
  226173. {
  226174. return state->font;
  226175. }
  226176. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226177. {
  226178. if (state->fontRef != 0 && state->fillType.isColour())
  226179. {
  226180. if (transform.isOnlyTranslation())
  226181. {
  226182. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226183. CGGlyph g = glyphNumber;
  226184. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226185. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226186. }
  226187. else
  226188. {
  226189. CGContextSaveGState (context);
  226190. flip();
  226191. applyTransform (transform);
  226192. CGAffineTransform t = state->fontTransform;
  226193. t.d = -t.d;
  226194. CGContextSetTextMatrix (context, t);
  226195. CGGlyph g = glyphNumber;
  226196. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226197. CGContextRestoreGState (context);
  226198. }
  226199. }
  226200. else
  226201. {
  226202. Path p;
  226203. Font& f = state->font;
  226204. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226205. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226206. .followedBy (transform));
  226207. }
  226208. }
  226209. private:
  226210. CGContextRef context;
  226211. const CGFloat flipHeight;
  226212. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226213. CGFunctionCallbacks gradientCallbacks;
  226214. mutable Rectangle<int> lastClipRect;
  226215. mutable bool lastClipRectIsValid;
  226216. struct SavedState
  226217. {
  226218. SavedState()
  226219. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226220. {
  226221. }
  226222. SavedState (const SavedState& other)
  226223. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226224. fontTransform (other.fontTransform)
  226225. {
  226226. }
  226227. FillType fillType;
  226228. Font font;
  226229. CGFontRef fontRef;
  226230. CGAffineTransform fontTransform;
  226231. };
  226232. ScopedPointer <SavedState> state;
  226233. OwnedArray <SavedState> stateStack;
  226234. HeapBlock <PixelARGB> gradientLookupTable;
  226235. int numGradientLookupEntries;
  226236. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226237. {
  226238. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226239. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226240. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226241. colour.unpremultiply();
  226242. outData[0] = colour.getRed() / 255.0f;
  226243. outData[1] = colour.getGreen() / 255.0f;
  226244. outData[2] = colour.getBlue() / 255.0f;
  226245. outData[3] = colour.getAlpha() / 255.0f;
  226246. }
  226247. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226248. {
  226249. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226250. CGShadingRef result = 0;
  226251. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226252. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226253. if (gradient.isRadial)
  226254. {
  226255. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226256. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226257. function, true, true);
  226258. }
  226259. else
  226260. {
  226261. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226262. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226263. function, true, true);
  226264. }
  226265. CGFunctionRelease (function);
  226266. return result;
  226267. }
  226268. void drawGradient()
  226269. {
  226270. flip();
  226271. applyTransform (state->fillType.transform);
  226272. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226273. // you draw a gradient with high quality interp enabled).
  226274. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226275. CGContextSetAlpha (context, state->fillType.getOpacity());
  226276. CGContextDrawShading (context, shading);
  226277. CGShadingRelease (shading);
  226278. }
  226279. void createPath (const Path& path) const
  226280. {
  226281. CGContextBeginPath (context);
  226282. Path::Iterator i (path);
  226283. while (i.next())
  226284. {
  226285. switch (i.elementType)
  226286. {
  226287. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226288. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226289. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226290. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226291. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226292. default: jassertfalse; break;
  226293. }
  226294. }
  226295. }
  226296. void createPath (const Path& path, const AffineTransform& transform) const
  226297. {
  226298. CGContextBeginPath (context);
  226299. Path::Iterator i (path);
  226300. while (i.next())
  226301. {
  226302. switch (i.elementType)
  226303. {
  226304. case Path::Iterator::startNewSubPath:
  226305. transform.transformPoint (i.x1, i.y1);
  226306. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226307. break;
  226308. case Path::Iterator::lineTo:
  226309. transform.transformPoint (i.x1, i.y1);
  226310. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226311. break;
  226312. case Path::Iterator::quadraticTo:
  226313. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226314. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226315. break;
  226316. case Path::Iterator::cubicTo:
  226317. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226318. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226319. break;
  226320. case Path::Iterator::closePath:
  226321. CGContextClosePath (context); break;
  226322. default:
  226323. jassertfalse;
  226324. break;
  226325. }
  226326. }
  226327. }
  226328. void flip() const
  226329. {
  226330. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226331. }
  226332. void applyTransform (const AffineTransform& transform) const
  226333. {
  226334. CGAffineTransform t;
  226335. t.a = transform.mat00;
  226336. t.b = transform.mat10;
  226337. t.c = transform.mat01;
  226338. t.d = transform.mat11;
  226339. t.tx = transform.mat02;
  226340. t.ty = transform.mat12;
  226341. CGContextConcatCTM (context, t);
  226342. }
  226343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226344. };
  226345. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226346. {
  226347. return new CoreGraphicsContext (context, height);
  226348. }
  226349. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226350. const Image juce_loadWithCoreImage (InputStream& input)
  226351. {
  226352. MemoryBlock data;
  226353. input.readIntoMemoryBlock (data, -1);
  226354. #if JUCE_IOS
  226355. JUCE_AUTORELEASEPOOL
  226356. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226357. length: data.getSize()
  226358. freeWhenDone: NO]];
  226359. if (image != nil)
  226360. {
  226361. CGImageRef loadedImage = image.CGImage;
  226362. #else
  226363. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226364. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226365. CGDataProviderRelease (provider);
  226366. if (imageSource != 0)
  226367. {
  226368. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226369. CFRelease (imageSource);
  226370. #endif
  226371. if (loadedImage != 0)
  226372. {
  226373. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226374. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226375. && alphaInfo != kCGImageAlphaNoneSkipLast
  226376. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226377. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226378. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226379. hasAlphaChan, Image::NativeImage);
  226380. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226381. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226382. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226383. CGContextFlush (cgImage->context);
  226384. #if ! JUCE_IOS
  226385. CFRelease (loadedImage);
  226386. #endif
  226387. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226388. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226389. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226390. return image;
  226391. }
  226392. }
  226393. return Image::null;
  226394. }
  226395. #endif
  226396. #endif
  226397. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226398. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  226399. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226400. // compiled on its own).
  226401. #if JUCE_INCLUDED_FILE
  226402. class UIViewComponentPeer;
  226403. END_JUCE_NAMESPACE
  226404. #define JuceUIView MakeObjCClassName(JuceUIView)
  226405. @interface JuceUIView : UIView <UITextViewDelegate>
  226406. {
  226407. @public
  226408. UIViewComponentPeer* owner;
  226409. UITextView* hiddenTextView;
  226410. }
  226411. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226412. - (void) dealloc;
  226413. - (void) drawRect: (CGRect) r;
  226414. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226415. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226416. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226417. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226418. - (BOOL) becomeFirstResponder;
  226419. - (BOOL) resignFirstResponder;
  226420. - (BOOL) canBecomeFirstResponder;
  226421. - (void) asyncRepaint: (id) rect;
  226422. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226423. @end
  226424. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226425. @interface JuceUIViewController : UIViewController
  226426. {
  226427. }
  226428. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226429. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226430. @end
  226431. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226432. @interface JuceUIWindow : UIWindow
  226433. {
  226434. @private
  226435. UIViewComponentPeer* owner;
  226436. bool isZooming;
  226437. }
  226438. - (void) setOwner: (UIViewComponentPeer*) owner;
  226439. - (void) becomeKeyWindow;
  226440. @end
  226441. BEGIN_JUCE_NAMESPACE
  226442. class UIViewComponentPeer : public ComponentPeer,
  226443. public FocusChangeListener
  226444. {
  226445. public:
  226446. UIViewComponentPeer (Component* const component,
  226447. const int windowStyleFlags,
  226448. UIView* viewToAttachTo);
  226449. ~UIViewComponentPeer();
  226450. void* getNativeHandle() const;
  226451. void setVisible (bool shouldBeVisible);
  226452. void setTitle (const String& title);
  226453. void setPosition (int x, int y);
  226454. void setSize (int w, int h);
  226455. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226456. const Rectangle<int> getBounds() const;
  226457. const Rectangle<int> getBounds (const bool global) const;
  226458. const Point<int> getScreenPosition() const;
  226459. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226460. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226461. void setAlpha (float newAlpha);
  226462. void setMinimised (bool shouldBeMinimised);
  226463. bool isMinimised() const;
  226464. void setFullScreen (bool shouldBeFullScreen);
  226465. bool isFullScreen() const;
  226466. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226467. const BorderSize<int> getFrameSize() const;
  226468. bool setAlwaysOnTop (bool alwaysOnTop);
  226469. void toFront (bool makeActiveWindow);
  226470. void toBehind (ComponentPeer* other);
  226471. void setIcon (const Image& newIcon);
  226472. virtual void drawRect (CGRect r);
  226473. virtual bool canBecomeKeyWindow();
  226474. virtual bool windowShouldClose();
  226475. virtual void redirectMovedOrResized();
  226476. virtual CGRect constrainRect (CGRect r);
  226477. virtual void viewFocusGain();
  226478. virtual void viewFocusLoss();
  226479. bool isFocused() const;
  226480. void grabFocus();
  226481. void textInputRequired (const Point<int>& position);
  226482. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226483. void updateHiddenTextContent (TextInputTarget* target);
  226484. void globalFocusChanged (Component*);
  226485. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226486. virtual void displayRotated();
  226487. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226488. void repaint (const Rectangle<int>& area);
  226489. void performAnyPendingRepaintsNow();
  226490. UIWindow* window;
  226491. JuceUIView* view;
  226492. JuceUIViewController* controller;
  226493. bool isSharedWindow, fullScreen, insideDrawRect;
  226494. static ModifierKeys currentModifiers;
  226495. static int64 getMouseTime (UIEvent* e)
  226496. {
  226497. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226498. + (int64) ([e timestamp] * 1000.0);
  226499. }
  226500. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226501. {
  226502. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226503. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226504. {
  226505. case UIInterfaceOrientationPortrait:
  226506. return r;
  226507. case UIInterfaceOrientationPortraitUpsideDown:
  226508. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226509. r.getWidth(), r.getHeight());
  226510. case UIInterfaceOrientationLandscapeLeft:
  226511. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226512. r.getHeight(), r.getWidth());
  226513. case UIInterfaceOrientationLandscapeRight:
  226514. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226515. r.getHeight(), r.getWidth());
  226516. default: jassertfalse; // unknown orientation!
  226517. }
  226518. return r;
  226519. }
  226520. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226521. {
  226522. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226523. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226524. {
  226525. case UIInterfaceOrientationPortrait:
  226526. return r;
  226527. case UIInterfaceOrientationPortraitUpsideDown:
  226528. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226529. r.getWidth(), r.getHeight());
  226530. case UIInterfaceOrientationLandscapeLeft:
  226531. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226532. r.getHeight(), r.getWidth());
  226533. case UIInterfaceOrientationLandscapeRight:
  226534. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226535. r.getHeight(), r.getWidth());
  226536. default: jassertfalse; // unknown orientation!
  226537. }
  226538. return r;
  226539. }
  226540. Array <UITouch*> currentTouches;
  226541. private:
  226542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226543. };
  226544. END_JUCE_NAMESPACE
  226545. @implementation JuceUIViewController
  226546. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226547. {
  226548. JuceUIView* juceView = (JuceUIView*) [self view];
  226549. jassert (juceView != 0 && juceView->owner != 0);
  226550. return juceView->owner->shouldRotate (interfaceOrientation);
  226551. }
  226552. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226553. {
  226554. JuceUIView* juceView = (JuceUIView*) [self view];
  226555. jassert (juceView != 0 && juceView->owner != 0);
  226556. juceView->owner->displayRotated();
  226557. }
  226558. @end
  226559. @implementation JuceUIView
  226560. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226561. withFrame: (CGRect) frame
  226562. {
  226563. [super initWithFrame: frame];
  226564. owner = owner_;
  226565. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226566. [self addSubview: hiddenTextView];
  226567. hiddenTextView.delegate = self;
  226568. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226569. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226570. return self;
  226571. }
  226572. - (void) dealloc
  226573. {
  226574. [hiddenTextView removeFromSuperview];
  226575. [hiddenTextView release];
  226576. [super dealloc];
  226577. }
  226578. - (void) drawRect: (CGRect) r
  226579. {
  226580. if (owner != 0)
  226581. owner->drawRect (r);
  226582. }
  226583. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226584. {
  226585. return false;
  226586. }
  226587. ModifierKeys UIViewComponentPeer::currentModifiers;
  226588. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226589. {
  226590. return UIViewComponentPeer::currentModifiers;
  226591. }
  226592. void ModifierKeys::updateCurrentModifiers() throw()
  226593. {
  226594. currentModifiers = UIViewComponentPeer::currentModifiers;
  226595. }
  226596. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226597. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226598. {
  226599. if (owner != 0)
  226600. owner->handleTouches (event, true, false, false);
  226601. }
  226602. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226603. {
  226604. if (owner != 0)
  226605. owner->handleTouches (event, false, false, false);
  226606. }
  226607. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226608. {
  226609. if (owner != 0)
  226610. owner->handleTouches (event, false, true, false);
  226611. }
  226612. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226613. {
  226614. if (owner != 0)
  226615. owner->handleTouches (event, false, true, true);
  226616. [self touchesEnded: touches withEvent: event];
  226617. }
  226618. - (BOOL) becomeFirstResponder
  226619. {
  226620. if (owner != 0)
  226621. owner->viewFocusGain();
  226622. return true;
  226623. }
  226624. - (BOOL) resignFirstResponder
  226625. {
  226626. if (owner != 0)
  226627. owner->viewFocusLoss();
  226628. return true;
  226629. }
  226630. - (BOOL) canBecomeFirstResponder
  226631. {
  226632. return owner != 0 && owner->canBecomeKeyWindow();
  226633. }
  226634. - (void) asyncRepaint: (id) rect
  226635. {
  226636. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226637. [self setNeedsDisplayInRect: *r];
  226638. }
  226639. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226640. {
  226641. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226642. nsStringToJuce (text));
  226643. }
  226644. @end
  226645. @implementation JuceUIWindow
  226646. - (void) setOwner: (UIViewComponentPeer*) owner_
  226647. {
  226648. owner = owner_;
  226649. isZooming = false;
  226650. }
  226651. - (void) becomeKeyWindow
  226652. {
  226653. [super becomeKeyWindow];
  226654. if (owner != 0)
  226655. owner->grabFocus();
  226656. }
  226657. @end
  226658. BEGIN_JUCE_NAMESPACE
  226659. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226660. const int windowStyleFlags,
  226661. UIView* viewToAttachTo)
  226662. : ComponentPeer (component, windowStyleFlags),
  226663. window (0),
  226664. view (0), controller (0),
  226665. isSharedWindow (viewToAttachTo != 0),
  226666. fullScreen (false),
  226667. insideDrawRect (false)
  226668. {
  226669. CGRect r = convertToCGRect (component->getLocalBounds());
  226670. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226671. if (isSharedWindow)
  226672. {
  226673. window = [viewToAttachTo window];
  226674. [viewToAttachTo addSubview: view];
  226675. setVisible (component->isVisible());
  226676. }
  226677. else
  226678. {
  226679. controller = [[JuceUIViewController alloc] init];
  226680. controller.view = view;
  226681. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226682. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226683. window = [[JuceUIWindow alloc] init];
  226684. window.frame = r;
  226685. window.opaque = component->isOpaque();
  226686. view.opaque = component->isOpaque();
  226687. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226688. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226689. [((JuceUIWindow*) window) setOwner: this];
  226690. if (component->isAlwaysOnTop())
  226691. window.windowLevel = UIWindowLevelAlert;
  226692. [window addSubview: view];
  226693. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226694. view.hidden = ! component->isVisible();
  226695. window.hidden = ! component->isVisible();
  226696. view.multipleTouchEnabled = YES;
  226697. }
  226698. setTitle (component->getName());
  226699. Desktop::getInstance().addFocusChangeListener (this);
  226700. }
  226701. UIViewComponentPeer::~UIViewComponentPeer()
  226702. {
  226703. Desktop::getInstance().removeFocusChangeListener (this);
  226704. view->owner = 0;
  226705. [view removeFromSuperview];
  226706. [view release];
  226707. [controller release];
  226708. if (! isSharedWindow)
  226709. {
  226710. [((JuceUIWindow*) window) setOwner: 0];
  226711. [window release];
  226712. }
  226713. }
  226714. void* UIViewComponentPeer::getNativeHandle() const
  226715. {
  226716. return view;
  226717. }
  226718. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226719. {
  226720. view.hidden = ! shouldBeVisible;
  226721. if (! isSharedWindow)
  226722. window.hidden = ! shouldBeVisible;
  226723. }
  226724. void UIViewComponentPeer::setTitle (const String& title)
  226725. {
  226726. // xxx is this possible?
  226727. }
  226728. void UIViewComponentPeer::setPosition (int x, int y)
  226729. {
  226730. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226731. }
  226732. void UIViewComponentPeer::setSize (int w, int h)
  226733. {
  226734. setBounds (component->getX(), component->getY(), w, h, false);
  226735. }
  226736. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226737. {
  226738. fullScreen = isNowFullScreen;
  226739. w = jmax (0, w);
  226740. h = jmax (0, h);
  226741. if (isSharedWindow)
  226742. {
  226743. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226744. if ([view frame].size.width != r.size.width
  226745. || [view frame].size.height != r.size.height)
  226746. [view setNeedsDisplay];
  226747. view.frame = r;
  226748. }
  226749. else
  226750. {
  226751. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226752. window.frame = convertToCGRect (bounds);
  226753. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226754. handleMovedOrResized();
  226755. }
  226756. }
  226757. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226758. {
  226759. CGRect r = [view frame];
  226760. if (global && [view window] != 0)
  226761. {
  226762. r = [view convertRect: r toView: nil];
  226763. CGRect wr = [[view window] frame];
  226764. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226765. r.origin.x = windowBounds.getX();
  226766. r.origin.y = windowBounds.getY();
  226767. }
  226768. return convertToRectInt (r);
  226769. }
  226770. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226771. {
  226772. return getBounds (! isSharedWindow);
  226773. }
  226774. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226775. {
  226776. return getBounds (true).getPosition();
  226777. }
  226778. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226779. {
  226780. return relativePosition + getScreenPosition();
  226781. }
  226782. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226783. {
  226784. return screenPosition - getScreenPosition();
  226785. }
  226786. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226787. {
  226788. if (constrainer != 0)
  226789. {
  226790. CGRect current = [window frame];
  226791. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226792. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226793. Rectangle<int> pos (convertToRectInt (r));
  226794. Rectangle<int> original (convertToRectInt (current));
  226795. constrainer->checkBounds (pos, original,
  226796. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226797. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226798. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226799. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226800. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226801. r.origin.x = pos.getX();
  226802. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226803. r.size.width = pos.getWidth();
  226804. r.size.height = pos.getHeight();
  226805. }
  226806. return r;
  226807. }
  226808. void UIViewComponentPeer::setAlpha (float newAlpha)
  226809. {
  226810. [[view window] setAlpha: (CGFloat) newAlpha];
  226811. }
  226812. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226813. {
  226814. }
  226815. bool UIViewComponentPeer::isMinimised() const
  226816. {
  226817. return false;
  226818. }
  226819. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226820. {
  226821. if (! isSharedWindow)
  226822. {
  226823. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  226824. : lastNonFullscreenBounds);
  226825. if ((! shouldBeFullScreen) && r.isEmpty())
  226826. r = getBounds();
  226827. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226828. if (! r.isEmpty())
  226829. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226830. component->repaint();
  226831. }
  226832. }
  226833. bool UIViewComponentPeer::isFullScreen() const
  226834. {
  226835. return fullScreen;
  226836. }
  226837. namespace
  226838. {
  226839. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  226840. {
  226841. switch (interfaceOrientation)
  226842. {
  226843. case UIInterfaceOrientationPortrait: return Desktop::upright;
  226844. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  226845. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  226846. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  226847. default: jassertfalse; // unknown orientation!
  226848. }
  226849. return Desktop::upright;
  226850. }
  226851. }
  226852. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  226853. {
  226854. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  226855. }
  226856. void UIViewComponentPeer::displayRotated()
  226857. {
  226858. const Rectangle<int> oldArea (component->getBounds());
  226859. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  226860. Desktop::getInstance().refreshMonitorSizes();
  226861. if (fullScreen)
  226862. {
  226863. fullScreen = false;
  226864. setFullScreen (true);
  226865. }
  226866. else
  226867. {
  226868. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  226869. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  226870. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  226871. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  226872. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  226873. setBounds ((int) (l * newDesktop.getWidth()),
  226874. (int) (t * newDesktop.getHeight()),
  226875. (int) ((r - l) * newDesktop.getWidth()),
  226876. (int) ((b - t) * newDesktop.getHeight()),
  226877. false);
  226878. }
  226879. }
  226880. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226881. {
  226882. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  226883. && isPositiveAndBelow (position.getY(), component->getHeight())))
  226884. return false;
  226885. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  226886. withEvent: nil];
  226887. if (trueIfInAChildWindow)
  226888. return v != nil;
  226889. return v == view;
  226890. }
  226891. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  226892. {
  226893. return BorderSize<int>();
  226894. }
  226895. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226896. {
  226897. if (! isSharedWindow)
  226898. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226899. return true;
  226900. }
  226901. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226902. {
  226903. if (isSharedWindow)
  226904. [[view superview] bringSubviewToFront: view];
  226905. if (window != 0 && component->isVisible())
  226906. [window makeKeyAndVisible];
  226907. }
  226908. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226909. {
  226910. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226911. jassert (otherPeer != 0); // wrong type of window?
  226912. if (otherPeer != 0)
  226913. {
  226914. if (isSharedWindow)
  226915. {
  226916. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226917. }
  226918. else
  226919. {
  226920. jassertfalse; // don't know how to do this
  226921. }
  226922. }
  226923. }
  226924. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226925. {
  226926. // to do..
  226927. }
  226928. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226929. {
  226930. NSArray* touches = [[event touchesForView: view] allObjects];
  226931. for (unsigned int i = 0; i < [touches count]; ++i)
  226932. {
  226933. UITouch* touch = [touches objectAtIndex: i];
  226934. CGPoint p = [touch locationInView: view];
  226935. const Point<int> pos ((int) p.x, (int) p.y);
  226936. juce_lastMousePos = pos + getScreenPosition();
  226937. const int64 time = getMouseTime (event);
  226938. int touchIndex = currentTouches.indexOf (touch);
  226939. if (touchIndex < 0)
  226940. {
  226941. touchIndex = currentTouches.size();
  226942. currentTouches.add (touch);
  226943. }
  226944. if (isDown)
  226945. {
  226946. currentModifiers = currentModifiers.withoutMouseButtons();
  226947. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226948. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226949. }
  226950. else if (isUp)
  226951. {
  226952. currentModifiers = currentModifiers.withoutMouseButtons();
  226953. currentTouches.remove (touchIndex);
  226954. }
  226955. if (isCancel)
  226956. currentTouches.clear();
  226957. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226958. }
  226959. }
  226960. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226961. void UIViewComponentPeer::viewFocusGain()
  226962. {
  226963. if (currentlyFocusedPeer != this)
  226964. {
  226965. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226966. currentlyFocusedPeer->handleFocusLoss();
  226967. currentlyFocusedPeer = this;
  226968. handleFocusGain();
  226969. }
  226970. }
  226971. void UIViewComponentPeer::viewFocusLoss()
  226972. {
  226973. if (currentlyFocusedPeer == this)
  226974. {
  226975. currentlyFocusedPeer = 0;
  226976. handleFocusLoss();
  226977. }
  226978. }
  226979. void juce_HandleProcessFocusChange()
  226980. {
  226981. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226982. {
  226983. if (Process::isForegroundProcess())
  226984. {
  226985. currentlyFocusedPeer->handleFocusGain();
  226986. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  226987. }
  226988. else
  226989. {
  226990. currentlyFocusedPeer->handleFocusLoss();
  226991. // turn kiosk mode off if we lose focus..
  226992. Desktop::getInstance().setKioskModeComponent (0);
  226993. }
  226994. }
  226995. }
  226996. bool UIViewComponentPeer::isFocused() const
  226997. {
  226998. return isSharedWindow ? this == currentlyFocusedPeer
  226999. : (window != 0 && [window isKeyWindow]);
  227000. }
  227001. void UIViewComponentPeer::grabFocus()
  227002. {
  227003. if (window != 0)
  227004. {
  227005. [window makeKeyWindow];
  227006. viewFocusGain();
  227007. }
  227008. }
  227009. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227010. {
  227011. }
  227012. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227013. {
  227014. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227015. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227016. }
  227017. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227018. {
  227019. TextInputTarget* const target = findCurrentTextInputTarget();
  227020. if (target != 0)
  227021. {
  227022. const Range<int> currentSelection (target->getHighlightedRegion());
  227023. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227024. if (currentSelection.isEmpty())
  227025. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227026. target->insertTextAtCaret (text);
  227027. updateHiddenTextContent (target);
  227028. }
  227029. return NO;
  227030. }
  227031. void UIViewComponentPeer::globalFocusChanged (Component*)
  227032. {
  227033. TextInputTarget* const target = findCurrentTextInputTarget();
  227034. if (target != 0)
  227035. {
  227036. Component* comp = dynamic_cast<Component*> (target);
  227037. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227038. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227039. updateHiddenTextContent (target);
  227040. [view->hiddenTextView becomeFirstResponder];
  227041. }
  227042. else
  227043. {
  227044. [view->hiddenTextView resignFirstResponder];
  227045. }
  227046. }
  227047. void UIViewComponentPeer::drawRect (CGRect r)
  227048. {
  227049. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227050. return;
  227051. CGContextRef cg = UIGraphicsGetCurrentContext();
  227052. if (! component->isOpaque())
  227053. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227054. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227055. CoreGraphicsContext g (cg, view.bounds.size.height);
  227056. insideDrawRect = true;
  227057. handlePaint (g);
  227058. insideDrawRect = false;
  227059. }
  227060. bool UIViewComponentPeer::canBecomeKeyWindow()
  227061. {
  227062. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227063. }
  227064. bool UIViewComponentPeer::windowShouldClose()
  227065. {
  227066. if (! isValidPeer (this))
  227067. return YES;
  227068. handleUserClosingWindow();
  227069. return NO;
  227070. }
  227071. void UIViewComponentPeer::redirectMovedOrResized()
  227072. {
  227073. handleMovedOrResized();
  227074. }
  227075. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227076. {
  227077. }
  227078. class AsyncRepaintMessage : public CallbackMessage
  227079. {
  227080. public:
  227081. UIViewComponentPeer* const peer;
  227082. const Rectangle<int> rect;
  227083. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227084. : peer (peer_), rect (rect_)
  227085. {
  227086. }
  227087. void messageCallback()
  227088. {
  227089. if (ComponentPeer::isValidPeer (peer))
  227090. peer->repaint (rect);
  227091. }
  227092. };
  227093. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227094. {
  227095. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227096. {
  227097. (new AsyncRepaintMessage (this, area))->post();
  227098. }
  227099. else
  227100. {
  227101. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227102. }
  227103. }
  227104. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227105. {
  227106. }
  227107. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227108. {
  227109. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227110. }
  227111. const Image juce_createIconForFile (const File& file)
  227112. {
  227113. return Image::null;
  227114. }
  227115. void Desktop::createMouseInputSources()
  227116. {
  227117. for (int i = 0; i < 10; ++i)
  227118. mouseSources.add (new MouseInputSource (i, false));
  227119. }
  227120. bool Desktop::canUseSemiTransparentWindows() throw()
  227121. {
  227122. return true;
  227123. }
  227124. const Point<int> MouseInputSource::getCurrentMousePosition()
  227125. {
  227126. return juce_lastMousePos;
  227127. }
  227128. void Desktop::setMousePosition (const Point<int>&)
  227129. {
  227130. }
  227131. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227132. {
  227133. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227134. }
  227135. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227136. {
  227137. const ScopedAutoReleasePool pool;
  227138. monitorCoords.clear();
  227139. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227140. : [[UIScreen mainScreen] bounds];
  227141. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227142. }
  227143. const int KeyPress::spaceKey = ' ';
  227144. const int KeyPress::returnKey = 0x0d;
  227145. const int KeyPress::escapeKey = 0x1b;
  227146. const int KeyPress::backspaceKey = 0x7f;
  227147. const int KeyPress::leftKey = 0x1000;
  227148. const int KeyPress::rightKey = 0x1001;
  227149. const int KeyPress::upKey = 0x1002;
  227150. const int KeyPress::downKey = 0x1003;
  227151. const int KeyPress::pageUpKey = 0x1004;
  227152. const int KeyPress::pageDownKey = 0x1005;
  227153. const int KeyPress::endKey = 0x1006;
  227154. const int KeyPress::homeKey = 0x1007;
  227155. const int KeyPress::deleteKey = 0x1008;
  227156. const int KeyPress::insertKey = -1;
  227157. const int KeyPress::tabKey = 9;
  227158. const int KeyPress::F1Key = 0x2001;
  227159. const int KeyPress::F2Key = 0x2002;
  227160. const int KeyPress::F3Key = 0x2003;
  227161. const int KeyPress::F4Key = 0x2004;
  227162. const int KeyPress::F5Key = 0x2005;
  227163. const int KeyPress::F6Key = 0x2006;
  227164. const int KeyPress::F7Key = 0x2007;
  227165. const int KeyPress::F8Key = 0x2008;
  227166. const int KeyPress::F9Key = 0x2009;
  227167. const int KeyPress::F10Key = 0x200a;
  227168. const int KeyPress::F11Key = 0x200b;
  227169. const int KeyPress::F12Key = 0x200c;
  227170. const int KeyPress::F13Key = 0x200d;
  227171. const int KeyPress::F14Key = 0x200e;
  227172. const int KeyPress::F15Key = 0x200f;
  227173. const int KeyPress::F16Key = 0x2010;
  227174. const int KeyPress::numberPad0 = 0x30020;
  227175. const int KeyPress::numberPad1 = 0x30021;
  227176. const int KeyPress::numberPad2 = 0x30022;
  227177. const int KeyPress::numberPad3 = 0x30023;
  227178. const int KeyPress::numberPad4 = 0x30024;
  227179. const int KeyPress::numberPad5 = 0x30025;
  227180. const int KeyPress::numberPad6 = 0x30026;
  227181. const int KeyPress::numberPad7 = 0x30027;
  227182. const int KeyPress::numberPad8 = 0x30028;
  227183. const int KeyPress::numberPad9 = 0x30029;
  227184. const int KeyPress::numberPadAdd = 0x3002a;
  227185. const int KeyPress::numberPadSubtract = 0x3002b;
  227186. const int KeyPress::numberPadMultiply = 0x3002c;
  227187. const int KeyPress::numberPadDivide = 0x3002d;
  227188. const int KeyPress::numberPadSeparator = 0x3002e;
  227189. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227190. const int KeyPress::numberPadEquals = 0x30030;
  227191. const int KeyPress::numberPadDelete = 0x30031;
  227192. const int KeyPress::playKey = 0x30000;
  227193. const int KeyPress::stopKey = 0x30001;
  227194. const int KeyPress::fastForwardKey = 0x30002;
  227195. const int KeyPress::rewindKey = 0x30003;
  227196. #endif
  227197. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227198. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227199. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227200. // compiled on its own).
  227201. #if JUCE_INCLUDED_FILE
  227202. struct CallbackMessagePayload
  227203. {
  227204. MessageCallbackFunction* function;
  227205. void* parameter;
  227206. void* volatile result;
  227207. bool volatile hasBeenExecuted;
  227208. };
  227209. END_JUCE_NAMESPACE
  227210. @interface JuceCustomMessageHandler : NSObject
  227211. {
  227212. }
  227213. - (void) performCallback: (id) info;
  227214. @end
  227215. @implementation JuceCustomMessageHandler
  227216. - (void) performCallback: (id) info
  227217. {
  227218. if ([info isKindOfClass: [NSData class]])
  227219. {
  227220. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227221. if (pl != 0)
  227222. {
  227223. pl->result = (*pl->function) (pl->parameter);
  227224. pl->hasBeenExecuted = true;
  227225. }
  227226. }
  227227. else
  227228. {
  227229. jassertfalse; // should never get here!
  227230. }
  227231. }
  227232. @end
  227233. BEGIN_JUCE_NAMESPACE
  227234. void MessageManager::runDispatchLoop()
  227235. {
  227236. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227237. runDispatchLoopUntil (-1);
  227238. }
  227239. void MessageManager::stopDispatchLoop()
  227240. {
  227241. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227242. exit (0); // iPhone apps get no mercy..
  227243. }
  227244. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227245. {
  227246. const ScopedAutoReleasePool pool;
  227247. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227248. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227249. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227250. while (! quitMessagePosted)
  227251. {
  227252. const ScopedAutoReleasePool pool;
  227253. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227254. beforeDate: endDate];
  227255. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227256. break;
  227257. }
  227258. return ! quitMessagePosted;
  227259. }
  227260. struct MessageDispatchSystem
  227261. {
  227262. MessageDispatchSystem()
  227263. : juceCustomMessageHandler (0)
  227264. {
  227265. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227266. }
  227267. ~MessageDispatchSystem()
  227268. {
  227269. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227270. [juceCustomMessageHandler release];
  227271. }
  227272. JuceCustomMessageHandler* juceCustomMessageHandler;
  227273. MessageQueue messageQueue;
  227274. };
  227275. static MessageDispatchSystem* dispatcher = 0;
  227276. void MessageManager::doPlatformSpecificInitialisation()
  227277. {
  227278. if (dispatcher == 0)
  227279. dispatcher = new MessageDispatchSystem();
  227280. }
  227281. void MessageManager::doPlatformSpecificShutdown()
  227282. {
  227283. deleteAndZero (dispatcher);
  227284. }
  227285. bool juce_postMessageToSystemQueue (Message* message)
  227286. {
  227287. if (dispatcher != 0)
  227288. dispatcher->messageQueue.post (message);
  227289. return true;
  227290. }
  227291. void MessageManager::broadcastMessage (const String& value)
  227292. {
  227293. }
  227294. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227295. {
  227296. if (isThisTheMessageThread())
  227297. {
  227298. return (*callback) (data);
  227299. }
  227300. else
  227301. {
  227302. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227303. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227304. // deadlock because the message manager is blocked from running, so can never
  227305. // call your function..
  227306. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227307. const ScopedAutoReleasePool pool;
  227308. CallbackMessagePayload cmp;
  227309. cmp.function = callback;
  227310. cmp.parameter = data;
  227311. cmp.result = 0;
  227312. cmp.hasBeenExecuted = false;
  227313. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227314. withObject: [NSData dataWithBytesNoCopy: &cmp
  227315. length: sizeof (cmp)
  227316. freeWhenDone: NO]
  227317. waitUntilDone: YES];
  227318. return cmp.result;
  227319. }
  227320. }
  227321. #endif
  227322. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227323. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227324. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227325. // compiled on its own).
  227326. #if JUCE_INCLUDED_FILE
  227327. #if JUCE_MAC
  227328. END_JUCE_NAMESPACE
  227329. using namespace JUCE_NAMESPACE;
  227330. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227331. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227332. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227333. #else
  227334. @interface JuceFileChooserDelegate : NSObject
  227335. #endif
  227336. {
  227337. StringArray* filters;
  227338. }
  227339. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227340. - (void) dealloc;
  227341. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227342. @end
  227343. @implementation JuceFileChooserDelegate
  227344. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227345. {
  227346. [super init];
  227347. filters = filters_;
  227348. return self;
  227349. }
  227350. - (void) dealloc
  227351. {
  227352. delete filters;
  227353. [super dealloc];
  227354. }
  227355. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227356. {
  227357. (void) sender;
  227358. const File f (nsStringToJuce (filename));
  227359. for (int i = filters->size(); --i >= 0;)
  227360. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227361. return true;
  227362. return f.isDirectory();
  227363. }
  227364. @end
  227365. BEGIN_JUCE_NAMESPACE
  227366. void FileChooser::showPlatformDialog (Array<File>& results,
  227367. const String& title,
  227368. const File& currentFileOrDirectory,
  227369. const String& filter,
  227370. bool selectsDirectory,
  227371. bool selectsFiles,
  227372. bool isSaveDialogue,
  227373. bool /*warnAboutOverwritingExistingFiles*/,
  227374. bool selectMultipleFiles,
  227375. FilePreviewComponent* /*extraInfoComponent*/)
  227376. {
  227377. const ScopedAutoReleasePool pool;
  227378. StringArray* filters = new StringArray();
  227379. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227380. filters->trim();
  227381. filters->removeEmptyStrings();
  227382. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227383. [delegate autorelease];
  227384. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227385. : [NSOpenPanel openPanel];
  227386. [panel setTitle: juceStringToNS (title)];
  227387. if (! isSaveDialogue)
  227388. {
  227389. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227390. [openPanel setCanChooseDirectories: selectsDirectory];
  227391. [openPanel setCanChooseFiles: selectsFiles];
  227392. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227393. }
  227394. [panel setDelegate: delegate];
  227395. if (isSaveDialogue || selectsDirectory)
  227396. [panel setCanCreateDirectories: YES];
  227397. String directory, filename;
  227398. if (currentFileOrDirectory.isDirectory())
  227399. {
  227400. directory = currentFileOrDirectory.getFullPathName();
  227401. }
  227402. else
  227403. {
  227404. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227405. filename = currentFileOrDirectory.getFileName();
  227406. }
  227407. if ([panel runModalForDirectory: juceStringToNS (directory)
  227408. file: juceStringToNS (filename)]
  227409. == NSOKButton)
  227410. {
  227411. if (isSaveDialogue)
  227412. {
  227413. results.add (File (nsStringToJuce ([panel filename])));
  227414. }
  227415. else
  227416. {
  227417. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227418. NSArray* urls = [openPanel filenames];
  227419. for (unsigned int i = 0; i < [urls count]; ++i)
  227420. {
  227421. NSString* f = [urls objectAtIndex: i];
  227422. results.add (File (nsStringToJuce (f)));
  227423. }
  227424. }
  227425. }
  227426. [panel setDelegate: nil];
  227427. }
  227428. #else
  227429. void FileChooser::showPlatformDialog (Array<File>& results,
  227430. const String& title,
  227431. const File& currentFileOrDirectory,
  227432. const String& filter,
  227433. bool selectsDirectory,
  227434. bool selectsFiles,
  227435. bool isSaveDialogue,
  227436. bool warnAboutOverwritingExistingFiles,
  227437. bool selectMultipleFiles,
  227438. FilePreviewComponent* extraInfoComponent)
  227439. {
  227440. const ScopedAutoReleasePool pool;
  227441. jassertfalse; //xxx to do
  227442. }
  227443. #endif
  227444. #endif
  227445. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227446. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227447. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227448. // compiled on its own).
  227449. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227450. #if JUCE_MAC
  227451. END_JUCE_NAMESPACE
  227452. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227453. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227454. {
  227455. CriticalSection* contextLock;
  227456. bool needsUpdate;
  227457. }
  227458. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227459. - (bool) makeActive;
  227460. - (void) makeInactive;
  227461. - (void) reshape;
  227462. @end
  227463. @implementation ThreadSafeNSOpenGLView
  227464. - (id) initWithFrame: (NSRect) frameRect
  227465. pixelFormat: (NSOpenGLPixelFormat*) format
  227466. {
  227467. contextLock = new CriticalSection();
  227468. self = [super initWithFrame: frameRect pixelFormat: format];
  227469. if (self != nil)
  227470. [[NSNotificationCenter defaultCenter] addObserver: self
  227471. selector: @selector (_surfaceNeedsUpdate:)
  227472. name: NSViewGlobalFrameDidChangeNotification
  227473. object: self];
  227474. return self;
  227475. }
  227476. - (void) dealloc
  227477. {
  227478. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227479. delete contextLock;
  227480. [super dealloc];
  227481. }
  227482. - (bool) makeActive
  227483. {
  227484. const ScopedLock sl (*contextLock);
  227485. if ([self openGLContext] == 0)
  227486. return false;
  227487. [[self openGLContext] makeCurrentContext];
  227488. if (needsUpdate)
  227489. {
  227490. [super update];
  227491. needsUpdate = false;
  227492. }
  227493. return true;
  227494. }
  227495. - (void) makeInactive
  227496. {
  227497. const ScopedLock sl (*contextLock);
  227498. [NSOpenGLContext clearCurrentContext];
  227499. }
  227500. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227501. {
  227502. (void) notification;
  227503. const ScopedLock sl (*contextLock);
  227504. needsUpdate = true;
  227505. }
  227506. - (void) update
  227507. {
  227508. const ScopedLock sl (*contextLock);
  227509. needsUpdate = true;
  227510. }
  227511. - (void) reshape
  227512. {
  227513. const ScopedLock sl (*contextLock);
  227514. needsUpdate = true;
  227515. }
  227516. @end
  227517. BEGIN_JUCE_NAMESPACE
  227518. class WindowedGLContext : public OpenGLContext
  227519. {
  227520. public:
  227521. WindowedGLContext (Component& component,
  227522. const OpenGLPixelFormat& pixelFormat_,
  227523. NSOpenGLContext* sharedContext)
  227524. : renderContext (0),
  227525. pixelFormat (pixelFormat_)
  227526. {
  227527. NSOpenGLPixelFormatAttribute attribs [64];
  227528. int n = 0;
  227529. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227530. attribs[n++] = NSOpenGLPFAAccelerated;
  227531. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227532. attribs[n++] = NSOpenGLPFAColorSize;
  227533. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227534. pixelFormat.greenBits,
  227535. pixelFormat.blueBits);
  227536. attribs[n++] = NSOpenGLPFAAlphaSize;
  227537. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227538. attribs[n++] = NSOpenGLPFADepthSize;
  227539. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227540. attribs[n++] = NSOpenGLPFAStencilSize;
  227541. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227542. attribs[n++] = NSOpenGLPFAAccumSize;
  227543. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227544. pixelFormat.accumulationBufferGreenBits,
  227545. pixelFormat.accumulationBufferBlueBits,
  227546. pixelFormat.accumulationBufferAlphaBits);
  227547. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227548. attribs[n++] = NSOpenGLPFASampleBuffers;
  227549. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227550. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227551. attribs[n++] = NSOpenGLPFANoRecovery;
  227552. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227553. NSOpenGLPixelFormat* format
  227554. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227555. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227556. pixelFormat: format];
  227557. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227558. shareContext: sharedContext] autorelease];
  227559. const GLint swapInterval = 1;
  227560. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227561. [view setOpenGLContext: renderContext];
  227562. [format release];
  227563. viewHolder = new NSViewComponentInternal (view, component);
  227564. }
  227565. ~WindowedGLContext()
  227566. {
  227567. deleteContext();
  227568. viewHolder = 0;
  227569. }
  227570. void deleteContext()
  227571. {
  227572. makeInactive();
  227573. [renderContext clearDrawable];
  227574. [renderContext setView: nil];
  227575. [view setOpenGLContext: nil];
  227576. renderContext = nil;
  227577. }
  227578. bool makeActive() const throw()
  227579. {
  227580. jassert (renderContext != 0);
  227581. if ([renderContext view] != view)
  227582. [renderContext setView: view];
  227583. [view makeActive];
  227584. return isActive();
  227585. }
  227586. bool makeInactive() const throw()
  227587. {
  227588. [view makeInactive];
  227589. return true;
  227590. }
  227591. bool isActive() const throw()
  227592. {
  227593. return [NSOpenGLContext currentContext] == renderContext;
  227594. }
  227595. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227596. void* getRawContext() const throw() { return renderContext; }
  227597. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  227598. {
  227599. }
  227600. void swapBuffers()
  227601. {
  227602. [renderContext flushBuffer];
  227603. }
  227604. bool setSwapInterval (const int numFramesPerSwap)
  227605. {
  227606. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227607. forParameter: NSOpenGLCPSwapInterval];
  227608. return true;
  227609. }
  227610. int getSwapInterval() const
  227611. {
  227612. GLint numFrames = 0;
  227613. [renderContext getValues: &numFrames
  227614. forParameter: NSOpenGLCPSwapInterval];
  227615. return numFrames;
  227616. }
  227617. void repaint()
  227618. {
  227619. // we need to invalidate the juce view that holds this gl view, to make it
  227620. // cause a repaint callback
  227621. NSView* v = (NSView*) viewHolder->view;
  227622. NSRect r = [v frame];
  227623. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227624. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227625. // repaint message, thus never causing our paint() callback, and never repainting
  227626. // the comp. So invalidating just a little bit around the edge helps..
  227627. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227628. }
  227629. void* getNativeWindowHandle() const { return viewHolder->view; }
  227630. NSOpenGLContext* renderContext;
  227631. ThreadSafeNSOpenGLView* view;
  227632. private:
  227633. OpenGLPixelFormat pixelFormat;
  227634. ScopedPointer <NSViewComponentInternal> viewHolder;
  227635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227636. };
  227637. OpenGLContext* OpenGLComponent::createContext()
  227638. {
  227639. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  227640. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227641. return (c->renderContext != 0) ? c.release() : 0;
  227642. }
  227643. void* OpenGLComponent::getNativeWindowHandle() const
  227644. {
  227645. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227646. : 0;
  227647. }
  227648. void juce_glViewport (const int w, const int h)
  227649. {
  227650. glViewport (0, 0, w, h);
  227651. }
  227652. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227653. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227654. {
  227655. /* GLint attribs [64];
  227656. int n = 0;
  227657. attribs[n++] = AGL_RGBA;
  227658. attribs[n++] = AGL_DOUBLEBUFFER;
  227659. attribs[n++] = AGL_ACCELERATED;
  227660. attribs[n++] = AGL_NO_RECOVERY;
  227661. attribs[n++] = AGL_NONE;
  227662. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227663. while (p != 0)
  227664. {
  227665. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227666. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227667. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227668. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227669. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227670. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227671. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227672. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227673. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227674. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227675. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227676. results.add (pf);
  227677. p = aglNextPixelFormat (p);
  227678. }*/
  227679. //jassertfalse // can't see how you do this in cocoa!
  227680. }
  227681. #else
  227682. END_JUCE_NAMESPACE
  227683. @interface JuceGLView : UIView
  227684. {
  227685. }
  227686. + (Class) layerClass;
  227687. @end
  227688. @implementation JuceGLView
  227689. + (Class) layerClass
  227690. {
  227691. return [CAEAGLLayer class];
  227692. }
  227693. @end
  227694. BEGIN_JUCE_NAMESPACE
  227695. class GLESContext : public OpenGLContext
  227696. {
  227697. public:
  227698. GLESContext (UIViewComponentPeer* peer,
  227699. Component* const component_,
  227700. const OpenGLPixelFormat& pixelFormat_,
  227701. const GLESContext* const sharedContext,
  227702. NSUInteger apiType)
  227703. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227704. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227705. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227706. {
  227707. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227708. view.opaque = YES;
  227709. view.hidden = NO;
  227710. view.backgroundColor = [UIColor blackColor];
  227711. view.userInteractionEnabled = NO;
  227712. glLayer = (CAEAGLLayer*) [view layer];
  227713. [peer->view addSubview: view];
  227714. if (sharedContext != 0)
  227715. context = [[EAGLContext alloc] initWithAPI: apiType
  227716. sharegroup: [sharedContext->context sharegroup]];
  227717. else
  227718. context = [[EAGLContext alloc] initWithAPI: apiType];
  227719. createGLBuffers();
  227720. }
  227721. ~GLESContext()
  227722. {
  227723. deleteContext();
  227724. [view removeFromSuperview];
  227725. [view release];
  227726. freeGLBuffers();
  227727. }
  227728. void deleteContext()
  227729. {
  227730. makeInactive();
  227731. [context release];
  227732. context = nil;
  227733. }
  227734. bool makeActive() const throw()
  227735. {
  227736. jassert (context != 0);
  227737. [EAGLContext setCurrentContext: context];
  227738. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227739. return true;
  227740. }
  227741. void swapBuffers()
  227742. {
  227743. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227744. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227745. }
  227746. bool makeInactive() const throw()
  227747. {
  227748. return [EAGLContext setCurrentContext: nil];
  227749. }
  227750. bool isActive() const throw()
  227751. {
  227752. return [EAGLContext currentContext] == context;
  227753. }
  227754. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227755. void* getRawContext() const throw() { return glLayer; }
  227756. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227757. {
  227758. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227759. if (lastWidth != w || lastHeight != h)
  227760. {
  227761. lastWidth = w;
  227762. lastHeight = h;
  227763. freeGLBuffers();
  227764. createGLBuffers();
  227765. }
  227766. }
  227767. bool setSwapInterval (const int numFramesPerSwap)
  227768. {
  227769. numFrames = numFramesPerSwap;
  227770. return true;
  227771. }
  227772. int getSwapInterval() const
  227773. {
  227774. return numFrames;
  227775. }
  227776. void repaint()
  227777. {
  227778. }
  227779. void createGLBuffers()
  227780. {
  227781. makeActive();
  227782. glGenFramebuffersOES (1, &frameBufferHandle);
  227783. glGenRenderbuffersOES (1, &colorBufferHandle);
  227784. glGenRenderbuffersOES (1, &depthBufferHandle);
  227785. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227786. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227787. GLint width, height;
  227788. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227789. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227790. if (useDepthBuffer)
  227791. {
  227792. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227793. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227794. }
  227795. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227796. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227797. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227798. if (useDepthBuffer)
  227799. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227800. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227801. }
  227802. void freeGLBuffers()
  227803. {
  227804. if (frameBufferHandle != 0)
  227805. {
  227806. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227807. frameBufferHandle = 0;
  227808. }
  227809. if (colorBufferHandle != 0)
  227810. {
  227811. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227812. colorBufferHandle = 0;
  227813. }
  227814. if (depthBufferHandle != 0)
  227815. {
  227816. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227817. depthBufferHandle = 0;
  227818. }
  227819. }
  227820. private:
  227821. WeakReference<Component> component;
  227822. OpenGLPixelFormat pixelFormat;
  227823. JuceGLView* view;
  227824. CAEAGLLayer* glLayer;
  227825. EAGLContext* context;
  227826. bool useDepthBuffer;
  227827. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227828. int numFrames;
  227829. int lastWidth, lastHeight;
  227830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  227831. };
  227832. OpenGLContext* OpenGLComponent::createContext()
  227833. {
  227834. ScopedAutoReleasePool pool;
  227835. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227836. if (peer != 0)
  227837. return new GLESContext (peer, this, preferredPixelFormat,
  227838. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227839. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227840. return 0;
  227841. }
  227842. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227843. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227844. {
  227845. }
  227846. void juce_glViewport (const int w, const int h)
  227847. {
  227848. glViewport (0, 0, w, h);
  227849. }
  227850. #endif
  227851. #endif
  227852. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227853. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227854. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227855. // compiled on its own).
  227856. #if JUCE_INCLUDED_FILE
  227857. #if JUCE_MAC
  227858. namespace MouseCursorHelpers
  227859. {
  227860. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227861. {
  227862. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227863. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227864. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227865. [im release];
  227866. return c;
  227867. }
  227868. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227869. {
  227870. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227871. BufferedInputStream buf (fileStream, 4096);
  227872. PNGImageFormat pngFormat;
  227873. Image im (pngFormat.decodeImage (buf));
  227874. if (im.isValid())
  227875. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227876. jassertfalse;
  227877. return 0;
  227878. }
  227879. }
  227880. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227881. {
  227882. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227883. }
  227884. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227885. {
  227886. const ScopedAutoReleasePool pool;
  227887. NSCursor* c = 0;
  227888. switch (type)
  227889. {
  227890. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227891. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227892. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227893. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227894. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227895. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227896. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227897. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227898. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227899. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227900. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227901. case UpDownResizeCursor:
  227902. case TopEdgeResizeCursor:
  227903. case BottomEdgeResizeCursor:
  227904. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227905. case TopLeftCornerResizeCursor:
  227906. case BottomRightCornerResizeCursor:
  227907. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227908. case TopRightCornerResizeCursor:
  227909. case BottomLeftCornerResizeCursor:
  227910. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227911. case UpDownLeftRightResizeCursor:
  227912. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227913. default:
  227914. jassertfalse;
  227915. break;
  227916. }
  227917. [c retain];
  227918. return c;
  227919. }
  227920. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227921. {
  227922. [((NSCursor*) cursorHandle) release];
  227923. }
  227924. void MouseCursor::showInAllWindows() const
  227925. {
  227926. showInWindow (0);
  227927. }
  227928. void MouseCursor::showInWindow (ComponentPeer*) const
  227929. {
  227930. NSCursor* c = (NSCursor*) getHandle();
  227931. if (c == 0)
  227932. c = [NSCursor arrowCursor];
  227933. [c set];
  227934. }
  227935. #else
  227936. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227937. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227938. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227939. void MouseCursor::showInAllWindows() const {}
  227940. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227941. #endif
  227942. #endif
  227943. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227944. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227945. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227946. // compiled on its own).
  227947. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227948. #if JUCE_MAC
  227949. END_JUCE_NAMESPACE
  227950. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227951. @interface DownloadClickDetector : NSObject
  227952. {
  227953. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227954. }
  227955. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227956. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227957. request: (NSURLRequest*) request
  227958. frame: (WebFrame*) frame
  227959. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227960. @end
  227961. @implementation DownloadClickDetector
  227962. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227963. {
  227964. [super init];
  227965. ownerComponent = ownerComponent_;
  227966. return self;
  227967. }
  227968. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227969. request: (NSURLRequest*) request
  227970. frame: (WebFrame*) frame
  227971. decisionListener: (id <WebPolicyDecisionListener>) listener
  227972. {
  227973. (void) sender;
  227974. (void) request;
  227975. (void) frame;
  227976. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227977. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227978. [listener use];
  227979. else
  227980. [listener ignore];
  227981. }
  227982. @end
  227983. BEGIN_JUCE_NAMESPACE
  227984. class WebBrowserComponentInternal : public NSViewComponent
  227985. {
  227986. public:
  227987. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227988. {
  227989. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227990. frameName: @""
  227991. groupName: @""];
  227992. setView (webView);
  227993. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227994. [webView setPolicyDelegate: clickListener];
  227995. }
  227996. ~WebBrowserComponentInternal()
  227997. {
  227998. [webView setPolicyDelegate: nil];
  227999. [clickListener release];
  228000. setView (0);
  228001. }
  228002. void goToURL (const String& url,
  228003. const StringArray* headers,
  228004. const MemoryBlock* postData)
  228005. {
  228006. NSMutableURLRequest* r
  228007. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228008. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228009. timeoutInterval: 30.0];
  228010. if (postData != 0 && postData->getSize() > 0)
  228011. {
  228012. [r setHTTPMethod: @"POST"];
  228013. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228014. length: postData->getSize()]];
  228015. }
  228016. if (headers != 0)
  228017. {
  228018. for (int i = 0; i < headers->size(); ++i)
  228019. {
  228020. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228021. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228022. [r setValue: juceStringToNS (headerValue)
  228023. forHTTPHeaderField: juceStringToNS (headerName)];
  228024. }
  228025. }
  228026. stop();
  228027. [[webView mainFrame] loadRequest: r];
  228028. }
  228029. void goBack()
  228030. {
  228031. [webView goBack];
  228032. }
  228033. void goForward()
  228034. {
  228035. [webView goForward];
  228036. }
  228037. void stop()
  228038. {
  228039. [webView stopLoading: nil];
  228040. }
  228041. void refresh()
  228042. {
  228043. [webView reload: nil];
  228044. }
  228045. void mouseMove (const MouseEvent&)
  228046. {
  228047. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228048. // them work is to push them via this non-public method..
  228049. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228050. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228051. }
  228052. private:
  228053. WebView* webView;
  228054. DownloadClickDetector* clickListener;
  228055. };
  228056. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228057. : browser (0),
  228058. blankPageShown (false),
  228059. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228060. {
  228061. setOpaque (true);
  228062. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228063. }
  228064. WebBrowserComponent::~WebBrowserComponent()
  228065. {
  228066. deleteAndZero (browser);
  228067. }
  228068. void WebBrowserComponent::goToURL (const String& url,
  228069. const StringArray* headers,
  228070. const MemoryBlock* postData)
  228071. {
  228072. lastURL = url;
  228073. lastHeaders.clear();
  228074. if (headers != 0)
  228075. lastHeaders = *headers;
  228076. lastPostData.setSize (0);
  228077. if (postData != 0)
  228078. lastPostData = *postData;
  228079. blankPageShown = false;
  228080. browser->goToURL (url, headers, postData);
  228081. }
  228082. void WebBrowserComponent::stop()
  228083. {
  228084. browser->stop();
  228085. }
  228086. void WebBrowserComponent::goBack()
  228087. {
  228088. lastURL = String::empty;
  228089. blankPageShown = false;
  228090. browser->goBack();
  228091. }
  228092. void WebBrowserComponent::goForward()
  228093. {
  228094. lastURL = String::empty;
  228095. browser->goForward();
  228096. }
  228097. void WebBrowserComponent::refresh()
  228098. {
  228099. browser->refresh();
  228100. }
  228101. void WebBrowserComponent::paint (Graphics&)
  228102. {
  228103. }
  228104. void WebBrowserComponent::checkWindowAssociation()
  228105. {
  228106. if (isShowing())
  228107. {
  228108. if (blankPageShown)
  228109. goBack();
  228110. }
  228111. else
  228112. {
  228113. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228114. {
  228115. // when the component becomes invisible, some stuff like flash
  228116. // carries on playing audio, so we need to force it onto a blank
  228117. // page to avoid this, (and send it back when it's made visible again).
  228118. blankPageShown = true;
  228119. browser->goToURL ("about:blank", 0, 0);
  228120. }
  228121. }
  228122. }
  228123. void WebBrowserComponent::reloadLastURL()
  228124. {
  228125. if (lastURL.isNotEmpty())
  228126. {
  228127. goToURL (lastURL, &lastHeaders, &lastPostData);
  228128. lastURL = String::empty;
  228129. }
  228130. }
  228131. void WebBrowserComponent::parentHierarchyChanged()
  228132. {
  228133. checkWindowAssociation();
  228134. }
  228135. void WebBrowserComponent::resized()
  228136. {
  228137. browser->setSize (getWidth(), getHeight());
  228138. }
  228139. void WebBrowserComponent::visibilityChanged()
  228140. {
  228141. checkWindowAssociation();
  228142. }
  228143. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228144. {
  228145. return true;
  228146. }
  228147. #else
  228148. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228149. {
  228150. }
  228151. WebBrowserComponent::~WebBrowserComponent()
  228152. {
  228153. }
  228154. void WebBrowserComponent::goToURL (const String& url,
  228155. const StringArray* headers,
  228156. const MemoryBlock* postData)
  228157. {
  228158. }
  228159. void WebBrowserComponent::stop()
  228160. {
  228161. }
  228162. void WebBrowserComponent::goBack()
  228163. {
  228164. }
  228165. void WebBrowserComponent::goForward()
  228166. {
  228167. }
  228168. void WebBrowserComponent::refresh()
  228169. {
  228170. }
  228171. void WebBrowserComponent::paint (Graphics& g)
  228172. {
  228173. }
  228174. void WebBrowserComponent::checkWindowAssociation()
  228175. {
  228176. }
  228177. void WebBrowserComponent::reloadLastURL()
  228178. {
  228179. }
  228180. void WebBrowserComponent::parentHierarchyChanged()
  228181. {
  228182. }
  228183. void WebBrowserComponent::resized()
  228184. {
  228185. }
  228186. void WebBrowserComponent::visibilityChanged()
  228187. {
  228188. }
  228189. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228190. {
  228191. return true;
  228192. }
  228193. #endif
  228194. #endif
  228195. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228196. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228197. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228198. // compiled on its own).
  228199. #if JUCE_INCLUDED_FILE
  228200. class IPhoneAudioIODevice : public AudioIODevice
  228201. {
  228202. public:
  228203. IPhoneAudioIODevice (const String& deviceName)
  228204. : AudioIODevice (deviceName, "Audio"),
  228205. actualBufferSize (0),
  228206. isRunning (false),
  228207. audioUnit (0),
  228208. callback (0),
  228209. floatData (1, 2)
  228210. {
  228211. numInputChannels = 2;
  228212. numOutputChannels = 2;
  228213. preferredBufferSize = 0;
  228214. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228215. updateDeviceInfo();
  228216. }
  228217. ~IPhoneAudioIODevice()
  228218. {
  228219. close();
  228220. }
  228221. const StringArray getOutputChannelNames()
  228222. {
  228223. StringArray s;
  228224. s.add ("Left");
  228225. s.add ("Right");
  228226. return s;
  228227. }
  228228. const StringArray getInputChannelNames()
  228229. {
  228230. StringArray s;
  228231. if (audioInputIsAvailable)
  228232. {
  228233. s.add ("Left");
  228234. s.add ("Right");
  228235. }
  228236. return s;
  228237. }
  228238. int getNumSampleRates()
  228239. {
  228240. return 1;
  228241. }
  228242. double getSampleRate (int index)
  228243. {
  228244. return sampleRate;
  228245. }
  228246. int getNumBufferSizesAvailable()
  228247. {
  228248. return 1;
  228249. }
  228250. int getBufferSizeSamples (int index)
  228251. {
  228252. return getDefaultBufferSize();
  228253. }
  228254. int getDefaultBufferSize()
  228255. {
  228256. return 1024;
  228257. }
  228258. const String open (const BigInteger& inputChannels,
  228259. const BigInteger& outputChannels,
  228260. double sampleRate,
  228261. int bufferSize)
  228262. {
  228263. close();
  228264. lastError = String::empty;
  228265. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228266. // xxx set up channel mapping
  228267. activeOutputChans = outputChannels;
  228268. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228269. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228270. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228271. activeInputChans = inputChannels;
  228272. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228273. numInputChannels = activeInputChans.countNumberOfSetBits();
  228274. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228275. AudioSessionSetActive (true);
  228276. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228277. : kAudioSessionCategory_MediaPlayback;
  228278. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228279. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228280. fixAudioRouteIfSetToReceiver();
  228281. updateDeviceInfo();
  228282. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228283. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228284. actualBufferSize = preferredBufferSize;
  228285. prepareFloatBuffers();
  228286. isRunning = true;
  228287. propertyChanged (0, 0, 0); // creates and starts the AU
  228288. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228289. return lastError;
  228290. }
  228291. void close()
  228292. {
  228293. if (isRunning)
  228294. {
  228295. isRunning = false;
  228296. AudioSessionSetActive (false);
  228297. if (audioUnit != 0)
  228298. {
  228299. AudioComponentInstanceDispose (audioUnit);
  228300. audioUnit = 0;
  228301. }
  228302. }
  228303. }
  228304. bool isOpen()
  228305. {
  228306. return isRunning;
  228307. }
  228308. int getCurrentBufferSizeSamples()
  228309. {
  228310. return actualBufferSize;
  228311. }
  228312. double getCurrentSampleRate()
  228313. {
  228314. return sampleRate;
  228315. }
  228316. int getCurrentBitDepth()
  228317. {
  228318. return 16;
  228319. }
  228320. const BigInteger getActiveOutputChannels() const
  228321. {
  228322. return activeOutputChans;
  228323. }
  228324. const BigInteger getActiveInputChannels() const
  228325. {
  228326. return activeInputChans;
  228327. }
  228328. int getOutputLatencyInSamples()
  228329. {
  228330. return 0; //xxx
  228331. }
  228332. int getInputLatencyInSamples()
  228333. {
  228334. return 0; //xxx
  228335. }
  228336. void start (AudioIODeviceCallback* callback_)
  228337. {
  228338. if (isRunning && callback != callback_)
  228339. {
  228340. if (callback_ != 0)
  228341. callback_->audioDeviceAboutToStart (this);
  228342. const ScopedLock sl (callbackLock);
  228343. callback = callback_;
  228344. }
  228345. }
  228346. void stop()
  228347. {
  228348. if (isRunning)
  228349. {
  228350. AudioIODeviceCallback* lastCallback;
  228351. {
  228352. const ScopedLock sl (callbackLock);
  228353. lastCallback = callback;
  228354. callback = 0;
  228355. }
  228356. if (lastCallback != 0)
  228357. lastCallback->audioDeviceStopped();
  228358. }
  228359. }
  228360. bool isPlaying()
  228361. {
  228362. return isRunning && callback != 0;
  228363. }
  228364. const String getLastError()
  228365. {
  228366. return lastError;
  228367. }
  228368. private:
  228369. CriticalSection callbackLock;
  228370. Float64 sampleRate;
  228371. int numInputChannels, numOutputChannels;
  228372. int preferredBufferSize;
  228373. int actualBufferSize;
  228374. bool isRunning;
  228375. String lastError;
  228376. AudioStreamBasicDescription format;
  228377. AudioUnit audioUnit;
  228378. UInt32 audioInputIsAvailable;
  228379. AudioIODeviceCallback* callback;
  228380. BigInteger activeOutputChans, activeInputChans;
  228381. AudioSampleBuffer floatData;
  228382. float* inputChannels[3];
  228383. float* outputChannels[3];
  228384. bool monoInputChannelNumber, monoOutputChannelNumber;
  228385. void prepareFloatBuffers()
  228386. {
  228387. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228388. zerostruct (inputChannels);
  228389. zerostruct (outputChannels);
  228390. for (int i = 0; i < numInputChannels; ++i)
  228391. inputChannels[i] = floatData.getSampleData (i);
  228392. for (int i = 0; i < numOutputChannels; ++i)
  228393. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228394. }
  228395. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228396. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228397. {
  228398. OSStatus err = noErr;
  228399. if (audioInputIsAvailable)
  228400. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228401. const ScopedLock sl (callbackLock);
  228402. if (callback != 0)
  228403. {
  228404. if (audioInputIsAvailable && numInputChannels > 0)
  228405. {
  228406. short* shortData = (short*) ioData->mBuffers[0].mData;
  228407. if (numInputChannels >= 2)
  228408. {
  228409. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228410. {
  228411. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228412. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228413. }
  228414. }
  228415. else
  228416. {
  228417. if (monoInputChannelNumber > 0)
  228418. ++shortData;
  228419. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228420. {
  228421. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228422. ++shortData;
  228423. }
  228424. }
  228425. }
  228426. else
  228427. {
  228428. for (int i = numInputChannels; --i >= 0;)
  228429. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228430. }
  228431. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228432. outputChannels, numOutputChannels,
  228433. (int) inNumberFrames);
  228434. short* shortData = (short*) ioData->mBuffers[0].mData;
  228435. int n = 0;
  228436. if (numOutputChannels >= 2)
  228437. {
  228438. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228439. {
  228440. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228441. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228442. }
  228443. }
  228444. else if (numOutputChannels == 1)
  228445. {
  228446. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228447. {
  228448. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228449. shortData [n++] = s;
  228450. shortData [n++] = s;
  228451. }
  228452. }
  228453. else
  228454. {
  228455. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228456. }
  228457. }
  228458. else
  228459. {
  228460. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228461. }
  228462. return err;
  228463. }
  228464. void updateDeviceInfo()
  228465. {
  228466. UInt32 size = sizeof (sampleRate);
  228467. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228468. size = sizeof (audioInputIsAvailable);
  228469. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228470. }
  228471. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228472. {
  228473. if (! isRunning)
  228474. return;
  228475. if (inPropertyValue != 0)
  228476. {
  228477. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228478. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228479. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228480. SInt32 routeChangeReason;
  228481. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228482. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228483. fixAudioRouteIfSetToReceiver();
  228484. }
  228485. updateDeviceInfo();
  228486. createAudioUnit();
  228487. AudioSessionSetActive (true);
  228488. if (audioUnit != 0)
  228489. {
  228490. UInt32 formatSize = sizeof (format);
  228491. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228492. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228493. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228494. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228495. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228496. AudioOutputUnitStart (audioUnit);
  228497. }
  228498. }
  228499. void interruptionListener (UInt32 inInterruption)
  228500. {
  228501. /*if (inInterruption == kAudioSessionBeginInterruption)
  228502. {
  228503. isRunning = false;
  228504. AudioOutputUnitStop (audioUnit);
  228505. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228506. "This could have been interrupted by another application or by unplugging a headset",
  228507. @"Resume",
  228508. @"Cancel"))
  228509. {
  228510. isRunning = true;
  228511. propertyChanged (0, 0, 0);
  228512. }
  228513. }*/
  228514. if (inInterruption == kAudioSessionEndInterruption)
  228515. {
  228516. isRunning = true;
  228517. AudioSessionSetActive (true);
  228518. AudioOutputUnitStart (audioUnit);
  228519. }
  228520. }
  228521. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228522. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228523. {
  228524. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228525. }
  228526. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228527. {
  228528. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228529. }
  228530. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228531. {
  228532. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228533. }
  228534. void resetFormat (const int numChannels)
  228535. {
  228536. memset (&format, 0, sizeof (format));
  228537. format.mFormatID = kAudioFormatLinearPCM;
  228538. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228539. format.mBitsPerChannel = 8 * sizeof (short);
  228540. format.mChannelsPerFrame = 2;
  228541. format.mFramesPerPacket = 1;
  228542. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228543. }
  228544. bool createAudioUnit()
  228545. {
  228546. if (audioUnit != 0)
  228547. {
  228548. AudioComponentInstanceDispose (audioUnit);
  228549. audioUnit = 0;
  228550. }
  228551. resetFormat (2);
  228552. AudioComponentDescription desc;
  228553. desc.componentType = kAudioUnitType_Output;
  228554. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228555. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228556. desc.componentFlags = 0;
  228557. desc.componentFlagsMask = 0;
  228558. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228559. AudioComponentInstanceNew (comp, &audioUnit);
  228560. if (audioUnit == 0)
  228561. return false;
  228562. const UInt32 one = 1;
  228563. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228564. AudioChannelLayout layout;
  228565. layout.mChannelBitmap = 0;
  228566. layout.mNumberChannelDescriptions = 0;
  228567. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228568. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228569. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228570. AURenderCallbackStruct inputProc;
  228571. inputProc.inputProc = processStatic;
  228572. inputProc.inputProcRefCon = this;
  228573. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228574. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228575. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228576. AudioUnitInitialize (audioUnit);
  228577. return true;
  228578. }
  228579. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228580. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228581. static void fixAudioRouteIfSetToReceiver()
  228582. {
  228583. CFStringRef audioRoute = 0;
  228584. UInt32 propertySize = sizeof (audioRoute);
  228585. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228586. {
  228587. NSString* route = (NSString*) audioRoute;
  228588. //DBG ("audio route: " + nsStringToJuce (route));
  228589. if ([route hasPrefix: @"Receiver"])
  228590. {
  228591. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228592. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228593. }
  228594. CFRelease (audioRoute);
  228595. }
  228596. }
  228597. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228598. };
  228599. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228600. {
  228601. public:
  228602. IPhoneAudioIODeviceType()
  228603. : AudioIODeviceType ("iPhone Audio")
  228604. {
  228605. }
  228606. void scanForDevices()
  228607. {
  228608. }
  228609. const StringArray getDeviceNames (bool wantInputNames) const
  228610. {
  228611. StringArray s;
  228612. s.add ("iPhone Audio");
  228613. return s;
  228614. }
  228615. int getDefaultDeviceIndex (bool forInput) const
  228616. {
  228617. return 0;
  228618. }
  228619. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228620. {
  228621. return device != 0 ? 0 : -1;
  228622. }
  228623. bool hasSeparateInputsAndOutputs() const { return false; }
  228624. AudioIODevice* createDevice (const String& outputDeviceName,
  228625. const String& inputDeviceName)
  228626. {
  228627. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228628. {
  228629. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228630. : inputDeviceName);
  228631. }
  228632. return 0;
  228633. }
  228634. private:
  228635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228636. };
  228637. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228638. {
  228639. return new IPhoneAudioIODeviceType();
  228640. }
  228641. #endif
  228642. /*** End of inlined file: juce_ios_Audio.cpp ***/
  228643. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228644. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228645. // compiled on its own).
  228646. #if JUCE_INCLUDED_FILE
  228647. #if JUCE_MAC
  228648. namespace CoreMidiHelpers
  228649. {
  228650. bool logError (const OSStatus err, const int lineNum)
  228651. {
  228652. if (err == noErr)
  228653. return true;
  228654. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228655. jassertfalse;
  228656. return false;
  228657. }
  228658. #undef CHECK_ERROR
  228659. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228660. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228661. {
  228662. String result;
  228663. CFStringRef str = 0;
  228664. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228665. if (str != 0)
  228666. {
  228667. result = PlatformUtilities::cfStringToJuceString (str);
  228668. CFRelease (str);
  228669. str = 0;
  228670. }
  228671. MIDIEntityRef entity = 0;
  228672. MIDIEndpointGetEntity (endpoint, &entity);
  228673. if (entity == 0)
  228674. return result; // probably virtual
  228675. if (result.isEmpty())
  228676. {
  228677. // endpoint name has zero length - try the entity
  228678. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228679. if (str != 0)
  228680. {
  228681. result += PlatformUtilities::cfStringToJuceString (str);
  228682. CFRelease (str);
  228683. str = 0;
  228684. }
  228685. }
  228686. // now consider the device's name
  228687. MIDIDeviceRef device = 0;
  228688. MIDIEntityGetDevice (entity, &device);
  228689. if (device == 0)
  228690. return result;
  228691. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228692. if (str != 0)
  228693. {
  228694. const String s (PlatformUtilities::cfStringToJuceString (str));
  228695. CFRelease (str);
  228696. // if an external device has only one entity, throw away
  228697. // the endpoint name and just use the device name
  228698. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228699. {
  228700. result = s;
  228701. }
  228702. else if (! result.startsWithIgnoreCase (s))
  228703. {
  228704. // prepend the device name to the entity name
  228705. result = (s + " " + result).trimEnd();
  228706. }
  228707. }
  228708. return result;
  228709. }
  228710. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228711. {
  228712. String result;
  228713. // Does the endpoint have connections?
  228714. CFDataRef connections = 0;
  228715. int numConnections = 0;
  228716. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228717. if (connections != 0)
  228718. {
  228719. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228720. if (numConnections > 0)
  228721. {
  228722. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228723. for (int i = 0; i < numConnections; ++i, ++pid)
  228724. {
  228725. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228726. MIDIObjectRef connObject;
  228727. MIDIObjectType connObjectType;
  228728. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228729. if (err == noErr)
  228730. {
  228731. String s;
  228732. if (connObjectType == kMIDIObjectType_ExternalSource
  228733. || connObjectType == kMIDIObjectType_ExternalDestination)
  228734. {
  228735. // Connected to an external device's endpoint (10.3 and later).
  228736. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228737. }
  228738. else
  228739. {
  228740. // Connected to an external device (10.2) (or something else, catch-all)
  228741. CFStringRef str = 0;
  228742. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228743. if (str != 0)
  228744. {
  228745. s = PlatformUtilities::cfStringToJuceString (str);
  228746. CFRelease (str);
  228747. }
  228748. }
  228749. if (s.isNotEmpty())
  228750. {
  228751. if (result.isNotEmpty())
  228752. result += ", ";
  228753. result += s;
  228754. }
  228755. }
  228756. }
  228757. }
  228758. CFRelease (connections);
  228759. }
  228760. if (result.isNotEmpty())
  228761. return result;
  228762. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228763. return getEndpointName (endpoint, false);
  228764. }
  228765. MIDIClientRef getGlobalMidiClient()
  228766. {
  228767. static MIDIClientRef globalMidiClient = 0;
  228768. if (globalMidiClient == 0)
  228769. {
  228770. String name ("JUCE");
  228771. if (JUCEApplication::getInstance() != 0)
  228772. name = JUCEApplication::getInstance()->getApplicationName();
  228773. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228774. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228775. CFRelease (appName);
  228776. }
  228777. return globalMidiClient;
  228778. }
  228779. class MidiPortAndEndpoint
  228780. {
  228781. public:
  228782. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228783. : port (port_), endPoint (endPoint_)
  228784. {
  228785. }
  228786. ~MidiPortAndEndpoint()
  228787. {
  228788. if (port != 0)
  228789. MIDIPortDispose (port);
  228790. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228791. MIDIEndpointDispose (endPoint);
  228792. }
  228793. void send (const MIDIPacketList* const packets)
  228794. {
  228795. if (port != 0)
  228796. MIDISend (port, endPoint, packets);
  228797. else
  228798. MIDIReceived (endPoint, packets);
  228799. }
  228800. MIDIPortRef port;
  228801. MIDIEndpointRef endPoint;
  228802. };
  228803. class MidiPortAndCallback;
  228804. CriticalSection callbackLock;
  228805. Array<MidiPortAndCallback*> activeCallbacks;
  228806. class MidiPortAndCallback
  228807. {
  228808. public:
  228809. MidiPortAndCallback (MidiInputCallback& callback_)
  228810. : input (0), active (false), callback (callback_), concatenator (2048)
  228811. {
  228812. }
  228813. ~MidiPortAndCallback()
  228814. {
  228815. active = false;
  228816. {
  228817. const ScopedLock sl (callbackLock);
  228818. activeCallbacks.removeValue (this);
  228819. }
  228820. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  228821. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  228822. }
  228823. void handlePackets (const MIDIPacketList* const pktlist)
  228824. {
  228825. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  228826. const ScopedLock sl (callbackLock);
  228827. if (activeCallbacks.contains (this) && active)
  228828. {
  228829. const MIDIPacket* packet = &pktlist->packet[0];
  228830. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228831. {
  228832. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  228833. input, callback);
  228834. packet = MIDIPacketNext (packet);
  228835. }
  228836. }
  228837. }
  228838. MidiInput* input;
  228839. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  228840. volatile bool active;
  228841. private:
  228842. MidiInputCallback& callback;
  228843. MidiDataConcatenator concatenator;
  228844. };
  228845. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  228846. {
  228847. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  228848. }
  228849. }
  228850. const StringArray MidiOutput::getDevices()
  228851. {
  228852. StringArray s;
  228853. const ItemCount num = MIDIGetNumberOfDestinations();
  228854. for (ItemCount i = 0; i < num; ++i)
  228855. {
  228856. MIDIEndpointRef dest = MIDIGetDestination (i);
  228857. if (dest != 0)
  228858. {
  228859. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  228860. if (name.isEmpty())
  228861. name = "<error>";
  228862. s.add (name);
  228863. }
  228864. else
  228865. {
  228866. s.add ("<error>");
  228867. }
  228868. }
  228869. return s;
  228870. }
  228871. int MidiOutput::getDefaultDeviceIndex()
  228872. {
  228873. return 0;
  228874. }
  228875. MidiOutput* MidiOutput::openDevice (int index)
  228876. {
  228877. MidiOutput* mo = 0;
  228878. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  228879. {
  228880. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228881. CFStringRef pname;
  228882. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228883. {
  228884. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228885. MIDIPortRef port;
  228886. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  228887. {
  228888. mo = new MidiOutput();
  228889. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  228890. }
  228891. CFRelease (pname);
  228892. }
  228893. }
  228894. return mo;
  228895. }
  228896. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228897. {
  228898. MidiOutput* mo = 0;
  228899. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228900. MIDIEndpointRef endPoint;
  228901. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228902. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  228903. {
  228904. mo = new MidiOutput();
  228905. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  228906. }
  228907. CFRelease (name);
  228908. return mo;
  228909. }
  228910. MidiOutput::~MidiOutput()
  228911. {
  228912. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228913. }
  228914. void MidiOutput::reset()
  228915. {
  228916. }
  228917. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228918. {
  228919. return false;
  228920. }
  228921. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228922. {
  228923. }
  228924. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228925. {
  228926. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228927. if (message.isSysEx())
  228928. {
  228929. const int maxPacketSize = 256;
  228930. int pos = 0, bytesLeft = message.getRawDataSize();
  228931. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228932. HeapBlock <MIDIPacketList> packets;
  228933. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228934. packets->numPackets = numPackets;
  228935. MIDIPacket* p = packets->packet;
  228936. for (int i = 0; i < numPackets; ++i)
  228937. {
  228938. p->timeStamp = AudioGetCurrentHostTime();
  228939. p->length = jmin (maxPacketSize, bytesLeft);
  228940. memcpy (p->data, message.getRawData() + pos, p->length);
  228941. pos += p->length;
  228942. bytesLeft -= p->length;
  228943. p = MIDIPacketNext (p);
  228944. }
  228945. mpe->send (packets);
  228946. }
  228947. else
  228948. {
  228949. MIDIPacketList packets;
  228950. packets.numPackets = 1;
  228951. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  228952. packets.packet[0].length = message.getRawDataSize();
  228953. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228954. mpe->send (&packets);
  228955. }
  228956. }
  228957. const StringArray MidiInput::getDevices()
  228958. {
  228959. StringArray s;
  228960. const ItemCount num = MIDIGetNumberOfSources();
  228961. for (ItemCount i = 0; i < num; ++i)
  228962. {
  228963. MIDIEndpointRef source = MIDIGetSource (i);
  228964. if (source != 0)
  228965. {
  228966. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  228967. if (name.isEmpty())
  228968. name = "<error>";
  228969. s.add (name);
  228970. }
  228971. else
  228972. {
  228973. s.add ("<error>");
  228974. }
  228975. }
  228976. return s;
  228977. }
  228978. int MidiInput::getDefaultDeviceIndex()
  228979. {
  228980. return 0;
  228981. }
  228982. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228983. {
  228984. jassert (callback != 0);
  228985. using namespace CoreMidiHelpers;
  228986. MidiInput* newInput = 0;
  228987. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  228988. {
  228989. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228990. if (endPoint != 0)
  228991. {
  228992. CFStringRef name;
  228993. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  228994. {
  228995. MIDIClientRef client = getGlobalMidiClient();
  228996. if (client != 0)
  228997. {
  228998. MIDIPortRef port;
  228999. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229000. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229001. {
  229002. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229003. {
  229004. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229005. newInput = new MidiInput (getDevices() [index]);
  229006. mpc->input = newInput;
  229007. newInput->internal = mpc;
  229008. const ScopedLock sl (callbackLock);
  229009. activeCallbacks.add (mpc.release());
  229010. }
  229011. else
  229012. {
  229013. CHECK_ERROR (MIDIPortDispose (port));
  229014. }
  229015. }
  229016. }
  229017. }
  229018. CFRelease (name);
  229019. }
  229020. }
  229021. return newInput;
  229022. }
  229023. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229024. {
  229025. jassert (callback != 0);
  229026. using namespace CoreMidiHelpers;
  229027. MidiInput* mi = 0;
  229028. MIDIClientRef client = getGlobalMidiClient();
  229029. if (client != 0)
  229030. {
  229031. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229032. mpc->active = false;
  229033. MIDIEndpointRef endPoint;
  229034. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229035. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229036. {
  229037. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229038. mi = new MidiInput (deviceName);
  229039. mpc->input = mi;
  229040. mi->internal = mpc;
  229041. const ScopedLock sl (callbackLock);
  229042. activeCallbacks.add (mpc.release());
  229043. }
  229044. CFRelease (name);
  229045. }
  229046. return mi;
  229047. }
  229048. MidiInput::MidiInput (const String& name_)
  229049. : name (name_)
  229050. {
  229051. }
  229052. MidiInput::~MidiInput()
  229053. {
  229054. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229055. }
  229056. void MidiInput::start()
  229057. {
  229058. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229059. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229060. }
  229061. void MidiInput::stop()
  229062. {
  229063. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229064. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229065. }
  229066. #undef CHECK_ERROR
  229067. #else // Stubs for iOS...
  229068. MidiOutput::~MidiOutput() {}
  229069. void MidiOutput::reset() {}
  229070. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229071. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229072. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229073. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229074. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229075. const StringArray MidiInput::getDevices() { return StringArray(); }
  229076. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229077. #endif
  229078. #endif
  229079. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229080. #else
  229081. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229082. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229083. // compiled on its own).
  229084. #if JUCE_INCLUDED_FILE
  229085. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229086. #define SUPPORT_10_4_FONTS 1
  229087. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229088. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229089. #define SUPPORT_ONLY_10_4_FONTS 1
  229090. #endif
  229091. END_JUCE_NAMESPACE
  229092. @interface NSFont (PrivateHack)
  229093. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229094. @end
  229095. BEGIN_JUCE_NAMESPACE
  229096. #endif
  229097. class MacTypeface : public Typeface
  229098. {
  229099. public:
  229100. MacTypeface (const Font& font)
  229101. : Typeface (font.getTypefaceName())
  229102. {
  229103. const ScopedAutoReleasePool pool;
  229104. renderingTransform = CGAffineTransformIdentity;
  229105. bool needsItalicTransform = false;
  229106. #if JUCE_IOS
  229107. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229108. if (font.isItalic() || font.isBold())
  229109. {
  229110. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229111. for (NSString* i in familyFonts)
  229112. {
  229113. const String fn (nsStringToJuce (i));
  229114. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229115. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229116. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229117. || afterDash.containsIgnoreCase ("italic")
  229118. || fn.endsWithIgnoreCase ("oblique")
  229119. || fn.endsWithIgnoreCase ("italic");
  229120. if (probablyBold == font.isBold()
  229121. && probablyItalic == font.isItalic())
  229122. {
  229123. fontName = i;
  229124. needsItalicTransform = false;
  229125. break;
  229126. }
  229127. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229128. {
  229129. fontName = i;
  229130. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229131. }
  229132. }
  229133. if (needsItalicTransform)
  229134. renderingTransform.c = 0.15f;
  229135. }
  229136. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229137. const int ascender = abs (CGFontGetAscent (fontRef));
  229138. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229139. ascent = ascender / totalHeight;
  229140. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229141. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229142. #else
  229143. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229144. if (font.isItalic())
  229145. {
  229146. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229147. toHaveTrait: NSItalicFontMask];
  229148. if (newFont == nsFont)
  229149. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229150. nsFont = newFont;
  229151. }
  229152. if (font.isBold())
  229153. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229154. [nsFont retain];
  229155. ascent = std::abs ((float) [nsFont ascender]);
  229156. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229157. ascent /= totalSize;
  229158. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229159. if (needsItalicTransform)
  229160. {
  229161. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229162. renderingTransform.c = 0.15f;
  229163. }
  229164. #if SUPPORT_ONLY_10_4_FONTS
  229165. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229166. if (atsFont == 0)
  229167. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229168. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229169. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229170. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229171. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229172. #else
  229173. #if SUPPORT_10_4_FONTS
  229174. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229175. {
  229176. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229177. if (atsFont == 0)
  229178. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229179. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229180. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229181. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229182. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229183. }
  229184. else
  229185. #endif
  229186. {
  229187. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229188. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229189. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229190. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229191. }
  229192. #endif
  229193. #endif
  229194. }
  229195. ~MacTypeface()
  229196. {
  229197. #if ! JUCE_IOS
  229198. [nsFont release];
  229199. #endif
  229200. if (fontRef != 0)
  229201. CGFontRelease (fontRef);
  229202. }
  229203. float getAscent() const
  229204. {
  229205. return ascent;
  229206. }
  229207. float getDescent() const
  229208. {
  229209. return 1.0f - ascent;
  229210. }
  229211. float getStringWidth (const String& text)
  229212. {
  229213. if (fontRef == 0 || text.isEmpty())
  229214. return 0;
  229215. const int length = text.length();
  229216. HeapBlock <CGGlyph> glyphs;
  229217. createGlyphsForString (text, length, glyphs);
  229218. float x = 0;
  229219. #if SUPPORT_ONLY_10_4_FONTS
  229220. HeapBlock <NSSize> advances (length);
  229221. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229222. for (int i = 0; i < length; ++i)
  229223. x += advances[i].width;
  229224. #else
  229225. #if SUPPORT_10_4_FONTS
  229226. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229227. {
  229228. HeapBlock <NSSize> advances (length);
  229229. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229230. for (int i = 0; i < length; ++i)
  229231. x += advances[i].width;
  229232. }
  229233. else
  229234. #endif
  229235. {
  229236. HeapBlock <int> advances (length);
  229237. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229238. for (int i = 0; i < length; ++i)
  229239. x += advances[i];
  229240. }
  229241. #endif
  229242. return x * unitsToHeightScaleFactor;
  229243. }
  229244. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229245. {
  229246. xOffsets.add (0);
  229247. if (fontRef == 0 || text.isEmpty())
  229248. return;
  229249. const int length = text.length();
  229250. HeapBlock <CGGlyph> glyphs;
  229251. createGlyphsForString (text, length, glyphs);
  229252. #if SUPPORT_ONLY_10_4_FONTS
  229253. HeapBlock <NSSize> advances (length);
  229254. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229255. int x = 0;
  229256. for (int i = 0; i < length; ++i)
  229257. {
  229258. x += advances[i].width;
  229259. xOffsets.add (x * unitsToHeightScaleFactor);
  229260. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229261. }
  229262. #else
  229263. #if SUPPORT_10_4_FONTS
  229264. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229265. {
  229266. HeapBlock <NSSize> advances (length);
  229267. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229268. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229269. float x = 0;
  229270. for (int i = 0; i < length; ++i)
  229271. {
  229272. x += advances[i].width;
  229273. xOffsets.add (x * unitsToHeightScaleFactor);
  229274. resultGlyphs.add (nsGlyphs[i]);
  229275. }
  229276. }
  229277. else
  229278. #endif
  229279. {
  229280. HeapBlock <int> advances (length);
  229281. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229282. {
  229283. int x = 0;
  229284. for (int i = 0; i < length; ++i)
  229285. {
  229286. x += advances [i];
  229287. xOffsets.add (x * unitsToHeightScaleFactor);
  229288. resultGlyphs.add (glyphs[i]);
  229289. }
  229290. }
  229291. }
  229292. #endif
  229293. }
  229294. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229295. {
  229296. #if JUCE_IOS
  229297. return false;
  229298. #else
  229299. if (nsFont == 0)
  229300. return false;
  229301. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229302. jassert (path.isEmpty());
  229303. const ScopedAutoReleasePool pool;
  229304. NSBezierPath* bez = [NSBezierPath bezierPath];
  229305. [bez moveToPoint: NSMakePoint (0, 0)];
  229306. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229307. inFont: nsFont];
  229308. for (int i = 0; i < [bez elementCount]; ++i)
  229309. {
  229310. NSPoint p[3];
  229311. switch ([bez elementAtIndex: i associatedPoints: p])
  229312. {
  229313. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229314. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229315. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229316. (float) p[1].x, (float) -p[1].y,
  229317. (float) p[2].x, (float) -p[2].y); break;
  229318. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229319. default: jassertfalse; break;
  229320. }
  229321. }
  229322. path.applyTransform (pathTransform);
  229323. return true;
  229324. #endif
  229325. }
  229326. CGFontRef fontRef;
  229327. float fontHeightToCGSizeFactor;
  229328. CGAffineTransform renderingTransform;
  229329. private:
  229330. float ascent, unitsToHeightScaleFactor;
  229331. #if JUCE_IOS
  229332. #else
  229333. NSFont* nsFont;
  229334. AffineTransform pathTransform;
  229335. #endif
  229336. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229337. {
  229338. #if SUPPORT_10_4_FONTS
  229339. #if ! SUPPORT_ONLY_10_4_FONTS
  229340. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229341. #endif
  229342. {
  229343. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229344. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229345. for (int i = 0; i < length; ++i)
  229346. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229347. return;
  229348. }
  229349. #endif
  229350. #if ! SUPPORT_ONLY_10_4_FONTS
  229351. if (charToGlyphMapper == 0)
  229352. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229353. glyphs.malloc (length);
  229354. for (int i = 0; i < length; ++i)
  229355. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229356. #endif
  229357. }
  229358. #if ! SUPPORT_ONLY_10_4_FONTS
  229359. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229360. class CharToGlyphMapper
  229361. {
  229362. public:
  229363. CharToGlyphMapper (CGFontRef fontRef)
  229364. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229365. idRangeOffset (0), glyphIndexes (0)
  229366. {
  229367. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229368. if (cmapTable != 0)
  229369. {
  229370. const int numSubtables = getValue16 (cmapTable, 2);
  229371. for (int i = 0; i < numSubtables; ++i)
  229372. {
  229373. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229374. {
  229375. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229376. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229377. {
  229378. const int length = getValue16 (cmapTable, offset + 2);
  229379. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229380. segCount = segCountX2 / 2;
  229381. const int endCodeOffset = offset + 14;
  229382. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229383. const int idDeltaOffset = startCodeOffset + segCountX2;
  229384. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229385. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229386. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229387. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229388. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229389. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229390. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229391. }
  229392. break;
  229393. }
  229394. }
  229395. CFRelease (cmapTable);
  229396. }
  229397. }
  229398. ~CharToGlyphMapper()
  229399. {
  229400. if (endCode != 0)
  229401. {
  229402. CFRelease (endCode);
  229403. CFRelease (startCode);
  229404. CFRelease (idDelta);
  229405. CFRelease (idRangeOffset);
  229406. CFRelease (glyphIndexes);
  229407. }
  229408. }
  229409. int getGlyphForCharacter (const juce_wchar c) const
  229410. {
  229411. for (int i = 0; i < segCount; ++i)
  229412. {
  229413. if (getValue16 (endCode, i * 2) >= c)
  229414. {
  229415. const int start = getValue16 (startCode, i * 2);
  229416. if (start > c)
  229417. break;
  229418. const int delta = getValue16 (idDelta, i * 2);
  229419. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229420. if (rangeOffset == 0)
  229421. return delta + c;
  229422. else
  229423. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229424. }
  229425. }
  229426. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229427. return jmax (-1, (int) c - 29);
  229428. }
  229429. private:
  229430. int segCount;
  229431. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229432. static uint16 getValue16 (CFDataRef data, const int index)
  229433. {
  229434. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229435. }
  229436. static uint32 getValue32 (CFDataRef data, const int index)
  229437. {
  229438. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229439. }
  229440. };
  229441. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229442. #endif
  229443. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229444. };
  229445. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229446. {
  229447. return new MacTypeface (font);
  229448. }
  229449. const StringArray Font::findAllTypefaceNames()
  229450. {
  229451. StringArray names;
  229452. const ScopedAutoReleasePool pool;
  229453. #if JUCE_IOS
  229454. NSArray* fonts = [UIFont familyNames];
  229455. #else
  229456. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229457. #endif
  229458. for (unsigned int i = 0; i < [fonts count]; ++i)
  229459. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229460. names.sort (true);
  229461. return names;
  229462. }
  229463. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229464. {
  229465. #if JUCE_IOS
  229466. defaultSans = "Helvetica";
  229467. defaultSerif = "Times New Roman";
  229468. defaultFixed = "Courier New";
  229469. #else
  229470. defaultSans = "Lucida Grande";
  229471. defaultSerif = "Times New Roman";
  229472. defaultFixed = "Monaco";
  229473. #endif
  229474. defaultFallback = "Arial Unicode MS";
  229475. }
  229476. #endif
  229477. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229478. // (must go before juce_mac_CoreGraphicsContext.mm)
  229479. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229480. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229481. // compiled on its own).
  229482. #if JUCE_INCLUDED_FILE
  229483. class CoreGraphicsImage : public Image::SharedImage
  229484. {
  229485. public:
  229486. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229487. : Image::SharedImage (format_, width_, height_)
  229488. {
  229489. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229490. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229491. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229492. imageData = imageDataAllocated;
  229493. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229494. : CGColorSpaceCreateDeviceRGB();
  229495. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229496. colourSpace, getCGImageFlags (format_));
  229497. CGColorSpaceRelease (colourSpace);
  229498. }
  229499. ~CoreGraphicsImage()
  229500. {
  229501. CGContextRelease (context);
  229502. }
  229503. Image::ImageType getType() const { return Image::NativeImage; }
  229504. LowLevelGraphicsContext* createLowLevelContext();
  229505. SharedImage* clone()
  229506. {
  229507. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229508. memcpy (im->imageData, imageData, lineStride * height);
  229509. return im;
  229510. }
  229511. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  229512. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  229513. {
  229514. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229515. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229516. {
  229517. return CGBitmapContextCreateImage (nativeImage->context);
  229518. }
  229519. else
  229520. {
  229521. const Image::BitmapData srcData (juceImage, false);
  229522. CGDataProviderRef provider;
  229523. if (mustOutliveSource)
  229524. {
  229525. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  229526. provider = CGDataProviderCreateWithCFData (data);
  229527. CFRelease (data);
  229528. }
  229529. else
  229530. {
  229531. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229532. }
  229533. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229534. 8, srcData.pixelStride * 8, srcData.lineStride,
  229535. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229536. 0, true, kCGRenderingIntentDefault);
  229537. CGDataProviderRelease (provider);
  229538. return imageRef;
  229539. }
  229540. }
  229541. #if JUCE_MAC
  229542. static NSImage* createNSImage (const Image& image)
  229543. {
  229544. const ScopedAutoReleasePool pool;
  229545. NSImage* im = [[NSImage alloc] init];
  229546. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229547. [im lockFocus];
  229548. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229549. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  229550. CGColorSpaceRelease (colourSpace);
  229551. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229552. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229553. CGImageRelease (imageRef);
  229554. [im unlockFocus];
  229555. return im;
  229556. }
  229557. #endif
  229558. CGContextRef context;
  229559. HeapBlock<uint8> imageDataAllocated;
  229560. private:
  229561. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229562. {
  229563. #if JUCE_BIG_ENDIAN
  229564. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229565. #else
  229566. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229567. #endif
  229568. }
  229569. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229570. };
  229571. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229572. {
  229573. #if USE_COREGRAPHICS_RENDERING
  229574. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229575. #else
  229576. return createSoftwareImage (format, width, height, clearImage);
  229577. #endif
  229578. }
  229579. class CoreGraphicsContext : public LowLevelGraphicsContext
  229580. {
  229581. public:
  229582. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229583. : context (context_),
  229584. flipHeight (flipHeight_),
  229585. lastClipRectIsValid (false),
  229586. state (new SavedState()),
  229587. numGradientLookupEntries (0)
  229588. {
  229589. CGContextRetain (context);
  229590. CGContextSaveGState(context);
  229591. CGContextSetShouldSmoothFonts (context, true);
  229592. CGContextSetShouldAntialias (context, true);
  229593. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229594. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229595. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229596. gradientCallbacks.version = 0;
  229597. gradientCallbacks.evaluate = gradientCallback;
  229598. gradientCallbacks.releaseInfo = 0;
  229599. setFont (Font());
  229600. }
  229601. ~CoreGraphicsContext()
  229602. {
  229603. CGContextRestoreGState (context);
  229604. CGContextRelease (context);
  229605. CGColorSpaceRelease (rgbColourSpace);
  229606. CGColorSpaceRelease (greyColourSpace);
  229607. }
  229608. bool isVectorDevice() const { return false; }
  229609. void setOrigin (int x, int y)
  229610. {
  229611. CGContextTranslateCTM (context, x, -y);
  229612. if (lastClipRectIsValid)
  229613. lastClipRect.translate (-x, -y);
  229614. }
  229615. void addTransform (const AffineTransform& transform)
  229616. {
  229617. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229618. .translated (0, flipHeight)
  229619. .followedBy (transform)
  229620. .translated (0, -flipHeight)
  229621. .scaled (1.0f, -1.0f));
  229622. lastClipRectIsValid = false;
  229623. }
  229624. float getScaleFactor()
  229625. {
  229626. CGAffineTransform t = CGContextGetCTM (context);
  229627. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229628. }
  229629. bool clipToRectangle (const Rectangle<int>& r)
  229630. {
  229631. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229632. if (lastClipRectIsValid)
  229633. {
  229634. // This is actually incorrect, because the actual clip region may be complex, and
  229635. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229636. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229637. // when calculating the resultant clip bounds, and makes the same mistake!
  229638. lastClipRect = lastClipRect.getIntersection (r);
  229639. return ! lastClipRect.isEmpty();
  229640. }
  229641. return ! isClipEmpty();
  229642. }
  229643. bool clipToRectangleList (const RectangleList& clipRegion)
  229644. {
  229645. if (clipRegion.isEmpty())
  229646. {
  229647. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229648. lastClipRectIsValid = true;
  229649. lastClipRect = Rectangle<int>();
  229650. return false;
  229651. }
  229652. else
  229653. {
  229654. const int numRects = clipRegion.getNumRectangles();
  229655. HeapBlock <CGRect> rects (numRects);
  229656. for (int i = 0; i < numRects; ++i)
  229657. {
  229658. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229659. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229660. }
  229661. CGContextClipToRects (context, rects, numRects);
  229662. lastClipRectIsValid = false;
  229663. return ! isClipEmpty();
  229664. }
  229665. }
  229666. void excludeClipRectangle (const Rectangle<int>& r)
  229667. {
  229668. RectangleList remaining (getClipBounds());
  229669. remaining.subtract (r);
  229670. clipToRectangleList (remaining);
  229671. lastClipRectIsValid = false;
  229672. }
  229673. void clipToPath (const Path& path, const AffineTransform& transform)
  229674. {
  229675. createPath (path, transform);
  229676. CGContextClip (context);
  229677. lastClipRectIsValid = false;
  229678. }
  229679. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229680. {
  229681. if (! transform.isSingularity())
  229682. {
  229683. Image singleChannelImage (sourceImage);
  229684. if (sourceImage.getFormat() != Image::SingleChannel)
  229685. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229686. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  229687. flip();
  229688. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229689. applyTransform (t);
  229690. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229691. CGContextClipToMask (context, r, image);
  229692. applyTransform (t.inverted());
  229693. flip();
  229694. CGImageRelease (image);
  229695. lastClipRectIsValid = false;
  229696. }
  229697. }
  229698. bool clipRegionIntersects (const Rectangle<int>& r)
  229699. {
  229700. return getClipBounds().intersects (r);
  229701. }
  229702. const Rectangle<int> getClipBounds() const
  229703. {
  229704. if (! lastClipRectIsValid)
  229705. {
  229706. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229707. lastClipRectIsValid = true;
  229708. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229709. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229710. roundToInt (bounds.size.width),
  229711. roundToInt (bounds.size.height));
  229712. }
  229713. return lastClipRect;
  229714. }
  229715. bool isClipEmpty() const
  229716. {
  229717. return getClipBounds().isEmpty();
  229718. }
  229719. void saveState()
  229720. {
  229721. CGContextSaveGState (context);
  229722. stateStack.add (new SavedState (*state));
  229723. }
  229724. void restoreState()
  229725. {
  229726. CGContextRestoreGState (context);
  229727. SavedState* const top = stateStack.getLast();
  229728. if (top != 0)
  229729. {
  229730. state = top;
  229731. stateStack.removeLast (1, false);
  229732. lastClipRectIsValid = false;
  229733. }
  229734. else
  229735. {
  229736. jassertfalse; // trying to pop with an empty stack!
  229737. }
  229738. }
  229739. void beginTransparencyLayer (float opacity)
  229740. {
  229741. saveState();
  229742. CGContextSetAlpha (context, opacity);
  229743. CGContextBeginTransparencyLayer (context, 0);
  229744. }
  229745. void endTransparencyLayer()
  229746. {
  229747. CGContextEndTransparencyLayer (context);
  229748. restoreState();
  229749. }
  229750. void setFill (const FillType& fillType)
  229751. {
  229752. state->fillType = fillType;
  229753. if (fillType.isColour())
  229754. {
  229755. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229756. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229757. CGContextSetAlpha (context, 1.0f);
  229758. }
  229759. }
  229760. void setOpacity (float newOpacity)
  229761. {
  229762. state->fillType.setOpacity (newOpacity);
  229763. setFill (state->fillType);
  229764. }
  229765. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229766. {
  229767. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229768. ? kCGInterpolationLow
  229769. : kCGInterpolationHigh);
  229770. }
  229771. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229772. {
  229773. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229774. }
  229775. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229776. {
  229777. if (replaceExistingContents)
  229778. {
  229779. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229780. CGContextClearRect (context, cgRect);
  229781. #else
  229782. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229783. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229784. CGContextClearRect (context, cgRect);
  229785. else
  229786. #endif
  229787. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229788. #endif
  229789. fillCGRect (cgRect, false);
  229790. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229791. }
  229792. else
  229793. {
  229794. if (state->fillType.isColour())
  229795. {
  229796. CGContextFillRect (context, cgRect);
  229797. }
  229798. else if (state->fillType.isGradient())
  229799. {
  229800. CGContextSaveGState (context);
  229801. CGContextClipToRect (context, cgRect);
  229802. drawGradient();
  229803. CGContextRestoreGState (context);
  229804. }
  229805. else
  229806. {
  229807. CGContextSaveGState (context);
  229808. CGContextClipToRect (context, cgRect);
  229809. drawImage (state->fillType.image, state->fillType.transform, true);
  229810. CGContextRestoreGState (context);
  229811. }
  229812. }
  229813. }
  229814. void fillPath (const Path& path, const AffineTransform& transform)
  229815. {
  229816. CGContextSaveGState (context);
  229817. if (state->fillType.isColour())
  229818. {
  229819. flip();
  229820. applyTransform (transform);
  229821. createPath (path);
  229822. if (path.isUsingNonZeroWinding())
  229823. CGContextFillPath (context);
  229824. else
  229825. CGContextEOFillPath (context);
  229826. }
  229827. else
  229828. {
  229829. createPath (path, transform);
  229830. if (path.isUsingNonZeroWinding())
  229831. CGContextClip (context);
  229832. else
  229833. CGContextEOClip (context);
  229834. if (state->fillType.isGradient())
  229835. drawGradient();
  229836. else
  229837. drawImage (state->fillType.image, state->fillType.transform, true);
  229838. }
  229839. CGContextRestoreGState (context);
  229840. }
  229841. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229842. {
  229843. const int iw = sourceImage.getWidth();
  229844. const int ih = sourceImage.getHeight();
  229845. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  229846. CGContextSaveGState (context);
  229847. CGContextSetAlpha (context, state->fillType.getOpacity());
  229848. flip();
  229849. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229850. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229851. if (fillEntireClipAsTiles)
  229852. {
  229853. #if JUCE_IOS
  229854. CGContextDrawTiledImage (context, imageRect, image);
  229855. #else
  229856. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229857. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229858. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229859. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229860. CGContextDrawTiledImage (context, imageRect, image);
  229861. else
  229862. #endif
  229863. {
  229864. // Fallback to manually doing a tiled fill on 10.4
  229865. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229866. int x = 0, y = 0;
  229867. while (x > clip.origin.x) x -= iw;
  229868. while (y > clip.origin.y) y -= ih;
  229869. const int right = (int) (clip.origin.x + clip.size.width);
  229870. const int bottom = (int) (clip.origin.y + clip.size.height);
  229871. while (y < bottom)
  229872. {
  229873. for (int x2 = x; x2 < right; x2 += iw)
  229874. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229875. y += ih;
  229876. }
  229877. }
  229878. #endif
  229879. }
  229880. else
  229881. {
  229882. CGContextDrawImage (context, imageRect, image);
  229883. }
  229884. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229885. CGContextRestoreGState (context);
  229886. }
  229887. void drawLine (const Line<float>& line)
  229888. {
  229889. if (state->fillType.isColour())
  229890. {
  229891. CGContextSetLineCap (context, kCGLineCapSquare);
  229892. CGContextSetLineWidth (context, 1.0f);
  229893. CGContextSetRGBStrokeColor (context,
  229894. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229895. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229896. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229897. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229898. CGContextStrokeLineSegments (context, cgLine, 1);
  229899. }
  229900. else
  229901. {
  229902. Path p;
  229903. p.addLineSegment (line, 1.0f);
  229904. fillPath (p, AffineTransform::identity);
  229905. }
  229906. }
  229907. void drawVerticalLine (const int x, float top, float bottom)
  229908. {
  229909. if (state->fillType.isColour())
  229910. {
  229911. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229912. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229913. #else
  229914. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229915. // the x co-ord slightly to trick it..
  229916. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229917. #endif
  229918. }
  229919. else
  229920. {
  229921. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  229922. }
  229923. }
  229924. void drawHorizontalLine (const int y, float left, float right)
  229925. {
  229926. if (state->fillType.isColour())
  229927. {
  229928. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229929. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229930. #else
  229931. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229932. // the x co-ord slightly to trick it..
  229933. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229934. #endif
  229935. }
  229936. else
  229937. {
  229938. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  229939. }
  229940. }
  229941. void setFont (const Font& newFont)
  229942. {
  229943. if (state->font != newFont)
  229944. {
  229945. state->fontRef = 0;
  229946. state->font = newFont;
  229947. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229948. if (mf != 0)
  229949. {
  229950. state->fontRef = mf->fontRef;
  229951. CGContextSetFont (context, state->fontRef);
  229952. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229953. state->fontTransform = mf->renderingTransform;
  229954. state->fontTransform.a *= state->font.getHorizontalScale();
  229955. CGContextSetTextMatrix (context, state->fontTransform);
  229956. }
  229957. }
  229958. }
  229959. const Font getFont()
  229960. {
  229961. return state->font;
  229962. }
  229963. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229964. {
  229965. if (state->fontRef != 0 && state->fillType.isColour())
  229966. {
  229967. if (transform.isOnlyTranslation())
  229968. {
  229969. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229970. CGGlyph g = glyphNumber;
  229971. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229972. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229973. }
  229974. else
  229975. {
  229976. CGContextSaveGState (context);
  229977. flip();
  229978. applyTransform (transform);
  229979. CGAffineTransform t = state->fontTransform;
  229980. t.d = -t.d;
  229981. CGContextSetTextMatrix (context, t);
  229982. CGGlyph g = glyphNumber;
  229983. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229984. CGContextRestoreGState (context);
  229985. }
  229986. }
  229987. else
  229988. {
  229989. Path p;
  229990. Font& f = state->font;
  229991. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229992. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229993. .followedBy (transform));
  229994. }
  229995. }
  229996. private:
  229997. CGContextRef context;
  229998. const CGFloat flipHeight;
  229999. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230000. CGFunctionCallbacks gradientCallbacks;
  230001. mutable Rectangle<int> lastClipRect;
  230002. mutable bool lastClipRectIsValid;
  230003. struct SavedState
  230004. {
  230005. SavedState()
  230006. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230007. {
  230008. }
  230009. SavedState (const SavedState& other)
  230010. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230011. fontTransform (other.fontTransform)
  230012. {
  230013. }
  230014. FillType fillType;
  230015. Font font;
  230016. CGFontRef fontRef;
  230017. CGAffineTransform fontTransform;
  230018. };
  230019. ScopedPointer <SavedState> state;
  230020. OwnedArray <SavedState> stateStack;
  230021. HeapBlock <PixelARGB> gradientLookupTable;
  230022. int numGradientLookupEntries;
  230023. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230024. {
  230025. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230026. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230027. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230028. colour.unpremultiply();
  230029. outData[0] = colour.getRed() / 255.0f;
  230030. outData[1] = colour.getGreen() / 255.0f;
  230031. outData[2] = colour.getBlue() / 255.0f;
  230032. outData[3] = colour.getAlpha() / 255.0f;
  230033. }
  230034. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230035. {
  230036. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230037. CGShadingRef result = 0;
  230038. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230039. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230040. if (gradient.isRadial)
  230041. {
  230042. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230043. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230044. function, true, true);
  230045. }
  230046. else
  230047. {
  230048. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230049. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230050. function, true, true);
  230051. }
  230052. CGFunctionRelease (function);
  230053. return result;
  230054. }
  230055. void drawGradient()
  230056. {
  230057. flip();
  230058. applyTransform (state->fillType.transform);
  230059. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230060. // you draw a gradient with high quality interp enabled).
  230061. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230062. CGContextSetAlpha (context, state->fillType.getOpacity());
  230063. CGContextDrawShading (context, shading);
  230064. CGShadingRelease (shading);
  230065. }
  230066. void createPath (const Path& path) const
  230067. {
  230068. CGContextBeginPath (context);
  230069. Path::Iterator i (path);
  230070. while (i.next())
  230071. {
  230072. switch (i.elementType)
  230073. {
  230074. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230075. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230076. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230077. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230078. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230079. default: jassertfalse; break;
  230080. }
  230081. }
  230082. }
  230083. void createPath (const Path& path, const AffineTransform& transform) const
  230084. {
  230085. CGContextBeginPath (context);
  230086. Path::Iterator i (path);
  230087. while (i.next())
  230088. {
  230089. switch (i.elementType)
  230090. {
  230091. case Path::Iterator::startNewSubPath:
  230092. transform.transformPoint (i.x1, i.y1);
  230093. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230094. break;
  230095. case Path::Iterator::lineTo:
  230096. transform.transformPoint (i.x1, i.y1);
  230097. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230098. break;
  230099. case Path::Iterator::quadraticTo:
  230100. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230101. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230102. break;
  230103. case Path::Iterator::cubicTo:
  230104. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230105. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230106. break;
  230107. case Path::Iterator::closePath:
  230108. CGContextClosePath (context); break;
  230109. default:
  230110. jassertfalse;
  230111. break;
  230112. }
  230113. }
  230114. }
  230115. void flip() const
  230116. {
  230117. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230118. }
  230119. void applyTransform (const AffineTransform& transform) const
  230120. {
  230121. CGAffineTransform t;
  230122. t.a = transform.mat00;
  230123. t.b = transform.mat10;
  230124. t.c = transform.mat01;
  230125. t.d = transform.mat11;
  230126. t.tx = transform.mat02;
  230127. t.ty = transform.mat12;
  230128. CGContextConcatCTM (context, t);
  230129. }
  230130. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230131. };
  230132. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230133. {
  230134. return new CoreGraphicsContext (context, height);
  230135. }
  230136. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230137. const Image juce_loadWithCoreImage (InputStream& input)
  230138. {
  230139. MemoryBlock data;
  230140. input.readIntoMemoryBlock (data, -1);
  230141. #if JUCE_IOS
  230142. JUCE_AUTORELEASEPOOL
  230143. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230144. length: data.getSize()
  230145. freeWhenDone: NO]];
  230146. if (image != nil)
  230147. {
  230148. CGImageRef loadedImage = image.CGImage;
  230149. #else
  230150. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230151. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230152. CGDataProviderRelease (provider);
  230153. if (imageSource != 0)
  230154. {
  230155. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230156. CFRelease (imageSource);
  230157. #endif
  230158. if (loadedImage != 0)
  230159. {
  230160. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230161. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230162. && alphaInfo != kCGImageAlphaNoneSkipLast
  230163. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230164. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230165. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230166. hasAlphaChan, Image::NativeImage);
  230167. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230168. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230169. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230170. CGContextFlush (cgImage->context);
  230171. #if ! JUCE_IOS
  230172. CFRelease (loadedImage);
  230173. #endif
  230174. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230175. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230176. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230177. return image;
  230178. }
  230179. }
  230180. return Image::null;
  230181. }
  230182. #endif
  230183. #endif
  230184. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230185. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230186. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230187. // compiled on its own).
  230188. #if JUCE_INCLUDED_FILE
  230189. class NSViewComponentPeer;
  230190. END_JUCE_NAMESPACE
  230191. @interface NSEvent (JuceDeviceDelta)
  230192. - (float) deviceDeltaX;
  230193. - (float) deviceDeltaY;
  230194. @end
  230195. #define JuceNSView MakeObjCClassName(JuceNSView)
  230196. @interface JuceNSView : NSView<NSTextInput>
  230197. {
  230198. @public
  230199. NSViewComponentPeer* owner;
  230200. NSNotificationCenter* notificationCenter;
  230201. String* stringBeingComposed;
  230202. bool textWasInserted;
  230203. }
  230204. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230205. - (void) dealloc;
  230206. - (BOOL) isOpaque;
  230207. - (void) drawRect: (NSRect) r;
  230208. - (void) mouseDown: (NSEvent*) ev;
  230209. - (void) asyncMouseDown: (NSEvent*) ev;
  230210. - (void) mouseUp: (NSEvent*) ev;
  230211. - (void) asyncMouseUp: (NSEvent*) ev;
  230212. - (void) mouseDragged: (NSEvent*) ev;
  230213. - (void) mouseMoved: (NSEvent*) ev;
  230214. - (void) mouseEntered: (NSEvent*) ev;
  230215. - (void) mouseExited: (NSEvent*) ev;
  230216. - (void) rightMouseDown: (NSEvent*) ev;
  230217. - (void) rightMouseDragged: (NSEvent*) ev;
  230218. - (void) rightMouseUp: (NSEvent*) ev;
  230219. - (void) otherMouseDown: (NSEvent*) ev;
  230220. - (void) otherMouseDragged: (NSEvent*) ev;
  230221. - (void) otherMouseUp: (NSEvent*) ev;
  230222. - (void) scrollWheel: (NSEvent*) ev;
  230223. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230224. - (void) frameChanged: (NSNotification*) n;
  230225. - (void) viewDidMoveToWindow;
  230226. - (void) keyDown: (NSEvent*) ev;
  230227. - (void) keyUp: (NSEvent*) ev;
  230228. // NSTextInput Methods
  230229. - (void) insertText: (id) aString;
  230230. - (void) doCommandBySelector: (SEL) aSelector;
  230231. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230232. - (void) unmarkText;
  230233. - (BOOL) hasMarkedText;
  230234. - (long) conversationIdentifier;
  230235. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230236. - (NSRange) markedRange;
  230237. - (NSRange) selectedRange;
  230238. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230239. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230240. - (NSArray*) validAttributesForMarkedText;
  230241. - (void) flagsChanged: (NSEvent*) ev;
  230242. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230243. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230244. #endif
  230245. - (BOOL) becomeFirstResponder;
  230246. - (BOOL) resignFirstResponder;
  230247. - (BOOL) acceptsFirstResponder;
  230248. - (void) asyncRepaint: (id) rect;
  230249. - (NSArray*) getSupportedDragTypes;
  230250. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230251. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230252. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230253. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230254. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230255. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230256. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230257. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230258. @end
  230259. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230260. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230261. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230262. #else
  230263. @interface JuceNSWindow : NSWindow
  230264. #endif
  230265. {
  230266. @private
  230267. NSViewComponentPeer* owner;
  230268. bool isZooming;
  230269. }
  230270. - (void) setOwner: (NSViewComponentPeer*) owner;
  230271. - (BOOL) canBecomeKeyWindow;
  230272. - (void) becomeKeyWindow;
  230273. - (BOOL) windowShouldClose: (id) window;
  230274. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230275. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230276. - (void) zoom: (id) sender;
  230277. @end
  230278. BEGIN_JUCE_NAMESPACE
  230279. class NSViewComponentPeer : public ComponentPeer
  230280. {
  230281. public:
  230282. NSViewComponentPeer (Component* const component,
  230283. const int windowStyleFlags,
  230284. NSView* viewToAttachTo);
  230285. ~NSViewComponentPeer();
  230286. void* getNativeHandle() const;
  230287. void setVisible (bool shouldBeVisible);
  230288. void setTitle (const String& title);
  230289. void setPosition (int x, int y);
  230290. void setSize (int w, int h);
  230291. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230292. const Rectangle<int> getBounds (const bool global) const;
  230293. const Rectangle<int> getBounds() const;
  230294. const Point<int> getScreenPosition() const;
  230295. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230296. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230297. void setAlpha (float newAlpha);
  230298. void setMinimised (bool shouldBeMinimised);
  230299. bool isMinimised() const;
  230300. void setFullScreen (bool shouldBeFullScreen);
  230301. bool isFullScreen() const;
  230302. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230303. const BorderSize<int> getFrameSize() const;
  230304. bool setAlwaysOnTop (bool alwaysOnTop);
  230305. void toFront (bool makeActiveWindow);
  230306. void toBehind (ComponentPeer* other);
  230307. void setIcon (const Image& newIcon);
  230308. const StringArray getAvailableRenderingEngines();
  230309. int getCurrentRenderingEngine() throw();
  230310. void setCurrentRenderingEngine (int index);
  230311. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230312. for example having more than one juce plugin loaded into a host, then when a
  230313. method is called, the actual code that runs might actually be in a different module
  230314. than the one you expect... So any calls to library functions or statics that are
  230315. made inside obj-c methods will probably end up getting executed in a different DLL's
  230316. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230317. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230318. virtual methods of an object that's known to live inside the right module's space.
  230319. */
  230320. virtual void redirectMouseDown (NSEvent* ev);
  230321. virtual void redirectMouseUp (NSEvent* ev);
  230322. virtual void redirectMouseDrag (NSEvent* ev);
  230323. virtual void redirectMouseMove (NSEvent* ev);
  230324. virtual void redirectMouseEnter (NSEvent* ev);
  230325. virtual void redirectMouseExit (NSEvent* ev);
  230326. virtual void redirectMouseWheel (NSEvent* ev);
  230327. void sendMouseEvent (NSEvent* ev);
  230328. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230329. virtual bool redirectKeyDown (NSEvent* ev);
  230330. virtual bool redirectKeyUp (NSEvent* ev);
  230331. virtual void redirectModKeyChange (NSEvent* ev);
  230332. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230333. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230334. #endif
  230335. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230336. virtual bool isOpaque();
  230337. virtual void drawRect (NSRect r);
  230338. virtual bool canBecomeKeyWindow();
  230339. virtual bool windowShouldClose();
  230340. virtual void redirectMovedOrResized();
  230341. virtual void viewMovedToWindow();
  230342. virtual NSRect constrainRect (NSRect r);
  230343. static void showArrowCursorIfNeeded();
  230344. static void updateModifiers (NSEvent* e);
  230345. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230346. static int getKeyCodeFromEvent (NSEvent* ev)
  230347. {
  230348. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230349. int keyCode = unmodified[0];
  230350. if (keyCode == 0x19) // (backwards-tab)
  230351. keyCode = '\t';
  230352. else if (keyCode == 0x03) // (enter)
  230353. keyCode = '\r';
  230354. else
  230355. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230356. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230357. {
  230358. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230359. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230360. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230361. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230362. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230363. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230364. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230365. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230366. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230367. if (keyCode == numPadConversions [i])
  230368. keyCode = numPadConversions [i + 1];
  230369. }
  230370. return keyCode;
  230371. }
  230372. static int64 getMouseTime (NSEvent* e)
  230373. {
  230374. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230375. + (int64) ([e timestamp] * 1000.0);
  230376. }
  230377. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230378. {
  230379. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230380. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230381. }
  230382. static int getModifierForButtonNumber (const NSInteger num)
  230383. {
  230384. return num == 0 ? ModifierKeys::leftButtonModifier
  230385. : (num == 1 ? ModifierKeys::rightButtonModifier
  230386. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230387. }
  230388. virtual void viewFocusGain();
  230389. virtual void viewFocusLoss();
  230390. bool isFocused() const;
  230391. void grabFocus();
  230392. void textInputRequired (const Point<int>& position);
  230393. void repaint (const Rectangle<int>& area);
  230394. void performAnyPendingRepaintsNow();
  230395. NSWindow* window;
  230396. JuceNSView* view;
  230397. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230398. static ModifierKeys currentModifiers;
  230399. static ComponentPeer* currentlyFocusedPeer;
  230400. static Array<int> keysCurrentlyDown;
  230401. private:
  230402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230403. };
  230404. END_JUCE_NAMESPACE
  230405. @implementation JuceNSView
  230406. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230407. withFrame: (NSRect) frame
  230408. {
  230409. [super initWithFrame: frame];
  230410. owner = owner_;
  230411. stringBeingComposed = 0;
  230412. textWasInserted = false;
  230413. notificationCenter = [NSNotificationCenter defaultCenter];
  230414. [notificationCenter addObserver: self
  230415. selector: @selector (frameChanged:)
  230416. name: NSViewFrameDidChangeNotification
  230417. object: self];
  230418. if (! owner_->isSharedWindow)
  230419. {
  230420. [notificationCenter addObserver: self
  230421. selector: @selector (frameChanged:)
  230422. name: NSWindowDidMoveNotification
  230423. object: owner_->window];
  230424. }
  230425. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230426. return self;
  230427. }
  230428. - (void) dealloc
  230429. {
  230430. [notificationCenter removeObserver: self];
  230431. delete stringBeingComposed;
  230432. [super dealloc];
  230433. }
  230434. - (void) drawRect: (NSRect) r
  230435. {
  230436. if (owner != 0)
  230437. owner->drawRect (r);
  230438. }
  230439. - (BOOL) isOpaque
  230440. {
  230441. return owner == 0 || owner->isOpaque();
  230442. }
  230443. - (void) mouseDown: (NSEvent*) ev
  230444. {
  230445. if (JUCEApplication::isStandaloneApp())
  230446. [self asyncMouseDown: ev];
  230447. else
  230448. // In some host situations, the host will stop modal loops from working
  230449. // correctly if they're called from a mouse event, so we'll trigger
  230450. // the event asynchronously..
  230451. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230452. withObject: ev
  230453. waitUntilDone: NO];
  230454. }
  230455. - (void) asyncMouseDown: (NSEvent*) ev
  230456. {
  230457. if (owner != 0)
  230458. owner->redirectMouseDown (ev);
  230459. }
  230460. - (void) mouseUp: (NSEvent*) ev
  230461. {
  230462. if (! JUCEApplication::isStandaloneApp())
  230463. [self asyncMouseUp: ev];
  230464. else
  230465. // In some host situations, the host will stop modal loops from working
  230466. // correctly if they're called from a mouse event, so we'll trigger
  230467. // the event asynchronously..
  230468. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230469. withObject: ev
  230470. waitUntilDone: NO];
  230471. }
  230472. - (void) asyncMouseUp: (NSEvent*) ev
  230473. {
  230474. if (owner != 0)
  230475. owner->redirectMouseUp (ev);
  230476. }
  230477. - (void) mouseDragged: (NSEvent*) ev
  230478. {
  230479. if (owner != 0)
  230480. owner->redirectMouseDrag (ev);
  230481. }
  230482. - (void) mouseMoved: (NSEvent*) ev
  230483. {
  230484. if (owner != 0)
  230485. owner->redirectMouseMove (ev);
  230486. }
  230487. - (void) mouseEntered: (NSEvent*) ev
  230488. {
  230489. if (owner != 0)
  230490. owner->redirectMouseEnter (ev);
  230491. }
  230492. - (void) mouseExited: (NSEvent*) ev
  230493. {
  230494. if (owner != 0)
  230495. owner->redirectMouseExit (ev);
  230496. }
  230497. - (void) rightMouseDown: (NSEvent*) ev
  230498. {
  230499. [self mouseDown: ev];
  230500. }
  230501. - (void) rightMouseDragged: (NSEvent*) ev
  230502. {
  230503. [self mouseDragged: ev];
  230504. }
  230505. - (void) rightMouseUp: (NSEvent*) ev
  230506. {
  230507. [self mouseUp: ev];
  230508. }
  230509. - (void) otherMouseDown: (NSEvent*) ev
  230510. {
  230511. [self mouseDown: ev];
  230512. }
  230513. - (void) otherMouseDragged: (NSEvent*) ev
  230514. {
  230515. [self mouseDragged: ev];
  230516. }
  230517. - (void) otherMouseUp: (NSEvent*) ev
  230518. {
  230519. [self mouseUp: ev];
  230520. }
  230521. - (void) scrollWheel: (NSEvent*) ev
  230522. {
  230523. if (owner != 0)
  230524. owner->redirectMouseWheel (ev);
  230525. }
  230526. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230527. {
  230528. (void) ev;
  230529. return YES;
  230530. }
  230531. - (void) frameChanged: (NSNotification*) n
  230532. {
  230533. (void) n;
  230534. if (owner != 0)
  230535. owner->redirectMovedOrResized();
  230536. }
  230537. - (void) viewDidMoveToWindow
  230538. {
  230539. if (owner != 0)
  230540. owner->viewMovedToWindow();
  230541. }
  230542. - (void) asyncRepaint: (id) rect
  230543. {
  230544. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230545. [self setNeedsDisplayInRect: *r];
  230546. }
  230547. - (void) keyDown: (NSEvent*) ev
  230548. {
  230549. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230550. textWasInserted = false;
  230551. if (target != 0)
  230552. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230553. else
  230554. deleteAndZero (stringBeingComposed);
  230555. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230556. [super keyDown: ev];
  230557. }
  230558. - (void) keyUp: (NSEvent*) ev
  230559. {
  230560. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230561. [super keyUp: ev];
  230562. }
  230563. - (void) insertText: (id) aString
  230564. {
  230565. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230566. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230567. if ([newText length] > 0)
  230568. {
  230569. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230570. if (target != 0)
  230571. {
  230572. target->insertTextAtCaret (nsStringToJuce (newText));
  230573. textWasInserted = true;
  230574. }
  230575. }
  230576. deleteAndZero (stringBeingComposed);
  230577. }
  230578. - (void) doCommandBySelector: (SEL) aSelector
  230579. {
  230580. (void) aSelector;
  230581. }
  230582. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230583. {
  230584. (void) selectionRange;
  230585. if (stringBeingComposed == 0)
  230586. stringBeingComposed = new String();
  230587. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230588. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230589. if (target != 0)
  230590. {
  230591. const Range<int> currentHighlight (target->getHighlightedRegion());
  230592. target->insertTextAtCaret (*stringBeingComposed);
  230593. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230594. textWasInserted = true;
  230595. }
  230596. }
  230597. - (void) unmarkText
  230598. {
  230599. if (stringBeingComposed != 0)
  230600. {
  230601. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230602. if (target != 0)
  230603. {
  230604. target->insertTextAtCaret (*stringBeingComposed);
  230605. textWasInserted = true;
  230606. }
  230607. }
  230608. deleteAndZero (stringBeingComposed);
  230609. }
  230610. - (BOOL) hasMarkedText
  230611. {
  230612. return stringBeingComposed != 0;
  230613. }
  230614. - (long) conversationIdentifier
  230615. {
  230616. return (long) (pointer_sized_int) self;
  230617. }
  230618. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230619. {
  230620. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230621. if (target != 0)
  230622. {
  230623. const Range<int> r ((int) theRange.location,
  230624. (int) (theRange.location + theRange.length));
  230625. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230626. }
  230627. return nil;
  230628. }
  230629. - (NSRange) markedRange
  230630. {
  230631. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230632. : NSMakeRange (NSNotFound, 0);
  230633. }
  230634. - (NSRange) selectedRange
  230635. {
  230636. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230637. if (target != 0)
  230638. {
  230639. const Range<int> highlight (target->getHighlightedRegion());
  230640. if (! highlight.isEmpty())
  230641. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230642. }
  230643. return NSMakeRange (NSNotFound, 0);
  230644. }
  230645. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230646. {
  230647. (void) theRange;
  230648. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230649. if (comp == 0)
  230650. return NSMakeRect (0, 0, 0, 0);
  230651. const Rectangle<int> bounds (comp->getScreenBounds());
  230652. return NSMakeRect (bounds.getX(),
  230653. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230654. bounds.getWidth(),
  230655. bounds.getHeight());
  230656. }
  230657. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230658. {
  230659. (void) thePoint;
  230660. return NSNotFound;
  230661. }
  230662. - (NSArray*) validAttributesForMarkedText
  230663. {
  230664. return [NSArray array];
  230665. }
  230666. - (void) flagsChanged: (NSEvent*) ev
  230667. {
  230668. if (owner != 0)
  230669. owner->redirectModKeyChange (ev);
  230670. }
  230671. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230672. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230673. {
  230674. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230675. return true;
  230676. return [super performKeyEquivalent: ev];
  230677. }
  230678. #endif
  230679. - (BOOL) becomeFirstResponder
  230680. {
  230681. if (owner != 0)
  230682. owner->viewFocusGain();
  230683. return true;
  230684. }
  230685. - (BOOL) resignFirstResponder
  230686. {
  230687. if (owner != 0)
  230688. owner->viewFocusLoss();
  230689. return true;
  230690. }
  230691. - (BOOL) acceptsFirstResponder
  230692. {
  230693. return owner != 0 && owner->canBecomeKeyWindow();
  230694. }
  230695. - (NSArray*) getSupportedDragTypes
  230696. {
  230697. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230698. }
  230699. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230700. {
  230701. return owner != 0 && owner->sendDragCallback (type, sender);
  230702. }
  230703. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230704. {
  230705. if ([self sendDragCallback: 0 sender: sender])
  230706. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230707. else
  230708. return NSDragOperationNone;
  230709. }
  230710. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230711. {
  230712. if ([self sendDragCallback: 0 sender: sender])
  230713. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230714. else
  230715. return NSDragOperationNone;
  230716. }
  230717. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230718. {
  230719. [self sendDragCallback: 1 sender: sender];
  230720. }
  230721. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230722. {
  230723. [self sendDragCallback: 1 sender: sender];
  230724. }
  230725. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230726. {
  230727. (void) sender;
  230728. return YES;
  230729. }
  230730. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230731. {
  230732. return [self sendDragCallback: 2 sender: sender];
  230733. }
  230734. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230735. {
  230736. (void) sender;
  230737. }
  230738. @end
  230739. @implementation JuceNSWindow
  230740. - (void) setOwner: (NSViewComponentPeer*) owner_
  230741. {
  230742. owner = owner_;
  230743. isZooming = false;
  230744. }
  230745. - (BOOL) canBecomeKeyWindow
  230746. {
  230747. return owner != 0 && owner->canBecomeKeyWindow();
  230748. }
  230749. - (void) becomeKeyWindow
  230750. {
  230751. [super becomeKeyWindow];
  230752. if (owner != 0)
  230753. owner->grabFocus();
  230754. }
  230755. - (BOOL) windowShouldClose: (id) window
  230756. {
  230757. (void) window;
  230758. return owner == 0 || owner->windowShouldClose();
  230759. }
  230760. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230761. {
  230762. (void) screen;
  230763. if (owner != 0)
  230764. frameRect = owner->constrainRect (frameRect);
  230765. return frameRect;
  230766. }
  230767. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230768. {
  230769. (void) window;
  230770. if (isZooming)
  230771. return proposedFrameSize;
  230772. NSRect frameRect = [self frame];
  230773. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230774. frameRect.size = proposedFrameSize;
  230775. if (owner != 0)
  230776. frameRect = owner->constrainRect (frameRect);
  230777. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230778. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230779. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230780. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230781. return frameRect.size;
  230782. }
  230783. - (void) zoom: (id) sender
  230784. {
  230785. isZooming = true;
  230786. [super zoom: sender];
  230787. isZooming = false;
  230788. }
  230789. - (void) windowWillMove: (NSNotification*) notification
  230790. {
  230791. (void) notification;
  230792. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230793. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230794. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230795. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230796. }
  230797. @end
  230798. BEGIN_JUCE_NAMESPACE
  230799. ModifierKeys NSViewComponentPeer::currentModifiers;
  230800. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230801. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230802. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230803. {
  230804. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230805. return true;
  230806. if (keyCode >= 'A' && keyCode <= 'Z'
  230807. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230808. return true;
  230809. if (keyCode >= 'a' && keyCode <= 'z'
  230810. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230811. return true;
  230812. return false;
  230813. }
  230814. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230815. {
  230816. int m = 0;
  230817. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230818. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230819. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230820. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230821. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230822. }
  230823. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230824. {
  230825. updateModifiers (ev);
  230826. int keyCode = getKeyCodeFromEvent (ev);
  230827. if (keyCode != 0)
  230828. {
  230829. if (isKeyDown)
  230830. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230831. else
  230832. keysCurrentlyDown.removeValue (keyCode);
  230833. }
  230834. }
  230835. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230836. {
  230837. return NSViewComponentPeer::currentModifiers;
  230838. }
  230839. void ModifierKeys::updateCurrentModifiers() throw()
  230840. {
  230841. currentModifiers = NSViewComponentPeer::currentModifiers;
  230842. }
  230843. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230844. const int windowStyleFlags,
  230845. NSView* viewToAttachTo)
  230846. : ComponentPeer (component_, windowStyleFlags),
  230847. window (0),
  230848. view (0),
  230849. isSharedWindow (viewToAttachTo != 0),
  230850. fullScreen (false),
  230851. insideDrawRect (false),
  230852. #if USE_COREGRAPHICS_RENDERING
  230853. usingCoreGraphics (true),
  230854. #else
  230855. usingCoreGraphics (false),
  230856. #endif
  230857. recursiveToFrontCall (false)
  230858. {
  230859. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  230860. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230861. [view setPostsFrameChangedNotifications: YES];
  230862. if (isSharedWindow)
  230863. {
  230864. window = [viewToAttachTo window];
  230865. [viewToAttachTo addSubview: view];
  230866. }
  230867. else
  230868. {
  230869. r.origin.x = (float) component->getX();
  230870. r.origin.y = (float) component->getY();
  230871. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230872. unsigned int style = 0;
  230873. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230874. style = NSBorderlessWindowMask;
  230875. else
  230876. style = NSTitledWindowMask;
  230877. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230878. style |= NSMiniaturizableWindowMask;
  230879. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230880. style |= NSClosableWindowMask;
  230881. if ((windowStyleFlags & windowIsResizable) != 0)
  230882. style |= NSResizableWindowMask;
  230883. window = [[JuceNSWindow alloc] initWithContentRect: r
  230884. styleMask: style
  230885. backing: NSBackingStoreBuffered
  230886. defer: YES];
  230887. [((JuceNSWindow*) window) setOwner: this];
  230888. [window orderOut: nil];
  230889. [window setDelegate: (JuceNSWindow*) window];
  230890. [window setOpaque: component->isOpaque()];
  230891. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230892. if (component->isAlwaysOnTop())
  230893. [window setLevel: NSFloatingWindowLevel];
  230894. [window setContentView: view];
  230895. [window setAutodisplay: YES];
  230896. [window setAcceptsMouseMovedEvents: YES];
  230897. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230898. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230899. [window setReleasedWhenClosed: YES];
  230900. [window retain];
  230901. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230902. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230903. }
  230904. const float alpha = component->getAlpha();
  230905. if (alpha < 1.0f)
  230906. setAlpha (alpha);
  230907. setTitle (component->getName());
  230908. }
  230909. NSViewComponentPeer::~NSViewComponentPeer()
  230910. {
  230911. view->owner = 0;
  230912. [view removeFromSuperview];
  230913. [view release];
  230914. if (! isSharedWindow)
  230915. {
  230916. [((JuceNSWindow*) window) setOwner: 0];
  230917. [window close];
  230918. [window release];
  230919. }
  230920. }
  230921. void* NSViewComponentPeer::getNativeHandle() const
  230922. {
  230923. return view;
  230924. }
  230925. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230926. {
  230927. if (isSharedWindow)
  230928. {
  230929. [view setHidden: ! shouldBeVisible];
  230930. }
  230931. else
  230932. {
  230933. if (shouldBeVisible)
  230934. {
  230935. [window orderFront: nil];
  230936. handleBroughtToFront();
  230937. }
  230938. else
  230939. {
  230940. [window orderOut: nil];
  230941. }
  230942. }
  230943. }
  230944. void NSViewComponentPeer::setTitle (const String& title)
  230945. {
  230946. const ScopedAutoReleasePool pool;
  230947. if (! isSharedWindow)
  230948. [window setTitle: juceStringToNS (title)];
  230949. }
  230950. void NSViewComponentPeer::setPosition (int x, int y)
  230951. {
  230952. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230953. }
  230954. void NSViewComponentPeer::setSize (int w, int h)
  230955. {
  230956. setBounds (component->getX(), component->getY(), w, h, false);
  230957. }
  230958. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230959. {
  230960. fullScreen = isNowFullScreen;
  230961. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  230962. if (isSharedWindow)
  230963. {
  230964. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230965. if ([view frame].size.width != r.size.width
  230966. || [view frame].size.height != r.size.height)
  230967. [view setNeedsDisplay: true];
  230968. [view setFrame: r];
  230969. }
  230970. else
  230971. {
  230972. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230973. [window setFrame: [window frameRectForContentRect: r]
  230974. display: true];
  230975. }
  230976. }
  230977. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230978. {
  230979. NSRect r = [view frame];
  230980. if (global && [view window] != 0)
  230981. {
  230982. r = [view convertRect: r toView: nil];
  230983. NSRect wr = [[view window] frame];
  230984. r.origin.x += wr.origin.x;
  230985. r.origin.y += wr.origin.y;
  230986. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230987. }
  230988. else
  230989. {
  230990. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230991. }
  230992. return Rectangle<int> (convertToRectInt (r));
  230993. }
  230994. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230995. {
  230996. return getBounds (! isSharedWindow);
  230997. }
  230998. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230999. {
  231000. return getBounds (true).getPosition();
  231001. }
  231002. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231003. {
  231004. return relativePosition + getScreenPosition();
  231005. }
  231006. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231007. {
  231008. return screenPosition - getScreenPosition();
  231009. }
  231010. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231011. {
  231012. if (constrainer != 0)
  231013. {
  231014. NSRect current = [window frame];
  231015. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231016. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231017. Rectangle<int> pos (convertToRectInt (r));
  231018. Rectangle<int> original (convertToRectInt (current));
  231019. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231020. if ([window inLiveResize])
  231021. #else
  231022. if ([window respondsToSelector: @selector (inLiveResize)]
  231023. && [window performSelector: @selector (inLiveResize)])
  231024. #endif
  231025. {
  231026. constrainer->checkBounds (pos, original,
  231027. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231028. false, false, true, true);
  231029. }
  231030. else
  231031. {
  231032. constrainer->checkBounds (pos, original,
  231033. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231034. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231035. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231036. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231037. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231038. }
  231039. r.origin.x = pos.getX();
  231040. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231041. r.size.width = pos.getWidth();
  231042. r.size.height = pos.getHeight();
  231043. }
  231044. return r;
  231045. }
  231046. void NSViewComponentPeer::setAlpha (float newAlpha)
  231047. {
  231048. if (! isSharedWindow)
  231049. [window setAlphaValue: (CGFloat) newAlpha];
  231050. else
  231051. [view setAlphaValue: (CGFloat) newAlpha];
  231052. }
  231053. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231054. {
  231055. if (! isSharedWindow)
  231056. {
  231057. if (shouldBeMinimised)
  231058. [window miniaturize: nil];
  231059. else
  231060. [window deminiaturize: nil];
  231061. }
  231062. }
  231063. bool NSViewComponentPeer::isMinimised() const
  231064. {
  231065. return window != 0 && [window isMiniaturized];
  231066. }
  231067. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231068. {
  231069. if (! isSharedWindow)
  231070. {
  231071. Rectangle<int> r (lastNonFullscreenBounds);
  231072. setMinimised (false);
  231073. if (fullScreen != shouldBeFullScreen)
  231074. {
  231075. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231076. {
  231077. fullScreen = true;
  231078. [window performZoom: nil];
  231079. }
  231080. else
  231081. {
  231082. if (shouldBeFullScreen)
  231083. r = Desktop::getInstance().getMainMonitorArea();
  231084. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231085. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231086. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231087. }
  231088. }
  231089. }
  231090. }
  231091. bool NSViewComponentPeer::isFullScreen() const
  231092. {
  231093. return fullScreen;
  231094. }
  231095. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231096. {
  231097. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231098. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231099. return false;
  231100. NSPoint p;
  231101. p.x = (float) position.getX();
  231102. p.y = (float) position.getY();
  231103. NSView* v = [view hitTest: p];
  231104. if (trueIfInAChildWindow)
  231105. return v != nil;
  231106. return v == view;
  231107. }
  231108. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231109. {
  231110. BorderSize<int> b;
  231111. if (! isSharedWindow)
  231112. {
  231113. NSRect v = [view convertRect: [view frame] toView: nil];
  231114. NSRect w = [window frame];
  231115. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231116. b.setBottom ((int) v.origin.y);
  231117. b.setLeft ((int) v.origin.x);
  231118. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231119. }
  231120. return b;
  231121. }
  231122. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231123. {
  231124. if (! isSharedWindow)
  231125. {
  231126. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231127. : NSNormalWindowLevel];
  231128. }
  231129. return true;
  231130. }
  231131. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231132. {
  231133. if (isSharedWindow)
  231134. {
  231135. [[view superview] addSubview: view
  231136. positioned: NSWindowAbove
  231137. relativeTo: nil];
  231138. }
  231139. if (window != 0 && component->isVisible())
  231140. {
  231141. if (makeActiveWindow)
  231142. [window makeKeyAndOrderFront: nil];
  231143. else
  231144. [window orderFront: nil];
  231145. if (! recursiveToFrontCall)
  231146. {
  231147. recursiveToFrontCall = true;
  231148. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231149. handleBroughtToFront();
  231150. recursiveToFrontCall = false;
  231151. }
  231152. }
  231153. }
  231154. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231155. {
  231156. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231157. jassert (otherPeer != 0); // wrong type of window?
  231158. if (otherPeer != 0)
  231159. {
  231160. if (isSharedWindow)
  231161. {
  231162. [[view superview] addSubview: view
  231163. positioned: NSWindowBelow
  231164. relativeTo: otherPeer->view];
  231165. }
  231166. else
  231167. {
  231168. [window orderWindow: NSWindowBelow
  231169. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231170. : nil ];
  231171. }
  231172. }
  231173. }
  231174. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231175. {
  231176. // to do..
  231177. }
  231178. void NSViewComponentPeer::viewFocusGain()
  231179. {
  231180. if (currentlyFocusedPeer != this)
  231181. {
  231182. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231183. currentlyFocusedPeer->handleFocusLoss();
  231184. currentlyFocusedPeer = this;
  231185. handleFocusGain();
  231186. }
  231187. }
  231188. void NSViewComponentPeer::viewFocusLoss()
  231189. {
  231190. if (currentlyFocusedPeer == this)
  231191. {
  231192. currentlyFocusedPeer = 0;
  231193. handleFocusLoss();
  231194. }
  231195. }
  231196. void juce_HandleProcessFocusChange()
  231197. {
  231198. NSViewComponentPeer::keysCurrentlyDown.clear();
  231199. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231200. {
  231201. if (Process::isForegroundProcess())
  231202. {
  231203. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231204. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231205. }
  231206. else
  231207. {
  231208. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231209. // turn kiosk mode off if we lose focus..
  231210. Desktop::getInstance().setKioskModeComponent (0);
  231211. }
  231212. }
  231213. }
  231214. bool NSViewComponentPeer::isFocused() const
  231215. {
  231216. return isSharedWindow ? this == currentlyFocusedPeer
  231217. : (window != 0 && [window isKeyWindow]);
  231218. }
  231219. void NSViewComponentPeer::grabFocus()
  231220. {
  231221. if (window != 0)
  231222. {
  231223. [window makeKeyWindow];
  231224. [window makeFirstResponder: view];
  231225. viewFocusGain();
  231226. }
  231227. }
  231228. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231229. {
  231230. }
  231231. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231232. {
  231233. String unicode (nsStringToJuce ([ev characters]));
  231234. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231235. int keyCode = getKeyCodeFromEvent (ev);
  231236. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231237. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231238. if (unicode.isNotEmpty() || keyCode != 0)
  231239. {
  231240. if (isKeyDown)
  231241. {
  231242. bool used = false;
  231243. while (unicode.length() > 0)
  231244. {
  231245. juce_wchar textCharacter = unicode[0];
  231246. unicode = unicode.substring (1);
  231247. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231248. textCharacter = 0;
  231249. used = handleKeyUpOrDown (true) || used;
  231250. used = handleKeyPress (keyCode, textCharacter) || used;
  231251. }
  231252. return used;
  231253. }
  231254. else
  231255. {
  231256. if (handleKeyUpOrDown (false))
  231257. return true;
  231258. }
  231259. }
  231260. return false;
  231261. }
  231262. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231263. {
  231264. updateKeysDown (ev, true);
  231265. bool used = handleKeyEvent (ev, true);
  231266. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231267. {
  231268. // for command keys, the key-up event is thrown away, so simulate one..
  231269. updateKeysDown (ev, false);
  231270. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231271. }
  231272. // (If we're running modally, don't allow unused keystrokes to be passed
  231273. // along to other blocked views..)
  231274. if (Component::getCurrentlyModalComponent() != 0)
  231275. used = true;
  231276. return used;
  231277. }
  231278. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231279. {
  231280. updateKeysDown (ev, false);
  231281. return handleKeyEvent (ev, false)
  231282. || Component::getCurrentlyModalComponent() != 0;
  231283. }
  231284. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231285. {
  231286. keysCurrentlyDown.clear();
  231287. handleKeyUpOrDown (true);
  231288. updateModifiers (ev);
  231289. handleModifierKeysChange();
  231290. }
  231291. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231292. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231293. {
  231294. if ([ev type] == NSKeyDown)
  231295. return redirectKeyDown (ev);
  231296. else if ([ev type] == NSKeyUp)
  231297. return redirectKeyUp (ev);
  231298. return false;
  231299. }
  231300. #endif
  231301. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231302. {
  231303. updateModifiers (ev);
  231304. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231305. }
  231306. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231307. {
  231308. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231309. sendMouseEvent (ev);
  231310. }
  231311. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231312. {
  231313. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231314. sendMouseEvent (ev);
  231315. showArrowCursorIfNeeded();
  231316. }
  231317. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231318. {
  231319. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231320. sendMouseEvent (ev);
  231321. }
  231322. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231323. {
  231324. currentModifiers = currentModifiers.withoutMouseButtons();
  231325. sendMouseEvent (ev);
  231326. showArrowCursorIfNeeded();
  231327. }
  231328. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231329. {
  231330. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231331. currentModifiers = currentModifiers.withoutMouseButtons();
  231332. sendMouseEvent (ev);
  231333. }
  231334. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231335. {
  231336. currentModifiers = currentModifiers.withoutMouseButtons();
  231337. sendMouseEvent (ev);
  231338. }
  231339. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231340. {
  231341. updateModifiers (ev);
  231342. float x = 0, y = 0;
  231343. @try
  231344. {
  231345. x = [ev deviceDeltaX] * 0.5f;
  231346. y = [ev deviceDeltaY] * 0.5f;
  231347. }
  231348. @catch (...)
  231349. {}
  231350. if (x == 0 && y == 0)
  231351. {
  231352. x = [ev deltaX] * 10.0f;
  231353. y = [ev deltaY] * 10.0f;
  231354. }
  231355. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231356. }
  231357. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231358. {
  231359. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231360. if (mouse.getComponentUnderMouse() == 0
  231361. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231362. {
  231363. [[NSCursor arrowCursor] set];
  231364. }
  231365. }
  231366. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231367. {
  231368. NSString* bestType
  231369. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231370. if (bestType == nil)
  231371. return false;
  231372. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231373. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231374. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231375. if (list == nil)
  231376. return false;
  231377. StringArray files;
  231378. if ([list isKindOfClass: [NSArray class]])
  231379. {
  231380. NSArray* items = (NSArray*) list;
  231381. for (unsigned int i = 0; i < [items count]; ++i)
  231382. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231383. }
  231384. if (files.size() == 0)
  231385. return false;
  231386. if (type == 0)
  231387. handleFileDragMove (files, pos);
  231388. else if (type == 1)
  231389. handleFileDragExit (files);
  231390. else if (type == 2)
  231391. handleFileDragDrop (files, pos);
  231392. return true;
  231393. }
  231394. bool NSViewComponentPeer::isOpaque()
  231395. {
  231396. return component == 0 || component->isOpaque();
  231397. }
  231398. void NSViewComponentPeer::drawRect (NSRect r)
  231399. {
  231400. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231401. return;
  231402. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231403. if (! component->isOpaque())
  231404. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231405. #if USE_COREGRAPHICS_RENDERING
  231406. if (usingCoreGraphics)
  231407. {
  231408. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231409. insideDrawRect = true;
  231410. handlePaint (context);
  231411. insideDrawRect = false;
  231412. }
  231413. else
  231414. #endif
  231415. {
  231416. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231417. (int) (r.size.width + 0.5f),
  231418. (int) (r.size.height + 0.5f),
  231419. ! getComponent()->isOpaque());
  231420. const int xOffset = -roundToInt (r.origin.x);
  231421. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231422. const NSRect* rects = 0;
  231423. NSInteger numRects = 0;
  231424. [view getRectsBeingDrawn: &rects count: &numRects];
  231425. const Rectangle<int> clipBounds (temp.getBounds());
  231426. RectangleList clip;
  231427. for (int i = 0; i < numRects; ++i)
  231428. {
  231429. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231430. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231431. roundToInt (rects[i].size.width),
  231432. roundToInt (rects[i].size.height))));
  231433. }
  231434. if (! clip.isEmpty())
  231435. {
  231436. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231437. insideDrawRect = true;
  231438. handlePaint (context);
  231439. insideDrawRect = false;
  231440. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231441. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  231442. CGColorSpaceRelease (colourSpace);
  231443. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231444. CGImageRelease (image);
  231445. }
  231446. }
  231447. }
  231448. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231449. {
  231450. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231451. #if USE_COREGRAPHICS_RENDERING
  231452. s.add ("CoreGraphics Renderer");
  231453. #endif
  231454. return s;
  231455. }
  231456. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231457. {
  231458. return usingCoreGraphics ? 1 : 0;
  231459. }
  231460. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231461. {
  231462. #if USE_COREGRAPHICS_RENDERING
  231463. if (usingCoreGraphics != (index > 0))
  231464. {
  231465. usingCoreGraphics = index > 0;
  231466. [view setNeedsDisplay: true];
  231467. }
  231468. #endif
  231469. }
  231470. bool NSViewComponentPeer::canBecomeKeyWindow()
  231471. {
  231472. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231473. }
  231474. bool NSViewComponentPeer::windowShouldClose()
  231475. {
  231476. if (! isValidPeer (this))
  231477. return YES;
  231478. handleUserClosingWindow();
  231479. return NO;
  231480. }
  231481. void NSViewComponentPeer::redirectMovedOrResized()
  231482. {
  231483. handleMovedOrResized();
  231484. }
  231485. void NSViewComponentPeer::viewMovedToWindow()
  231486. {
  231487. if (isSharedWindow)
  231488. window = [view window];
  231489. }
  231490. void Desktop::createMouseInputSources()
  231491. {
  231492. mouseSources.add (new MouseInputSource (0, true));
  231493. }
  231494. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231495. {
  231496. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231497. if (enableOrDisable)
  231498. {
  231499. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231500. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231501. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231502. }
  231503. else
  231504. {
  231505. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  231506. }
  231507. #else
  231508. if (enableOrDisable)
  231509. {
  231510. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231511. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231512. }
  231513. else
  231514. {
  231515. SetSystemUIMode (kUIModeNormal, 0);
  231516. }
  231517. #endif
  231518. }
  231519. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231520. {
  231521. if (insideDrawRect)
  231522. {
  231523. class AsyncRepaintMessage : public CallbackMessage
  231524. {
  231525. public:
  231526. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231527. : peer (peer_), rect (rect_)
  231528. {
  231529. }
  231530. void messageCallback()
  231531. {
  231532. if (ComponentPeer::isValidPeer (peer))
  231533. peer->repaint (rect);
  231534. }
  231535. private:
  231536. NSViewComponentPeer* const peer;
  231537. const Rectangle<int> rect;
  231538. };
  231539. (new AsyncRepaintMessage (this, area))->post();
  231540. }
  231541. else
  231542. {
  231543. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231544. (float) area.getWidth(), (float) area.getHeight())];
  231545. }
  231546. }
  231547. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231548. {
  231549. [view displayIfNeeded];
  231550. }
  231551. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231552. {
  231553. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231554. }
  231555. const Image juce_createIconForFile (const File& file)
  231556. {
  231557. const ScopedAutoReleasePool pool;
  231558. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231559. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231560. [NSGraphicsContext saveGraphicsState];
  231561. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231562. [image drawAtPoint: NSMakePoint (0, 0)
  231563. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231564. operation: NSCompositeSourceOver fraction: 1.0f];
  231565. [[NSGraphicsContext currentContext] flushGraphics];
  231566. [NSGraphicsContext restoreGraphicsState];
  231567. return Image (result);
  231568. }
  231569. const int KeyPress::spaceKey = ' ';
  231570. const int KeyPress::returnKey = 0x0d;
  231571. const int KeyPress::escapeKey = 0x1b;
  231572. const int KeyPress::backspaceKey = 0x7f;
  231573. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231574. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231575. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231576. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231577. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231578. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231579. const int KeyPress::endKey = NSEndFunctionKey;
  231580. const int KeyPress::homeKey = NSHomeFunctionKey;
  231581. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231582. const int KeyPress::insertKey = -1;
  231583. const int KeyPress::tabKey = 9;
  231584. const int KeyPress::F1Key = NSF1FunctionKey;
  231585. const int KeyPress::F2Key = NSF2FunctionKey;
  231586. const int KeyPress::F3Key = NSF3FunctionKey;
  231587. const int KeyPress::F4Key = NSF4FunctionKey;
  231588. const int KeyPress::F5Key = NSF5FunctionKey;
  231589. const int KeyPress::F6Key = NSF6FunctionKey;
  231590. const int KeyPress::F7Key = NSF7FunctionKey;
  231591. const int KeyPress::F8Key = NSF8FunctionKey;
  231592. const int KeyPress::F9Key = NSF9FunctionKey;
  231593. const int KeyPress::F10Key = NSF10FunctionKey;
  231594. const int KeyPress::F11Key = NSF1FunctionKey;
  231595. const int KeyPress::F12Key = NSF12FunctionKey;
  231596. const int KeyPress::F13Key = NSF13FunctionKey;
  231597. const int KeyPress::F14Key = NSF14FunctionKey;
  231598. const int KeyPress::F15Key = NSF15FunctionKey;
  231599. const int KeyPress::F16Key = NSF16FunctionKey;
  231600. const int KeyPress::numberPad0 = 0x30020;
  231601. const int KeyPress::numberPad1 = 0x30021;
  231602. const int KeyPress::numberPad2 = 0x30022;
  231603. const int KeyPress::numberPad3 = 0x30023;
  231604. const int KeyPress::numberPad4 = 0x30024;
  231605. const int KeyPress::numberPad5 = 0x30025;
  231606. const int KeyPress::numberPad6 = 0x30026;
  231607. const int KeyPress::numberPad7 = 0x30027;
  231608. const int KeyPress::numberPad8 = 0x30028;
  231609. const int KeyPress::numberPad9 = 0x30029;
  231610. const int KeyPress::numberPadAdd = 0x3002a;
  231611. const int KeyPress::numberPadSubtract = 0x3002b;
  231612. const int KeyPress::numberPadMultiply = 0x3002c;
  231613. const int KeyPress::numberPadDivide = 0x3002d;
  231614. const int KeyPress::numberPadSeparator = 0x3002e;
  231615. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231616. const int KeyPress::numberPadEquals = 0x30030;
  231617. const int KeyPress::numberPadDelete = 0x30031;
  231618. const int KeyPress::playKey = 0x30000;
  231619. const int KeyPress::stopKey = 0x30001;
  231620. const int KeyPress::fastForwardKey = 0x30002;
  231621. const int KeyPress::rewindKey = 0x30003;
  231622. #endif
  231623. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231624. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231625. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231626. // compiled on its own).
  231627. #if JUCE_INCLUDED_FILE
  231628. #if JUCE_MAC
  231629. namespace MouseCursorHelpers
  231630. {
  231631. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231632. {
  231633. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231634. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231635. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231636. [im release];
  231637. return c;
  231638. }
  231639. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231640. {
  231641. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231642. BufferedInputStream buf (fileStream, 4096);
  231643. PNGImageFormat pngFormat;
  231644. Image im (pngFormat.decodeImage (buf));
  231645. if (im.isValid())
  231646. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231647. jassertfalse;
  231648. return 0;
  231649. }
  231650. }
  231651. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231652. {
  231653. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231654. }
  231655. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231656. {
  231657. const ScopedAutoReleasePool pool;
  231658. NSCursor* c = 0;
  231659. switch (type)
  231660. {
  231661. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231662. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231663. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231664. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231665. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231666. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231667. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231668. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231669. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231670. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231671. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231672. case UpDownResizeCursor:
  231673. case TopEdgeResizeCursor:
  231674. case BottomEdgeResizeCursor:
  231675. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231676. case TopLeftCornerResizeCursor:
  231677. case BottomRightCornerResizeCursor:
  231678. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231679. case TopRightCornerResizeCursor:
  231680. case BottomLeftCornerResizeCursor:
  231681. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231682. case UpDownLeftRightResizeCursor:
  231683. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231684. default:
  231685. jassertfalse;
  231686. break;
  231687. }
  231688. [c retain];
  231689. return c;
  231690. }
  231691. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231692. {
  231693. [((NSCursor*) cursorHandle) release];
  231694. }
  231695. void MouseCursor::showInAllWindows() const
  231696. {
  231697. showInWindow (0);
  231698. }
  231699. void MouseCursor::showInWindow (ComponentPeer*) const
  231700. {
  231701. NSCursor* c = (NSCursor*) getHandle();
  231702. if (c == 0)
  231703. c = [NSCursor arrowCursor];
  231704. [c set];
  231705. }
  231706. #else
  231707. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231708. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231709. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231710. void MouseCursor::showInAllWindows() const {}
  231711. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231712. #endif
  231713. #endif
  231714. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231715. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231716. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231717. // compiled on its own).
  231718. #if JUCE_INCLUDED_FILE
  231719. class NSViewComponentInternal : public ComponentMovementWatcher
  231720. {
  231721. public:
  231722. NSViewComponentInternal (NSView* const view_, Component& owner_)
  231723. : ComponentMovementWatcher (&owner_),
  231724. owner (owner_),
  231725. currentPeer (0),
  231726. view (view_)
  231727. {
  231728. [view_ retain];
  231729. if (owner.isShowing())
  231730. componentPeerChanged();
  231731. }
  231732. ~NSViewComponentInternal()
  231733. {
  231734. [view removeFromSuperview];
  231735. [view release];
  231736. }
  231737. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231738. {
  231739. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231740. // The ComponentMovementWatcher version of this method avoids calling
  231741. // us when the top-level comp is resized, but for an NSView we need to know this
  231742. // because with inverted co-ords, we need to update the position even if the
  231743. // top-left pos hasn't changed
  231744. if (comp.isOnDesktop() && wasResized)
  231745. componentMovedOrResized (wasMoved, wasResized);
  231746. }
  231747. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231748. {
  231749. Component* const topComp = owner.getTopLevelComponent();
  231750. if (topComp->getPeer() != 0)
  231751. {
  231752. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  231753. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  231754. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231755. [view setFrame: r];
  231756. }
  231757. }
  231758. void componentPeerChanged()
  231759. {
  231760. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  231761. if (currentPeer != peer)
  231762. {
  231763. if ([view superview] != nil)
  231764. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231765. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231766. currentPeer = peer;
  231767. if (peer != 0)
  231768. {
  231769. [peer->view addSubview: view];
  231770. componentMovedOrResized (false, false);
  231771. }
  231772. }
  231773. [view setHidden: ! owner.isShowing()];
  231774. }
  231775. void componentVisibilityChanged()
  231776. {
  231777. componentPeerChanged();
  231778. }
  231779. const Rectangle<int> getViewBounds() const
  231780. {
  231781. NSRect r = [view frame];
  231782. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  231783. }
  231784. private:
  231785. Component& owner;
  231786. NSViewComponentPeer* currentPeer;
  231787. public:
  231788. NSView* const view;
  231789. private:
  231790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  231791. };
  231792. NSViewComponent::NSViewComponent()
  231793. {
  231794. }
  231795. NSViewComponent::~NSViewComponent()
  231796. {
  231797. }
  231798. void NSViewComponent::setView (void* view)
  231799. {
  231800. if (view != getView())
  231801. {
  231802. if (view != 0)
  231803. info = new NSViewComponentInternal ((NSView*) view, *this);
  231804. else
  231805. info = 0;
  231806. }
  231807. }
  231808. void* NSViewComponent::getView() const
  231809. {
  231810. return info == 0 ? 0 : info->view;
  231811. }
  231812. void NSViewComponent::resizeToFitView()
  231813. {
  231814. if (info != 0)
  231815. setBounds (info->getViewBounds());
  231816. }
  231817. void NSViewComponent::paint (Graphics&)
  231818. {
  231819. }
  231820. #endif
  231821. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231822. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231823. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231824. // compiled on its own).
  231825. #if JUCE_INCLUDED_FILE
  231826. AppleRemoteDevice::AppleRemoteDevice()
  231827. : device (0),
  231828. queue (0),
  231829. remoteId (0)
  231830. {
  231831. }
  231832. AppleRemoteDevice::~AppleRemoteDevice()
  231833. {
  231834. stop();
  231835. }
  231836. namespace
  231837. {
  231838. io_object_t getAppleRemoteDevice()
  231839. {
  231840. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231841. io_iterator_t iter = 0;
  231842. io_object_t iod = 0;
  231843. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231844. && iter != 0)
  231845. {
  231846. iod = IOIteratorNext (iter);
  231847. }
  231848. IOObjectRelease (iter);
  231849. return iod;
  231850. }
  231851. bool createAppleRemoteInterface (io_object_t iod, void** device)
  231852. {
  231853. jassert (*device == 0);
  231854. io_name_t classname;
  231855. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231856. {
  231857. IOCFPlugInInterface** cfPlugInInterface = 0;
  231858. SInt32 score = 0;
  231859. if (IOCreatePlugInInterfaceForService (iod,
  231860. kIOHIDDeviceUserClientTypeID,
  231861. kIOCFPlugInInterfaceID,
  231862. &cfPlugInInterface,
  231863. &score) == kIOReturnSuccess)
  231864. {
  231865. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231866. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231867. device);
  231868. (void) hr;
  231869. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231870. }
  231871. }
  231872. return *device != 0;
  231873. }
  231874. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231875. {
  231876. if (result == kIOReturnSuccess)
  231877. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231878. }
  231879. }
  231880. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231881. {
  231882. if (queue != 0)
  231883. return true;
  231884. stop();
  231885. bool result = false;
  231886. io_object_t iod = getAppleRemoteDevice();
  231887. if (iod != 0)
  231888. {
  231889. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231890. result = true;
  231891. else
  231892. stop();
  231893. IOObjectRelease (iod);
  231894. }
  231895. return result;
  231896. }
  231897. void AppleRemoteDevice::stop()
  231898. {
  231899. if (queue != 0)
  231900. {
  231901. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231902. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231903. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231904. queue = 0;
  231905. }
  231906. if (device != 0)
  231907. {
  231908. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231909. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231910. device = 0;
  231911. }
  231912. }
  231913. bool AppleRemoteDevice::isActive() const
  231914. {
  231915. return queue != 0;
  231916. }
  231917. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231918. {
  231919. Array <int> cookies;
  231920. CFArrayRef elements;
  231921. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231922. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231923. return false;
  231924. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231925. {
  231926. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231927. // get the cookie
  231928. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231929. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231930. continue;
  231931. long number;
  231932. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231933. continue;
  231934. cookies.add ((int) number);
  231935. }
  231936. CFRelease (elements);
  231937. if ((*(IOHIDDeviceInterface**) device)
  231938. ->open ((IOHIDDeviceInterface**) device,
  231939. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231940. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231941. {
  231942. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231943. if (queue != 0)
  231944. {
  231945. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231946. for (int i = 0; i < cookies.size(); ++i)
  231947. {
  231948. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231949. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231950. }
  231951. CFRunLoopSourceRef eventSource;
  231952. if ((*(IOHIDQueueInterface**) queue)
  231953. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231954. {
  231955. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231956. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231957. {
  231958. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231959. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231960. return true;
  231961. }
  231962. }
  231963. }
  231964. }
  231965. return false;
  231966. }
  231967. void AppleRemoteDevice::handleCallbackInternal()
  231968. {
  231969. int totalValues = 0;
  231970. AbsoluteTime nullTime = { 0, 0 };
  231971. char cookies [12];
  231972. int numCookies = 0;
  231973. while (numCookies < numElementsInArray (cookies))
  231974. {
  231975. IOHIDEventStruct e;
  231976. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231977. break;
  231978. if ((int) e.elementCookie == 19)
  231979. {
  231980. remoteId = e.value;
  231981. buttonPressed (switched, false);
  231982. }
  231983. else
  231984. {
  231985. totalValues += e.value;
  231986. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231987. }
  231988. }
  231989. cookies [numCookies++] = 0;
  231990. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231991. static const char buttonPatterns[] =
  231992. {
  231993. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231994. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231995. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231996. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231997. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231998. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231999. 0x1f, 0x12, 0x04, 0x02, 0,
  232000. 0x1f, 0x12, 0x03, 0x02, 0,
  232001. 0x1f, 0x12, 0x1f, 0x12, 0,
  232002. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232003. 19, 0
  232004. };
  232005. int buttonNum = (int) menuButton;
  232006. int i = 0;
  232007. while (i < numElementsInArray (buttonPatterns))
  232008. {
  232009. if (strcmp (cookies, buttonPatterns + i) == 0)
  232010. {
  232011. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232012. break;
  232013. }
  232014. i += (int) strlen (buttonPatterns + i) + 1;
  232015. ++buttonNum;
  232016. }
  232017. }
  232018. #endif
  232019. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232020. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232021. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232022. // compiled on its own).
  232023. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232024. #if JUCE_MAC
  232025. END_JUCE_NAMESPACE
  232026. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232027. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232028. {
  232029. CriticalSection* contextLock;
  232030. bool needsUpdate;
  232031. }
  232032. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232033. - (bool) makeActive;
  232034. - (void) makeInactive;
  232035. - (void) reshape;
  232036. @end
  232037. @implementation ThreadSafeNSOpenGLView
  232038. - (id) initWithFrame: (NSRect) frameRect
  232039. pixelFormat: (NSOpenGLPixelFormat*) format
  232040. {
  232041. contextLock = new CriticalSection();
  232042. self = [super initWithFrame: frameRect pixelFormat: format];
  232043. if (self != nil)
  232044. [[NSNotificationCenter defaultCenter] addObserver: self
  232045. selector: @selector (_surfaceNeedsUpdate:)
  232046. name: NSViewGlobalFrameDidChangeNotification
  232047. object: self];
  232048. return self;
  232049. }
  232050. - (void) dealloc
  232051. {
  232052. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232053. delete contextLock;
  232054. [super dealloc];
  232055. }
  232056. - (bool) makeActive
  232057. {
  232058. const ScopedLock sl (*contextLock);
  232059. if ([self openGLContext] == 0)
  232060. return false;
  232061. [[self openGLContext] makeCurrentContext];
  232062. if (needsUpdate)
  232063. {
  232064. [super update];
  232065. needsUpdate = false;
  232066. }
  232067. return true;
  232068. }
  232069. - (void) makeInactive
  232070. {
  232071. const ScopedLock sl (*contextLock);
  232072. [NSOpenGLContext clearCurrentContext];
  232073. }
  232074. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232075. {
  232076. (void) notification;
  232077. const ScopedLock sl (*contextLock);
  232078. needsUpdate = true;
  232079. }
  232080. - (void) update
  232081. {
  232082. const ScopedLock sl (*contextLock);
  232083. needsUpdate = true;
  232084. }
  232085. - (void) reshape
  232086. {
  232087. const ScopedLock sl (*contextLock);
  232088. needsUpdate = true;
  232089. }
  232090. @end
  232091. BEGIN_JUCE_NAMESPACE
  232092. class WindowedGLContext : public OpenGLContext
  232093. {
  232094. public:
  232095. WindowedGLContext (Component& component,
  232096. const OpenGLPixelFormat& pixelFormat_,
  232097. NSOpenGLContext* sharedContext)
  232098. : renderContext (0),
  232099. pixelFormat (pixelFormat_)
  232100. {
  232101. NSOpenGLPixelFormatAttribute attribs [64];
  232102. int n = 0;
  232103. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232104. attribs[n++] = NSOpenGLPFAAccelerated;
  232105. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232106. attribs[n++] = NSOpenGLPFAColorSize;
  232107. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232108. pixelFormat.greenBits,
  232109. pixelFormat.blueBits);
  232110. attribs[n++] = NSOpenGLPFAAlphaSize;
  232111. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232112. attribs[n++] = NSOpenGLPFADepthSize;
  232113. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232114. attribs[n++] = NSOpenGLPFAStencilSize;
  232115. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232116. attribs[n++] = NSOpenGLPFAAccumSize;
  232117. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232118. pixelFormat.accumulationBufferGreenBits,
  232119. pixelFormat.accumulationBufferBlueBits,
  232120. pixelFormat.accumulationBufferAlphaBits);
  232121. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232122. attribs[n++] = NSOpenGLPFASampleBuffers;
  232123. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232124. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232125. attribs[n++] = NSOpenGLPFANoRecovery;
  232126. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232127. NSOpenGLPixelFormat* format
  232128. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232129. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232130. pixelFormat: format];
  232131. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232132. shareContext: sharedContext] autorelease];
  232133. const GLint swapInterval = 1;
  232134. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232135. [view setOpenGLContext: renderContext];
  232136. [format release];
  232137. viewHolder = new NSViewComponentInternal (view, component);
  232138. }
  232139. ~WindowedGLContext()
  232140. {
  232141. deleteContext();
  232142. viewHolder = 0;
  232143. }
  232144. void deleteContext()
  232145. {
  232146. makeInactive();
  232147. [renderContext clearDrawable];
  232148. [renderContext setView: nil];
  232149. [view setOpenGLContext: nil];
  232150. renderContext = nil;
  232151. }
  232152. bool makeActive() const throw()
  232153. {
  232154. jassert (renderContext != 0);
  232155. if ([renderContext view] != view)
  232156. [renderContext setView: view];
  232157. [view makeActive];
  232158. return isActive();
  232159. }
  232160. bool makeInactive() const throw()
  232161. {
  232162. [view makeInactive];
  232163. return true;
  232164. }
  232165. bool isActive() const throw()
  232166. {
  232167. return [NSOpenGLContext currentContext] == renderContext;
  232168. }
  232169. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232170. void* getRawContext() const throw() { return renderContext; }
  232171. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232172. {
  232173. }
  232174. void swapBuffers()
  232175. {
  232176. [renderContext flushBuffer];
  232177. }
  232178. bool setSwapInterval (const int numFramesPerSwap)
  232179. {
  232180. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232181. forParameter: NSOpenGLCPSwapInterval];
  232182. return true;
  232183. }
  232184. int getSwapInterval() const
  232185. {
  232186. GLint numFrames = 0;
  232187. [renderContext getValues: &numFrames
  232188. forParameter: NSOpenGLCPSwapInterval];
  232189. return numFrames;
  232190. }
  232191. void repaint()
  232192. {
  232193. // we need to invalidate the juce view that holds this gl view, to make it
  232194. // cause a repaint callback
  232195. NSView* v = (NSView*) viewHolder->view;
  232196. NSRect r = [v frame];
  232197. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232198. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232199. // repaint message, thus never causing our paint() callback, and never repainting
  232200. // the comp. So invalidating just a little bit around the edge helps..
  232201. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232202. }
  232203. void* getNativeWindowHandle() const { return viewHolder->view; }
  232204. NSOpenGLContext* renderContext;
  232205. ThreadSafeNSOpenGLView* view;
  232206. private:
  232207. OpenGLPixelFormat pixelFormat;
  232208. ScopedPointer <NSViewComponentInternal> viewHolder;
  232209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232210. };
  232211. OpenGLContext* OpenGLComponent::createContext()
  232212. {
  232213. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232214. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232215. return (c->renderContext != 0) ? c.release() : 0;
  232216. }
  232217. void* OpenGLComponent::getNativeWindowHandle() const
  232218. {
  232219. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232220. : 0;
  232221. }
  232222. void juce_glViewport (const int w, const int h)
  232223. {
  232224. glViewport (0, 0, w, h);
  232225. }
  232226. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232227. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232228. {
  232229. /* GLint attribs [64];
  232230. int n = 0;
  232231. attribs[n++] = AGL_RGBA;
  232232. attribs[n++] = AGL_DOUBLEBUFFER;
  232233. attribs[n++] = AGL_ACCELERATED;
  232234. attribs[n++] = AGL_NO_RECOVERY;
  232235. attribs[n++] = AGL_NONE;
  232236. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232237. while (p != 0)
  232238. {
  232239. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232240. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232241. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232242. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232243. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232244. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232245. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232246. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232247. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232248. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232249. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232250. results.add (pf);
  232251. p = aglNextPixelFormat (p);
  232252. }*/
  232253. //jassertfalse // can't see how you do this in cocoa!
  232254. }
  232255. #else
  232256. END_JUCE_NAMESPACE
  232257. @interface JuceGLView : UIView
  232258. {
  232259. }
  232260. + (Class) layerClass;
  232261. @end
  232262. @implementation JuceGLView
  232263. + (Class) layerClass
  232264. {
  232265. return [CAEAGLLayer class];
  232266. }
  232267. @end
  232268. BEGIN_JUCE_NAMESPACE
  232269. class GLESContext : public OpenGLContext
  232270. {
  232271. public:
  232272. GLESContext (UIViewComponentPeer* peer,
  232273. Component* const component_,
  232274. const OpenGLPixelFormat& pixelFormat_,
  232275. const GLESContext* const sharedContext,
  232276. NSUInteger apiType)
  232277. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232278. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232279. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232280. {
  232281. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232282. view.opaque = YES;
  232283. view.hidden = NO;
  232284. view.backgroundColor = [UIColor blackColor];
  232285. view.userInteractionEnabled = NO;
  232286. glLayer = (CAEAGLLayer*) [view layer];
  232287. [peer->view addSubview: view];
  232288. if (sharedContext != 0)
  232289. context = [[EAGLContext alloc] initWithAPI: apiType
  232290. sharegroup: [sharedContext->context sharegroup]];
  232291. else
  232292. context = [[EAGLContext alloc] initWithAPI: apiType];
  232293. createGLBuffers();
  232294. }
  232295. ~GLESContext()
  232296. {
  232297. deleteContext();
  232298. [view removeFromSuperview];
  232299. [view release];
  232300. freeGLBuffers();
  232301. }
  232302. void deleteContext()
  232303. {
  232304. makeInactive();
  232305. [context release];
  232306. context = nil;
  232307. }
  232308. bool makeActive() const throw()
  232309. {
  232310. jassert (context != 0);
  232311. [EAGLContext setCurrentContext: context];
  232312. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232313. return true;
  232314. }
  232315. void swapBuffers()
  232316. {
  232317. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232318. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232319. }
  232320. bool makeInactive() const throw()
  232321. {
  232322. return [EAGLContext setCurrentContext: nil];
  232323. }
  232324. bool isActive() const throw()
  232325. {
  232326. return [EAGLContext currentContext] == context;
  232327. }
  232328. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232329. void* getRawContext() const throw() { return glLayer; }
  232330. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232331. {
  232332. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232333. if (lastWidth != w || lastHeight != h)
  232334. {
  232335. lastWidth = w;
  232336. lastHeight = h;
  232337. freeGLBuffers();
  232338. createGLBuffers();
  232339. }
  232340. }
  232341. bool setSwapInterval (const int numFramesPerSwap)
  232342. {
  232343. numFrames = numFramesPerSwap;
  232344. return true;
  232345. }
  232346. int getSwapInterval() const
  232347. {
  232348. return numFrames;
  232349. }
  232350. void repaint()
  232351. {
  232352. }
  232353. void createGLBuffers()
  232354. {
  232355. makeActive();
  232356. glGenFramebuffersOES (1, &frameBufferHandle);
  232357. glGenRenderbuffersOES (1, &colorBufferHandle);
  232358. glGenRenderbuffersOES (1, &depthBufferHandle);
  232359. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232360. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232361. GLint width, height;
  232362. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232363. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232364. if (useDepthBuffer)
  232365. {
  232366. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232367. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232368. }
  232369. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232370. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232371. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232372. if (useDepthBuffer)
  232373. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232374. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232375. }
  232376. void freeGLBuffers()
  232377. {
  232378. if (frameBufferHandle != 0)
  232379. {
  232380. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232381. frameBufferHandle = 0;
  232382. }
  232383. if (colorBufferHandle != 0)
  232384. {
  232385. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232386. colorBufferHandle = 0;
  232387. }
  232388. if (depthBufferHandle != 0)
  232389. {
  232390. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232391. depthBufferHandle = 0;
  232392. }
  232393. }
  232394. private:
  232395. WeakReference<Component> component;
  232396. OpenGLPixelFormat pixelFormat;
  232397. JuceGLView* view;
  232398. CAEAGLLayer* glLayer;
  232399. EAGLContext* context;
  232400. bool useDepthBuffer;
  232401. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232402. int numFrames;
  232403. int lastWidth, lastHeight;
  232404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232405. };
  232406. OpenGLContext* OpenGLComponent::createContext()
  232407. {
  232408. ScopedAutoReleasePool pool;
  232409. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232410. if (peer != 0)
  232411. return new GLESContext (peer, this, preferredPixelFormat,
  232412. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232413. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232414. return 0;
  232415. }
  232416. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232417. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232418. {
  232419. }
  232420. void juce_glViewport (const int w, const int h)
  232421. {
  232422. glViewport (0, 0, w, h);
  232423. }
  232424. #endif
  232425. #endif
  232426. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232427. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232428. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232429. // compiled on its own).
  232430. #if JUCE_INCLUDED_FILE
  232431. class JuceMainMenuHandler;
  232432. END_JUCE_NAMESPACE
  232433. using namespace JUCE_NAMESPACE;
  232434. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232435. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232436. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232437. #else
  232438. @interface JuceMenuCallback : NSObject
  232439. #endif
  232440. {
  232441. JuceMainMenuHandler* owner;
  232442. }
  232443. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232444. - (void) dealloc;
  232445. - (void) menuItemInvoked: (id) menu;
  232446. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232447. @end
  232448. BEGIN_JUCE_NAMESPACE
  232449. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232450. private DeletedAtShutdown
  232451. {
  232452. public:
  232453. JuceMainMenuHandler()
  232454. : currentModel (0),
  232455. lastUpdateTime (0)
  232456. {
  232457. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232458. }
  232459. ~JuceMainMenuHandler()
  232460. {
  232461. setMenu (0);
  232462. jassert (instance == this);
  232463. instance = 0;
  232464. [callback release];
  232465. }
  232466. void setMenu (MenuBarModel* const newMenuBarModel)
  232467. {
  232468. if (currentModel != newMenuBarModel)
  232469. {
  232470. if (currentModel != 0)
  232471. currentModel->removeListener (this);
  232472. currentModel = newMenuBarModel;
  232473. if (currentModel != 0)
  232474. currentModel->addListener (this);
  232475. menuBarItemsChanged (0);
  232476. }
  232477. }
  232478. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232479. const String& name, const int menuId, const int tag)
  232480. {
  232481. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232482. action: nil
  232483. keyEquivalent: @""];
  232484. [item setTag: tag];
  232485. NSMenu* sub = createMenu (child, name, menuId, tag);
  232486. [parent setSubmenu: sub forItem: item];
  232487. [sub setAutoenablesItems: false];
  232488. [sub release];
  232489. }
  232490. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232491. const String& name, const int menuId, const int tag)
  232492. {
  232493. [parentItem setTag: tag];
  232494. NSMenu* menu = [parentItem submenu];
  232495. [menu setTitle: juceStringToNS (name)];
  232496. while ([menu numberOfItems] > 0)
  232497. [menu removeItemAtIndex: 0];
  232498. PopupMenu::MenuItemIterator iter (menuToCopy);
  232499. while (iter.next())
  232500. addMenuItem (iter, menu, menuId, tag);
  232501. [menu setAutoenablesItems: false];
  232502. [menu update];
  232503. }
  232504. void menuBarItemsChanged (MenuBarModel*)
  232505. {
  232506. lastUpdateTime = Time::getMillisecondCounter();
  232507. StringArray menuNames;
  232508. if (currentModel != 0)
  232509. menuNames = currentModel->getMenuBarNames();
  232510. NSMenu* menuBar = [NSApp mainMenu];
  232511. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232512. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232513. int menuId = 1;
  232514. for (int i = 0; i < menuNames.size(); ++i)
  232515. {
  232516. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232517. if (i >= [menuBar numberOfItems] - 1)
  232518. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232519. else
  232520. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232521. }
  232522. }
  232523. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232524. {
  232525. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232526. if (item != 0)
  232527. flashMenuBar ([item menu]);
  232528. }
  232529. void updateMenus (NSMenu* menu)
  232530. {
  232531. if (PopupMenu::dismissAllActiveMenus())
  232532. {
  232533. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232534. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232535. if ([menu respondsToSelector: @selector (cancelTracking)])
  232536. [menu performSelector: @selector (cancelTracking)];
  232537. }
  232538. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232539. menuBarItemsChanged (0);
  232540. }
  232541. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232542. {
  232543. if (currentModel != 0)
  232544. {
  232545. if (commandManager != 0)
  232546. {
  232547. ApplicationCommandTarget::InvocationInfo info (commandId);
  232548. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232549. commandManager->invoke (info, true);
  232550. }
  232551. currentModel->menuItemSelected (commandId, topLevelIndex);
  232552. }
  232553. }
  232554. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232555. const int topLevelMenuId, const int topLevelIndex)
  232556. {
  232557. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232558. if (text == 0)
  232559. text = @"";
  232560. if (iter.isSeparator)
  232561. {
  232562. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232563. }
  232564. else if (iter.isSectionHeader)
  232565. {
  232566. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232567. action: nil
  232568. keyEquivalent: @""];
  232569. [item setEnabled: false];
  232570. }
  232571. else if (iter.subMenu != 0)
  232572. {
  232573. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232574. action: nil
  232575. keyEquivalent: @""];
  232576. [item setTag: iter.itemId];
  232577. [item setEnabled: iter.isEnabled];
  232578. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232579. [sub setDelegate: nil];
  232580. [menuToAddTo setSubmenu: sub forItem: item];
  232581. [sub release];
  232582. }
  232583. else
  232584. {
  232585. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232586. action: @selector (menuItemInvoked:)
  232587. keyEquivalent: @""];
  232588. [item setTag: iter.itemId];
  232589. [item setEnabled: iter.isEnabled];
  232590. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232591. [item setTarget: (id) callback];
  232592. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232593. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232594. [item setRepresentedObject: info];
  232595. if (iter.commandManager != 0)
  232596. {
  232597. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232598. ->getKeyPressesAssignedToCommand (iter.itemId));
  232599. if (keyPresses.size() > 0)
  232600. {
  232601. const KeyPress& kp = keyPresses.getReference(0);
  232602. if (kp.getKeyCode() != KeyPress::backspaceKey
  232603. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232604. // every time you press the key while editing text)
  232605. {
  232606. juce_wchar key = kp.getTextCharacter();
  232607. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232608. key = NSBackspaceCharacter;
  232609. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232610. key = NSDeleteCharacter;
  232611. else if (key == 0)
  232612. key = (juce_wchar) kp.getKeyCode();
  232613. unsigned int mods = 0;
  232614. if (kp.getModifiers().isShiftDown())
  232615. mods |= NSShiftKeyMask;
  232616. if (kp.getModifiers().isCtrlDown())
  232617. mods |= NSControlKeyMask;
  232618. if (kp.getModifiers().isAltDown())
  232619. mods |= NSAlternateKeyMask;
  232620. if (kp.getModifiers().isCommandDown())
  232621. mods |= NSCommandKeyMask;
  232622. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232623. [item setKeyEquivalentModifierMask: mods];
  232624. }
  232625. }
  232626. }
  232627. }
  232628. }
  232629. static JuceMainMenuHandler* instance;
  232630. MenuBarModel* currentModel;
  232631. uint32 lastUpdateTime;
  232632. JuceMenuCallback* callback;
  232633. private:
  232634. NSMenu* createMenu (const PopupMenu menu,
  232635. const String& menuName,
  232636. const int topLevelMenuId,
  232637. const int topLevelIndex)
  232638. {
  232639. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232640. [m setAutoenablesItems: false];
  232641. [m setDelegate: callback];
  232642. PopupMenu::MenuItemIterator iter (menu);
  232643. while (iter.next())
  232644. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232645. [m update];
  232646. return m;
  232647. }
  232648. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232649. {
  232650. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232651. {
  232652. NSMenuItem* m = [menu itemAtIndex: i];
  232653. if ([m tag] == info.commandID)
  232654. return m;
  232655. if ([m submenu] != 0)
  232656. {
  232657. NSMenuItem* found = findMenuItem ([m submenu], info);
  232658. if (found != 0)
  232659. return found;
  232660. }
  232661. }
  232662. return 0;
  232663. }
  232664. static void flashMenuBar (NSMenu* menu)
  232665. {
  232666. if ([[menu title] isEqualToString: @"Apple"])
  232667. return;
  232668. [menu retain];
  232669. const unichar f35Key = NSF35FunctionKey;
  232670. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232671. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232672. action: nil
  232673. keyEquivalent: f35String];
  232674. [item setTarget: nil];
  232675. [menu insertItem: item atIndex: [menu numberOfItems]];
  232676. [item release];
  232677. if ([menu indexOfItem: item] >= 0)
  232678. {
  232679. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232680. location: NSZeroPoint
  232681. modifierFlags: NSCommandKeyMask
  232682. timestamp: 0
  232683. windowNumber: 0
  232684. context: [NSGraphicsContext currentContext]
  232685. characters: f35String
  232686. charactersIgnoringModifiers: f35String
  232687. isARepeat: NO
  232688. keyCode: 0];
  232689. [menu performKeyEquivalent: f35Event];
  232690. if ([menu indexOfItem: item] >= 0)
  232691. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232692. }
  232693. [menu release];
  232694. }
  232695. };
  232696. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232697. END_JUCE_NAMESPACE
  232698. @implementation JuceMenuCallback
  232699. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232700. {
  232701. [super init];
  232702. owner = owner_;
  232703. return self;
  232704. }
  232705. - (void) dealloc
  232706. {
  232707. [super dealloc];
  232708. }
  232709. - (void) menuItemInvoked: (id) menu
  232710. {
  232711. NSMenuItem* item = (NSMenuItem*) menu;
  232712. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232713. {
  232714. // 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
  232715. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232716. // into the focused component and let it trigger the menu item indirectly.
  232717. NSEvent* e = [NSApp currentEvent];
  232718. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232719. {
  232720. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232721. {
  232722. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232723. if (peer != 0)
  232724. {
  232725. if ([e type] == NSKeyDown)
  232726. peer->redirectKeyDown (e);
  232727. else
  232728. peer->redirectKeyUp (e);
  232729. return;
  232730. }
  232731. }
  232732. }
  232733. NSArray* info = (NSArray*) [item representedObject];
  232734. owner->invoke ((int) [item tag],
  232735. (ApplicationCommandManager*) (pointer_sized_int)
  232736. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232737. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232738. }
  232739. }
  232740. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232741. {
  232742. if (JuceMainMenuHandler::instance != 0)
  232743. JuceMainMenuHandler::instance->updateMenus (menu);
  232744. }
  232745. @end
  232746. BEGIN_JUCE_NAMESPACE
  232747. namespace MainMenuHelpers
  232748. {
  232749. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232750. {
  232751. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232752. {
  232753. PopupMenu::MenuItemIterator iter (*extraItems);
  232754. while (iter.next())
  232755. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232756. [menu addItem: [NSMenuItem separatorItem]];
  232757. }
  232758. NSMenuItem* item;
  232759. // Services...
  232760. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232761. action: nil keyEquivalent: @""];
  232762. [menu addItem: item];
  232763. [item release];
  232764. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232765. [menu setSubmenu: servicesMenu forItem: item];
  232766. [NSApp setServicesMenu: servicesMenu];
  232767. [servicesMenu release];
  232768. [menu addItem: [NSMenuItem separatorItem]];
  232769. // Hide + Show stuff...
  232770. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232771. action: @selector (hide:) keyEquivalent: @"h"];
  232772. [item setTarget: NSApp];
  232773. [menu addItem: item];
  232774. [item release];
  232775. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232776. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232777. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232778. [item setTarget: NSApp];
  232779. [menu addItem: item];
  232780. [item release];
  232781. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232782. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232783. [item setTarget: NSApp];
  232784. [menu addItem: item];
  232785. [item release];
  232786. [menu addItem: [NSMenuItem separatorItem]];
  232787. // Quit item....
  232788. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232789. action: @selector (terminate:) keyEquivalent: @"q"];
  232790. [item setTarget: NSApp];
  232791. [menu addItem: item];
  232792. [item release];
  232793. return menu;
  232794. }
  232795. // Since our app has no NIB, this initialises a standard app menu...
  232796. void rebuildMainMenu (const PopupMenu* extraItems)
  232797. {
  232798. // this can't be used in a plugin!
  232799. jassert (JUCEApplication::isStandaloneApp());
  232800. if (JUCEApplication::getInstance() != 0)
  232801. {
  232802. const ScopedAutoReleasePool pool;
  232803. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232804. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232805. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232806. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232807. [mainMenu setSubmenu: appMenu forItem: item];
  232808. [NSApp setMainMenu: mainMenu];
  232809. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232810. [appMenu release];
  232811. [mainMenu release];
  232812. }
  232813. }
  232814. }
  232815. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232816. const PopupMenu* extraAppleMenuItems)
  232817. {
  232818. if (getMacMainMenu() != newMenuBarModel)
  232819. {
  232820. const ScopedAutoReleasePool pool;
  232821. if (newMenuBarModel == 0)
  232822. {
  232823. delete JuceMainMenuHandler::instance;
  232824. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232825. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232826. extraAppleMenuItems = 0;
  232827. }
  232828. else
  232829. {
  232830. if (JuceMainMenuHandler::instance == 0)
  232831. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232832. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232833. }
  232834. }
  232835. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  232836. if (newMenuBarModel != 0)
  232837. newMenuBarModel->menuItemsChanged();
  232838. }
  232839. MenuBarModel* MenuBarModel::getMacMainMenu()
  232840. {
  232841. return JuceMainMenuHandler::instance != 0
  232842. ? JuceMainMenuHandler::instance->currentModel : 0;
  232843. }
  232844. void juce_initialiseMacMainMenu()
  232845. {
  232846. if (JuceMainMenuHandler::instance == 0)
  232847. MainMenuHelpers::rebuildMainMenu (0);
  232848. }
  232849. #endif
  232850. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232851. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232852. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232853. // compiled on its own).
  232854. #if JUCE_INCLUDED_FILE
  232855. #if JUCE_MAC
  232856. END_JUCE_NAMESPACE
  232857. using namespace JUCE_NAMESPACE;
  232858. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232859. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232860. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232861. #else
  232862. @interface JuceFileChooserDelegate : NSObject
  232863. #endif
  232864. {
  232865. StringArray* filters;
  232866. }
  232867. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232868. - (void) dealloc;
  232869. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232870. @end
  232871. @implementation JuceFileChooserDelegate
  232872. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232873. {
  232874. [super init];
  232875. filters = filters_;
  232876. return self;
  232877. }
  232878. - (void) dealloc
  232879. {
  232880. delete filters;
  232881. [super dealloc];
  232882. }
  232883. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232884. {
  232885. (void) sender;
  232886. const File f (nsStringToJuce (filename));
  232887. for (int i = filters->size(); --i >= 0;)
  232888. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232889. return true;
  232890. return f.isDirectory();
  232891. }
  232892. @end
  232893. BEGIN_JUCE_NAMESPACE
  232894. void FileChooser::showPlatformDialog (Array<File>& results,
  232895. const String& title,
  232896. const File& currentFileOrDirectory,
  232897. const String& filter,
  232898. bool selectsDirectory,
  232899. bool selectsFiles,
  232900. bool isSaveDialogue,
  232901. bool /*warnAboutOverwritingExistingFiles*/,
  232902. bool selectMultipleFiles,
  232903. FilePreviewComponent* /*extraInfoComponent*/)
  232904. {
  232905. const ScopedAutoReleasePool pool;
  232906. StringArray* filters = new StringArray();
  232907. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232908. filters->trim();
  232909. filters->removeEmptyStrings();
  232910. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232911. [delegate autorelease];
  232912. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232913. : [NSOpenPanel openPanel];
  232914. [panel setTitle: juceStringToNS (title)];
  232915. if (! isSaveDialogue)
  232916. {
  232917. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232918. [openPanel setCanChooseDirectories: selectsDirectory];
  232919. [openPanel setCanChooseFiles: selectsFiles];
  232920. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232921. }
  232922. [panel setDelegate: delegate];
  232923. if (isSaveDialogue || selectsDirectory)
  232924. [panel setCanCreateDirectories: YES];
  232925. String directory, filename;
  232926. if (currentFileOrDirectory.isDirectory())
  232927. {
  232928. directory = currentFileOrDirectory.getFullPathName();
  232929. }
  232930. else
  232931. {
  232932. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232933. filename = currentFileOrDirectory.getFileName();
  232934. }
  232935. if ([panel runModalForDirectory: juceStringToNS (directory)
  232936. file: juceStringToNS (filename)]
  232937. == NSOKButton)
  232938. {
  232939. if (isSaveDialogue)
  232940. {
  232941. results.add (File (nsStringToJuce ([panel filename])));
  232942. }
  232943. else
  232944. {
  232945. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232946. NSArray* urls = [openPanel filenames];
  232947. for (unsigned int i = 0; i < [urls count]; ++i)
  232948. {
  232949. NSString* f = [urls objectAtIndex: i];
  232950. results.add (File (nsStringToJuce (f)));
  232951. }
  232952. }
  232953. }
  232954. [panel setDelegate: nil];
  232955. }
  232956. #else
  232957. void FileChooser::showPlatformDialog (Array<File>& results,
  232958. const String& title,
  232959. const File& currentFileOrDirectory,
  232960. const String& filter,
  232961. bool selectsDirectory,
  232962. bool selectsFiles,
  232963. bool isSaveDialogue,
  232964. bool warnAboutOverwritingExistingFiles,
  232965. bool selectMultipleFiles,
  232966. FilePreviewComponent* extraInfoComponent)
  232967. {
  232968. const ScopedAutoReleasePool pool;
  232969. jassertfalse; //xxx to do
  232970. }
  232971. #endif
  232972. #endif
  232973. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232974. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232975. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232976. // compiled on its own).
  232977. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232978. END_JUCE_NAMESPACE
  232979. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232980. @interface NonInterceptingQTMovieView : QTMovieView
  232981. {
  232982. }
  232983. - (id) initWithFrame: (NSRect) frame;
  232984. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232985. - (NSView*) hitTest: (NSPoint) p;
  232986. @end
  232987. @implementation NonInterceptingQTMovieView
  232988. - (id) initWithFrame: (NSRect) frame
  232989. {
  232990. self = [super initWithFrame: frame];
  232991. [self setNextResponder: [self superview]];
  232992. return self;
  232993. }
  232994. - (void) dealloc
  232995. {
  232996. [super dealloc];
  232997. }
  232998. - (NSView*) hitTest: (NSPoint) point
  232999. {
  233000. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233001. }
  233002. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233003. {
  233004. return YES;
  233005. }
  233006. @end
  233007. BEGIN_JUCE_NAMESPACE
  233008. #define theMovie (static_cast <QTMovie*> (movie))
  233009. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233010. : movie (0)
  233011. {
  233012. setOpaque (true);
  233013. setVisible (true);
  233014. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233015. setView (view);
  233016. [view release];
  233017. }
  233018. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233019. {
  233020. closeMovie();
  233021. setView (0);
  233022. }
  233023. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233024. {
  233025. return true;
  233026. }
  233027. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233028. {
  233029. // unfortunately, QTMovie objects can only be created on the main thread..
  233030. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233031. QTMovie* movie = 0;
  233032. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233033. if (fin != 0)
  233034. {
  233035. movieFile = fin->getFile();
  233036. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233037. error: nil];
  233038. }
  233039. else
  233040. {
  233041. MemoryBlock temp;
  233042. movieStream->readIntoMemoryBlock (temp);
  233043. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233044. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233045. {
  233046. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233047. length: temp.getSize()]
  233048. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233049. MIMEType: @""]
  233050. error: nil];
  233051. if (movie != 0)
  233052. break;
  233053. }
  233054. }
  233055. return movie;
  233056. }
  233057. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233058. const bool isControllerVisible_)
  233059. {
  233060. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233061. }
  233062. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233063. const bool controllerVisible_)
  233064. {
  233065. closeMovie();
  233066. if (getPeer() == 0)
  233067. {
  233068. // To open a movie, this component must be visible inside a functioning window, so that
  233069. // the QT control can be assigned to the window.
  233070. jassertfalse;
  233071. return false;
  233072. }
  233073. movie = openMovieFromStream (movieStream, movieFile);
  233074. [theMovie retain];
  233075. QTMovieView* view = (QTMovieView*) getView();
  233076. [view setMovie: theMovie];
  233077. [view setControllerVisible: controllerVisible_];
  233078. setLooping (looping);
  233079. return movie != nil;
  233080. }
  233081. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233082. const bool isControllerVisible_)
  233083. {
  233084. // unfortunately, QTMovie objects can only be created on the main thread..
  233085. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233086. closeMovie();
  233087. if (getPeer() == 0)
  233088. {
  233089. // To open a movie, this component must be visible inside a functioning window, so that
  233090. // the QT control can be assigned to the window.
  233091. jassertfalse;
  233092. return false;
  233093. }
  233094. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233095. NSError* err;
  233096. if ([QTMovie canInitWithURL: url])
  233097. movie = [QTMovie movieWithURL: url error: &err];
  233098. [theMovie retain];
  233099. QTMovieView* view = (QTMovieView*) getView();
  233100. [view setMovie: theMovie];
  233101. [view setControllerVisible: controllerVisible];
  233102. setLooping (looping);
  233103. return movie != nil;
  233104. }
  233105. void QuickTimeMovieComponent::closeMovie()
  233106. {
  233107. stop();
  233108. QTMovieView* view = (QTMovieView*) getView();
  233109. [view setMovie: nil];
  233110. [theMovie release];
  233111. movie = 0;
  233112. movieFile = File::nonexistent;
  233113. }
  233114. bool QuickTimeMovieComponent::isMovieOpen() const
  233115. {
  233116. return movie != nil;
  233117. }
  233118. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233119. {
  233120. return movieFile;
  233121. }
  233122. void QuickTimeMovieComponent::play()
  233123. {
  233124. [theMovie play];
  233125. }
  233126. void QuickTimeMovieComponent::stop()
  233127. {
  233128. [theMovie stop];
  233129. }
  233130. bool QuickTimeMovieComponent::isPlaying() const
  233131. {
  233132. return movie != 0 && [theMovie rate] != 0;
  233133. }
  233134. void QuickTimeMovieComponent::setPosition (const double seconds)
  233135. {
  233136. if (movie != 0)
  233137. {
  233138. QTTime t;
  233139. t.timeValue = (uint64) (100000.0 * seconds);
  233140. t.timeScale = 100000;
  233141. t.flags = 0;
  233142. [theMovie setCurrentTime: t];
  233143. }
  233144. }
  233145. double QuickTimeMovieComponent::getPosition() const
  233146. {
  233147. if (movie == 0)
  233148. return 0.0;
  233149. QTTime t = [theMovie currentTime];
  233150. return t.timeValue / (double) t.timeScale;
  233151. }
  233152. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233153. {
  233154. [theMovie setRate: newSpeed];
  233155. }
  233156. double QuickTimeMovieComponent::getMovieDuration() const
  233157. {
  233158. if (movie == 0)
  233159. return 0.0;
  233160. QTTime t = [theMovie duration];
  233161. return t.timeValue / (double) t.timeScale;
  233162. }
  233163. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233164. {
  233165. looping = shouldLoop;
  233166. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233167. forKey: QTMovieLoopsAttribute];
  233168. }
  233169. bool QuickTimeMovieComponent::isLooping() const
  233170. {
  233171. return looping;
  233172. }
  233173. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233174. {
  233175. [theMovie setVolume: newVolume];
  233176. }
  233177. float QuickTimeMovieComponent::getMovieVolume() const
  233178. {
  233179. return movie != 0 ? [theMovie volume] : 0.0f;
  233180. }
  233181. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233182. {
  233183. width = 0;
  233184. height = 0;
  233185. if (movie != 0)
  233186. {
  233187. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233188. width = (int) s.width;
  233189. height = (int) s.height;
  233190. }
  233191. }
  233192. void QuickTimeMovieComponent::paint (Graphics& g)
  233193. {
  233194. if (movie == 0)
  233195. g.fillAll (Colours::black);
  233196. }
  233197. bool QuickTimeMovieComponent::isControllerVisible() const
  233198. {
  233199. return controllerVisible;
  233200. }
  233201. void QuickTimeMovieComponent::goToStart()
  233202. {
  233203. setPosition (0.0);
  233204. }
  233205. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233206. const RectanglePlacement& placement)
  233207. {
  233208. int normalWidth, normalHeight;
  233209. getMovieNormalSize (normalWidth, normalHeight);
  233210. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233211. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233212. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233213. else
  233214. setBounds (spaceToFitWithin);
  233215. }
  233216. #if ! (JUCE_MAC && JUCE_64BIT)
  233217. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233218. {
  233219. if (movieStream == 0)
  233220. return false;
  233221. File file;
  233222. QTMovie* movie = openMovieFromStream (movieStream, file);
  233223. if (movie != nil)
  233224. result = [movie quickTimeMovie];
  233225. return movie != nil;
  233226. }
  233227. #endif
  233228. #endif
  233229. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233230. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233231. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233232. // compiled on its own).
  233233. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233234. const int kilobytesPerSecond1x = 176;
  233235. END_JUCE_NAMESPACE
  233236. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233237. @interface OpenDiskDevice : NSObject
  233238. {
  233239. @public
  233240. DRDevice* device;
  233241. NSMutableArray* tracks;
  233242. bool underrunProtection;
  233243. }
  233244. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233245. - (void) dealloc;
  233246. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233247. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233248. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233249. @end
  233250. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233251. @interface AudioTrackProducer : NSObject
  233252. {
  233253. JUCE_NAMESPACE::AudioSource* source;
  233254. int readPosition, lengthInFrames;
  233255. }
  233256. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233257. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233258. - (void) dealloc;
  233259. - (void) setupTrackProperties: (DRTrack*) track;
  233260. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233261. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233262. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233263. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233264. toMedia:(NSDictionary*)mediaInfo;
  233265. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233266. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233267. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233268. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233269. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233270. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233271. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233272. ioFlags:(uint32_t*)flags;
  233273. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233274. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233275. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233276. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233277. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233278. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233279. ioFlags:(uint32_t*)flags;
  233280. @end
  233281. @implementation OpenDiskDevice
  233282. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233283. {
  233284. [super init];
  233285. device = device_;
  233286. tracks = [[NSMutableArray alloc] init];
  233287. underrunProtection = true;
  233288. return self;
  233289. }
  233290. - (void) dealloc
  233291. {
  233292. [tracks release];
  233293. [super dealloc];
  233294. }
  233295. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233296. {
  233297. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233298. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233299. [p setupTrackProperties: t];
  233300. [tracks addObject: t];
  233301. [t release];
  233302. [p release];
  233303. }
  233304. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233305. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233306. {
  233307. DRBurn* burn = [DRBurn burnForDevice: device];
  233308. if (! [device acquireExclusiveAccess])
  233309. {
  233310. *error = "Couldn't open or write to the CD device";
  233311. return;
  233312. }
  233313. [device acquireMediaReservation];
  233314. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233315. [d autorelease];
  233316. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233317. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233318. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233319. if (burnSpeed > 0)
  233320. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233321. if (! underrunProtection)
  233322. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233323. [burn setProperties: d];
  233324. [burn writeLayout: tracks];
  233325. for (;;)
  233326. {
  233327. JUCE_NAMESPACE::Thread::sleep (300);
  233328. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233329. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233330. {
  233331. [burn abort];
  233332. *error = "User cancelled the write operation";
  233333. break;
  233334. }
  233335. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233336. {
  233337. *error = "Write operation failed";
  233338. break;
  233339. }
  233340. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233341. {
  233342. break;
  233343. }
  233344. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233345. objectForKey: DRErrorStatusErrorStringKey];
  233346. if ([err length] > 0)
  233347. {
  233348. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233349. break;
  233350. }
  233351. }
  233352. [device releaseMediaReservation];
  233353. [device releaseExclusiveAccess];
  233354. }
  233355. @end
  233356. @implementation AudioTrackProducer
  233357. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233358. {
  233359. lengthInFrames = lengthInFrames_;
  233360. readPosition = 0;
  233361. return self;
  233362. }
  233363. - (void) setupTrackProperties: (DRTrack*) track
  233364. {
  233365. NSMutableDictionary* p = [[track properties] mutableCopy];
  233366. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233367. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233368. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233369. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233370. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233371. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233372. [track setProperties: p];
  233373. [p release];
  233374. }
  233375. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233376. {
  233377. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233378. if (s != nil)
  233379. s->source = source_;
  233380. return s;
  233381. }
  233382. - (void) dealloc
  233383. {
  233384. if (source != 0)
  233385. {
  233386. source->releaseResources();
  233387. delete source;
  233388. }
  233389. [super dealloc];
  233390. }
  233391. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233392. {
  233393. (void) track;
  233394. }
  233395. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233396. {
  233397. (void) track;
  233398. return true;
  233399. }
  233400. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233401. {
  233402. (void) track;
  233403. return lengthInFrames;
  233404. }
  233405. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233406. toMedia: (NSDictionary*) mediaInfo
  233407. {
  233408. (void) track; (void) burn; (void) mediaInfo;
  233409. if (source != 0)
  233410. source->prepareToPlay (44100 / 75, 44100);
  233411. readPosition = 0;
  233412. return true;
  233413. }
  233414. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233415. {
  233416. (void) track;
  233417. if (source != 0)
  233418. source->prepareToPlay (44100 / 75, 44100);
  233419. return true;
  233420. }
  233421. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233422. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233423. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233424. {
  233425. (void) track; (void) address; (void) blockSize; (void) flags;
  233426. if (source != 0)
  233427. {
  233428. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233429. if (numSamples > 0)
  233430. {
  233431. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233432. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233433. info.buffer = &tempBuffer;
  233434. info.startSample = 0;
  233435. info.numSamples = numSamples;
  233436. source->getNextAudioBlock (info);
  233437. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233438. JUCE_NAMESPACE::AudioData::LittleEndian,
  233439. JUCE_NAMESPACE::AudioData::Interleaved,
  233440. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233441. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233442. JUCE_NAMESPACE::AudioData::NativeEndian,
  233443. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233444. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233445. CDSampleFormat left (buffer, 2);
  233446. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233447. CDSampleFormat right (buffer + 2, 2);
  233448. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233449. readPosition += numSamples;
  233450. }
  233451. return numSamples * 4;
  233452. }
  233453. return 0;
  233454. }
  233455. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233456. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233457. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233458. ioFlags: (uint32_t*) flags
  233459. {
  233460. (void) track; (void) address; (void) blockSize; (void) flags;
  233461. zeromem (buffer, bufferLength);
  233462. return bufferLength;
  233463. }
  233464. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233465. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233466. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233467. {
  233468. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233469. return true;
  233470. }
  233471. @end
  233472. BEGIN_JUCE_NAMESPACE
  233473. class AudioCDBurner::Pimpl : public Timer
  233474. {
  233475. public:
  233476. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233477. : device (0), owner (owner_)
  233478. {
  233479. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233480. if (dev != 0)
  233481. {
  233482. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233483. lastState = getDiskState();
  233484. startTimer (1000);
  233485. }
  233486. }
  233487. ~Pimpl()
  233488. {
  233489. stopTimer();
  233490. [device release];
  233491. }
  233492. void timerCallback()
  233493. {
  233494. const DiskState state = getDiskState();
  233495. if (state != lastState)
  233496. {
  233497. lastState = state;
  233498. owner.sendChangeMessage();
  233499. }
  233500. }
  233501. DiskState getDiskState() const
  233502. {
  233503. if ([device->device isValid])
  233504. {
  233505. NSDictionary* status = [device->device status];
  233506. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233507. if ([state isEqualTo: DRDeviceMediaStateNone])
  233508. {
  233509. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233510. return trayOpen;
  233511. return noDisc;
  233512. }
  233513. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233514. {
  233515. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233516. return writableDiskPresent;
  233517. else
  233518. return readOnlyDiskPresent;
  233519. }
  233520. }
  233521. return unknown;
  233522. }
  233523. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233524. const Array<int> getAvailableWriteSpeeds() const
  233525. {
  233526. Array<int> results;
  233527. if ([device->device isValid])
  233528. {
  233529. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233530. for (unsigned int i = 0; i < [speeds count]; ++i)
  233531. {
  233532. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233533. results.add (kbPerSec / kilobytesPerSecond1x);
  233534. }
  233535. }
  233536. return results;
  233537. }
  233538. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233539. {
  233540. if ([device->device isValid])
  233541. {
  233542. device->underrunProtection = shouldBeEnabled;
  233543. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233544. }
  233545. return false;
  233546. }
  233547. int getNumAvailableAudioBlocks() const
  233548. {
  233549. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233550. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233551. }
  233552. OpenDiskDevice* device;
  233553. private:
  233554. DiskState lastState;
  233555. AudioCDBurner& owner;
  233556. };
  233557. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233558. {
  233559. pimpl = new Pimpl (*this, deviceIndex);
  233560. }
  233561. AudioCDBurner::~AudioCDBurner()
  233562. {
  233563. }
  233564. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233565. {
  233566. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233567. if (b->pimpl->device == 0)
  233568. b = 0;
  233569. return b.release();
  233570. }
  233571. namespace
  233572. {
  233573. NSArray* findDiskBurnerDevices()
  233574. {
  233575. NSMutableArray* results = [NSMutableArray array];
  233576. NSArray* devs = [DRDevice devices];
  233577. for (int i = 0; i < [devs count]; ++i)
  233578. {
  233579. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233580. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233581. if (name != nil)
  233582. [results addObject: name];
  233583. }
  233584. return results;
  233585. }
  233586. }
  233587. const StringArray AudioCDBurner::findAvailableDevices()
  233588. {
  233589. NSArray* names = findDiskBurnerDevices();
  233590. StringArray s;
  233591. for (unsigned int i = 0; i < [names count]; ++i)
  233592. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233593. return s;
  233594. }
  233595. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233596. {
  233597. return pimpl->getDiskState();
  233598. }
  233599. bool AudioCDBurner::isDiskPresent() const
  233600. {
  233601. return getDiskState() == writableDiskPresent;
  233602. }
  233603. bool AudioCDBurner::openTray()
  233604. {
  233605. return pimpl->openTray();
  233606. }
  233607. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233608. {
  233609. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233610. DiskState oldState = getDiskState();
  233611. DiskState newState = oldState;
  233612. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233613. {
  233614. newState = getDiskState();
  233615. Thread::sleep (100);
  233616. }
  233617. return newState;
  233618. }
  233619. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233620. {
  233621. return pimpl->getAvailableWriteSpeeds();
  233622. }
  233623. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233624. {
  233625. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233626. }
  233627. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233628. {
  233629. return pimpl->getNumAvailableAudioBlocks();
  233630. }
  233631. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233632. {
  233633. if ([pimpl->device->device isValid])
  233634. {
  233635. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233636. return true;
  233637. }
  233638. return false;
  233639. }
  233640. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233641. bool ejectDiscAfterwards,
  233642. bool performFakeBurnForTesting,
  233643. int writeSpeed)
  233644. {
  233645. String error ("Couldn't open or write to the CD device");
  233646. if ([pimpl->device->device isValid])
  233647. {
  233648. error = String::empty;
  233649. [pimpl->device burn: listener
  233650. errorString: &error
  233651. ejectAfterwards: ejectDiscAfterwards
  233652. isFake: performFakeBurnForTesting
  233653. speed: writeSpeed];
  233654. }
  233655. return error;
  233656. }
  233657. #endif
  233658. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233659. void AudioCDReader::ejectDisk()
  233660. {
  233661. const ScopedAutoReleasePool p;
  233662. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233663. }
  233664. #endif
  233665. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233666. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233667. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233668. // compiled on its own).
  233669. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233670. namespace CDReaderHelpers
  233671. {
  233672. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233673. {
  233674. forEachXmlChildElementWithTagName (xml, child, "key")
  233675. if (child->getAllSubText().trim() == key)
  233676. return child->getNextElement();
  233677. return 0;
  233678. }
  233679. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233680. {
  233681. const XmlElement* const block = getElementForKey (xml, key);
  233682. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233683. }
  233684. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233685. // Returns NULL on success, otherwise a const char* representing an error.
  233686. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233687. {
  233688. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233689. if (xml == 0)
  233690. return "Couldn't parse XML in file";
  233691. const XmlElement* const dict = xml->getChildByName ("dict");
  233692. if (dict == 0)
  233693. return "Couldn't get top level dictionary";
  233694. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233695. if (sessions == 0)
  233696. return "Couldn't find sessions key";
  233697. const XmlElement* const session = sessions->getFirstChildElement();
  233698. if (session == 0)
  233699. return "Couldn't find first session";
  233700. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233701. if (leadOut < 0)
  233702. return "Couldn't find Leadout Block";
  233703. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233704. if (trackArray == 0)
  233705. return "Couldn't find Track Array";
  233706. forEachXmlChildElement (*trackArray, track)
  233707. {
  233708. const int trackValue = getIntValueForKey (*track, "Start Block");
  233709. if (trackValue < 0)
  233710. return "Couldn't find Start Block in the track";
  233711. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233712. }
  233713. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233714. return 0;
  233715. }
  233716. static void findDevices (Array<File>& cds)
  233717. {
  233718. File volumes ("/Volumes");
  233719. volumes.findChildFiles (cds, File::findDirectories, false);
  233720. for (int i = cds.size(); --i >= 0;)
  233721. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233722. cds.remove (i);
  233723. }
  233724. struct TrackSorter
  233725. {
  233726. static int getCDTrackNumber (const File& file)
  233727. {
  233728. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233729. }
  233730. static int compareElements (const File& first, const File& second)
  233731. {
  233732. const int firstTrack = getCDTrackNumber (first);
  233733. const int secondTrack = getCDTrackNumber (second);
  233734. jassert (firstTrack > 0 && secondTrack > 0);
  233735. return firstTrack - secondTrack;
  233736. }
  233737. };
  233738. }
  233739. const StringArray AudioCDReader::getAvailableCDNames()
  233740. {
  233741. Array<File> cds;
  233742. CDReaderHelpers::findDevices (cds);
  233743. StringArray names;
  233744. for (int i = 0; i < cds.size(); ++i)
  233745. names.add (cds.getReference(i).getFileName());
  233746. return names;
  233747. }
  233748. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233749. {
  233750. Array<File> cds;
  233751. CDReaderHelpers::findDevices (cds);
  233752. if (cds[index].exists())
  233753. return new AudioCDReader (cds[index]);
  233754. return 0;
  233755. }
  233756. AudioCDReader::AudioCDReader (const File& volume)
  233757. : AudioFormatReader (0, "CD Audio"),
  233758. volumeDir (volume),
  233759. currentReaderTrack (-1),
  233760. reader (0)
  233761. {
  233762. sampleRate = 44100.0;
  233763. bitsPerSample = 16;
  233764. numChannels = 2;
  233765. usesFloatingPointData = false;
  233766. refreshTrackLengths();
  233767. }
  233768. AudioCDReader::~AudioCDReader()
  233769. {
  233770. }
  233771. void AudioCDReader::refreshTrackLengths()
  233772. {
  233773. tracks.clear();
  233774. trackStartSamples.clear();
  233775. lengthInSamples = 0;
  233776. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233777. CDReaderHelpers::TrackSorter sorter;
  233778. tracks.sort (sorter);
  233779. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233780. if (toc.exists())
  233781. {
  233782. XmlDocument doc (toc);
  233783. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233784. (void) error; // could be logged..
  233785. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233786. }
  233787. }
  233788. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233789. int64 startSampleInFile, int numSamples)
  233790. {
  233791. while (numSamples > 0)
  233792. {
  233793. int track = -1;
  233794. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233795. {
  233796. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233797. {
  233798. track = i;
  233799. break;
  233800. }
  233801. }
  233802. if (track < 0)
  233803. return false;
  233804. if (track != currentReaderTrack)
  233805. {
  233806. reader = 0;
  233807. FileInputStream* const in = tracks [track].createInputStream();
  233808. if (in != 0)
  233809. {
  233810. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233811. AiffAudioFormat format;
  233812. reader = format.createReaderFor (bin, true);
  233813. if (reader == 0)
  233814. currentReaderTrack = -1;
  233815. else
  233816. currentReaderTrack = track;
  233817. }
  233818. }
  233819. if (reader == 0)
  233820. return false;
  233821. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233822. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233823. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233824. numSamples -= numAvailable;
  233825. startSampleInFile += numAvailable;
  233826. }
  233827. return true;
  233828. }
  233829. bool AudioCDReader::isCDStillPresent() const
  233830. {
  233831. return volumeDir.exists();
  233832. }
  233833. bool AudioCDReader::isTrackAudio (int trackNum) const
  233834. {
  233835. return tracks [trackNum].hasFileExtension (".aiff");
  233836. }
  233837. void AudioCDReader::enableIndexScanning (bool)
  233838. {
  233839. // any way to do this on a Mac??
  233840. }
  233841. int AudioCDReader::getLastIndex() const
  233842. {
  233843. return 0;
  233844. }
  233845. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  233846. {
  233847. return Array <int>();
  233848. }
  233849. #endif
  233850. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233851. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233852. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233853. // compiled on its own).
  233854. #if JUCE_INCLUDED_FILE
  233855. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233856. for example having more than one juce plugin loaded into a host, then when a
  233857. method is called, the actual code that runs might actually be in a different module
  233858. than the one you expect... So any calls to library functions or statics that are
  233859. made inside obj-c methods will probably end up getting executed in a different DLL's
  233860. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233861. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233862. virtual methods of an object that's known to live inside the right module's space.
  233863. */
  233864. class AppDelegateRedirector
  233865. {
  233866. public:
  233867. AppDelegateRedirector()
  233868. {
  233869. }
  233870. virtual ~AppDelegateRedirector()
  233871. {
  233872. }
  233873. virtual NSApplicationTerminateReply shouldTerminate()
  233874. {
  233875. if (JUCEApplication::getInstance() != 0)
  233876. {
  233877. JUCEApplication::getInstance()->systemRequestedQuit();
  233878. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  233879. return NSTerminateCancel;
  233880. }
  233881. return NSTerminateNow;
  233882. }
  233883. virtual void willTerminate()
  233884. {
  233885. JUCEApplication::appWillTerminateByForce();
  233886. }
  233887. virtual BOOL openFile (NSString* filename)
  233888. {
  233889. if (JUCEApplication::getInstance() != 0)
  233890. {
  233891. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  233892. return YES;
  233893. }
  233894. return NO;
  233895. }
  233896. virtual void openFiles (NSArray* filenames)
  233897. {
  233898. StringArray files;
  233899. for (unsigned int i = 0; i < [filenames count]; ++i)
  233900. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  233901. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233902. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233903. }
  233904. virtual void focusChanged()
  233905. {
  233906. juce_HandleProcessFocusChange();
  233907. }
  233908. struct CallbackMessagePayload
  233909. {
  233910. MessageCallbackFunction* function;
  233911. void* parameter;
  233912. void* volatile result;
  233913. bool volatile hasBeenExecuted;
  233914. };
  233915. virtual void performCallback (CallbackMessagePayload* pl)
  233916. {
  233917. pl->result = (*pl->function) (pl->parameter);
  233918. pl->hasBeenExecuted = true;
  233919. }
  233920. virtual void deleteSelf()
  233921. {
  233922. delete this;
  233923. }
  233924. void postMessage (Message* const m)
  233925. {
  233926. messageQueue.post (m);
  233927. }
  233928. private:
  233929. CFRunLoopRef runLoop;
  233930. CFRunLoopSourceRef runLoopSource;
  233931. MessageQueue messageQueue;
  233932. static const String quotedIfContainsSpaces (NSString* file)
  233933. {
  233934. String s (nsStringToJuce (file));
  233935. if (s.containsChar (' '))
  233936. s = s.quoted ('"');
  233937. return s;
  233938. }
  233939. };
  233940. END_JUCE_NAMESPACE
  233941. using namespace JUCE_NAMESPACE;
  233942. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233943. @interface JuceAppDelegate : NSObject
  233944. {
  233945. @private
  233946. id oldDelegate;
  233947. @public
  233948. AppDelegateRedirector* redirector;
  233949. }
  233950. - (JuceAppDelegate*) init;
  233951. - (void) dealloc;
  233952. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  233953. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  233954. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  233955. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  233956. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  233957. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  233958. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  233959. - (void) performCallback: (id) info;
  233960. - (void) dummyMethod;
  233961. @end
  233962. @implementation JuceAppDelegate
  233963. - (JuceAppDelegate*) init
  233964. {
  233965. [super init];
  233966. redirector = new AppDelegateRedirector();
  233967. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233968. if (JUCEApplication::isStandaloneApp())
  233969. {
  233970. oldDelegate = [NSApp delegate];
  233971. [NSApp setDelegate: self];
  233972. }
  233973. else
  233974. {
  233975. oldDelegate = 0;
  233976. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233977. name: NSApplicationDidResignActiveNotification object: NSApp];
  233978. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233979. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233980. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233981. name: NSApplicationWillUnhideNotification object: NSApp];
  233982. }
  233983. return self;
  233984. }
  233985. - (void) dealloc
  233986. {
  233987. if (oldDelegate != 0)
  233988. [NSApp setDelegate: oldDelegate];
  233989. redirector->deleteSelf();
  233990. [super dealloc];
  233991. }
  233992. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233993. {
  233994. (void) app;
  233995. return redirector->shouldTerminate();
  233996. }
  233997. - (void) applicationWillTerminate: (NSNotification*) aNotification
  233998. {
  233999. (void) aNotification;
  234000. redirector->willTerminate();
  234001. }
  234002. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234003. {
  234004. (void) app;
  234005. return redirector->openFile (filename);
  234006. }
  234007. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234008. {
  234009. (void) sender;
  234010. return redirector->openFiles (filenames);
  234011. }
  234012. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234013. {
  234014. (void) notification;
  234015. redirector->focusChanged();
  234016. }
  234017. - (void) applicationDidResignActive: (NSNotification*) notification
  234018. {
  234019. (void) notification;
  234020. redirector->focusChanged();
  234021. }
  234022. - (void) applicationWillUnhide: (NSNotification*) notification
  234023. {
  234024. (void) notification;
  234025. redirector->focusChanged();
  234026. }
  234027. - (void) performCallback: (id) info
  234028. {
  234029. if ([info isKindOfClass: [NSData class]])
  234030. {
  234031. AppDelegateRedirector::CallbackMessagePayload* pl
  234032. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234033. if (pl != 0)
  234034. redirector->performCallback (pl);
  234035. }
  234036. else
  234037. {
  234038. jassertfalse; // should never get here!
  234039. }
  234040. }
  234041. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234042. @end
  234043. BEGIN_JUCE_NAMESPACE
  234044. static JuceAppDelegate* juceAppDelegate = 0;
  234045. void MessageManager::runDispatchLoop()
  234046. {
  234047. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234048. {
  234049. const ScopedAutoReleasePool pool;
  234050. // must only be called by the message thread!
  234051. jassert (isThisTheMessageThread());
  234052. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234053. @try
  234054. {
  234055. [NSApp run];
  234056. }
  234057. @catch (NSException* e)
  234058. {
  234059. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234060. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234061. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234062. }
  234063. @finally
  234064. {
  234065. }
  234066. #else
  234067. [NSApp run];
  234068. #endif
  234069. }
  234070. }
  234071. void MessageManager::stopDispatchLoop()
  234072. {
  234073. quitMessagePosted = true;
  234074. [NSApp stop: nil];
  234075. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234076. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234077. }
  234078. namespace
  234079. {
  234080. bool isEventBlockedByModalComps (NSEvent* e)
  234081. {
  234082. if (Component::getNumCurrentlyModalComponents() == 0)
  234083. return false;
  234084. NSWindow* const w = [e window];
  234085. if (w == 0 || [w worksWhenModal])
  234086. return false;
  234087. bool isKey = false, isInputAttempt = false;
  234088. switch ([e type])
  234089. {
  234090. case NSKeyDown:
  234091. case NSKeyUp:
  234092. isKey = isInputAttempt = true;
  234093. break;
  234094. case NSLeftMouseDown:
  234095. case NSRightMouseDown:
  234096. case NSOtherMouseDown:
  234097. isInputAttempt = true;
  234098. break;
  234099. case NSLeftMouseDragged:
  234100. case NSRightMouseDragged:
  234101. case NSLeftMouseUp:
  234102. case NSRightMouseUp:
  234103. case NSOtherMouseUp:
  234104. case NSOtherMouseDragged:
  234105. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234106. return false;
  234107. break;
  234108. case NSMouseMoved:
  234109. case NSMouseEntered:
  234110. case NSMouseExited:
  234111. case NSCursorUpdate:
  234112. case NSScrollWheel:
  234113. case NSTabletPoint:
  234114. case NSTabletProximity:
  234115. break;
  234116. default:
  234117. return false;
  234118. }
  234119. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234120. {
  234121. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234122. NSView* const compView = (NSView*) peer->getNativeHandle();
  234123. if ([compView window] == w)
  234124. {
  234125. if (isKey)
  234126. {
  234127. if (compView == [w firstResponder])
  234128. return false;
  234129. }
  234130. else
  234131. {
  234132. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234133. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234134. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234135. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234136. return false;
  234137. }
  234138. }
  234139. }
  234140. if (isInputAttempt)
  234141. {
  234142. if (! [NSApp isActive])
  234143. [NSApp activateIgnoringOtherApps: YES];
  234144. Component* const modal = Component::getCurrentlyModalComponent (0);
  234145. if (modal != 0)
  234146. modal->inputAttemptWhenModal();
  234147. }
  234148. return true;
  234149. }
  234150. }
  234151. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234152. {
  234153. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234154. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234155. while (! quitMessagePosted)
  234156. {
  234157. const ScopedAutoReleasePool pool;
  234158. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234159. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234160. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234161. inMode: NSDefaultRunLoopMode
  234162. dequeue: YES];
  234163. if (e != 0 && ! isEventBlockedByModalComps (e))
  234164. [NSApp sendEvent: e];
  234165. if (Time::getMillisecondCounter() >= endTime)
  234166. break;
  234167. }
  234168. return ! quitMessagePosted;
  234169. }
  234170. void MessageManager::doPlatformSpecificInitialisation()
  234171. {
  234172. if (juceAppDelegate == 0)
  234173. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234174. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234175. // correctly (needed prior to 10.5)
  234176. if (! [NSThread isMultiThreaded])
  234177. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234178. toTarget: juceAppDelegate
  234179. withObject: nil];
  234180. }
  234181. void MessageManager::doPlatformSpecificShutdown()
  234182. {
  234183. if (juceAppDelegate != 0)
  234184. {
  234185. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234186. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234187. [juceAppDelegate release];
  234188. juceAppDelegate = 0;
  234189. }
  234190. }
  234191. bool juce_postMessageToSystemQueue (Message* message)
  234192. {
  234193. juceAppDelegate->redirector->postMessage (message);
  234194. return true;
  234195. }
  234196. void MessageManager::broadcastMessage (const String&)
  234197. {
  234198. }
  234199. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234200. {
  234201. if (isThisTheMessageThread())
  234202. {
  234203. return (*callback) (data);
  234204. }
  234205. else
  234206. {
  234207. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234208. // deadlock because the message manager is blocked from running, so can never
  234209. // call your function..
  234210. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234211. const ScopedAutoReleasePool pool;
  234212. AppDelegateRedirector::CallbackMessagePayload cmp;
  234213. cmp.function = callback;
  234214. cmp.parameter = data;
  234215. cmp.result = 0;
  234216. cmp.hasBeenExecuted = false;
  234217. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234218. withObject: [NSData dataWithBytesNoCopy: &cmp
  234219. length: sizeof (cmp)
  234220. freeWhenDone: NO]
  234221. waitUntilDone: YES];
  234222. return cmp.result;
  234223. }
  234224. }
  234225. #endif
  234226. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234227. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234228. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234229. // compiled on its own).
  234230. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234231. #if JUCE_MAC
  234232. END_JUCE_NAMESPACE
  234233. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234234. @interface DownloadClickDetector : NSObject
  234235. {
  234236. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234237. }
  234238. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234239. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234240. request: (NSURLRequest*) request
  234241. frame: (WebFrame*) frame
  234242. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234243. @end
  234244. @implementation DownloadClickDetector
  234245. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234246. {
  234247. [super init];
  234248. ownerComponent = ownerComponent_;
  234249. return self;
  234250. }
  234251. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234252. request: (NSURLRequest*) request
  234253. frame: (WebFrame*) frame
  234254. decisionListener: (id <WebPolicyDecisionListener>) listener
  234255. {
  234256. (void) sender;
  234257. (void) request;
  234258. (void) frame;
  234259. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234260. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234261. [listener use];
  234262. else
  234263. [listener ignore];
  234264. }
  234265. @end
  234266. BEGIN_JUCE_NAMESPACE
  234267. class WebBrowserComponentInternal : public NSViewComponent
  234268. {
  234269. public:
  234270. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234271. {
  234272. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234273. frameName: @""
  234274. groupName: @""];
  234275. setView (webView);
  234276. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234277. [webView setPolicyDelegate: clickListener];
  234278. }
  234279. ~WebBrowserComponentInternal()
  234280. {
  234281. [webView setPolicyDelegate: nil];
  234282. [clickListener release];
  234283. setView (0);
  234284. }
  234285. void goToURL (const String& url,
  234286. const StringArray* headers,
  234287. const MemoryBlock* postData)
  234288. {
  234289. NSMutableURLRequest* r
  234290. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234291. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234292. timeoutInterval: 30.0];
  234293. if (postData != 0 && postData->getSize() > 0)
  234294. {
  234295. [r setHTTPMethod: @"POST"];
  234296. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234297. length: postData->getSize()]];
  234298. }
  234299. if (headers != 0)
  234300. {
  234301. for (int i = 0; i < headers->size(); ++i)
  234302. {
  234303. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234304. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234305. [r setValue: juceStringToNS (headerValue)
  234306. forHTTPHeaderField: juceStringToNS (headerName)];
  234307. }
  234308. }
  234309. stop();
  234310. [[webView mainFrame] loadRequest: r];
  234311. }
  234312. void goBack()
  234313. {
  234314. [webView goBack];
  234315. }
  234316. void goForward()
  234317. {
  234318. [webView goForward];
  234319. }
  234320. void stop()
  234321. {
  234322. [webView stopLoading: nil];
  234323. }
  234324. void refresh()
  234325. {
  234326. [webView reload: nil];
  234327. }
  234328. void mouseMove (const MouseEvent&)
  234329. {
  234330. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234331. // them work is to push them via this non-public method..
  234332. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234333. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234334. }
  234335. private:
  234336. WebView* webView;
  234337. DownloadClickDetector* clickListener;
  234338. };
  234339. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234340. : browser (0),
  234341. blankPageShown (false),
  234342. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234343. {
  234344. setOpaque (true);
  234345. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234346. }
  234347. WebBrowserComponent::~WebBrowserComponent()
  234348. {
  234349. deleteAndZero (browser);
  234350. }
  234351. void WebBrowserComponent::goToURL (const String& url,
  234352. const StringArray* headers,
  234353. const MemoryBlock* postData)
  234354. {
  234355. lastURL = url;
  234356. lastHeaders.clear();
  234357. if (headers != 0)
  234358. lastHeaders = *headers;
  234359. lastPostData.setSize (0);
  234360. if (postData != 0)
  234361. lastPostData = *postData;
  234362. blankPageShown = false;
  234363. browser->goToURL (url, headers, postData);
  234364. }
  234365. void WebBrowserComponent::stop()
  234366. {
  234367. browser->stop();
  234368. }
  234369. void WebBrowserComponent::goBack()
  234370. {
  234371. lastURL = String::empty;
  234372. blankPageShown = false;
  234373. browser->goBack();
  234374. }
  234375. void WebBrowserComponent::goForward()
  234376. {
  234377. lastURL = String::empty;
  234378. browser->goForward();
  234379. }
  234380. void WebBrowserComponent::refresh()
  234381. {
  234382. browser->refresh();
  234383. }
  234384. void WebBrowserComponent::paint (Graphics&)
  234385. {
  234386. }
  234387. void WebBrowserComponent::checkWindowAssociation()
  234388. {
  234389. if (isShowing())
  234390. {
  234391. if (blankPageShown)
  234392. goBack();
  234393. }
  234394. else
  234395. {
  234396. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234397. {
  234398. // when the component becomes invisible, some stuff like flash
  234399. // carries on playing audio, so we need to force it onto a blank
  234400. // page to avoid this, (and send it back when it's made visible again).
  234401. blankPageShown = true;
  234402. browser->goToURL ("about:blank", 0, 0);
  234403. }
  234404. }
  234405. }
  234406. void WebBrowserComponent::reloadLastURL()
  234407. {
  234408. if (lastURL.isNotEmpty())
  234409. {
  234410. goToURL (lastURL, &lastHeaders, &lastPostData);
  234411. lastURL = String::empty;
  234412. }
  234413. }
  234414. void WebBrowserComponent::parentHierarchyChanged()
  234415. {
  234416. checkWindowAssociation();
  234417. }
  234418. void WebBrowserComponent::resized()
  234419. {
  234420. browser->setSize (getWidth(), getHeight());
  234421. }
  234422. void WebBrowserComponent::visibilityChanged()
  234423. {
  234424. checkWindowAssociation();
  234425. }
  234426. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234427. {
  234428. return true;
  234429. }
  234430. #else
  234431. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234432. {
  234433. }
  234434. WebBrowserComponent::~WebBrowserComponent()
  234435. {
  234436. }
  234437. void WebBrowserComponent::goToURL (const String& url,
  234438. const StringArray* headers,
  234439. const MemoryBlock* postData)
  234440. {
  234441. }
  234442. void WebBrowserComponent::stop()
  234443. {
  234444. }
  234445. void WebBrowserComponent::goBack()
  234446. {
  234447. }
  234448. void WebBrowserComponent::goForward()
  234449. {
  234450. }
  234451. void WebBrowserComponent::refresh()
  234452. {
  234453. }
  234454. void WebBrowserComponent::paint (Graphics& g)
  234455. {
  234456. }
  234457. void WebBrowserComponent::checkWindowAssociation()
  234458. {
  234459. }
  234460. void WebBrowserComponent::reloadLastURL()
  234461. {
  234462. }
  234463. void WebBrowserComponent::parentHierarchyChanged()
  234464. {
  234465. }
  234466. void WebBrowserComponent::resized()
  234467. {
  234468. }
  234469. void WebBrowserComponent::visibilityChanged()
  234470. {
  234471. }
  234472. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234473. {
  234474. return true;
  234475. }
  234476. #endif
  234477. #endif
  234478. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234479. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234480. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234481. // compiled on its own).
  234482. #if JUCE_INCLUDED_FILE
  234483. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234484. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234485. #endif
  234486. #undef log
  234487. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234488. #define log(a) Logger::writeToLog (a)
  234489. #else
  234490. #define log(a)
  234491. #endif
  234492. #undef OK
  234493. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234494. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234495. {
  234496. if (err == noErr)
  234497. return true;
  234498. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234499. jassertfalse;
  234500. return false;
  234501. }
  234502. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234503. #else
  234504. #define OK(a) (a == noErr)
  234505. #endif
  234506. class CoreAudioInternal : public Timer
  234507. {
  234508. public:
  234509. CoreAudioInternal (AudioDeviceID id)
  234510. : inputLatency (0),
  234511. outputLatency (0),
  234512. callback (0),
  234513. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234514. audioProcID (0),
  234515. #endif
  234516. isSlaveDevice (false),
  234517. deviceID (id),
  234518. started (false),
  234519. sampleRate (0),
  234520. bufferSize (512),
  234521. numInputChans (0),
  234522. numOutputChans (0),
  234523. callbacksAllowed (true),
  234524. numInputChannelInfos (0),
  234525. numOutputChannelInfos (0)
  234526. {
  234527. jassert (deviceID != 0);
  234528. updateDetailsFromDevice();
  234529. AudioObjectPropertyAddress pa;
  234530. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234531. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234532. pa.mElement = kAudioObjectPropertyElementWildcard;
  234533. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234534. }
  234535. ~CoreAudioInternal()
  234536. {
  234537. AudioObjectPropertyAddress pa;
  234538. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234539. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234540. pa.mElement = kAudioObjectPropertyElementWildcard;
  234541. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234542. stop (false);
  234543. }
  234544. void allocateTempBuffers()
  234545. {
  234546. const int tempBufSize = bufferSize + 4;
  234547. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234548. tempInputBuffers.calloc (numInputChans + 2);
  234549. tempOutputBuffers.calloc (numOutputChans + 2);
  234550. int i, count = 0;
  234551. for (i = 0; i < numInputChans; ++i)
  234552. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234553. for (i = 0; i < numOutputChans; ++i)
  234554. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234555. }
  234556. // returns the number of actual available channels
  234557. void fillInChannelInfo (const bool input)
  234558. {
  234559. int chanNum = 0;
  234560. UInt32 size;
  234561. AudioObjectPropertyAddress pa;
  234562. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234563. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234564. pa.mElement = kAudioObjectPropertyElementMaster;
  234565. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234566. {
  234567. HeapBlock <AudioBufferList> bufList;
  234568. bufList.calloc (size, 1);
  234569. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234570. {
  234571. const int numStreams = bufList->mNumberBuffers;
  234572. for (int i = 0; i < numStreams; ++i)
  234573. {
  234574. const AudioBuffer& b = bufList->mBuffers[i];
  234575. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234576. {
  234577. String name;
  234578. {
  234579. char channelName [256];
  234580. zerostruct (channelName);
  234581. UInt32 nameSize = sizeof (channelName);
  234582. UInt32 channelNum = chanNum + 1;
  234583. pa.mSelector = kAudioDevicePropertyChannelName;
  234584. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234585. name = String::fromUTF8 (channelName, nameSize);
  234586. }
  234587. if (input)
  234588. {
  234589. if (activeInputChans[chanNum])
  234590. {
  234591. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234592. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234593. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234594. ++numInputChannelInfos;
  234595. }
  234596. if (name.isEmpty())
  234597. name << "Input " << (chanNum + 1);
  234598. inChanNames.add (name);
  234599. }
  234600. else
  234601. {
  234602. if (activeOutputChans[chanNum])
  234603. {
  234604. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234605. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234606. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234607. ++numOutputChannelInfos;
  234608. }
  234609. if (name.isEmpty())
  234610. name << "Output " << (chanNum + 1);
  234611. outChanNames.add (name);
  234612. }
  234613. ++chanNum;
  234614. }
  234615. }
  234616. }
  234617. }
  234618. }
  234619. void updateDetailsFromDevice()
  234620. {
  234621. stopTimer();
  234622. if (deviceID == 0)
  234623. return;
  234624. const ScopedLock sl (callbackLock);
  234625. Float64 sr;
  234626. UInt32 size = sizeof (Float64);
  234627. AudioObjectPropertyAddress pa;
  234628. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234629. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234630. pa.mElement = kAudioObjectPropertyElementMaster;
  234631. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234632. sampleRate = sr;
  234633. UInt32 framesPerBuf;
  234634. size = sizeof (framesPerBuf);
  234635. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234636. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234637. {
  234638. bufferSize = framesPerBuf;
  234639. allocateTempBuffers();
  234640. }
  234641. bufferSizes.clear();
  234642. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234643. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234644. {
  234645. HeapBlock <AudioValueRange> ranges;
  234646. ranges.calloc (size, 1);
  234647. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234648. {
  234649. bufferSizes.add ((int) ranges[0].mMinimum);
  234650. for (int i = 32; i < 2048; i += 32)
  234651. {
  234652. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234653. {
  234654. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234655. {
  234656. bufferSizes.addIfNotAlreadyThere (i);
  234657. break;
  234658. }
  234659. }
  234660. }
  234661. if (bufferSize > 0)
  234662. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234663. }
  234664. }
  234665. if (bufferSizes.size() == 0 && bufferSize > 0)
  234666. bufferSizes.add (bufferSize);
  234667. sampleRates.clear();
  234668. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234669. String rates;
  234670. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234671. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234672. {
  234673. HeapBlock <AudioValueRange> ranges;
  234674. ranges.calloc (size, 1);
  234675. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234676. {
  234677. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234678. {
  234679. bool ok = false;
  234680. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234681. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234682. ok = true;
  234683. if (ok)
  234684. {
  234685. sampleRates.add (possibleRates[i]);
  234686. rates << possibleRates[i] << ' ';
  234687. }
  234688. }
  234689. }
  234690. }
  234691. if (sampleRates.size() == 0 && sampleRate > 0)
  234692. {
  234693. sampleRates.add (sampleRate);
  234694. rates << sampleRate;
  234695. }
  234696. log ("sr: " + rates);
  234697. inputLatency = 0;
  234698. outputLatency = 0;
  234699. UInt32 lat;
  234700. size = sizeof (lat);
  234701. pa.mSelector = kAudioDevicePropertyLatency;
  234702. pa.mScope = kAudioDevicePropertyScopeInput;
  234703. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234704. inputLatency = (int) lat;
  234705. pa.mScope = kAudioDevicePropertyScopeOutput;
  234706. size = sizeof (lat);
  234707. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234708. outputLatency = (int) lat;
  234709. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234710. inChanNames.clear();
  234711. outChanNames.clear();
  234712. inputChannelInfo.calloc (numInputChans + 2);
  234713. numInputChannelInfos = 0;
  234714. outputChannelInfo.calloc (numOutputChans + 2);
  234715. numOutputChannelInfos = 0;
  234716. fillInChannelInfo (true);
  234717. fillInChannelInfo (false);
  234718. }
  234719. const StringArray getSources (bool input)
  234720. {
  234721. StringArray s;
  234722. HeapBlock <OSType> types;
  234723. const int num = getAllDataSourcesForDevice (deviceID, types);
  234724. for (int i = 0; i < num; ++i)
  234725. {
  234726. AudioValueTranslation avt;
  234727. char buffer[256];
  234728. avt.mInputData = &(types[i]);
  234729. avt.mInputDataSize = sizeof (UInt32);
  234730. avt.mOutputData = buffer;
  234731. avt.mOutputDataSize = 256;
  234732. UInt32 transSize = sizeof (avt);
  234733. AudioObjectPropertyAddress pa;
  234734. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234735. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234736. pa.mElement = kAudioObjectPropertyElementMaster;
  234737. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234738. {
  234739. DBG (buffer);
  234740. s.add (buffer);
  234741. }
  234742. }
  234743. return s;
  234744. }
  234745. int getCurrentSourceIndex (bool input) const
  234746. {
  234747. OSType currentSourceID = 0;
  234748. UInt32 size = sizeof (currentSourceID);
  234749. int result = -1;
  234750. AudioObjectPropertyAddress pa;
  234751. pa.mSelector = kAudioDevicePropertyDataSource;
  234752. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234753. pa.mElement = kAudioObjectPropertyElementMaster;
  234754. if (deviceID != 0)
  234755. {
  234756. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234757. {
  234758. HeapBlock <OSType> types;
  234759. const int num = getAllDataSourcesForDevice (deviceID, types);
  234760. for (int i = 0; i < num; ++i)
  234761. {
  234762. if (types[num] == currentSourceID)
  234763. {
  234764. result = i;
  234765. break;
  234766. }
  234767. }
  234768. }
  234769. }
  234770. return result;
  234771. }
  234772. void setCurrentSourceIndex (int index, bool input)
  234773. {
  234774. if (deviceID != 0)
  234775. {
  234776. HeapBlock <OSType> types;
  234777. const int num = getAllDataSourcesForDevice (deviceID, types);
  234778. if (isPositiveAndBelow (index, num))
  234779. {
  234780. AudioObjectPropertyAddress pa;
  234781. pa.mSelector = kAudioDevicePropertyDataSource;
  234782. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234783. pa.mElement = kAudioObjectPropertyElementMaster;
  234784. OSType typeId = types[index];
  234785. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234786. }
  234787. }
  234788. }
  234789. const String reopen (const BigInteger& inputChannels,
  234790. const BigInteger& outputChannels,
  234791. double newSampleRate,
  234792. int bufferSizeSamples)
  234793. {
  234794. String error;
  234795. log ("CoreAudio reopen");
  234796. callbacksAllowed = false;
  234797. stopTimer();
  234798. stop (false);
  234799. activeInputChans = inputChannels;
  234800. activeInputChans.setRange (inChanNames.size(),
  234801. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234802. false);
  234803. activeOutputChans = outputChannels;
  234804. activeOutputChans.setRange (outChanNames.size(),
  234805. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234806. false);
  234807. numInputChans = activeInputChans.countNumberOfSetBits();
  234808. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234809. // set sample rate
  234810. AudioObjectPropertyAddress pa;
  234811. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234812. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234813. pa.mElement = kAudioObjectPropertyElementMaster;
  234814. Float64 sr = newSampleRate;
  234815. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234816. {
  234817. error = "Couldn't change sample rate";
  234818. }
  234819. else
  234820. {
  234821. // change buffer size
  234822. UInt32 framesPerBuf = bufferSizeSamples;
  234823. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234824. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234825. {
  234826. error = "Couldn't change buffer size";
  234827. }
  234828. else
  234829. {
  234830. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234831. // correctly report their new settings until some random time in the future, so
  234832. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234833. // to make sure we're using the correct numbers..
  234834. updateDetailsFromDevice();
  234835. sampleRate = newSampleRate;
  234836. bufferSize = bufferSizeSamples;
  234837. if (sampleRates.size() == 0)
  234838. error = "Device has no available sample-rates";
  234839. else if (bufferSizes.size() == 0)
  234840. error = "Device has no available buffer-sizes";
  234841. else if (inputDevice != 0)
  234842. error = inputDevice->reopen (inputChannels,
  234843. outputChannels,
  234844. newSampleRate,
  234845. bufferSizeSamples);
  234846. }
  234847. }
  234848. callbacksAllowed = true;
  234849. return error;
  234850. }
  234851. bool start (AudioIODeviceCallback* cb)
  234852. {
  234853. if (! started)
  234854. {
  234855. callback = 0;
  234856. if (deviceID != 0)
  234857. {
  234858. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234859. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234860. #else
  234861. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234862. #endif
  234863. {
  234864. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234865. {
  234866. started = true;
  234867. }
  234868. else
  234869. {
  234870. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234871. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234872. #else
  234873. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234874. audioProcID = 0;
  234875. #endif
  234876. }
  234877. }
  234878. }
  234879. }
  234880. if (started)
  234881. {
  234882. const ScopedLock sl (callbackLock);
  234883. callback = cb;
  234884. }
  234885. if (inputDevice != 0)
  234886. return started && inputDevice->start (cb);
  234887. else
  234888. return started;
  234889. }
  234890. void stop (bool leaveInterruptRunning)
  234891. {
  234892. {
  234893. const ScopedLock sl (callbackLock);
  234894. callback = 0;
  234895. }
  234896. if (started
  234897. && (deviceID != 0)
  234898. && ! leaveInterruptRunning)
  234899. {
  234900. OK (AudioDeviceStop (deviceID, audioIOProc));
  234901. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234902. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234903. #else
  234904. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234905. audioProcID = 0;
  234906. #endif
  234907. started = false;
  234908. { const ScopedLock sl (callbackLock); }
  234909. // wait until it's definately stopped calling back..
  234910. for (int i = 40; --i >= 0;)
  234911. {
  234912. Thread::sleep (50);
  234913. UInt32 running = 0;
  234914. UInt32 size = sizeof (running);
  234915. AudioObjectPropertyAddress pa;
  234916. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234917. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234918. pa.mElement = kAudioObjectPropertyElementMaster;
  234919. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234920. if (running == 0)
  234921. break;
  234922. }
  234923. const ScopedLock sl (callbackLock);
  234924. }
  234925. if (inputDevice != 0)
  234926. inputDevice->stop (leaveInterruptRunning);
  234927. }
  234928. double getSampleRate() const
  234929. {
  234930. return sampleRate;
  234931. }
  234932. int getBufferSize() const
  234933. {
  234934. return bufferSize;
  234935. }
  234936. void audioCallback (const AudioBufferList* inInputData,
  234937. AudioBufferList* outOutputData)
  234938. {
  234939. int i;
  234940. const ScopedLock sl (callbackLock);
  234941. if (callback != 0)
  234942. {
  234943. if (inputDevice == 0)
  234944. {
  234945. for (i = numInputChans; --i >= 0;)
  234946. {
  234947. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  234948. float* dest = tempInputBuffers [i];
  234949. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  234950. + info.dataOffsetSamples;
  234951. const int stride = info.dataStrideSamples;
  234952. if (stride != 0) // if this is zero, info is invalid
  234953. {
  234954. for (int j = bufferSize; --j >= 0;)
  234955. {
  234956. *dest++ = *src;
  234957. src += stride;
  234958. }
  234959. }
  234960. }
  234961. }
  234962. if (! isSlaveDevice)
  234963. {
  234964. if (inputDevice == 0)
  234965. {
  234966. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  234967. numInputChans,
  234968. tempOutputBuffers,
  234969. numOutputChans,
  234970. bufferSize);
  234971. }
  234972. else
  234973. {
  234974. jassert (inputDevice->bufferSize == bufferSize);
  234975. // Sometimes the two linked devices seem to get their callbacks in
  234976. // parallel, so we need to lock both devices to stop the input data being
  234977. // changed while inside our callback..
  234978. const ScopedLock sl2 (inputDevice->callbackLock);
  234979. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234980. inputDevice->numInputChans,
  234981. tempOutputBuffers,
  234982. numOutputChans,
  234983. bufferSize);
  234984. }
  234985. for (i = numOutputChans; --i >= 0;)
  234986. {
  234987. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234988. const float* src = tempOutputBuffers [i];
  234989. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234990. + info.dataOffsetSamples;
  234991. const int stride = info.dataStrideSamples;
  234992. if (stride != 0) // if this is zero, info is invalid
  234993. {
  234994. for (int j = bufferSize; --j >= 0;)
  234995. {
  234996. *dest = *src++;
  234997. dest += stride;
  234998. }
  234999. }
  235000. }
  235001. }
  235002. }
  235003. else
  235004. {
  235005. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235006. {
  235007. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235008. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235009. + info.dataOffsetSamples;
  235010. const int stride = info.dataStrideSamples;
  235011. if (stride != 0) // if this is zero, info is invalid
  235012. {
  235013. for (int j = bufferSize; --j >= 0;)
  235014. {
  235015. *dest = 0.0f;
  235016. dest += stride;
  235017. }
  235018. }
  235019. }
  235020. }
  235021. }
  235022. // called by callbacks
  235023. void deviceDetailsChanged()
  235024. {
  235025. if (callbacksAllowed)
  235026. startTimer (100);
  235027. }
  235028. void timerCallback()
  235029. {
  235030. stopTimer();
  235031. log ("CoreAudio device changed callback");
  235032. const double oldSampleRate = sampleRate;
  235033. const int oldBufferSize = bufferSize;
  235034. updateDetailsFromDevice();
  235035. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235036. {
  235037. callbacksAllowed = false;
  235038. stop (false);
  235039. updateDetailsFromDevice();
  235040. callbacksAllowed = true;
  235041. }
  235042. }
  235043. CoreAudioInternal* getRelatedDevice() const
  235044. {
  235045. UInt32 size = 0;
  235046. ScopedPointer <CoreAudioInternal> result;
  235047. AudioObjectPropertyAddress pa;
  235048. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235049. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235050. pa.mElement = kAudioObjectPropertyElementMaster;
  235051. if (deviceID != 0
  235052. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235053. && size > 0)
  235054. {
  235055. HeapBlock <AudioDeviceID> devs;
  235056. devs.calloc (size, 1);
  235057. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235058. {
  235059. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235060. {
  235061. if (devs[i] != deviceID && devs[i] != 0)
  235062. {
  235063. result = new CoreAudioInternal (devs[i]);
  235064. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235065. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235066. if (thisIsInput != otherIsInput
  235067. || (inChanNames.size() + outChanNames.size() == 0)
  235068. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235069. break;
  235070. result = 0;
  235071. }
  235072. }
  235073. }
  235074. }
  235075. return result.release();
  235076. }
  235077. int inputLatency, outputLatency;
  235078. BigInteger activeInputChans, activeOutputChans;
  235079. StringArray inChanNames, outChanNames;
  235080. Array <double> sampleRates;
  235081. Array <int> bufferSizes;
  235082. AudioIODeviceCallback* callback;
  235083. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235084. AudioDeviceIOProcID audioProcID;
  235085. #endif
  235086. ScopedPointer<CoreAudioInternal> inputDevice;
  235087. bool isSlaveDevice;
  235088. private:
  235089. CriticalSection callbackLock;
  235090. AudioDeviceID deviceID;
  235091. bool started;
  235092. double sampleRate;
  235093. int bufferSize;
  235094. HeapBlock <float> audioBuffer;
  235095. int numInputChans, numOutputChans;
  235096. bool callbacksAllowed;
  235097. struct CallbackDetailsForChannel
  235098. {
  235099. int streamNum;
  235100. int dataOffsetSamples;
  235101. int dataStrideSamples;
  235102. };
  235103. int numInputChannelInfos, numOutputChannelInfos;
  235104. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235105. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235106. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235107. const AudioTimeStamp* /*inNow*/,
  235108. const AudioBufferList* inInputData,
  235109. const AudioTimeStamp* /*inInputTime*/,
  235110. AudioBufferList* outOutputData,
  235111. const AudioTimeStamp* /*inOutputTime*/,
  235112. void* device)
  235113. {
  235114. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235115. return noErr;
  235116. }
  235117. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235118. {
  235119. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235120. switch (pa->mSelector)
  235121. {
  235122. case kAudioDevicePropertyBufferSize:
  235123. case kAudioDevicePropertyBufferFrameSize:
  235124. case kAudioDevicePropertyNominalSampleRate:
  235125. case kAudioDevicePropertyStreamFormat:
  235126. case kAudioDevicePropertyDeviceIsAlive:
  235127. intern->deviceDetailsChanged();
  235128. break;
  235129. case kAudioDevicePropertyBufferSizeRange:
  235130. case kAudioDevicePropertyVolumeScalar:
  235131. case kAudioDevicePropertyMute:
  235132. case kAudioDevicePropertyPlayThru:
  235133. case kAudioDevicePropertyDataSource:
  235134. case kAudioDevicePropertyDeviceIsRunning:
  235135. break;
  235136. }
  235137. return noErr;
  235138. }
  235139. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235140. {
  235141. AudioObjectPropertyAddress pa;
  235142. pa.mSelector = kAudioDevicePropertyDataSources;
  235143. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235144. pa.mElement = kAudioObjectPropertyElementMaster;
  235145. UInt32 size = 0;
  235146. if (deviceID != 0
  235147. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235148. {
  235149. types.calloc (size, 1);
  235150. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235151. return size / (int) sizeof (OSType);
  235152. }
  235153. return 0;
  235154. }
  235155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235156. };
  235157. class CoreAudioIODevice : public AudioIODevice
  235158. {
  235159. public:
  235160. CoreAudioIODevice (const String& deviceName,
  235161. AudioDeviceID inputDeviceId,
  235162. const int inputIndex_,
  235163. AudioDeviceID outputDeviceId,
  235164. const int outputIndex_)
  235165. : AudioIODevice (deviceName, "CoreAudio"),
  235166. inputIndex (inputIndex_),
  235167. outputIndex (outputIndex_),
  235168. isOpen_ (false),
  235169. isStarted (false)
  235170. {
  235171. CoreAudioInternal* device = 0;
  235172. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235173. {
  235174. jassert (inputDeviceId != 0);
  235175. device = new CoreAudioInternal (inputDeviceId);
  235176. }
  235177. else
  235178. {
  235179. device = new CoreAudioInternal (outputDeviceId);
  235180. if (inputDeviceId != 0)
  235181. {
  235182. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235183. device->inputDevice = secondDevice;
  235184. secondDevice->isSlaveDevice = true;
  235185. }
  235186. }
  235187. internal = device;
  235188. AudioObjectPropertyAddress pa;
  235189. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235190. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235191. pa.mElement = kAudioObjectPropertyElementWildcard;
  235192. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235193. }
  235194. ~CoreAudioIODevice()
  235195. {
  235196. AudioObjectPropertyAddress pa;
  235197. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235198. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235199. pa.mElement = kAudioObjectPropertyElementWildcard;
  235200. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235201. }
  235202. const StringArray getOutputChannelNames()
  235203. {
  235204. return internal->outChanNames;
  235205. }
  235206. const StringArray getInputChannelNames()
  235207. {
  235208. if (internal->inputDevice != 0)
  235209. return internal->inputDevice->inChanNames;
  235210. else
  235211. return internal->inChanNames;
  235212. }
  235213. int getNumSampleRates()
  235214. {
  235215. return internal->sampleRates.size();
  235216. }
  235217. double getSampleRate (int index)
  235218. {
  235219. return internal->sampleRates [index];
  235220. }
  235221. int getNumBufferSizesAvailable()
  235222. {
  235223. return internal->bufferSizes.size();
  235224. }
  235225. int getBufferSizeSamples (int index)
  235226. {
  235227. return internal->bufferSizes [index];
  235228. }
  235229. int getDefaultBufferSize()
  235230. {
  235231. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235232. if (getBufferSizeSamples(i) >= 512)
  235233. return getBufferSizeSamples(i);
  235234. return 512;
  235235. }
  235236. const String open (const BigInteger& inputChannels,
  235237. const BigInteger& outputChannels,
  235238. double sampleRate,
  235239. int bufferSizeSamples)
  235240. {
  235241. isOpen_ = true;
  235242. if (bufferSizeSamples <= 0)
  235243. bufferSizeSamples = getDefaultBufferSize();
  235244. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235245. isOpen_ = lastError.isEmpty();
  235246. return lastError;
  235247. }
  235248. void close()
  235249. {
  235250. isOpen_ = false;
  235251. internal->stop (false);
  235252. }
  235253. bool isOpen()
  235254. {
  235255. return isOpen_;
  235256. }
  235257. int getCurrentBufferSizeSamples()
  235258. {
  235259. return internal != 0 ? internal->getBufferSize() : 512;
  235260. }
  235261. double getCurrentSampleRate()
  235262. {
  235263. return internal != 0 ? internal->getSampleRate() : 0;
  235264. }
  235265. int getCurrentBitDepth()
  235266. {
  235267. return 32; // no way to find out, so just assume it's high..
  235268. }
  235269. const BigInteger getActiveOutputChannels() const
  235270. {
  235271. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235272. }
  235273. const BigInteger getActiveInputChannels() const
  235274. {
  235275. BigInteger chans;
  235276. if (internal != 0)
  235277. {
  235278. chans = internal->activeInputChans;
  235279. if (internal->inputDevice != 0)
  235280. chans |= internal->inputDevice->activeInputChans;
  235281. }
  235282. return chans;
  235283. }
  235284. int getOutputLatencyInSamples()
  235285. {
  235286. if (internal == 0)
  235287. return 0;
  235288. // this seems like a good guess at getting the latency right - comparing
  235289. // this with a round-trip measurement, it gets it to within a few millisecs
  235290. // for the built-in mac soundcard
  235291. return internal->outputLatency + internal->getBufferSize() * 2;
  235292. }
  235293. int getInputLatencyInSamples()
  235294. {
  235295. if (internal == 0)
  235296. return 0;
  235297. return internal->inputLatency + internal->getBufferSize() * 2;
  235298. }
  235299. void start (AudioIODeviceCallback* callback)
  235300. {
  235301. if (internal != 0 && ! isStarted)
  235302. {
  235303. if (callback != 0)
  235304. callback->audioDeviceAboutToStart (this);
  235305. isStarted = true;
  235306. internal->start (callback);
  235307. }
  235308. }
  235309. void stop()
  235310. {
  235311. if (isStarted && internal != 0)
  235312. {
  235313. AudioIODeviceCallback* const lastCallback = internal->callback;
  235314. isStarted = false;
  235315. internal->stop (true);
  235316. if (lastCallback != 0)
  235317. lastCallback->audioDeviceStopped();
  235318. }
  235319. }
  235320. bool isPlaying()
  235321. {
  235322. if (internal->callback == 0)
  235323. isStarted = false;
  235324. return isStarted;
  235325. }
  235326. const String getLastError()
  235327. {
  235328. return lastError;
  235329. }
  235330. int inputIndex, outputIndex;
  235331. private:
  235332. ScopedPointer<CoreAudioInternal> internal;
  235333. bool isOpen_, isStarted;
  235334. String lastError;
  235335. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235336. {
  235337. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235338. switch (pa->mSelector)
  235339. {
  235340. case kAudioHardwarePropertyDevices:
  235341. intern->deviceDetailsChanged();
  235342. break;
  235343. case kAudioHardwarePropertyDefaultOutputDevice:
  235344. case kAudioHardwarePropertyDefaultInputDevice:
  235345. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235346. break;
  235347. }
  235348. return noErr;
  235349. }
  235350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235351. };
  235352. class CoreAudioIODeviceType : public AudioIODeviceType
  235353. {
  235354. public:
  235355. CoreAudioIODeviceType()
  235356. : AudioIODeviceType ("CoreAudio"),
  235357. hasScanned (false)
  235358. {
  235359. }
  235360. ~CoreAudioIODeviceType()
  235361. {
  235362. }
  235363. void scanForDevices()
  235364. {
  235365. hasScanned = true;
  235366. inputDeviceNames.clear();
  235367. outputDeviceNames.clear();
  235368. inputIds.clear();
  235369. outputIds.clear();
  235370. UInt32 size;
  235371. AudioObjectPropertyAddress pa;
  235372. pa.mSelector = kAudioHardwarePropertyDevices;
  235373. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235374. pa.mElement = kAudioObjectPropertyElementMaster;
  235375. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235376. {
  235377. HeapBlock <AudioDeviceID> devs;
  235378. devs.calloc (size, 1);
  235379. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235380. {
  235381. const int num = size / (int) sizeof (AudioDeviceID);
  235382. for (int i = 0; i < num; ++i)
  235383. {
  235384. char name [1024];
  235385. size = sizeof (name);
  235386. pa.mSelector = kAudioDevicePropertyDeviceName;
  235387. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235388. {
  235389. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235390. const int numIns = getNumChannels (devs[i], true);
  235391. const int numOuts = getNumChannels (devs[i], false);
  235392. if (numIns > 0)
  235393. {
  235394. inputDeviceNames.add (nameString);
  235395. inputIds.add (devs[i]);
  235396. }
  235397. if (numOuts > 0)
  235398. {
  235399. outputDeviceNames.add (nameString);
  235400. outputIds.add (devs[i]);
  235401. }
  235402. }
  235403. }
  235404. }
  235405. }
  235406. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235407. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235408. }
  235409. const StringArray getDeviceNames (bool wantInputNames) const
  235410. {
  235411. jassert (hasScanned); // need to call scanForDevices() before doing this
  235412. if (wantInputNames)
  235413. return inputDeviceNames;
  235414. else
  235415. return outputDeviceNames;
  235416. }
  235417. int getDefaultDeviceIndex (bool forInput) const
  235418. {
  235419. jassert (hasScanned); // need to call scanForDevices() before doing this
  235420. AudioDeviceID deviceID;
  235421. UInt32 size = sizeof (deviceID);
  235422. // if they're asking for any input channels at all, use the default input, so we
  235423. // get the built-in mic rather than the built-in output with no inputs..
  235424. AudioObjectPropertyAddress pa;
  235425. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235426. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235427. pa.mElement = kAudioObjectPropertyElementMaster;
  235428. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235429. {
  235430. if (forInput)
  235431. {
  235432. for (int i = inputIds.size(); --i >= 0;)
  235433. if (inputIds[i] == deviceID)
  235434. return i;
  235435. }
  235436. else
  235437. {
  235438. for (int i = outputIds.size(); --i >= 0;)
  235439. if (outputIds[i] == deviceID)
  235440. return i;
  235441. }
  235442. }
  235443. return 0;
  235444. }
  235445. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235446. {
  235447. jassert (hasScanned); // need to call scanForDevices() before doing this
  235448. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235449. if (d == 0)
  235450. return -1;
  235451. return asInput ? d->inputIndex
  235452. : d->outputIndex;
  235453. }
  235454. bool hasSeparateInputsAndOutputs() const { return true; }
  235455. AudioIODevice* createDevice (const String& outputDeviceName,
  235456. const String& inputDeviceName)
  235457. {
  235458. jassert (hasScanned); // need to call scanForDevices() before doing this
  235459. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235460. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235461. String deviceName (outputDeviceName);
  235462. if (deviceName.isEmpty())
  235463. deviceName = inputDeviceName;
  235464. if (index >= 0)
  235465. return new CoreAudioIODevice (deviceName,
  235466. inputIds [inputIndex],
  235467. inputIndex,
  235468. outputIds [outputIndex],
  235469. outputIndex);
  235470. return 0;
  235471. }
  235472. private:
  235473. StringArray inputDeviceNames, outputDeviceNames;
  235474. Array <AudioDeviceID> inputIds, outputIds;
  235475. bool hasScanned;
  235476. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235477. {
  235478. int total = 0;
  235479. UInt32 size;
  235480. AudioObjectPropertyAddress pa;
  235481. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235482. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235483. pa.mElement = kAudioObjectPropertyElementMaster;
  235484. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235485. {
  235486. HeapBlock <AudioBufferList> bufList;
  235487. bufList.calloc (size, 1);
  235488. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235489. {
  235490. const int numStreams = bufList->mNumberBuffers;
  235491. for (int i = 0; i < numStreams; ++i)
  235492. {
  235493. const AudioBuffer& b = bufList->mBuffers[i];
  235494. total += b.mNumberChannels;
  235495. }
  235496. }
  235497. }
  235498. return total;
  235499. }
  235500. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235501. };
  235502. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235503. {
  235504. return new CoreAudioIODeviceType();
  235505. }
  235506. #undef log
  235507. #endif
  235508. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235509. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235510. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235511. // compiled on its own).
  235512. #if JUCE_INCLUDED_FILE
  235513. #if JUCE_MAC
  235514. namespace CoreMidiHelpers
  235515. {
  235516. bool logError (const OSStatus err, const int lineNum)
  235517. {
  235518. if (err == noErr)
  235519. return true;
  235520. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235521. jassertfalse;
  235522. return false;
  235523. }
  235524. #undef CHECK_ERROR
  235525. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235526. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235527. {
  235528. String result;
  235529. CFStringRef str = 0;
  235530. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235531. if (str != 0)
  235532. {
  235533. result = PlatformUtilities::cfStringToJuceString (str);
  235534. CFRelease (str);
  235535. str = 0;
  235536. }
  235537. MIDIEntityRef entity = 0;
  235538. MIDIEndpointGetEntity (endpoint, &entity);
  235539. if (entity == 0)
  235540. return result; // probably virtual
  235541. if (result.isEmpty())
  235542. {
  235543. // endpoint name has zero length - try the entity
  235544. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235545. if (str != 0)
  235546. {
  235547. result += PlatformUtilities::cfStringToJuceString (str);
  235548. CFRelease (str);
  235549. str = 0;
  235550. }
  235551. }
  235552. // now consider the device's name
  235553. MIDIDeviceRef device = 0;
  235554. MIDIEntityGetDevice (entity, &device);
  235555. if (device == 0)
  235556. return result;
  235557. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235558. if (str != 0)
  235559. {
  235560. const String s (PlatformUtilities::cfStringToJuceString (str));
  235561. CFRelease (str);
  235562. // if an external device has only one entity, throw away
  235563. // the endpoint name and just use the device name
  235564. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235565. {
  235566. result = s;
  235567. }
  235568. else if (! result.startsWithIgnoreCase (s))
  235569. {
  235570. // prepend the device name to the entity name
  235571. result = (s + " " + result).trimEnd();
  235572. }
  235573. }
  235574. return result;
  235575. }
  235576. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235577. {
  235578. String result;
  235579. // Does the endpoint have connections?
  235580. CFDataRef connections = 0;
  235581. int numConnections = 0;
  235582. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235583. if (connections != 0)
  235584. {
  235585. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235586. if (numConnections > 0)
  235587. {
  235588. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235589. for (int i = 0; i < numConnections; ++i, ++pid)
  235590. {
  235591. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235592. MIDIObjectRef connObject;
  235593. MIDIObjectType connObjectType;
  235594. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235595. if (err == noErr)
  235596. {
  235597. String s;
  235598. if (connObjectType == kMIDIObjectType_ExternalSource
  235599. || connObjectType == kMIDIObjectType_ExternalDestination)
  235600. {
  235601. // Connected to an external device's endpoint (10.3 and later).
  235602. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235603. }
  235604. else
  235605. {
  235606. // Connected to an external device (10.2) (or something else, catch-all)
  235607. CFStringRef str = 0;
  235608. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235609. if (str != 0)
  235610. {
  235611. s = PlatformUtilities::cfStringToJuceString (str);
  235612. CFRelease (str);
  235613. }
  235614. }
  235615. if (s.isNotEmpty())
  235616. {
  235617. if (result.isNotEmpty())
  235618. result += ", ";
  235619. result += s;
  235620. }
  235621. }
  235622. }
  235623. }
  235624. CFRelease (connections);
  235625. }
  235626. if (result.isNotEmpty())
  235627. return result;
  235628. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235629. return getEndpointName (endpoint, false);
  235630. }
  235631. MIDIClientRef getGlobalMidiClient()
  235632. {
  235633. static MIDIClientRef globalMidiClient = 0;
  235634. if (globalMidiClient == 0)
  235635. {
  235636. String name ("JUCE");
  235637. if (JUCEApplication::getInstance() != 0)
  235638. name = JUCEApplication::getInstance()->getApplicationName();
  235639. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235640. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235641. CFRelease (appName);
  235642. }
  235643. return globalMidiClient;
  235644. }
  235645. class MidiPortAndEndpoint
  235646. {
  235647. public:
  235648. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235649. : port (port_), endPoint (endPoint_)
  235650. {
  235651. }
  235652. ~MidiPortAndEndpoint()
  235653. {
  235654. if (port != 0)
  235655. MIDIPortDispose (port);
  235656. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235657. MIDIEndpointDispose (endPoint);
  235658. }
  235659. void send (const MIDIPacketList* const packets)
  235660. {
  235661. if (port != 0)
  235662. MIDISend (port, endPoint, packets);
  235663. else
  235664. MIDIReceived (endPoint, packets);
  235665. }
  235666. MIDIPortRef port;
  235667. MIDIEndpointRef endPoint;
  235668. };
  235669. class MidiPortAndCallback;
  235670. CriticalSection callbackLock;
  235671. Array<MidiPortAndCallback*> activeCallbacks;
  235672. class MidiPortAndCallback
  235673. {
  235674. public:
  235675. MidiPortAndCallback (MidiInputCallback& callback_)
  235676. : input (0), active (false), callback (callback_), concatenator (2048)
  235677. {
  235678. }
  235679. ~MidiPortAndCallback()
  235680. {
  235681. active = false;
  235682. {
  235683. const ScopedLock sl (callbackLock);
  235684. activeCallbacks.removeValue (this);
  235685. }
  235686. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235687. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235688. }
  235689. void handlePackets (const MIDIPacketList* const pktlist)
  235690. {
  235691. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235692. const ScopedLock sl (callbackLock);
  235693. if (activeCallbacks.contains (this) && active)
  235694. {
  235695. const MIDIPacket* packet = &pktlist->packet[0];
  235696. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235697. {
  235698. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235699. input, callback);
  235700. packet = MIDIPacketNext (packet);
  235701. }
  235702. }
  235703. }
  235704. MidiInput* input;
  235705. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235706. volatile bool active;
  235707. private:
  235708. MidiInputCallback& callback;
  235709. MidiDataConcatenator concatenator;
  235710. };
  235711. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235712. {
  235713. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235714. }
  235715. }
  235716. const StringArray MidiOutput::getDevices()
  235717. {
  235718. StringArray s;
  235719. const ItemCount num = MIDIGetNumberOfDestinations();
  235720. for (ItemCount i = 0; i < num; ++i)
  235721. {
  235722. MIDIEndpointRef dest = MIDIGetDestination (i);
  235723. if (dest != 0)
  235724. {
  235725. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235726. if (name.isEmpty())
  235727. name = "<error>";
  235728. s.add (name);
  235729. }
  235730. else
  235731. {
  235732. s.add ("<error>");
  235733. }
  235734. }
  235735. return s;
  235736. }
  235737. int MidiOutput::getDefaultDeviceIndex()
  235738. {
  235739. return 0;
  235740. }
  235741. MidiOutput* MidiOutput::openDevice (int index)
  235742. {
  235743. MidiOutput* mo = 0;
  235744. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235745. {
  235746. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235747. CFStringRef pname;
  235748. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235749. {
  235750. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235751. MIDIPortRef port;
  235752. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235753. {
  235754. mo = new MidiOutput();
  235755. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235756. }
  235757. CFRelease (pname);
  235758. }
  235759. }
  235760. return mo;
  235761. }
  235762. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235763. {
  235764. MidiOutput* mo = 0;
  235765. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235766. MIDIEndpointRef endPoint;
  235767. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235768. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235769. {
  235770. mo = new MidiOutput();
  235771. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235772. }
  235773. CFRelease (name);
  235774. return mo;
  235775. }
  235776. MidiOutput::~MidiOutput()
  235777. {
  235778. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235779. }
  235780. void MidiOutput::reset()
  235781. {
  235782. }
  235783. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235784. {
  235785. return false;
  235786. }
  235787. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235788. {
  235789. }
  235790. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235791. {
  235792. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235793. if (message.isSysEx())
  235794. {
  235795. const int maxPacketSize = 256;
  235796. int pos = 0, bytesLeft = message.getRawDataSize();
  235797. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235798. HeapBlock <MIDIPacketList> packets;
  235799. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235800. packets->numPackets = numPackets;
  235801. MIDIPacket* p = packets->packet;
  235802. for (int i = 0; i < numPackets; ++i)
  235803. {
  235804. p->timeStamp = AudioGetCurrentHostTime();
  235805. p->length = jmin (maxPacketSize, bytesLeft);
  235806. memcpy (p->data, message.getRawData() + pos, p->length);
  235807. pos += p->length;
  235808. bytesLeft -= p->length;
  235809. p = MIDIPacketNext (p);
  235810. }
  235811. mpe->send (packets);
  235812. }
  235813. else
  235814. {
  235815. MIDIPacketList packets;
  235816. packets.numPackets = 1;
  235817. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  235818. packets.packet[0].length = message.getRawDataSize();
  235819. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235820. mpe->send (&packets);
  235821. }
  235822. }
  235823. const StringArray MidiInput::getDevices()
  235824. {
  235825. StringArray s;
  235826. const ItemCount num = MIDIGetNumberOfSources();
  235827. for (ItemCount i = 0; i < num; ++i)
  235828. {
  235829. MIDIEndpointRef source = MIDIGetSource (i);
  235830. if (source != 0)
  235831. {
  235832. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  235833. if (name.isEmpty())
  235834. name = "<error>";
  235835. s.add (name);
  235836. }
  235837. else
  235838. {
  235839. s.add ("<error>");
  235840. }
  235841. }
  235842. return s;
  235843. }
  235844. int MidiInput::getDefaultDeviceIndex()
  235845. {
  235846. return 0;
  235847. }
  235848. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235849. {
  235850. jassert (callback != 0);
  235851. using namespace CoreMidiHelpers;
  235852. MidiInput* newInput = 0;
  235853. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  235854. {
  235855. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235856. if (endPoint != 0)
  235857. {
  235858. CFStringRef name;
  235859. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  235860. {
  235861. MIDIClientRef client = getGlobalMidiClient();
  235862. if (client != 0)
  235863. {
  235864. MIDIPortRef port;
  235865. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235866. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  235867. {
  235868. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  235869. {
  235870. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235871. newInput = new MidiInput (getDevices() [index]);
  235872. mpc->input = newInput;
  235873. newInput->internal = mpc;
  235874. const ScopedLock sl (callbackLock);
  235875. activeCallbacks.add (mpc.release());
  235876. }
  235877. else
  235878. {
  235879. CHECK_ERROR (MIDIPortDispose (port));
  235880. }
  235881. }
  235882. }
  235883. }
  235884. CFRelease (name);
  235885. }
  235886. }
  235887. return newInput;
  235888. }
  235889. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235890. {
  235891. jassert (callback != 0);
  235892. using namespace CoreMidiHelpers;
  235893. MidiInput* mi = 0;
  235894. MIDIClientRef client = getGlobalMidiClient();
  235895. if (client != 0)
  235896. {
  235897. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235898. mpc->active = false;
  235899. MIDIEndpointRef endPoint;
  235900. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235901. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  235902. {
  235903. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235904. mi = new MidiInput (deviceName);
  235905. mpc->input = mi;
  235906. mi->internal = mpc;
  235907. const ScopedLock sl (callbackLock);
  235908. activeCallbacks.add (mpc.release());
  235909. }
  235910. CFRelease (name);
  235911. }
  235912. return mi;
  235913. }
  235914. MidiInput::MidiInput (const String& name_)
  235915. : name (name_)
  235916. {
  235917. }
  235918. MidiInput::~MidiInput()
  235919. {
  235920. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  235921. }
  235922. void MidiInput::start()
  235923. {
  235924. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235925. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  235926. }
  235927. void MidiInput::stop()
  235928. {
  235929. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235930. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  235931. }
  235932. #undef CHECK_ERROR
  235933. #else // Stubs for iOS...
  235934. MidiOutput::~MidiOutput() {}
  235935. void MidiOutput::reset() {}
  235936. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  235937. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  235938. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  235939. const StringArray MidiOutput::getDevices() { return StringArray(); }
  235940. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  235941. const StringArray MidiInput::getDevices() { return StringArray(); }
  235942. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  235943. #endif
  235944. #endif
  235945. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235946. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235947. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235948. // compiled on its own).
  235949. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235950. #if ! JUCE_QUICKTIME
  235951. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235952. #endif
  235953. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235954. class QTCameraDeviceInteral;
  235955. END_JUCE_NAMESPACE
  235956. @interface QTCaptureCallbackDelegate : NSObject
  235957. {
  235958. @public
  235959. CameraDevice* owner;
  235960. QTCameraDeviceInteral* internal;
  235961. int64 firstPresentationTime;
  235962. int64 averageTimeOffset;
  235963. }
  235964. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235965. - (void) dealloc;
  235966. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235967. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235968. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235969. fromConnection: (QTCaptureConnection*) connection;
  235970. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235971. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235972. fromConnection: (QTCaptureConnection*) connection;
  235973. @end
  235974. BEGIN_JUCE_NAMESPACE
  235975. class QTCameraDeviceInteral
  235976. {
  235977. public:
  235978. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235979. {
  235980. const ScopedAutoReleasePool pool;
  235981. session = [[QTCaptureSession alloc] init];
  235982. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235983. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235984. input = 0;
  235985. audioInput = 0;
  235986. audioDevice = 0;
  235987. fileOutput = 0;
  235988. imageOutput = 0;
  235989. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235990. internalDev: this];
  235991. NSError* err = 0;
  235992. [device retain];
  235993. [device open: &err];
  235994. if (err == 0)
  235995. {
  235996. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235997. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235998. [session addInput: input error: &err];
  235999. if (err == 0)
  236000. {
  236001. resetFile();
  236002. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236003. [imageOutput setDelegate: callbackDelegate];
  236004. if (err == 0)
  236005. {
  236006. [session startRunning];
  236007. return;
  236008. }
  236009. }
  236010. }
  236011. openingError = nsStringToJuce ([err description]);
  236012. DBG (openingError);
  236013. }
  236014. ~QTCameraDeviceInteral()
  236015. {
  236016. [session stopRunning];
  236017. [session removeOutput: imageOutput];
  236018. [session release];
  236019. [input release];
  236020. [device release];
  236021. [audioDevice release];
  236022. [audioInput release];
  236023. [fileOutput release];
  236024. [imageOutput release];
  236025. [callbackDelegate release];
  236026. }
  236027. void resetFile()
  236028. {
  236029. [fileOutput recordToOutputFileURL: nil];
  236030. [session removeOutput: fileOutput];
  236031. [fileOutput release];
  236032. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236033. [session removeInput: audioInput];
  236034. [audioInput release];
  236035. audioInput = 0;
  236036. [audioDevice release];
  236037. audioDevice = 0;
  236038. [fileOutput setDelegate: callbackDelegate];
  236039. }
  236040. void addDefaultAudioInput()
  236041. {
  236042. NSError* err = nil;
  236043. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236044. if ([audioDevice open: &err])
  236045. [audioDevice retain];
  236046. else
  236047. audioDevice = nil;
  236048. if (audioDevice != 0)
  236049. {
  236050. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236051. [session addInput: audioInput error: &err];
  236052. }
  236053. }
  236054. void addListener (CameraDevice::Listener* listenerToAdd)
  236055. {
  236056. const ScopedLock sl (listenerLock);
  236057. if (listeners.size() == 0)
  236058. [session addOutput: imageOutput error: nil];
  236059. listeners.addIfNotAlreadyThere (listenerToAdd);
  236060. }
  236061. void removeListener (CameraDevice::Listener* listenerToRemove)
  236062. {
  236063. const ScopedLock sl (listenerLock);
  236064. listeners.removeValue (listenerToRemove);
  236065. if (listeners.size() == 0)
  236066. [session removeOutput: imageOutput];
  236067. }
  236068. void callListeners (CIImage* frame, int w, int h)
  236069. {
  236070. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236071. Image image (cgImage);
  236072. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236073. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236074. CGContextFlush (cgImage->context);
  236075. const ScopedLock sl (listenerLock);
  236076. for (int i = listeners.size(); --i >= 0;)
  236077. {
  236078. CameraDevice::Listener* const l = listeners[i];
  236079. if (l != 0)
  236080. l->imageReceived (image);
  236081. }
  236082. }
  236083. QTCaptureDevice* device;
  236084. QTCaptureDeviceInput* input;
  236085. QTCaptureDevice* audioDevice;
  236086. QTCaptureDeviceInput* audioInput;
  236087. QTCaptureSession* session;
  236088. QTCaptureMovieFileOutput* fileOutput;
  236089. QTCaptureDecompressedVideoOutput* imageOutput;
  236090. QTCaptureCallbackDelegate* callbackDelegate;
  236091. String openingError;
  236092. Array<CameraDevice::Listener*> listeners;
  236093. CriticalSection listenerLock;
  236094. };
  236095. END_JUCE_NAMESPACE
  236096. @implementation QTCaptureCallbackDelegate
  236097. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236098. internalDev: (QTCameraDeviceInteral*) d
  236099. {
  236100. [super init];
  236101. owner = owner_;
  236102. internal = d;
  236103. firstPresentationTime = 0;
  236104. averageTimeOffset = 0;
  236105. return self;
  236106. }
  236107. - (void) dealloc
  236108. {
  236109. [super dealloc];
  236110. }
  236111. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236112. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236113. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236114. fromConnection: (QTCaptureConnection*) connection
  236115. {
  236116. if (internal->listeners.size() > 0)
  236117. {
  236118. const ScopedAutoReleasePool pool;
  236119. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236120. CVPixelBufferGetWidth (videoFrame),
  236121. CVPixelBufferGetHeight (videoFrame));
  236122. }
  236123. }
  236124. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236125. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236126. fromConnection: (QTCaptureConnection*) connection
  236127. {
  236128. const Time now (Time::getCurrentTime());
  236129. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236130. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236131. #else
  236132. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236133. #endif
  236134. int64 presentationTime = (hosttime != nil)
  236135. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236136. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236137. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236138. if (firstPresentationTime == 0)
  236139. {
  236140. firstPresentationTime = presentationTime;
  236141. averageTimeOffset = timeDiff;
  236142. }
  236143. else
  236144. {
  236145. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236146. }
  236147. }
  236148. @end
  236149. BEGIN_JUCE_NAMESPACE
  236150. class QTCaptureViewerComp : public NSViewComponent
  236151. {
  236152. public:
  236153. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236154. {
  236155. const ScopedAutoReleasePool pool;
  236156. captureView = [[QTCaptureView alloc] init];
  236157. [captureView setCaptureSession: internal->session];
  236158. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236159. setView (captureView);
  236160. }
  236161. ~QTCaptureViewerComp()
  236162. {
  236163. setView (0);
  236164. [captureView setCaptureSession: nil];
  236165. [captureView release];
  236166. }
  236167. QTCaptureView* captureView;
  236168. };
  236169. CameraDevice::CameraDevice (const String& name_, int index)
  236170. : name (name_)
  236171. {
  236172. isRecording = false;
  236173. internal = new QTCameraDeviceInteral (this, index);
  236174. }
  236175. CameraDevice::~CameraDevice()
  236176. {
  236177. stopRecording();
  236178. delete static_cast <QTCameraDeviceInteral*> (internal);
  236179. internal = 0;
  236180. }
  236181. Component* CameraDevice::createViewerComponent()
  236182. {
  236183. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236184. }
  236185. const String CameraDevice::getFileExtension()
  236186. {
  236187. return ".mov";
  236188. }
  236189. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236190. {
  236191. stopRecording();
  236192. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236193. d->callbackDelegate->firstPresentationTime = 0;
  236194. file.deleteFile();
  236195. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236196. // out wrong, so we'll put some audio in there too..,
  236197. d->addDefaultAudioInput();
  236198. [d->session addOutput: d->fileOutput error: nil];
  236199. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236200. for (;;)
  236201. {
  236202. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236203. if (connection == 0)
  236204. break;
  236205. QTCompressionOptions* options = 0;
  236206. NSString* mediaType = [connection mediaType];
  236207. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236208. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236209. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236210. : @"QTCompressionOptions240SizeH264Video"];
  236211. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236212. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236213. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236214. }
  236215. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236216. isRecording = true;
  236217. }
  236218. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236219. {
  236220. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236221. if (d->callbackDelegate->firstPresentationTime != 0)
  236222. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236223. return Time();
  236224. }
  236225. void CameraDevice::stopRecording()
  236226. {
  236227. if (isRecording)
  236228. {
  236229. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236230. isRecording = false;
  236231. }
  236232. }
  236233. void CameraDevice::addListener (Listener* listenerToAdd)
  236234. {
  236235. if (listenerToAdd != 0)
  236236. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236237. }
  236238. void CameraDevice::removeListener (Listener* listenerToRemove)
  236239. {
  236240. if (listenerToRemove != 0)
  236241. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236242. }
  236243. const StringArray CameraDevice::getAvailableDevices()
  236244. {
  236245. const ScopedAutoReleasePool pool;
  236246. StringArray results;
  236247. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236248. for (int i = 0; i < (int) [devs count]; ++i)
  236249. {
  236250. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236251. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236252. }
  236253. return results;
  236254. }
  236255. CameraDevice* CameraDevice::openDevice (int index,
  236256. int minWidth, int minHeight,
  236257. int maxWidth, int maxHeight)
  236258. {
  236259. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236260. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236261. return d.release();
  236262. return 0;
  236263. }
  236264. #endif
  236265. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236266. #endif
  236267. #endif
  236268. END_JUCE_NAMESPACE
  236269. #endif
  236270. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236271. #elif JUCE_ANDROID
  236272. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236273. /*
  236274. This file wraps together all the android-specific code, so that
  236275. we can include all the native headers just once, and compile all our
  236276. platform-specific stuff in one big lump, keeping it out of the way of
  236277. the rest of the codebase.
  236278. */
  236279. #if JUCE_ANDROID
  236280. #undef JUCE_BUILD_NATIVE
  236281. #define JUCE_BUILD_NATIVE 1
  236282. BEGIN_JUCE_NAMESPACE
  236283. #define JUCE_INCLUDED_FILE 1
  236284. // Now include the actual code files..
  236285. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  236286. /*
  236287. This file contains posix routines that are common to both the Linux and Mac builds.
  236288. It gets included directly in the cpp files for these platforms.
  236289. */
  236290. CriticalSection::CriticalSection() throw()
  236291. {
  236292. pthread_mutexattr_t atts;
  236293. pthread_mutexattr_init (&atts);
  236294. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  236295. #if ! JUCE_ANDROID
  236296. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236297. #endif
  236298. pthread_mutex_init (&internal, &atts);
  236299. }
  236300. CriticalSection::~CriticalSection() throw()
  236301. {
  236302. pthread_mutex_destroy (&internal);
  236303. }
  236304. void CriticalSection::enter() const throw()
  236305. {
  236306. pthread_mutex_lock (&internal);
  236307. }
  236308. bool CriticalSection::tryEnter() const throw()
  236309. {
  236310. return pthread_mutex_trylock (&internal) == 0;
  236311. }
  236312. void CriticalSection::exit() const throw()
  236313. {
  236314. pthread_mutex_unlock (&internal);
  236315. }
  236316. class WaitableEventImpl
  236317. {
  236318. public:
  236319. WaitableEventImpl (const bool manualReset_)
  236320. : triggered (false),
  236321. manualReset (manualReset_)
  236322. {
  236323. pthread_cond_init (&condition, 0);
  236324. pthread_mutexattr_t atts;
  236325. pthread_mutexattr_init (&atts);
  236326. #if ! JUCE_ANDROID
  236327. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236328. #endif
  236329. pthread_mutex_init (&mutex, &atts);
  236330. }
  236331. ~WaitableEventImpl()
  236332. {
  236333. pthread_cond_destroy (&condition);
  236334. pthread_mutex_destroy (&mutex);
  236335. }
  236336. bool wait (const int timeOutMillisecs) throw()
  236337. {
  236338. pthread_mutex_lock (&mutex);
  236339. if (! triggered)
  236340. {
  236341. if (timeOutMillisecs < 0)
  236342. {
  236343. do
  236344. {
  236345. pthread_cond_wait (&condition, &mutex);
  236346. }
  236347. while (! triggered);
  236348. }
  236349. else
  236350. {
  236351. struct timeval now;
  236352. gettimeofday (&now, 0);
  236353. struct timespec time;
  236354. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  236355. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  236356. if (time.tv_nsec >= 1000000000)
  236357. {
  236358. time.tv_nsec -= 1000000000;
  236359. time.tv_sec++;
  236360. }
  236361. do
  236362. {
  236363. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  236364. {
  236365. pthread_mutex_unlock (&mutex);
  236366. return false;
  236367. }
  236368. }
  236369. while (! triggered);
  236370. }
  236371. }
  236372. if (! manualReset)
  236373. triggered = false;
  236374. pthread_mutex_unlock (&mutex);
  236375. return true;
  236376. }
  236377. void signal() throw()
  236378. {
  236379. pthread_mutex_lock (&mutex);
  236380. triggered = true;
  236381. pthread_cond_broadcast (&condition);
  236382. pthread_mutex_unlock (&mutex);
  236383. }
  236384. void reset() throw()
  236385. {
  236386. pthread_mutex_lock (&mutex);
  236387. triggered = false;
  236388. pthread_mutex_unlock (&mutex);
  236389. }
  236390. private:
  236391. pthread_cond_t condition;
  236392. pthread_mutex_t mutex;
  236393. bool triggered;
  236394. const bool manualReset;
  236395. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  236396. };
  236397. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  236398. : internal (new WaitableEventImpl (manualReset))
  236399. {
  236400. }
  236401. WaitableEvent::~WaitableEvent() throw()
  236402. {
  236403. delete static_cast <WaitableEventImpl*> (internal);
  236404. }
  236405. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  236406. {
  236407. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  236408. }
  236409. void WaitableEvent::signal() const throw()
  236410. {
  236411. static_cast <WaitableEventImpl*> (internal)->signal();
  236412. }
  236413. void WaitableEvent::reset() const throw()
  236414. {
  236415. static_cast <WaitableEventImpl*> (internal)->reset();
  236416. }
  236417. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  236418. {
  236419. struct timespec time;
  236420. time.tv_sec = millisecs / 1000;
  236421. time.tv_nsec = (millisecs % 1000) * 1000000;
  236422. nanosleep (&time, 0);
  236423. }
  236424. const juce_wchar File::separator = '/';
  236425. const String File::separatorString ("/");
  236426. const File File::getCurrentWorkingDirectory()
  236427. {
  236428. HeapBlock<char> heapBuffer;
  236429. char localBuffer [1024];
  236430. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  236431. int bufferSize = 4096;
  236432. while (cwd == 0 && errno == ERANGE)
  236433. {
  236434. heapBuffer.malloc (bufferSize);
  236435. cwd = getcwd (heapBuffer, bufferSize - 1);
  236436. bufferSize += 1024;
  236437. }
  236438. return File (String::fromUTF8 (cwd));
  236439. }
  236440. bool File::setAsCurrentWorkingDirectory() const
  236441. {
  236442. return chdir (getFullPathName().toUTF8()) == 0;
  236443. }
  236444. namespace
  236445. {
  236446. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236447. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  236448. #else
  236449. typedef struct stat juce_statStruct;
  236450. #endif
  236451. bool juce_stat (const String& fileName, juce_statStruct& info)
  236452. {
  236453. return fileName.isNotEmpty()
  236454. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236455. && (stat64 (fileName.toUTF8(), &info) == 0);
  236456. #else
  236457. && (stat (fileName.toUTF8(), &info) == 0);
  236458. #endif
  236459. }
  236460. // if this file doesn't exist, find a parent of it that does..
  236461. bool juce_doStatFS (File f, struct statfs& result)
  236462. {
  236463. for (int i = 5; --i >= 0;)
  236464. {
  236465. if (f.exists())
  236466. break;
  236467. f = f.getParentDirectory();
  236468. }
  236469. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  236470. }
  236471. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  236472. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  236473. {
  236474. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  236475. {
  236476. juce_statStruct info;
  236477. const bool statOk = juce_stat (path, info);
  236478. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  236479. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  236480. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  236481. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  236482. }
  236483. if (isReadOnly != 0)
  236484. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  236485. }
  236486. }
  236487. bool File::isDirectory() const
  236488. {
  236489. juce_statStruct info;
  236490. return fullPath.isEmpty()
  236491. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  236492. }
  236493. bool File::exists() const
  236494. {
  236495. juce_statStruct info;
  236496. return fullPath.isNotEmpty()
  236497. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236498. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  236499. #else
  236500. && (lstat (fullPath.toUTF8(), &info) == 0);
  236501. #endif
  236502. }
  236503. bool File::existsAsFile() const
  236504. {
  236505. return exists() && ! isDirectory();
  236506. }
  236507. int64 File::getSize() const
  236508. {
  236509. juce_statStruct info;
  236510. return juce_stat (fullPath, info) ? info.st_size : 0;
  236511. }
  236512. bool File::hasWriteAccess() const
  236513. {
  236514. if (exists())
  236515. return access (fullPath.toUTF8(), W_OK) == 0;
  236516. if ((! isDirectory()) && fullPath.containsChar (separator))
  236517. return getParentDirectory().hasWriteAccess();
  236518. return false;
  236519. }
  236520. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  236521. {
  236522. juce_statStruct info;
  236523. if (! juce_stat (fullPath, info))
  236524. return false;
  236525. info.st_mode &= 0777; // Just permissions
  236526. if (shouldBeReadOnly)
  236527. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  236528. else
  236529. // Give everybody write permission?
  236530. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  236531. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  236532. }
  236533. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  236534. {
  236535. modificationTime = 0;
  236536. accessTime = 0;
  236537. creationTime = 0;
  236538. juce_statStruct info;
  236539. if (juce_stat (fullPath, info))
  236540. {
  236541. modificationTime = (int64) info.st_mtime * 1000;
  236542. accessTime = (int64) info.st_atime * 1000;
  236543. creationTime = (int64) info.st_ctime * 1000;
  236544. }
  236545. }
  236546. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  236547. {
  236548. juce_statStruct info;
  236549. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  236550. {
  236551. struct utimbuf times;
  236552. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  236553. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  236554. return utime (fullPath.toUTF8(), &times) == 0;
  236555. }
  236556. return false;
  236557. }
  236558. bool File::deleteFile() const
  236559. {
  236560. if (! exists())
  236561. return true;
  236562. if (isDirectory())
  236563. return rmdir (fullPath.toUTF8()) == 0;
  236564. return remove (fullPath.toUTF8()) == 0;
  236565. }
  236566. bool File::moveInternal (const File& dest) const
  236567. {
  236568. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  236569. return true;
  236570. if (hasWriteAccess() && copyInternal (dest))
  236571. {
  236572. if (deleteFile())
  236573. return true;
  236574. dest.deleteFile();
  236575. }
  236576. return false;
  236577. }
  236578. void File::createDirectoryInternal (const String& fileName) const
  236579. {
  236580. mkdir (fileName.toUTF8(), 0777);
  236581. }
  236582. int64 juce_fileSetPosition (void* handle, int64 pos)
  236583. {
  236584. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  236585. return pos;
  236586. return -1;
  236587. }
  236588. void FileInputStream::openHandle()
  236589. {
  236590. totalSize = file.getSize();
  236591. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  236592. if (f != -1)
  236593. fileHandle = (void*) f;
  236594. }
  236595. void FileInputStream::closeHandle()
  236596. {
  236597. if (fileHandle != 0)
  236598. {
  236599. close ((int) (pointer_sized_int) fileHandle);
  236600. fileHandle = 0;
  236601. }
  236602. }
  236603. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  236604. {
  236605. if (fileHandle != 0)
  236606. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  236607. return 0;
  236608. }
  236609. void FileOutputStream::openHandle()
  236610. {
  236611. if (file.exists())
  236612. {
  236613. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  236614. if (f != -1)
  236615. {
  236616. currentPosition = lseek (f, 0, SEEK_END);
  236617. if (currentPosition >= 0)
  236618. fileHandle = (void*) f;
  236619. else
  236620. close (f);
  236621. }
  236622. }
  236623. else
  236624. {
  236625. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  236626. if (f != -1)
  236627. fileHandle = (void*) f;
  236628. }
  236629. }
  236630. void FileOutputStream::closeHandle()
  236631. {
  236632. if (fileHandle != 0)
  236633. {
  236634. close ((int) (pointer_sized_int) fileHandle);
  236635. fileHandle = 0;
  236636. }
  236637. }
  236638. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  236639. {
  236640. if (fileHandle != 0)
  236641. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  236642. return 0;
  236643. }
  236644. void FileOutputStream::flushInternal()
  236645. {
  236646. if (fileHandle != 0)
  236647. fsync ((int) (pointer_sized_int) fileHandle);
  236648. }
  236649. const File juce_getExecutableFile()
  236650. {
  236651. #if JUCE_ANDROID
  236652. // TODO
  236653. return File::nonexistent;
  236654. #else
  236655. Dl_info exeInfo;
  236656. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  236657. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  236658. #endif
  236659. }
  236660. int64 File::getBytesFreeOnVolume() const
  236661. {
  236662. struct statfs buf;
  236663. if (juce_doStatFS (*this, buf))
  236664. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  236665. return 0;
  236666. }
  236667. int64 File::getVolumeTotalSize() const
  236668. {
  236669. struct statfs buf;
  236670. if (juce_doStatFS (*this, buf))
  236671. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  236672. return 0;
  236673. }
  236674. const String File::getVolumeLabel() const
  236675. {
  236676. #if JUCE_MAC
  236677. struct VolAttrBuf
  236678. {
  236679. u_int32_t length;
  236680. attrreference_t mountPointRef;
  236681. char mountPointSpace [MAXPATHLEN];
  236682. } attrBuf;
  236683. struct attrlist attrList;
  236684. zerostruct (attrList);
  236685. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  236686. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  236687. File f (*this);
  236688. for (;;)
  236689. {
  236690. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  236691. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  236692. (int) attrBuf.mountPointRef.attr_length);
  236693. const File parent (f.getParentDirectory());
  236694. if (f == parent)
  236695. break;
  236696. f = parent;
  236697. }
  236698. #endif
  236699. return String::empty;
  236700. }
  236701. int File::getVolumeSerialNumber() const
  236702. {
  236703. int result = 0;
  236704. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  236705. char info [512];
  236706. #ifndef HDIO_GET_IDENTITY
  236707. #define HDIO_GET_IDENTITY 0x030d
  236708. #endif
  236709. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  236710. {
  236711. DBG (String (info + 20, 20));
  236712. result = String (info + 20, 20).trim().getIntValue();
  236713. }
  236714. close (fd);*/
  236715. return result;
  236716. }
  236717. void juce_runSystemCommand (const String& command)
  236718. {
  236719. int result = system (command.toUTF8());
  236720. (void) result;
  236721. }
  236722. const String juce_getOutputFromCommand (const String& command)
  236723. {
  236724. // slight bodge here, as we just pipe the output into a temp file and read it...
  236725. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  236726. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  236727. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  236728. String result (tempFile.loadFileAsString());
  236729. tempFile.deleteFile();
  236730. return result;
  236731. }
  236732. class InterProcessLock::Pimpl
  236733. {
  236734. public:
  236735. Pimpl (const String& name, const int timeOutMillisecs)
  236736. : handle (0), refCount (1)
  236737. {
  236738. #if JUCE_MAC
  236739. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  236740. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  236741. #else
  236742. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  236743. #endif
  236744. temp.create();
  236745. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  236746. if (handle != 0)
  236747. {
  236748. struct flock fl;
  236749. zerostruct (fl);
  236750. fl.l_whence = SEEK_SET;
  236751. fl.l_type = F_WRLCK;
  236752. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  236753. for (;;)
  236754. {
  236755. const int result = fcntl (handle, F_SETLK, &fl);
  236756. if (result >= 0)
  236757. return;
  236758. if (errno != EINTR)
  236759. {
  236760. if (timeOutMillisecs == 0
  236761. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  236762. break;
  236763. Thread::sleep (10);
  236764. }
  236765. }
  236766. }
  236767. closeFile();
  236768. }
  236769. ~Pimpl()
  236770. {
  236771. closeFile();
  236772. }
  236773. void closeFile()
  236774. {
  236775. if (handle != 0)
  236776. {
  236777. struct flock fl;
  236778. zerostruct (fl);
  236779. fl.l_whence = SEEK_SET;
  236780. fl.l_type = F_UNLCK;
  236781. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  236782. {}
  236783. close (handle);
  236784. handle = 0;
  236785. }
  236786. }
  236787. int handle, refCount;
  236788. };
  236789. InterProcessLock::InterProcessLock (const String& name_)
  236790. : name (name_)
  236791. {
  236792. }
  236793. InterProcessLock::~InterProcessLock()
  236794. {
  236795. }
  236796. bool InterProcessLock::enter (const int timeOutMillisecs)
  236797. {
  236798. const ScopedLock sl (lock);
  236799. if (pimpl == 0)
  236800. {
  236801. pimpl = new Pimpl (name, timeOutMillisecs);
  236802. if (pimpl->handle == 0)
  236803. pimpl = 0;
  236804. }
  236805. else
  236806. {
  236807. pimpl->refCount++;
  236808. }
  236809. return pimpl != 0;
  236810. }
  236811. void InterProcessLock::exit()
  236812. {
  236813. const ScopedLock sl (lock);
  236814. // Trying to release the lock too many times!
  236815. jassert (pimpl != 0);
  236816. if (pimpl != 0 && --(pimpl->refCount) == 0)
  236817. pimpl = 0;
  236818. }
  236819. void JUCE_API juce_threadEntryPoint (void*);
  236820. void* threadEntryProc (void* userData)
  236821. {
  236822. JUCE_AUTORELEASEPOOL
  236823. juce_threadEntryPoint (userData);
  236824. return 0;
  236825. }
  236826. void Thread::launchThread()
  236827. {
  236828. threadHandle_ = 0;
  236829. pthread_t handle = 0;
  236830. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  236831. {
  236832. pthread_detach (handle);
  236833. threadHandle_ = (void*) handle;
  236834. threadId_ = (ThreadID) threadHandle_;
  236835. }
  236836. }
  236837. void Thread::closeThreadHandle()
  236838. {
  236839. threadId_ = 0;
  236840. threadHandle_ = 0;
  236841. }
  236842. void Thread::killThread()
  236843. {
  236844. if (threadHandle_ != 0)
  236845. {
  236846. #if JUCE_ANDROID
  236847. jassertfalse; // pthread_cancel not available!
  236848. #else
  236849. pthread_cancel ((pthread_t) threadHandle_);
  236850. #endif
  236851. }
  236852. }
  236853. void Thread::setCurrentThreadName (const String& /*name*/)
  236854. {
  236855. }
  236856. bool Thread::setThreadPriority (void* handle, int priority)
  236857. {
  236858. struct sched_param param;
  236859. int policy;
  236860. priority = jlimit (0, 10, priority);
  236861. if (handle == 0)
  236862. handle = (void*) pthread_self();
  236863. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  236864. return false;
  236865. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  236866. const int minPriority = sched_get_priority_min (policy);
  236867. const int maxPriority = sched_get_priority_max (policy);
  236868. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  236869. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  236870. }
  236871. Thread::ThreadID Thread::getCurrentThreadId()
  236872. {
  236873. return (ThreadID) pthread_self();
  236874. }
  236875. void Thread::yield()
  236876. {
  236877. sched_yield();
  236878. }
  236879. /* Remove this macro if you're having problems compiling the cpu affinity
  236880. calls (the API for these has changed about quite a bit in various Linux
  236881. versions, and a lot of distros seem to ship with obsolete versions)
  236882. */
  236883. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  236884. #define SUPPORT_AFFINITIES 1
  236885. #endif
  236886. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  236887. {
  236888. #if SUPPORT_AFFINITIES
  236889. cpu_set_t affinity;
  236890. CPU_ZERO (&affinity);
  236891. for (int i = 0; i < 32; ++i)
  236892. if ((affinityMask & (1 << i)) != 0)
  236893. CPU_SET (i, &affinity);
  236894. /*
  236895. N.B. If this line causes a compile error, then you've probably not got the latest
  236896. version of glibc installed.
  236897. If you don't want to update your copy of glibc and don't care about cpu affinities,
  236898. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  236899. */
  236900. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  236901. sched_yield();
  236902. #else
  236903. /* affinities aren't supported because either the appropriate header files weren't found,
  236904. or the SUPPORT_AFFINITIES macro was turned off
  236905. */
  236906. jassertfalse;
  236907. (void) affinityMask;
  236908. #endif
  236909. }
  236910. /*** End of inlined file: juce_posix_SharedCode.h ***/
  236911. /*** Start of inlined file: juce_android_Files.cpp ***/
  236912. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236913. // compiled on its own).
  236914. #if JUCE_INCLUDED_FILE
  236915. bool File::copyInternal (const File& dest) const
  236916. {
  236917. // TODO
  236918. FileInputStream in (*this);
  236919. if (dest.deleteFile())
  236920. {
  236921. {
  236922. FileOutputStream out (dest);
  236923. if (out.failedToOpen())
  236924. return false;
  236925. if (out.writeFromInputStream (in, -1) == getSize())
  236926. return true;
  236927. }
  236928. dest.deleteFile();
  236929. }
  236930. return false;
  236931. }
  236932. void File::findFileSystemRoots (Array<File>& destArray)
  236933. {
  236934. // TODO
  236935. destArray.add (File ("/"));
  236936. }
  236937. bool File::isOnCDRomDrive() const
  236938. {
  236939. return false;
  236940. }
  236941. bool File::isOnHardDisk() const
  236942. {
  236943. return true;
  236944. }
  236945. bool File::isOnRemovableDrive() const
  236946. {
  236947. return false;
  236948. }
  236949. bool File::isHidden() const
  236950. {
  236951. // TODO
  236952. return getFileName().startsWithChar ('.');
  236953. }
  236954. namespace
  236955. {
  236956. const File juce_readlink (const String& file, const File& defaultFile)
  236957. {
  236958. const int size = 8192;
  236959. HeapBlock<char> buffer;
  236960. buffer.malloc (size + 4);
  236961. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  236962. if (numBytes > 0 && numBytes <= size)
  236963. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  236964. return defaultFile;
  236965. }
  236966. }
  236967. const File File::getLinkedTarget() const
  236968. {
  236969. // TODO
  236970. return juce_readlink (getFullPathName().toUTF8(), *this);
  236971. }
  236972. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  236973. const File File::getSpecialLocation (const SpecialLocationType type)
  236974. {
  236975. // TODO
  236976. switch (type)
  236977. {
  236978. case userHomeDirectory:
  236979. {
  236980. const char* homeDir = getenv ("HOME");
  236981. if (homeDir == 0)
  236982. {
  236983. struct passwd* const pw = getpwuid (getuid());
  236984. if (pw != 0)
  236985. homeDir = pw->pw_dir;
  236986. }
  236987. return File (String::fromUTF8 (homeDir));
  236988. }
  236989. case userDocumentsDirectory:
  236990. case userMusicDirectory:
  236991. case userMoviesDirectory:
  236992. case userApplicationDataDirectory:
  236993. return File ("~");
  236994. case userDesktopDirectory:
  236995. return File ("~/Desktop");
  236996. case commonApplicationDataDirectory:
  236997. return File ("/var");
  236998. case globalApplicationsDirectory:
  236999. return File ("/usr");
  237000. case tempDirectory:
  237001. {
  237002. File tmp ("/var/tmp");
  237003. if (! tmp.isDirectory())
  237004. {
  237005. tmp = "/tmp";
  237006. if (! tmp.isDirectory())
  237007. tmp = File::getCurrentWorkingDirectory();
  237008. }
  237009. return tmp;
  237010. }
  237011. case invokedExecutableFile:
  237012. if (juce_Argv0 != 0)
  237013. return File (String::fromUTF8 (juce_Argv0));
  237014. // deliberate fall-through...
  237015. case currentExecutableFile:
  237016. case currentApplicationFile:
  237017. return juce_getExecutableFile();
  237018. case hostApplicationPath:
  237019. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  237020. default:
  237021. jassertfalse; // unknown type?
  237022. break;
  237023. }
  237024. return File::nonexistent;
  237025. }
  237026. const String File::getVersion() const
  237027. {
  237028. return String::empty;
  237029. }
  237030. bool File::moveToTrash() const
  237031. {
  237032. if (! exists())
  237033. return true;
  237034. // TODO
  237035. return false;
  237036. }
  237037. class DirectoryIterator::NativeIterator::Pimpl
  237038. {
  237039. public:
  237040. Pimpl (const File& directory, const String& wildCard_)
  237041. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  237042. wildCard (wildCard_),
  237043. dir (opendir (directory.getFullPathName().toUTF8()))
  237044. {
  237045. wildcardUTF8 = wildCard.toUTF8();
  237046. }
  237047. ~Pimpl()
  237048. {
  237049. if (dir != 0)
  237050. closedir (dir);
  237051. }
  237052. bool next (String& filenameFound,
  237053. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237054. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237055. {
  237056. if (dir != 0)
  237057. {
  237058. for (;;)
  237059. {
  237060. struct dirent* const de = readdir (dir);
  237061. if (de == 0)
  237062. break;
  237063. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  237064. {
  237065. filenameFound = String::fromUTF8 (de->d_name);
  237066. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  237067. if (isHidden != 0)
  237068. *isHidden = filenameFound.startsWithChar ('.');
  237069. return true;
  237070. }
  237071. }
  237072. }
  237073. return false;
  237074. }
  237075. private:
  237076. String parentDir, wildCard;
  237077. const char* wildcardUTF8;
  237078. DIR* dir;
  237079. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  237080. };
  237081. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  237082. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  237083. {
  237084. }
  237085. DirectoryIterator::NativeIterator::~NativeIterator()
  237086. {
  237087. }
  237088. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  237089. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237090. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237091. {
  237092. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  237093. }
  237094. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  237095. {
  237096. }
  237097. void File::revealToUser() const
  237098. {
  237099. }
  237100. #endif
  237101. /*** End of inlined file: juce_android_Files.cpp ***/
  237102. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  237103. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237104. // compiled on its own).
  237105. #if JUCE_INCLUDED_FILE
  237106. struct NamedPipeInternal
  237107. {
  237108. String pipeInName, pipeOutName;
  237109. int pipeIn, pipeOut;
  237110. bool volatile createdPipe, blocked, stopReadOperation;
  237111. static void signalHandler (int) {}
  237112. };
  237113. void NamedPipe::cancelPendingReads()
  237114. {
  237115. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  237116. {
  237117. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237118. intern->stopReadOperation = true;
  237119. char buffer [1] = { 0 };
  237120. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  237121. (void) bytesWritten;
  237122. int timeout = 2000;
  237123. while (intern->blocked && --timeout >= 0)
  237124. Thread::sleep (2);
  237125. intern->stopReadOperation = false;
  237126. }
  237127. }
  237128. void NamedPipe::close()
  237129. {
  237130. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237131. if (intern != 0)
  237132. {
  237133. internal = 0;
  237134. if (intern->pipeIn != -1)
  237135. ::close (intern->pipeIn);
  237136. if (intern->pipeOut != -1)
  237137. ::close (intern->pipeOut);
  237138. if (intern->createdPipe)
  237139. {
  237140. unlink (intern->pipeInName.toUTF8());
  237141. unlink (intern->pipeOutName.toUTF8());
  237142. }
  237143. delete intern;
  237144. }
  237145. }
  237146. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  237147. {
  237148. close();
  237149. NamedPipeInternal* const intern = new NamedPipeInternal();
  237150. internal = intern;
  237151. intern->createdPipe = createPipe;
  237152. intern->blocked = false;
  237153. intern->stopReadOperation = false;
  237154. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  237155. siginterrupt (SIGPIPE, 1);
  237156. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  237157. intern->pipeInName = pipePath + "_in";
  237158. intern->pipeOutName = pipePath + "_out";
  237159. intern->pipeIn = -1;
  237160. intern->pipeOut = -1;
  237161. if (createPipe)
  237162. {
  237163. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  237164. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  237165. {
  237166. delete intern;
  237167. internal = 0;
  237168. return false;
  237169. }
  237170. }
  237171. return true;
  237172. }
  237173. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  237174. {
  237175. int bytesRead = -1;
  237176. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237177. if (intern != 0)
  237178. {
  237179. intern->blocked = true;
  237180. if (intern->pipeIn == -1)
  237181. {
  237182. if (intern->createdPipe)
  237183. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  237184. else
  237185. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  237186. if (intern->pipeIn == -1)
  237187. {
  237188. intern->blocked = false;
  237189. return -1;
  237190. }
  237191. }
  237192. bytesRead = 0;
  237193. char* p = static_cast<char*> (destBuffer);
  237194. while (bytesRead < maxBytesToRead)
  237195. {
  237196. const int bytesThisTime = maxBytesToRead - bytesRead;
  237197. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  237198. if (numRead <= 0 || intern->stopReadOperation)
  237199. {
  237200. bytesRead = -1;
  237201. break;
  237202. }
  237203. bytesRead += numRead;
  237204. p += bytesRead;
  237205. }
  237206. intern->blocked = false;
  237207. }
  237208. return bytesRead;
  237209. }
  237210. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  237211. {
  237212. int bytesWritten = -1;
  237213. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237214. if (intern != 0)
  237215. {
  237216. if (intern->pipeOut == -1)
  237217. {
  237218. if (intern->createdPipe)
  237219. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  237220. else
  237221. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  237222. if (intern->pipeOut == -1)
  237223. {
  237224. return -1;
  237225. }
  237226. }
  237227. const char* p = static_cast<const char*> (sourceBuffer);
  237228. bytesWritten = 0;
  237229. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  237230. while (bytesWritten < numBytesToWrite
  237231. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  237232. {
  237233. const int bytesThisTime = numBytesToWrite - bytesWritten;
  237234. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  237235. if (numWritten <= 0)
  237236. {
  237237. bytesWritten = -1;
  237238. break;
  237239. }
  237240. bytesWritten += numWritten;
  237241. p += bytesWritten;
  237242. }
  237243. }
  237244. return bytesWritten;
  237245. }
  237246. #endif
  237247. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  237248. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  237249. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237250. // compiled on its own).
  237251. #if JUCE_INCLUDED_FILE
  237252. void PlatformUtilities::beep()
  237253. {
  237254. // TODO
  237255. }
  237256. void Logger::outputDebugString (const String& text)
  237257. {
  237258. // TODO
  237259. std::cerr << text << std::endl;
  237260. }
  237261. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  237262. {
  237263. return Android;
  237264. }
  237265. const String SystemStats::getOperatingSystemName()
  237266. {
  237267. return "Android";
  237268. }
  237269. bool SystemStats::isOperatingSystem64Bit()
  237270. {
  237271. #if JUCE_64BIT
  237272. return true;
  237273. #else
  237274. return false;
  237275. #endif
  237276. }
  237277. namespace LinuxStatsHelpers
  237278. {
  237279. // TODO
  237280. const String getCpuInfo (const char* const key)
  237281. {
  237282. StringArray lines;
  237283. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  237284. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  237285. if (lines[i].startsWithIgnoreCase (key))
  237286. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  237287. return String::empty;
  237288. }
  237289. }
  237290. const String SystemStats::getCpuVendor()
  237291. {
  237292. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  237293. }
  237294. int SystemStats::getCpuSpeedInMegaherz()
  237295. {
  237296. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  237297. }
  237298. int SystemStats::getMemorySizeInMegabytes()
  237299. {
  237300. // TODO
  237301. struct sysinfo sysi;
  237302. if (sysinfo (&sysi) == 0)
  237303. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  237304. return 0;
  237305. }
  237306. int SystemStats::getPageSize()
  237307. {
  237308. // TODO
  237309. return sysconf (_SC_PAGESIZE);
  237310. }
  237311. const String SystemStats::getLogonName()
  237312. {
  237313. // TODO
  237314. const char* user = getenv ("USER");
  237315. if (user == 0)
  237316. {
  237317. struct passwd* const pw = getpwuid (getuid());
  237318. if (pw != 0)
  237319. user = pw->pw_name;
  237320. }
  237321. return String::fromUTF8 (user);
  237322. }
  237323. const String SystemStats::getFullUserName()
  237324. {
  237325. return getLogonName();
  237326. }
  237327. void SystemStats::initialiseStats()
  237328. {
  237329. // TODO
  237330. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  237331. cpuFlags.hasMMX = flags.contains ("mmx");
  237332. cpuFlags.hasSSE = flags.contains ("sse");
  237333. cpuFlags.hasSSE2 = flags.contains ("sse2");
  237334. cpuFlags.has3DNow = flags.contains ("3dnow");
  237335. // TODO
  237336. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  237337. }
  237338. void PlatformUtilities::fpuReset() {}
  237339. uint32 juce_millisecondsSinceStartup() throw()
  237340. {
  237341. // TODO
  237342. timespec t;
  237343. clock_gettime (CLOCK_MONOTONIC, &t);
  237344. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  237345. }
  237346. int64 Time::getHighResolutionTicks() throw()
  237347. {
  237348. // TODO
  237349. timespec t;
  237350. clock_gettime (CLOCK_MONOTONIC, &t);
  237351. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  237352. }
  237353. int64 Time::getHighResolutionTicksPerSecond() throw()
  237354. {
  237355. // TODO
  237356. return 1000000; // (microseconds)
  237357. }
  237358. double Time::getMillisecondCounterHiRes() throw()
  237359. {
  237360. return getHighResolutionTicks() * 0.001;
  237361. }
  237362. bool Time::setSystemTimeToThisTime() const
  237363. {
  237364. jassertfalse;
  237365. return false;
  237366. }
  237367. #endif
  237368. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  237369. /*** Start of inlined file: juce_android_Threads.cpp ***/
  237370. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237371. // compiled on its own).
  237372. #if JUCE_INCLUDED_FILE
  237373. /*
  237374. Note that a lot of methods that you'd expect to find in this file actually
  237375. live in juce_posix_SharedCode.h!
  237376. */
  237377. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  237378. void Process::setPriority (ProcessPriority prior)
  237379. {
  237380. // TODO
  237381. struct sched_param param;
  237382. int policy, maxp, minp;
  237383. const int p = (int) prior;
  237384. if (p <= 1)
  237385. policy = SCHED_OTHER;
  237386. else
  237387. policy = SCHED_RR;
  237388. minp = sched_get_priority_min (policy);
  237389. maxp = sched_get_priority_max (policy);
  237390. if (p < 2)
  237391. param.sched_priority = 0;
  237392. else if (p == 2 )
  237393. // Set to middle of lower realtime priority range
  237394. param.sched_priority = minp + (maxp - minp) / 4;
  237395. else
  237396. // Set to middle of higher realtime priority range
  237397. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  237398. pthread_setschedparam (pthread_self(), policy, &param);
  237399. }
  237400. void Process::terminate()
  237401. {
  237402. // TODO
  237403. exit (0);
  237404. }
  237405. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  237406. {
  237407. return false;
  237408. }
  237409. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  237410. {
  237411. return juce_isRunningUnderDebugger();
  237412. }
  237413. void Process::raisePrivilege() {}
  237414. void Process::lowerPrivilege() {}
  237415. #endif
  237416. /*** End of inlined file: juce_android_Threads.cpp ***/
  237417. /*** Start of inlined file: juce_android_Network.cpp ***/
  237418. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237419. // compiled on its own).
  237420. #if JUCE_INCLUDED_FILE
  237421. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  237422. {
  237423. // TODO
  237424. }
  237425. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  237426. const String& emailSubject,
  237427. const String& bodyText,
  237428. const StringArray& filesToAttach)
  237429. {
  237430. // TODO
  237431. return false;
  237432. }
  237433. class WebInputStream : public InputStream
  237434. {
  237435. public:
  237436. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  237437. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237438. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  237439. {
  237440. // TODO
  237441. openedOk = false;
  237442. }
  237443. ~WebInputStream()
  237444. {
  237445. }
  237446. bool isExhausted()
  237447. {
  237448. return true; // TODO
  237449. }
  237450. int64 getPosition()
  237451. {
  237452. return 0; // TODO
  237453. }
  237454. int64 getTotalLength()
  237455. {
  237456. return -1; // TODO
  237457. }
  237458. int read (void* buffer, int bytesToRead)
  237459. {
  237460. // TODO
  237461. return 0;
  237462. }
  237463. bool setPosition (int64 wantedPos)
  237464. {
  237465. // TODO
  237466. return false;
  237467. }
  237468. bool openedOk;
  237469. private:
  237470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  237471. };
  237472. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  237473. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237474. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  237475. {
  237476. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  237477. progressCallback, progressCallbackContext,
  237478. headers, timeOutMs, responseHeaders));
  237479. return wi->openedOk ? wi.release() : 0;
  237480. }
  237481. #endif
  237482. /*** End of inlined file: juce_android_Network.cpp ***/
  237483. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  237484. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237485. // compiled on its own).
  237486. #if JUCE_INCLUDED_FILE
  237487. void MessageManager::doPlatformSpecificInitialisation()
  237488. {
  237489. }
  237490. void MessageManager::doPlatformSpecificShutdown()
  237491. {
  237492. }
  237493. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  237494. {
  237495. // TODO
  237496. /*
  237497. The idea here is that this will check the system message queue, pull off a
  237498. message if there is one, deliver it, and return true if a message was delivered.
  237499. If the queue's empty, return false.
  237500. If the message is one of our special ones (i.e. a Message object being delivered,
  237501. this must call MessageManager::getInstance()->deliverMessage() to deliver it
  237502. */
  237503. return true;
  237504. }
  237505. bool juce_postMessageToSystemQueue (Message* message)
  237506. {
  237507. // TODO
  237508. return true;
  237509. }
  237510. class AsyncFunctionCaller : public AsyncUpdater
  237511. {
  237512. public:
  237513. static void* call (MessageCallbackFunction* func_, void* parameter_)
  237514. {
  237515. if (MessageManager::getInstance()->isThisTheMessageThread())
  237516. return func_ (parameter_);
  237517. AsyncFunctionCaller caller (func_, parameter_);
  237518. caller.triggerAsyncUpdate();
  237519. caller.finished.wait();
  237520. return caller.result;
  237521. }
  237522. void handleAsyncUpdate()
  237523. {
  237524. result = (*func) (parameter);
  237525. finished.signal();
  237526. }
  237527. private:
  237528. WaitableEvent finished;
  237529. MessageCallbackFunction* func;
  237530. void* parameter;
  237531. void* volatile result;
  237532. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  237533. : result (0), func (func_), parameter (parameter_)
  237534. {}
  237535. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  237536. };
  237537. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  237538. {
  237539. return AsyncFunctionCaller::call (func, parameter);
  237540. }
  237541. void MessageManager::broadcastMessage (const String&)
  237542. {
  237543. }
  237544. #endif
  237545. /*** End of inlined file: juce_android_Messaging.cpp ***/
  237546. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  237547. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237548. // compiled on its own).
  237549. #if JUCE_INCLUDED_FILE
  237550. const StringArray Font::findAllTypefaceNames()
  237551. {
  237552. StringArray results;
  237553. // TODO
  237554. return results;
  237555. }
  237556. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  237557. {
  237558. // TODO
  237559. defaultSans = "Verdana";
  237560. defaultSerif = "Times";
  237561. defaultFixed = "Lucida Console";
  237562. defaultFallback = "Tahoma";
  237563. }
  237564. class AndroidTypeface : public Typeface
  237565. {
  237566. public:
  237567. AndroidTypeface (const Font& font)
  237568. : Typeface (font.getTypefaceName())
  237569. {
  237570. // TODO
  237571. }
  237572. float getAscent() const
  237573. {
  237574. return 0; // TODO
  237575. }
  237576. float getDescent() const
  237577. {
  237578. return 0; // TODO
  237579. }
  237580. float getStringWidth (const String& text)
  237581. {
  237582. // TODO
  237583. return 0;
  237584. }
  237585. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  237586. {
  237587. // TODO
  237588. }
  237589. bool getOutlineForGlyph (int glyphNumber, Path& destPath)
  237590. {
  237591. // TODO
  237592. return false;
  237593. }
  237594. private:
  237595. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  237596. };
  237597. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  237598. {
  237599. return new AndroidTypeface (font);
  237600. }
  237601. #endif
  237602. /*** End of inlined file: juce_android_Fonts.cpp ***/
  237603. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  237604. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237605. // compiled on its own).
  237606. #if JUCE_INCLUDED_FILE
  237607. // TODO
  237608. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  237609. {
  237610. public:
  237611. AndroidLowLevelGraphicsContext()
  237612. {
  237613. }
  237614. ~AndroidLowLevelGraphicsContext()
  237615. {
  237616. }
  237617. bool isVectorDevice() const { return false; }
  237618. void setOrigin (int x, int y)
  237619. {
  237620. }
  237621. void addTransform (const AffineTransform& transform)
  237622. {
  237623. }
  237624. float getScaleFactor()
  237625. {
  237626. return 1.0f;
  237627. }
  237628. bool clipToRectangle (const Rectangle<int>& r)
  237629. {
  237630. return false;
  237631. }
  237632. bool clipToRectangleList (const RectangleList& clipRegion)
  237633. {
  237634. return false;
  237635. }
  237636. void excludeClipRectangle (const Rectangle<int>& r)
  237637. {
  237638. }
  237639. void clipToPath (const Path& path, const AffineTransform& transform)
  237640. {
  237641. }
  237642. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  237643. {
  237644. }
  237645. bool clipRegionIntersects (const Rectangle<int>& r)
  237646. {
  237647. return true;
  237648. }
  237649. const Rectangle<int> getClipBounds() const
  237650. {
  237651. return Rectangle<int>();
  237652. }
  237653. bool isClipEmpty() const
  237654. {
  237655. return false;
  237656. }
  237657. void saveState()
  237658. {
  237659. }
  237660. void restoreState()
  237661. {
  237662. }
  237663. void beginTransparencyLayer (float opacity)
  237664. {
  237665. }
  237666. void endTransparencyLayer()
  237667. {
  237668. }
  237669. void setFill (const FillType& fillType)
  237670. {
  237671. }
  237672. void setOpacity (float newOpacity)
  237673. {
  237674. }
  237675. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  237676. {
  237677. }
  237678. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  237679. {
  237680. }
  237681. void fillPath (const Path& path, const AffineTransform& transform)
  237682. {
  237683. }
  237684. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  237685. {
  237686. }
  237687. void drawLine (const Line <float>& line)
  237688. {
  237689. }
  237690. void drawVerticalLine (int x, float top, float bottom)
  237691. {
  237692. }
  237693. void drawHorizontalLine (int y, float left, float right)
  237694. {
  237695. }
  237696. void setFont (const Font& newFont)
  237697. {
  237698. }
  237699. const Font getFont()
  237700. {
  237701. return Font();
  237702. }
  237703. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  237704. {
  237705. }
  237706. private:
  237707. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  237708. };
  237709. #endif
  237710. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  237711. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  237712. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  237713. // compiled on its own).
  237714. #if JUCE_INCLUDED_FILE
  237715. class AndroidComponentPeer : public ComponentPeer
  237716. {
  237717. public:
  237718. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  237719. : ComponentPeer (component, windowStyleFlags)
  237720. {
  237721. // TODO
  237722. }
  237723. ~AndroidComponentPeer()
  237724. {
  237725. }
  237726. void* getNativeHandle() const
  237727. {
  237728. return 0; // TODO
  237729. }
  237730. void setVisible (bool shouldBeVisible)
  237731. {
  237732. }
  237733. void setTitle (const String& title)
  237734. {
  237735. }
  237736. void setPosition (int x, int y)
  237737. {
  237738. // TODO
  237739. }
  237740. void setSize (int w, int h)
  237741. {
  237742. }
  237743. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  237744. {
  237745. // TODO
  237746. }
  237747. const Rectangle<int> getBounds() const
  237748. {
  237749. // TODO
  237750. return Rectangle<int>();
  237751. }
  237752. const Point<int> getScreenPosition() const
  237753. {
  237754. // TODO
  237755. return Point<int>();
  237756. }
  237757. const Point<int> localToGlobal (const Point<int>& relativePosition)
  237758. {
  237759. // TODO
  237760. return relativePosition + getScreenPosition();
  237761. }
  237762. const Point<int> globalToLocal (const Point<int>& screenPosition)
  237763. {
  237764. // TODO
  237765. return screenPosition - getScreenPosition();
  237766. }
  237767. void setMinimised (bool shouldBeMinimised)
  237768. {
  237769. // TODO
  237770. }
  237771. bool isMinimised() const
  237772. {
  237773. }
  237774. void setFullScreen (bool shouldBeFullScreen)
  237775. {
  237776. // TODO
  237777. }
  237778. bool isFullScreen() const
  237779. {
  237780. // TODO
  237781. return false;
  237782. }
  237783. void setIcon (const Image& newIcon)
  237784. {
  237785. // TODO
  237786. }
  237787. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  237788. {
  237789. // TODO
  237790. return isPositiveAndBelow (position.getX(), component->getWidth())
  237791. && isPositiveAndBelow (position.getY(), component->getHeight());
  237792. }
  237793. const BorderSize<int> getFrameSize() const
  237794. {
  237795. // TODO
  237796. return BorderSize<int>();
  237797. }
  237798. bool setAlwaysOnTop (bool alwaysOnTop)
  237799. {
  237800. // TODO
  237801. return false;
  237802. }
  237803. void toFront (bool makeActive)
  237804. {
  237805. // TODO
  237806. }
  237807. void toBehind (ComponentPeer* other)
  237808. {
  237809. // TODO
  237810. }
  237811. bool isFocused() const
  237812. {
  237813. // TODO
  237814. return false;
  237815. }
  237816. void grabFocus()
  237817. {
  237818. // TODO
  237819. }
  237820. void textInputRequired (const Point<int>& position)
  237821. {
  237822. // TODO
  237823. }
  237824. void repaint (const Rectangle<int>& area)
  237825. {
  237826. // TODO
  237827. }
  237828. void performAnyPendingRepaintsNow()
  237829. {
  237830. // TODO
  237831. }
  237832. void setAlpha (float newAlpha)
  237833. {
  237834. // TODO
  237835. }
  237836. private:
  237837. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  237838. };
  237839. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  237840. {
  237841. return new AndroidComponentPeer (this, styleFlags);
  237842. }
  237843. bool Desktop::canUseSemiTransparentWindows() throw()
  237844. {
  237845. return true; // TODO
  237846. }
  237847. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  237848. {
  237849. // TODO
  237850. return upright;
  237851. }
  237852. void Desktop::createMouseInputSources()
  237853. {
  237854. // This creates a mouse input source for each possible finger
  237855. for (int i = 0; i < 10; ++i)
  237856. mouseSources.add (new MouseInputSource (i, false));
  237857. }
  237858. const Point<int> MouseInputSource::getCurrentMousePosition()
  237859. {
  237860. // TODO
  237861. return Point<int>();
  237862. }
  237863. void Desktop::setMousePosition (const Point<int>& newPosition)
  237864. {
  237865. // not needed
  237866. }
  237867. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  237868. {
  237869. // TODO
  237870. return false;
  237871. }
  237872. void ModifierKeys::updateCurrentModifiers() throw()
  237873. {
  237874. // not needed
  237875. }
  237876. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  237877. {
  237878. // TODO
  237879. return ModifierKeys();
  237880. }
  237881. bool Process::isForegroundProcess()
  237882. {
  237883. return true; // TODO
  237884. }
  237885. bool AlertWindow::showNativeDialogBox (const String& title,
  237886. const String& bodyText,
  237887. bool isOkCancel)
  237888. {
  237889. // TODO
  237890. }
  237891. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  237892. {
  237893. return createSoftwareImage (format, width, height, clearImage);
  237894. }
  237895. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  237896. {
  237897. // TODO
  237898. }
  237899. bool Desktop::isScreenSaverEnabled()
  237900. {
  237901. return true;
  237902. }
  237903. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  237904. {
  237905. }
  237906. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  237907. {
  237908. // TODO
  237909. monitorCoords.add (Rectangle<int> (0, 0, 640, 480));
  237910. }
  237911. const Image juce_createIconForFile (const File& file)
  237912. {
  237913. Image image;
  237914. // TODO
  237915. return image;
  237916. }
  237917. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  237918. {
  237919. return 0;
  237920. }
  237921. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  237922. {
  237923. }
  237924. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  237925. {
  237926. return 0;
  237927. }
  237928. void MouseCursor::showInWindow (ComponentPeer*) const {}
  237929. void MouseCursor::showInAllWindows() const {}
  237930. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  237931. {
  237932. return false;
  237933. }
  237934. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  237935. {
  237936. return false;
  237937. }
  237938. const int extendedKeyModifier = 0x10000;
  237939. const int KeyPress::spaceKey = ' ';
  237940. const int KeyPress::returnKey = 0x0d;
  237941. const int KeyPress::escapeKey = 0x1b;
  237942. const int KeyPress::backspaceKey = 0x7f;
  237943. const int KeyPress::leftKey = extendedKeyModifier + 1;
  237944. const int KeyPress::rightKey = extendedKeyModifier + 2;
  237945. const int KeyPress::upKey = extendedKeyModifier + 3;
  237946. const int KeyPress::downKey = extendedKeyModifier + 4;
  237947. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  237948. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  237949. const int KeyPress::endKey = extendedKeyModifier + 7;
  237950. const int KeyPress::homeKey = extendedKeyModifier + 8;
  237951. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  237952. const int KeyPress::insertKey = -1;
  237953. const int KeyPress::tabKey = 9;
  237954. const int KeyPress::F1Key = extendedKeyModifier + 10;
  237955. const int KeyPress::F2Key = extendedKeyModifier + 11;
  237956. const int KeyPress::F3Key = extendedKeyModifier + 12;
  237957. const int KeyPress::F4Key = extendedKeyModifier + 13;
  237958. const int KeyPress::F5Key = extendedKeyModifier + 14;
  237959. const int KeyPress::F6Key = extendedKeyModifier + 16;
  237960. const int KeyPress::F7Key = extendedKeyModifier + 17;
  237961. const int KeyPress::F8Key = extendedKeyModifier + 18;
  237962. const int KeyPress::F9Key = extendedKeyModifier + 19;
  237963. const int KeyPress::F10Key = extendedKeyModifier + 20;
  237964. const int KeyPress::F11Key = extendedKeyModifier + 21;
  237965. const int KeyPress::F12Key = extendedKeyModifier + 22;
  237966. const int KeyPress::F13Key = extendedKeyModifier + 23;
  237967. const int KeyPress::F14Key = extendedKeyModifier + 24;
  237968. const int KeyPress::F15Key = extendedKeyModifier + 25;
  237969. const int KeyPress::F16Key = extendedKeyModifier + 26;
  237970. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  237971. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  237972. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  237973. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  237974. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  237975. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  237976. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  237977. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  237978. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  237979. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  237980. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  237981. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  237982. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  237983. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  237984. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  237985. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  237986. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  237987. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  237988. const int KeyPress::playKey = extendedKeyModifier + 45;
  237989. const int KeyPress::stopKey = extendedKeyModifier + 46;
  237990. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  237991. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  237992. #endif
  237993. /*** End of inlined file: juce_android_Windowing.cpp ***/
  237994. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  237995. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237996. // compiled on its own).
  237997. #if JUCE_INCLUDED_FILE
  237998. void FileChooser::showPlatformDialog (Array<File>& results,
  237999. const String& title,
  238000. const File& currentFileOrDirectory,
  238001. const String& filter,
  238002. bool selectsDirectory,
  238003. bool selectsFiles,
  238004. bool isSaveDialogue,
  238005. bool warnAboutOverwritingExistingFiles,
  238006. bool selectMultipleFiles,
  238007. FilePreviewComponent* extraInfoComponent)
  238008. {
  238009. // TODO
  238010. }
  238011. #endif
  238012. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  238013. /*** Start of inlined file: juce_android_Misc.cpp ***/
  238014. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238015. // compiled on its own).
  238016. #if JUCE_INCLUDED_FILE
  238017. void SystemClipboard::copyTextToClipboard (const String& text)
  238018. {
  238019. // TODO
  238020. }
  238021. const String SystemClipboard::getTextFromClipboard()
  238022. {
  238023. String result;
  238024. // TODO
  238025. return result;
  238026. }
  238027. #endif
  238028. /*** End of inlined file: juce_android_Misc.cpp ***/
  238029. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238030. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238031. // compiled on its own).
  238032. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  238033. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  238034. : browser (0),
  238035. blankPageShown (false),
  238036. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  238037. {
  238038. setOpaque (true);
  238039. }
  238040. WebBrowserComponent::~WebBrowserComponent()
  238041. {
  238042. }
  238043. void WebBrowserComponent::goToURL (const String& url,
  238044. const StringArray* headers,
  238045. const MemoryBlock* postData)
  238046. {
  238047. lastURL = url;
  238048. lastHeaders.clear();
  238049. if (headers != 0)
  238050. lastHeaders = *headers;
  238051. lastPostData.setSize (0);
  238052. if (postData != 0)
  238053. lastPostData = *postData;
  238054. blankPageShown = false;
  238055. }
  238056. void WebBrowserComponent::stop()
  238057. {
  238058. }
  238059. void WebBrowserComponent::goBack()
  238060. {
  238061. lastURL = String::empty;
  238062. blankPageShown = false;
  238063. }
  238064. void WebBrowserComponent::goForward()
  238065. {
  238066. lastURL = String::empty;
  238067. }
  238068. void WebBrowserComponent::refresh()
  238069. {
  238070. }
  238071. void WebBrowserComponent::paint (Graphics& g)
  238072. {
  238073. g.fillAll (Colours::white);
  238074. }
  238075. void WebBrowserComponent::checkWindowAssociation()
  238076. {
  238077. }
  238078. void WebBrowserComponent::reloadLastURL()
  238079. {
  238080. if (lastURL.isNotEmpty())
  238081. {
  238082. goToURL (lastURL, &lastHeaders, &lastPostData);
  238083. lastURL = String::empty;
  238084. }
  238085. }
  238086. void WebBrowserComponent::parentHierarchyChanged()
  238087. {
  238088. checkWindowAssociation();
  238089. }
  238090. void WebBrowserComponent::resized()
  238091. {
  238092. }
  238093. void WebBrowserComponent::visibilityChanged()
  238094. {
  238095. checkWindowAssociation();
  238096. }
  238097. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  238098. {
  238099. return true;
  238100. }
  238101. #endif
  238102. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238103. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  238104. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238105. // compiled on its own).
  238106. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  238107. // TODO
  238108. OpenGLContext* OpenGLComponent::createContext()
  238109. {
  238110. return 0;
  238111. }
  238112. void* OpenGLComponent::getNativeWindowHandle() const
  238113. {
  238114. return 0;
  238115. }
  238116. void juce_glViewport (const int w, const int h)
  238117. {
  238118. // glViewport (0, 0, w, h);
  238119. }
  238120. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  238121. OwnedArray <OpenGLPixelFormat>& results)
  238122. {
  238123. }
  238124. #endif
  238125. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  238126. /*** Start of inlined file: juce_android_Midi.cpp ***/
  238127. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238128. // compiled on its own).
  238129. #if JUCE_INCLUDED_FILE
  238130. const StringArray MidiOutput::getDevices()
  238131. {
  238132. StringArray devices;
  238133. return devices;
  238134. }
  238135. int MidiOutput::getDefaultDeviceIndex()
  238136. {
  238137. return 0;
  238138. }
  238139. MidiOutput* MidiOutput::openDevice (int index)
  238140. {
  238141. return 0;
  238142. }
  238143. MidiOutput::~MidiOutput()
  238144. {
  238145. }
  238146. void MidiOutput::reset()
  238147. {
  238148. }
  238149. bool MidiOutput::getVolume (float&, float&)
  238150. {
  238151. return false;
  238152. }
  238153. void MidiOutput::setVolume (float, float)
  238154. {
  238155. }
  238156. void MidiOutput::sendMessageNow (const MidiMessage&)
  238157. {
  238158. }
  238159. MidiInput::MidiInput (const String& name_)
  238160. : name (name_),
  238161. internal (0)
  238162. {
  238163. }
  238164. MidiInput::~MidiInput()
  238165. {
  238166. }
  238167. void MidiInput::start()
  238168. {
  238169. }
  238170. void MidiInput::stop()
  238171. {
  238172. }
  238173. int MidiInput::getDefaultDeviceIndex()
  238174. {
  238175. return 0;
  238176. }
  238177. const StringArray MidiInput::getDevices()
  238178. {
  238179. StringArray devs;
  238180. return devs;
  238181. }
  238182. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  238183. {
  238184. return 0;
  238185. }
  238186. #endif
  238187. /*** End of inlined file: juce_android_Midi.cpp ***/
  238188. /*** Start of inlined file: juce_android_Audio.cpp ***/
  238189. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238190. // compiled on its own).
  238191. #if JUCE_INCLUDED_FILE
  238192. class AndroidAudioIODevice : public AudioIODevice
  238193. {
  238194. public:
  238195. AndroidAudioIODevice (const String& deviceName)
  238196. : AudioIODevice (deviceName, "Audio"),
  238197. callback (0),
  238198. sampleRate (0),
  238199. numInputChannels (0),
  238200. numOutputChannels (0),
  238201. actualBufferSize (0),
  238202. isRunning (false)
  238203. {
  238204. numInputChannels = 2;
  238205. numOutputChannels = 2;
  238206. // TODO
  238207. }
  238208. ~AndroidAudioIODevice()
  238209. {
  238210. close();
  238211. }
  238212. const StringArray getOutputChannelNames()
  238213. {
  238214. StringArray s;
  238215. s.add ("Left"); // TODO
  238216. s.add ("Right");
  238217. return s;
  238218. }
  238219. const StringArray getInputChannelNames()
  238220. {
  238221. StringArray s;
  238222. s.add ("Left");
  238223. s.add ("Right");
  238224. return s;
  238225. }
  238226. int getNumSampleRates() { return 1;}
  238227. double getSampleRate (int index) { return sampleRate; }
  238228. int getNumBufferSizesAvailable() { return 1; }
  238229. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  238230. int getDefaultBufferSize() { return 1024; }
  238231. const String open (const BigInteger& inputChannels,
  238232. const BigInteger& outputChannels,
  238233. double sampleRate,
  238234. int bufferSize)
  238235. {
  238236. close();
  238237. lastError = String::empty;
  238238. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  238239. activeOutputChans = outputChannels;
  238240. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  238241. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  238242. activeInputChans = inputChannels;
  238243. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  238244. numInputChannels = activeInputChans.countNumberOfSetBits();
  238245. // TODO
  238246. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  238247. isRunning = true;
  238248. return lastError;
  238249. }
  238250. void close()
  238251. {
  238252. if (isRunning)
  238253. {
  238254. isRunning = false;
  238255. // TODO
  238256. }
  238257. }
  238258. int getOutputLatencyInSamples()
  238259. {
  238260. return 0; // TODO
  238261. }
  238262. int getInputLatencyInSamples()
  238263. {
  238264. return 0; // TODO
  238265. }
  238266. bool isOpen() { return isRunning; }
  238267. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  238268. int getCurrentBitDepth() { return 16; }
  238269. double getCurrentSampleRate() { return sampleRate; }
  238270. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  238271. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  238272. const String getLastError() { return lastError; }
  238273. bool isPlaying() { return isRunning && callback != 0; }
  238274. // TODO
  238275. void start (AudioIODeviceCallback* newCallback)
  238276. {
  238277. if (isRunning && callback != newCallback)
  238278. {
  238279. if (newCallback != 0)
  238280. newCallback->audioDeviceAboutToStart (this);
  238281. const ScopedLock sl (callbackLock);
  238282. callback = newCallback;
  238283. }
  238284. }
  238285. void stop()
  238286. {
  238287. if (isRunning)
  238288. {
  238289. AudioIODeviceCallback* lastCallback;
  238290. {
  238291. const ScopedLock sl (callbackLock);
  238292. lastCallback = callback;
  238293. callback = 0;
  238294. }
  238295. if (lastCallback != 0)
  238296. lastCallback->audioDeviceStopped();
  238297. }
  238298. }
  238299. private:
  238300. CriticalSection callbackLock;
  238301. AudioIODeviceCallback* callback;
  238302. double sampleRate;
  238303. int numInputChannels, numOutputChannels;
  238304. int actualBufferSize;
  238305. bool isRunning;
  238306. String lastError;
  238307. BigInteger activeOutputChans, activeInputChans;
  238308. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  238309. };
  238310. // TODO
  238311. class AndroidAudioIODeviceType : public AudioIODeviceType
  238312. {
  238313. public:
  238314. AndroidAudioIODeviceType()
  238315. : AudioIODeviceType ("Android Audio")
  238316. {
  238317. }
  238318. void scanForDevices()
  238319. {
  238320. }
  238321. const StringArray getDeviceNames (bool wantInputNames) const
  238322. {
  238323. StringArray s;
  238324. s.add ("Android Audio");
  238325. return s;
  238326. }
  238327. int getDefaultDeviceIndex (bool forInput) const
  238328. {
  238329. return 0;
  238330. }
  238331. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  238332. {
  238333. return device != 0 ? 0 : -1;
  238334. }
  238335. bool hasSeparateInputsAndOutputs() const { return false; }
  238336. AudioIODevice* createDevice (const String& outputDeviceName,
  238337. const String& inputDeviceName)
  238338. {
  238339. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  238340. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  238341. : inputDeviceName);
  238342. return 0;
  238343. }
  238344. private:
  238345. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  238346. };
  238347. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  238348. {
  238349. return new AndroidAudioIODeviceType();
  238350. }
  238351. #endif
  238352. /*** End of inlined file: juce_android_Audio.cpp ***/
  238353. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  238354. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238355. // compiled on its own).
  238356. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  238357. // TODO
  238358. class AndroidCameraInternal
  238359. {
  238360. public:
  238361. AndroidCameraInternal()
  238362. {
  238363. }
  238364. ~AndroidCameraInternal()
  238365. {
  238366. }
  238367. private:
  238368. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  238369. };
  238370. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  238371. : name (name_)
  238372. {
  238373. internal = new AndroidCameraInternal();
  238374. // TODO
  238375. }
  238376. CameraDevice::~CameraDevice()
  238377. {
  238378. stopRecording();
  238379. delete static_cast <AndroidCameraInternal*> (internal);
  238380. internal = 0;
  238381. }
  238382. Component* CameraDevice::createViewerComponent()
  238383. {
  238384. // TODO
  238385. return 0;
  238386. }
  238387. const String CameraDevice::getFileExtension()
  238388. {
  238389. return ".m4a"; // TODO correct?
  238390. }
  238391. void CameraDevice::startRecordingToFile (const File& file, int quality)
  238392. {
  238393. // TODO
  238394. }
  238395. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  238396. {
  238397. // TODO
  238398. return Time();
  238399. }
  238400. void CameraDevice::stopRecording()
  238401. {
  238402. // TODO
  238403. }
  238404. void CameraDevice::addListener (Listener* listenerToAdd)
  238405. {
  238406. // TODO
  238407. }
  238408. void CameraDevice::removeListener (Listener* listenerToRemove)
  238409. {
  238410. // TODO
  238411. }
  238412. const StringArray CameraDevice::getAvailableDevices()
  238413. {
  238414. StringArray devs;
  238415. // TODO
  238416. return devs;
  238417. }
  238418. CameraDevice* CameraDevice::openDevice (int index,
  238419. int minWidth, int minHeight,
  238420. int maxWidth, int maxHeight)
  238421. {
  238422. // TODO
  238423. return 0;
  238424. }
  238425. #endif
  238426. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  238427. END_JUCE_NAMESPACE
  238428. #endif
  238429. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  238430. #endif
  238431. #endif